Skip to main content

quickjs/
objects.rs

1//! Objects, properties and C functions: the `JS_NewObject` family.
2//!
3//! Everything here is a translation, not an implementation: the engine already has objects,
4//! property tables, accessors and host functions (`docs/m15-plan.md` §5, S1). What this
5//! module adds is the C API's *shapes* — a `JSCFunctionListEntry` table, a `JS_CFUNC_*`
6//! calling convention, `JS_SetConstructor`'s two reciprocal properties.
7//!
8//! # The one real decision: who owns the returned value
9//!
10//! A function that answers `JSValue` answers a *new reference*: the caller owns it and is
11//! responsible for `JS_FreeValue`. That is why `JS_NewObject` boxes its answer with a count
12//! of one and why a C function's return value is `release`d by the trampoline once the
13//! engine value has been cloned out. `argv` is the opposite — borrowed, never freed by us —
14//! which is the asymmetry [`crate::convert`] is built around.
15
16use core::ffi::{c_char, c_int};
17
18use engine::interp::JsResult;
19use engine::object::Property;
20use engine::{ClassId, Value};
21
22use crate::cdefs::{self, CFunctionEnum, JSCFunctionListEntry, JSCFunctionType, JSClassDef, prop};
23use crate::jsvalue::{self, JsValue};
24use crate::runtime::{self, JsContext, JsRuntime};
25use crate::value_helpers::jsvalue_of;
26
27/// Read a `JSValue` argument.
28///
29/// # Safety
30///
31/// `value` must be a `JSValue` this crate produced, or a primitive.
32pub(crate) unsafe fn arg(value: JsValue) -> Option<Value> {
33    // SAFETY: the caller's contract.
34    unsafe { runtime::argument(value) }
35}
36
37// ---------------------------------------------------------------------------
38// Objects
39// ---------------------------------------------------------------------------
40
41/// `JS_NewObject`: an ordinary object inheriting `Object.prototype`.
42///
43/// # Safety
44///
45/// `ctx` must be a live context.
46#[unsafe(no_mangle)]
47pub unsafe extern "C" fn JS_NewObject(ctx: *mut JsContext) -> JsValue {
48    let Some(context) = (unsafe { ctx.as_ref() }) else {
49        return jsvalue::EXCEPTION;
50    };
51    context.with_current_interp(|interp| {
52        let proto = interp.realm.object_proto.clone();
53        jsvalue_of(Value::Object(interp.new_object(Some(proto))))
54    })
55}
56
57/// The global object (`JS_GetGlobalObject`).
58///
59/// # Safety
60///
61/// `ctx` must be a live context.
62#[unsafe(no_mangle)]
63pub unsafe extern "C" fn JS_GetGlobalObject(ctx: *mut JsContext) -> JsValue {
64    let Some(context) = (unsafe { ctx.as_ref() }) else {
65        return jsvalue::EXCEPTION;
66    };
67    context.with_current_interp(|interp| {
68        let global = interp.realm.global.clone();
69        jsvalue_of(Value::Object(global))
70    })
71}
72
73/// `JS_NewObjectProtoClass`: an instance of `class_id` whose prototype is `proto`.
74///
75/// # Safety
76///
77/// `ctx` must be a live context and `proto` a live `JSValue`.
78#[unsafe(no_mangle)]
79pub unsafe extern "C" fn JS_NewObjectProtoClass(
80    ctx: *mut JsContext,
81    proto: JsValue,
82    class_id: cdefs::ClassId,
83) -> JsValue {
84    let Some(context) = (unsafe { ctx.as_ref() }) else {
85        return jsvalue::EXCEPTION;
86    };
87    let Some(proto) = (unsafe { arg(proto) }) else {
88        return runtime::throw_error(context, "TypeError", "prototype is not an object");
89    };
90    let Some(prototype) = proto.as_object().cloned() else {
91        return runtime::throw_error(context, "TypeError", "prototype is not an object");
92    };
93    context.with_current_interp(|interp| {
94        match interp.new_host_object(Some(prototype), ClassId::from_raw(class_id)) {
95            Some(object) => jsvalue_of(Value::Object(object)),
96            // The C API answers `NULL` here, which the caller reports as an exception; the
97            // reference spells it as a `TypeError` from `JS_ThrowTypeErrorInvalidClass`.
98            None => runtime::throw_error(
99                context,
100                "TypeError",
101                &format!("invalid class id {class_id}"),
102            ),
103        }
104    })
105}
106
107/// `JS_NewObjectClass`: an instance of `class_id` with the prototype installed for it.
108///
109/// # Safety
110///
111/// `ctx` must be a live context.
112#[unsafe(no_mangle)]
113pub unsafe extern "C" fn JS_NewObjectClass(ctx: *mut JsContext, class_id: c_int) -> JsValue {
114    let Some(context) = (unsafe { ctx.as_ref() }) else {
115        return jsvalue::EXCEPTION;
116    };
117    context.with_current_interp(|interp| {
118        match interp.new_host_object(None, ClassId::from_raw(class_id as u32)) {
119            Some(object) => jsvalue_of(Value::Object(object)),
120            None => runtime::throw_error(
121                context,
122                "TypeError",
123                &format!("invalid class id {class_id}"),
124            ),
125        }
126    })
127}
128
129/// `JS_GetPropertyStr`: read a property by name, answering a new reference.
130///
131/// # Safety
132///
133/// `ctx` must be a live context, `this_obj` a live `JSValue`, and `name` a NUL-terminated
134/// string.
135#[unsafe(no_mangle)]
136pub unsafe extern "C" fn JS_GetPropertyStr(
137    ctx: *mut JsContext,
138    this_obj: JsValue,
139    name: *const c_char,
140) -> JsValue {
141    let Some(context) = (unsafe { ctx.as_ref() }) else {
142        return jsvalue::EXCEPTION;
143    };
144    let Some(target) = (unsafe { arg(this_obj) }) else {
145        return runtime::throw_error(context, "TypeError", "not an object");
146    };
147    // SAFETY: the caller guarantees a NUL-terminated string.
148    let name = unsafe { std::ffi::CStr::from_ptr(name) }.to_string_lossy();
149    // `read_field` rather than `get_property`: a `JSValue` may be a string primitive, whose
150    // `length` and indices the engine answers without boxing it.
151    let result = context.with_current_interp(|interp| interp.read_field(&target, &name));
152    runtime::result_value(context, result)
153}
154
155/// `JS_SetPropertyStr`: write a property by name, answering `-1` on failure.
156///
157/// # Safety
158///
159/// `ctx` must be a live context, `this_obj` a live `JSValue`, `name` a NUL-terminated
160/// string, and `value` a live `JSValue` whose reference this call consumes.
161#[unsafe(no_mangle)]
162pub unsafe extern "C" fn JS_SetPropertyStr(
163    ctx: *mut JsContext,
164    this_obj: JsValue,
165    name: *const c_char,
166    value: JsValue,
167) -> c_int {
168    let Some(context) = (unsafe { ctx.as_ref() }) else {
169        return -1;
170    };
171    let Some(target) = (unsafe { arg(this_obj) }) else {
172        runtime::throw_error(context, "TypeError", "not an object");
173        return -1;
174    };
175    let Some(new_value) = (unsafe { arg(value) }) else {
176        runtime::throw_error(context, "TypeError", "not a value");
177        return -1;
178    };
179    // SAFETY: the caller guarantees a NUL-terminated string.
180    let name = unsafe { std::ffi::CStr::from_ptr(name) }.to_string_lossy();
181    let result = context.with_current_interp(|interp| match target.as_object() {
182        Some(object) => interp.set_property(object, &name, new_value),
183        None => Err(engine::Signal::Throw(interp.make_error(
184            "TypeError",
185            &format!("cannot set property '{name}' of a primitive"),
186        ))),
187    });
188    // The reference takes `JSValue val` here, not `JSValueConst`: the write consumes the
189    // caller's reference.
190    // SAFETY: the caller's reference is ours to drop.
191    unsafe { runtime::release(value) };
192    match result {
193        Ok(()) => 0,
194        Err(signal) => {
195            let _ = runtime::result_value(context, Err(signal));
196            -1
197        }
198    }
199}
200
201/// `JS_ToBool`: the truthiness of a value, or `-1` for an exception.
202///
203/// # Safety
204///
205/// `val` must be a live `JSValue`.
206#[unsafe(no_mangle)]
207pub unsafe extern "C" fn JS_ToBool(ctx: *mut JsContext, val: JsValue) -> c_int {
208    let Some(context) = (unsafe { ctx.as_ref() }) else {
209        return -1;
210    };
211    match unsafe { arg(val) } {
212        Some(value) => c_int::from(value.to_boolean()),
213        None => {
214            runtime::throw_error(context, "TypeError", "not a value");
215            -1
216        }
217    }
218}
219
220/// `JS_ToIndex`: a valid array index, or a `RangeError`.
221///
222/// # Safety
223///
224/// `plen` must be writable and `val` a live `JSValue`.
225#[unsafe(no_mangle)]
226pub unsafe extern "C" fn JS_ToIndex(ctx: *mut JsContext, plen: *mut u64, val: JsValue) -> c_int {
227    let Some(context) = (unsafe { ctx.as_ref() }) else {
228        return -1;
229    };
230    let Some(value) = (unsafe { arg(val) }) else {
231        runtime::throw_error(context, "TypeError", "not a value");
232        return -1;
233    };
234    let number = match context.with_current_interp(|interp| interp.to_js_number(&value)) {
235        Ok(number) => number,
236        Err(signal) => {
237            let _ = runtime::result_value(context, Err(signal));
238            return -1;
239        }
240    };
241    // `ToIndex`: an integer in `0 ..= 2^53 - 1`, and `-0` is `0`.
242    let index = number.trunc();
243    if number.is_nan() || index != number || index < 0.0 || index > 9_007_199_254_740_991.0 {
244        runtime::throw_error(context, "RangeError", "invalid array index");
245        return -1;
246    }
247    if !plen.is_null() {
248        // SAFETY: the caller guarantees the pointer is writable.
249        unsafe { *plen = index as u64 };
250    }
251    0
252}
253
254// ---------------------------------------------------------------------------
255// C functions
256// ---------------------------------------------------------------------------
257
258/// The shape of every C function the API installs, as a raw pointer.
259///
260/// One opaque type for fourteen signatures: which one applies is decided by the
261/// [`CFunctionEnum`] stored beside it, exactly as in the reference's `JSCFunctionType`
262/// union.
263pub type RawFunction = *const core::ffi::c_void;
264
265/// `JS_NewCFunction2`: wrap a C function pointer as a JavaScript function.
266///
267/// # Safety
268///
269/// `ctx` must be a live context, `func` must be a function pointer of the signature
270/// `cproto` names, and `name` a NUL-terminated string.
271#[unsafe(no_mangle)]
272pub unsafe extern "C" fn JS_NewCFunction2(
273    ctx: *mut JsContext,
274    func: RawFunction,
275    name: *const c_char,
276    length: c_int,
277    cproto: c_int,
278    magic: c_int,
279) -> JsValue {
280    let Some(context) = (unsafe { ctx.as_ref() }) else {
281        return jsvalue::EXCEPTION;
282    };
283    // SAFETY: the caller guarantees a NUL-terminated string.
284    let name = unsafe { std::ffi::CStr::from_ptr(name) }
285        .to_string_lossy()
286        .into_owned();
287    let Some(kind) = u8::try_from(cproto).ok().and_then(CFunctionEnum::from_raw) else {
288        return runtime::throw_error(
289            context,
290            "TypeError",
291            &format!("unsupported JSCFunctionEnum {cproto}"),
292        );
293    };
294    context.with_current_interp(|interp| {
295        let function = make_c_function(interp, func, kind, name, length, magic);
296        jsvalue_of(Value::Object(function))
297    })
298}
299
300/// Build the engine function object for a C function pointer.
301pub(crate) fn make_c_function(
302    interp: &mut engine::Interp<'static>,
303    func: RawFunction,
304    kind: CFunctionEnum,
305    name: String,
306    length: c_int,
307    magic: c_int,
308) -> engine::Gc<engine::JsObject> {
309    let arity = u32::try_from(length).unwrap_or(0);
310    let body: engine::object::HostFn = Box::new(move |interp, this, args| {
311        let context = current_context_or_null();
312        call_c_function(context, interp, func, kind, magic, this, args)
313    });
314    // A constructor gets `own_instance`: `new` hands it `undefined` for `this` and it builds
315    // its own instance from `new.target`, which is the shape `JS_CFUNC_constructor`
316    // documents and the reason `point.c` reads `new_target` at all.
317    if kind.is_constructor() {
318        interp.new_host_ctor(name, arity, body)
319    } else {
320        interp.new_host_function(name, arity, body)
321    }
322}
323
324/// The context a function object belongs to.
325///
326/// A C function is always *called* through a `JSContext`, so reading the current one at call
327/// time would be enough — except that `make_c_function`'s closure must capture something
328/// stable, and the value being built right now is being built *for* this context.
329fn current_context_or_null() -> *mut JsContext {
330    runtime::current_context()
331        .map(|context| context as *const JsContext as *mut JsContext)
332        .unwrap_or(std::ptr::null_mut())
333}
334
335/// Invoke a C function pointer with the convention `kind` names.
336///
337/// Arguments are handed over as an array of `JSValue`s, borrowed: the C function must not
338/// free them, which is what the `JSValueConst` in its signature means. The return value is
339/// owned by us, so it is decoded and then released.
340fn call_c_function<'i>(
341    ctx: *mut JsContext,
342    interp: &mut engine::Interp<'i>,
343    func: RawFunction,
344    kind: CFunctionEnum,
345    magic: c_int,
346    this: Value,
347    args: &[Value],
348) -> JsResult<Value> {
349    // `this` for a constructor is `new.target`, which the engine parked for exactly this
350    // purpose; for everything else it is the receiver.
351    let this = if kind.is_constructor() {
352        interp.current_new_target()
353    } else {
354        this
355    };
356    let this_value = crate::convert::encode(&this);
357    let arguments: Vec<JsValue> = args.iter().map(crate::convert::encode).collect();
358    let pointer = arguments.as_ptr();
359    let argc = c_int::try_from(arguments.len()).unwrap_or(c_int::MAX);
360    // The `JSContext *` a C function receives is the current one; if there is none this is
361    // a function that outlived its context, which the C API cannot express either.
362    let context = current_context_or_null();
363    let _ = ctx;
364
365    // SAFETY: `func` is a pointer of the signature `kind` names — the caller of
366    // `JS_NewCFunction2` promised that. Every arm below is one of the reference's
367    // `JSCFunctionType` variants spelled out.
368    let answer = unsafe {
369        match kind {
370            CFunctionEnum::Generic => {
371                let f: unsafe extern "C" fn(
372                    *mut JsContext,
373                    JsValue,
374                    c_int,
375                    *const JsValue,
376                ) -> JsValue = core::mem::transmute(func);
377                f(context, this_value, argc, pointer)
378            }
379            CFunctionEnum::GenericMagic => {
380                let f: unsafe extern "C" fn(
381                    *mut JsContext,
382                    JsValue,
383                    c_int,
384                    *const JsValue,
385                    c_int,
386                ) -> JsValue = core::mem::transmute(func);
387                f(context, this_value, argc, pointer, magic)
388            }
389            CFunctionEnum::Constructor | CFunctionEnum::ConstructorOrFunc => {
390                let f: unsafe extern "C" fn(
391                    *mut JsContext,
392                    JsValue,
393                    c_int,
394                    *const JsValue,
395                ) -> JsValue = core::mem::transmute(func);
396                f(context, this_value, argc, pointer)
397            }
398            CFunctionEnum::ConstructorMagic | CFunctionEnum::ConstructorOrFuncMagic => {
399                let f: unsafe extern "C" fn(
400                    *mut JsContext,
401                    JsValue,
402                    c_int,
403                    *const JsValue,
404                    c_int,
405                ) -> JsValue = core::mem::transmute(func);
406                f(context, this_value, argc, pointer, magic)
407            }
408            CFunctionEnum::ConstructorOrFuncFlags => {
409                // `(ctx, func_obj, this_val, argc, argv, flags)`: the flag says whether this
410                // is a constructor call, which is the only difference from the plain form.
411                let flags = if this_value.is_undefined() {
412                    0
413                } else {
414                    cdefs::JS_CALL_FLAG_CONSTRUCTOR
415                };
416                let f: unsafe extern "C" fn(
417                    *mut JsContext,
418                    JsValue,
419                    JsValue,
420                    c_int,
421                    *const JsValue,
422                    c_int,
423                ) -> JsValue = core::mem::transmute(func);
424                f(context, this_value, this_value, argc, pointer, flags)
425            }
426            CFunctionEnum::Getter => {
427                let f: unsafe extern "C" fn(*mut JsContext, JsValue) -> JsValue =
428                    core::mem::transmute(func);
429                f(context, this_value)
430            }
431            CFunctionEnum::GetterMagic => {
432                let f: unsafe extern "C" fn(*mut JsContext, JsValue, c_int) -> JsValue =
433                    core::mem::transmute(func);
434                f(context, this_value, magic)
435            }
436            CFunctionEnum::Setter => {
437                let f: unsafe extern "C" fn(*mut JsContext, JsValue, JsValue) -> JsValue =
438                    core::mem::transmute(func);
439                let value = args.first().cloned().unwrap_or(Value::Undefined);
440                let encoded = crate::convert::encode(&value);
441                let answer = f(context, this_value, encoded);
442                runtime::release(encoded);
443                answer
444            }
445            CFunctionEnum::SetterMagic => {
446                let f: unsafe extern "C" fn(*mut JsContext, JsValue, JsValue, c_int) -> JsValue =
447                    core::mem::transmute(func);
448                let value = args.first().cloned().unwrap_or(Value::Undefined);
449                let encoded = crate::convert::encode(&value);
450                let answer = f(context, this_value, encoded, magic);
451                runtime::release(encoded);
452                answer
453            }
454            // `f_f`/`f_f_f`/`iterator_next`: not reachable from a `JSCFunctionListEntry`
455            // this layer installs, and `JS_NewCFunction2` is only ever called with a
456            // convention it can honour.
457            CFunctionEnum::FF | CFunctionEnum::FFF | CFunctionEnum::IteratorNext => {
458                return Err(engine::Signal::Throw(
459                    interp.make_error("TypeError", "unsupported C function convention"),
460                ));
461            }
462        }
463    };
464
465    // Every `JSValue` that went out is ours to free: the arguments and `this` were encoded
466    // here (the C side treats them as borrowed), and the answer is a new reference.
467    for value in arguments {
468        // SAFETY: each was produced by `encode` in this function and is not used again.
469        unsafe { runtime::release(value) };
470    }
471    let answer_is_this = answer.has_ref_count() && answer.payload() == this_value.payload();
472    let result = finish_call(context, interp, answer);
473    // `this` is released *after* the answer is decoded, and skipped when the C function
474    // returned `this` itself: in that case the answer's own reference is the same box, and
475    // `finish_call` already dropped it. Releasing it twice was the first version's bug — it
476    // showed up as a host object that never ran its finalizer, because one box kept a `Gc`
477    // alive for the life of the process.
478    if !answer_is_this {
479        // SAFETY: `this_value` was produced by `encode` here and is not used again.
480        unsafe { runtime::release(this_value) };
481    }
482    result
483}
484
485/// Turn what a C function answered into an engine result.
486///
487/// Three cases:
488///
489/// * a real value — decoded, and its C-side reference released;
490/// * `JS_EXCEPTION` with a pending exception — that becomes `Signal::Throw`, so the
491///   `catch` that wraps the call sees the very object C raised;
492/// * `JS_EXCEPTION` with nothing pending — a bug in the C function, reported as an
493///   `InternalError` rather than a silent `undefined`.
494fn finish_call(
495    context: *mut JsContext,
496    interp: &mut engine::Interp<'_>,
497    answer: JsValue,
498) -> JsResult<Value> {
499    if answer.is_exception() {
500        // SAFETY: the pointer came from `current_context_or_null`, which answers the
501        // context currently running this callback.
502        let pending = unsafe { context.as_ref() }.and_then(|context| context.take_pending());
503        return Err(match pending {
504            Some(value) => engine::Signal::Throw(value),
505            None => engine::Signal::Throw(interp.make_error(
506                "InternalError",
507                "C function returned JS_EXCEPTION without raising",
508            )),
509        });
510    }
511    let decoded = if answer.is_undefined() {
512        Some(Value::Undefined)
513    } else {
514        // SAFETY: the answer is a `JSValue` this layer produced (or a primitive).
515        unsafe { runtime::argument(answer) }
516    };
517    // SAFETY: the answer is an owned reference, and it is no longer used.
518    unsafe { runtime::release(answer) };
519    Ok(decoded.unwrap_or(Value::Undefined))
520}
521
522/// `JS_SetConstructor`: make `func_obj.prototype` and `proto.constructor` point at each
523/// other.
524///
525/// # Safety
526///
527/// Both values must be live and both must be objects.
528#[unsafe(no_mangle)]
529pub unsafe extern "C" fn JS_SetConstructor(
530    ctx: *mut JsContext,
531    func_obj: JsValue,
532    proto: JsValue,
533) -> c_int {
534    let Some(context) = (unsafe { ctx.as_ref() }) else {
535        return -1;
536    };
537    let (Some(function), Some(prototype)) = (unsafe { arg(func_obj) }, unsafe { arg(proto) })
538    else {
539        runtime::throw_error(context, "TypeError", "not an object");
540        return -1;
541    };
542    let (Some(function), Some(prototype)) = (function.as_object(), prototype.as_object()) else {
543        runtime::throw_error(context, "TypeError", "not an object");
544        return -1;
545    };
546    // `prototype` is `{writable: true, enumerable: false, configurable: false}` and
547    // `constructor` is `{writable: true, enumerable: false, configurable: true}` — the two
548    // shapes `JS_SetConstructor2` spells with `0` and `JS_PROP_WRITABLE|JS_PROP_CONFIGURABLE`.
549    function.define(
550        "prototype",
551        Property {
552            value: Some(Value::Object(prototype.clone())),
553            writable: true,
554            enumerable: false,
555            configurable: false,
556            ..Property::default()
557        },
558    );
559    prototype.define(
560        "constructor",
561        Property::with_attributes(Value::Object(function.clone()), true, false),
562    );
563    0
564}
565
566/// `JS_SetPropertyFunctionList`: install a static table of definitions.
567///
568/// The table is the module's `.data`, read entry by entry. Every `JS_DEF_*` the reference
569/// documents is handled except `JS_DEF_ALIAS`/`JS_DEF_PROP_ATOM`, which nothing in the
570/// acceptance surface uses and which need an atom table this layer does not have.
571///
572/// # Safety
573///
574/// `ctx` must be a live context, `obj` a live object `JSValue`, and `tab` must point at
575/// `len` valid entries.
576#[unsafe(no_mangle)]
577pub unsafe extern "C" fn JS_SetPropertyFunctionList(
578    ctx: *mut JsContext,
579    obj: JsValue,
580    tab: *const JSCFunctionListEntry,
581    len: c_int,
582) -> c_int {
583    let Some(context) = (unsafe { ctx.as_ref() }) else {
584        return -1;
585    };
586    let Some(object) = (unsafe { arg(obj) }).and_then(|value| value.as_object().cloned()) else {
587        runtime::throw_error(context, "TypeError", "not an object");
588        return -1;
589    };
590    if tab.is_null() || len <= 0 {
591        return 0;
592    }
593    context.with_current_interp(|interp| {
594        for index in 0..len as usize {
595            // SAFETY: the caller guarantees `tab` holds `len` entries.
596            let entry = unsafe { &*tab.add(index) };
597            if let Err(signal) = install_entry(interp, &object, entry) {
598                let _ = runtime::result_value(context, Err(signal));
599                return -1;
600            }
601        }
602        0
603    })
604}
605
606/// Install one row of a `JSCFunctionListEntry` table.
607fn install_entry(
608    interp: &mut engine::Interp<'static>,
609    object: &engine::Gc<engine::JsObject>,
610    entry: &JSCFunctionListEntry,
611) -> JsResult<()> {
612    if entry.name.is_null() {
613        return Ok(());
614    }
615    // SAFETY: an entry's `name` is a NUL-terminated string in the module's static data.
616    let name = unsafe { std::ffi::CStr::from_ptr(entry.name) }
617        .to_string_lossy()
618        .into_owned();
619    // The C API's flags are a superset of the property attributes: the low three bits are
620    // writable/enumerable/configurable and the rest say "this descriptor field is present",
621    // which a *definition* always implies.
622    let writable = entry.prop_flags & prop::WRITABLE != 0;
623    let enumerable = entry.prop_flags & prop::ENUMERABLE != 0;
624    let configurable = entry.prop_flags & prop::CONFIGURABLE != 0;
625
626    let data_property = |value: Value| Property {
627        value: Some(value),
628        writable,
629        enumerable,
630        configurable,
631        ..Property::default()
632    };
633    let accessor_property = |getter: Option<Value>, setter: Option<Value>| Property {
634        getter,
635        setter,
636        writable: false,
637        enumerable,
638        configurable,
639        ..Property::default()
640    };
641
642    match entry.def_type {
643        cdefs::JS_DEF_CFUNC => {
644            // SAFETY: `def_type` selects this arm of the union.
645            let func = unsafe { &entry.u.func };
646            let Some(kind) = CFunctionEnum::from_raw(func.cproto) else {
647                return Err(engine::Signal::Throw(interp.make_error(
648                    "TypeError",
649                    &format!("unsupported JSCFunctionEnum {}", func.cproto),
650                )));
651            };
652            // SAFETY: the pointer is the variant of `JSCFunctionType` that `cproto` names.
653            let pointer = func.cfunc.as_ptr();
654            // `make_c_function` decides betwen a plain function and a constructor, which is
655            // what makes `JS_CFUNC_constructor` in a list `new`-able.
656            let value = make_c_function(
657                interp,
658                pointer,
659                kind,
660                name.clone(),
661                c_int::from(func.length),
662                entry.magic as c_int,
663            );
664            object.define(&name, data_property(Value::Object(value)));
665        }
666        cdefs::JS_DEF_CGETSET | cdefs::JS_DEF_CGETSET_MAGIC => {
667            let magic = entry.magic as c_int;
668            // Two conventions, and choosing the wrong one is silent: `JS_CGETSET_DEF` passes
669            // `(ctx, this_val)` and `JS_CGETSET_MAGIC_DEF` passes `(ctx, this_val, magic)`,
670            // so calling a magic accessor through the plain convention leaves its `magic`
671            // argument reading whatever the register happened to hold.
672            let (getter_kind, setter_kind) = if entry.def_type == cdefs::JS_DEF_CGETSET_MAGIC {
673                (CFunctionEnum::GetterMagic, CFunctionEnum::SetterMagic)
674            } else {
675                (CFunctionEnum::Getter, CFunctionEnum::Setter)
676            };
677            // SAFETY: `def_type` selects this arm.
678            let pair = unsafe { &entry.u.getset };
679            let getter = wrap_accessor(interp, pair.get, getter_kind, magic, "get");
680            let setter = wrap_accessor(interp, pair.set, setter_kind, magic, "set");
681            object.define(&entry_name(entry), accessor_property(getter, setter));
682        }
683        cdefs::JS_DEF_PROP_STRING => {
684            // SAFETY: `def_type` selects this arm.
685            let text = unsafe { entry.u.str_ };
686            let value = if text.is_null() {
687                Value::Undefined
688            } else {
689                // SAFETY: a `JS_PROP_STRING_DEF` names a NUL-terminated static string.
690                let text = unsafe { std::ffi::CStr::from_ptr(text) };
691                interp.string(text.to_string_lossy().into_owned())
692            };
693            object.define(&entry_name(entry), data_property(value));
694        }
695        cdefs::JS_DEF_PROP_INT32 => {
696            // SAFETY: `def_type` selects this arm.
697            let number = unsafe { entry.u.i32 };
698            object.define(&entry_name(entry), data_property(Value::Int(number)));
699        }
700        cdefs::JS_DEF_PROP_INT64 => {
701            // SAFETY: `def_type` selects this arm.
702            let number = unsafe { entry.u.i64 };
703            object.define(
704                &entry_name(entry),
705                data_property(Value::Float(number as f64)),
706            );
707        }
708        cdefs::JS_DEF_PROP_DOUBLE => {
709            // SAFETY: `def_type` selects this arm.
710            let number = unsafe { entry.u.f64 };
711            object.define(&entry_name(entry), data_property(Value::Float(number)));
712        }
713        cdefs::JS_DEF_PROP_UNDEFINED => {
714            object.define(&entry_name(entry), data_property(Value::Undefined));
715        }
716        cdefs::JS_DEF_PROP_BOOL => {
717            // SAFETY: `def_type` selects this arm; a bool definition stores an `i32`.
718            let flag = unsafe { entry.u.i32 } != 0;
719            object.define(&entry_name(entry), data_property(Value::Bool(flag)));
720        }
721        other => {
722            return Err(engine::Signal::Throw(interp.make_error(
723                "TypeError",
724                &format!("unsupported JS_DEF_* {other} in a function list"),
725            )));
726        }
727    }
728    Ok(())
729}
730
731/// The property name of an entry, as a `String`.
732fn entry_name(entry: &JSCFunctionListEntry) -> String {
733    if entry.name.is_null() {
734        return String::new();
735    }
736    // SAFETY: an entry's `name` is a NUL-terminated string in the module's static data.
737    unsafe { std::ffi::CStr::from_ptr(entry.name) }
738        .to_string_lossy()
739        .into_owned()
740}
741
742/// Wrap one half of a getter/setter pair as a JavaScript accessor function.
743///
744/// A null pointer means "this half does not exist", which the property system already
745/// spells as `None` — so an entry with only a getter is read-only rather than a function
746/// that returns `undefined`.
747fn wrap_accessor(
748    interp: &mut engine::Interp<'static>,
749    function: JSCFunctionType,
750    kind: CFunctionEnum,
751    magic: c_int,
752    which: &str,
753) -> Option<Value> {
754    if function.is_null() {
755        return None;
756    }
757    let pointer = function.as_ptr();
758    let body: engine::object::HostFn = Box::new(move |interp, this, args| {
759        let context = current_context_or_null();
760        call_c_function(context, interp, pointer, kind, magic, this, args)
761    });
762    Some(Value::Object(interp.new_host_function(which, 0, body)))
763}
764
765// ---------------------------------------------------------------------------
766// Classes
767// ---------------------------------------------------------------------------
768
769/// `JS_NewClassID`: allocate an id, storing it in `*pclass_id`.
770///
771/// Mirrors the reference: an id that is already non-zero is kept, so a second call is not a
772/// second allocation. That is what makes a module's static `JSClassID` idempotent.
773///
774/// # Safety
775///
776/// `pclass_id` must be writable.
777#[unsafe(no_mangle)]
778pub unsafe extern "C" fn JS_NewClassID(pclass_id: *mut cdefs::ClassId) -> cdefs::ClassId {
779    let Some(slot) = (unsafe { pclass_id.as_mut() }) else {
780        return 0;
781    };
782    if *slot != 0 {
783        return *slot;
784    }
785    // No runtime needed: ids are global, exactly as in the reference, because the id a
786    // module remembers has to keep meaning the same class in every runtime it is
787    // registered with.
788    *slot = runtime::allocate_class_id();
789    *slot
790}
791
792/// `JS_NewClass`: register a class with the runtime.
793///
794/// # Safety
795///
796/// `rt` must be a live runtime and `class_def` a valid `JSClassDef` whose strings and
797/// function pointers outlive the class.
798#[unsafe(no_mangle)]
799pub unsafe extern "C" fn JS_NewClass(
800    rt: *mut JsRuntime,
801    class_id: cdefs::ClassId,
802    class_def: *const JSClassDef,
803) -> c_int {
804    let (Some(runtime), Some(definition)) = (unsafe { rt.as_ref() }, unsafe { class_def.as_ref() })
805    else {
806        return -1;
807    };
808    let declaration = runtime::ClassDecl {
809        finalizer: definition.finalizer,
810        gc_mark: definition.gc_mark,
811        exotic: definition.exotic,
812        name: definition.class_name,
813    };
814    -c_int::from(!runtime.define_class(class_id, declaration))
815}
816
817/// `JS_IsRegisteredClass`.
818///
819/// # Safety
820///
821/// `rt` must be a live runtime.
822#[unsafe(no_mangle)]
823pub unsafe extern "C" fn JS_IsRegisteredClass(
824    rt: *mut JsRuntime,
825    class_id: cdefs::ClassId,
826) -> c_int {
827    match unsafe { rt.as_ref() } {
828        Some(runtime) => c_int::from(runtime.has_class(class_id)),
829        None => 0,
830    }
831}
832
833/// `JS_GetClassID`: the class an object belongs to, or `JS_INVALID_CLASS_ID`.
834///
835/// # Safety
836///
837/// `value` must be a live `JSValue`.
838#[unsafe(no_mangle)]
839pub unsafe extern "C" fn JS_GetClassID(value: JsValue) -> cdefs::ClassId {
840    let Some(value) = (unsafe { arg(value) }) else {
841        return 0;
842    };
843    value
844        .as_object()
845        .and_then(|object| object.host_class_id())
846        .map_or(0, |id| id.get())
847}
848
849/// `JS_SetClassProto`: the prototype `JS_NewObjectClass` uses for `class_id`.
850///
851/// # Safety
852///
853/// `ctx` must be a live context and `obj` a live object `JSValue` whose reference this call
854/// consumes.
855#[unsafe(no_mangle)]
856pub unsafe extern "C" fn JS_SetClassProto(
857    ctx: *mut JsContext,
858    class_id: cdefs::ClassId,
859    obj: JsValue,
860) {
861    let Some(context) = (unsafe { ctx.as_ref() }) else {
862        return;
863    };
864    let Some(prototype) = (unsafe { arg(obj) }).and_then(|value| value.as_object().cloned()) else {
865        return;
866    };
867    // SAFETY: the C API consumes the reference it was handed.
868    unsafe { runtime::release(obj) };
869    context.with_current_interp(|interp| {
870        interp.set_host_class_proto(ClassId::from_raw(class_id), prototype);
871    });
872}
873
874/// `JS_GetClassProto`: the prototype installed for `class_id`, as a new reference.
875///
876/// # Safety
877///
878/// `ctx` must be a live context.
879#[unsafe(no_mangle)]
880pub unsafe extern "C" fn JS_GetClassProto(
881    ctx: *mut JsContext,
882    class_id: cdefs::ClassId,
883) -> JsValue {
884    let Some(context) = (unsafe { ctx.as_ref() }) else {
885        return jsvalue::EXCEPTION;
886    };
887    context.with_interp(
888        |interp| match interp.host_class_proto(ClassId::from_raw(class_id)) {
889            Some(proto) => jsvalue_of(Value::Object(proto)),
890            None => jsvalue::UNDEFINED,
891        },
892    )
893}
894
895/// `JS_SetOpaque`: attach a payload pointer to a host-class instance.
896///
897/// # Safety
898///
899/// `obj` must be a live `JSValue`; `opaque` is the host's to own.
900#[unsafe(no_mangle)]
901pub unsafe extern "C" fn JS_SetOpaque(obj: JsValue, opaque: *mut core::ffi::c_void) {
902    let Some(value) = (unsafe { arg(obj) }) else {
903        return;
904    };
905    let Some(object) = value.as_object() else {
906        return;
907    };
908    object.set_host_opaque(engine::Opaque::new(opaque.cast()));
909}
910
911/// `JS_GetOpaque`: the payload of `obj` when it is an instance of `class_id`.
912///
913/// The one place in this file that answers from somewhere other than a live object: while a
914/// finalizer runs there is no object left, so the value C was handed is a sentinel and the
915/// payload comes from the finalizer's own frame. See [`crate::runtime`].
916///
917/// # Safety
918///
919/// `obj` must be a live `JSValue`.
920#[unsafe(no_mangle)]
921pub unsafe extern "C" fn JS_GetOpaque(
922    obj: JsValue,
923    class_id: cdefs::ClassId,
924) -> *mut core::ffi::c_void {
925    if runtime::is_finalizer_sentinel(obj) {
926        return runtime::finalizer_opaque(class_id)
927            .map(|opaque| opaque.cast())
928            .unwrap_or(std::ptr::null_mut());
929    }
930    let Some(value) = (unsafe { arg(obj) }) else {
931        return std::ptr::null_mut();
932    };
933    let Some(object) = value.as_object() else {
934        return std::ptr::null_mut();
935    };
936    if object.host_class_id().is_none_or(|id| id.get() != class_id) {
937        return std::ptr::null_mut();
938    }
939    object
940        .host_opaque()
941        .map_or(std::ptr::null_mut(), |opaque| opaque.as_ptr().cast())
942}
943
944/// `JS_GetOpaque2`: [`JS_GetOpaque`], raising a `TypeError` instead of answering null.
945///
946/// # Safety
947///
948/// `ctx` must be a live context and `obj` a live `JSValue`.
949#[unsafe(no_mangle)]
950pub unsafe extern "C" fn JS_GetOpaque2(
951    ctx: *mut JsContext,
952    obj: JsValue,
953    class_id: cdefs::ClassId,
954) -> *mut core::ffi::c_void {
955    // SAFETY: the caller's contract.
956    let opaque = unsafe { JS_GetOpaque(obj, class_id) };
957    if !opaque.is_null() {
958        return opaque;
959    }
960    if let Some(context) = unsafe { ctx.as_ref() } {
961        // The reference names the class in its message ("not a Point"), which is what tells
962        // a script author which `this` was wrong.
963        // SAFETY: the runtime pointer is live for as long as the context is.
964        let runtime = unsafe { context.runtime().as_ref() };
965        let name = runtime
966            .and_then(|runtime| runtime.class(class_id))
967            .map(|decl| class_name(decl.name))
968            .unwrap_or_else(|| format!("class {class_id}"));
969        runtime::throw_error(context, "TypeError", &format!("not a {name}"));
970    }
971    std::ptr::null_mut()
972}
973
974/// A class's name, from the C string it was registered with.
975fn class_name(name: *const c_char) -> String {
976    if name.is_null() {
977        return "<anonymous>".to_string();
978    }
979    // SAFETY: `JSClassDef::class_name` is a NUL-terminated string the module keeps alive.
980    unsafe { std::ffi::CStr::from_ptr(name) }
981        .to_string_lossy()
982        .into_owned()
983}
984
985/// `JS_GetRuntime`: the runtime a context belongs to.
986///
987/// # Safety
988///
989/// `ctx` must be a live context.
990#[unsafe(no_mangle)]
991pub unsafe extern "C" fn JS_GetRuntime(ctx: *mut JsContext) -> *mut JsRuntime {
992    match unsafe { ctx.as_ref() } {
993        Some(context) => context.runtime(),
994        None => std::ptr::null_mut(),
995    }
996}
997
998/// `JS_ThrowRangeError`: raise a `RangeError` with the given message.
999///
1000/// The reference's version is variadic (`fmt, ...`). Ours reads only `fmt`, which is correct
1001/// for every call in the acceptance surface — none of them carry a `%` conversion. A
1002/// variadic Rust function is not expressible on stable, and a wrong-arity call would be
1003/// worse than one that ignores surplus arguments: on x86-64 SysV the surplus ones are simply
1004/// not read.
1005///
1006/// # Safety
1007///
1008/// `ctx` must be a live context and `message` a NUL-terminated string.
1009#[unsafe(no_mangle)]
1010pub unsafe extern "C" fn JS_ThrowRangeError(
1011    ctx: *mut JsContext,
1012    message: *const c_char,
1013) -> JsValue {
1014    let Some(context) = (unsafe { ctx.as_ref() }) else {
1015        return jsvalue::EXCEPTION;
1016    };
1017    let message = if message.is_null() {
1018        String::new()
1019    } else {
1020        // SAFETY: the caller guarantees a NUL-terminated string.
1021        unsafe { std::ffi::CStr::from_ptr(message) }
1022            .to_string_lossy()
1023            .into_owned()
1024    };
1025    runtime::throw_error(context, "RangeError", &message)
1026}
1027
1028// ---------------------------------------------------------------------------
1029// Coercions that are not int32s
1030// ---------------------------------------------------------------------------
1031
1032/// `JS_ToFloat64`: `ToNumber`, or `-1` with a pending exception.
1033///
1034/// # Safety
1035///
1036/// `pres` must be writable and `val` a live `JSValue`.
1037#[unsafe(no_mangle)]
1038pub unsafe extern "C" fn JS_ToFloat64(ctx: *mut JsContext, pres: *mut f64, val: JsValue) -> c_int {
1039    let Some(context) = (unsafe { ctx.as_ref() }) else {
1040        return -1;
1041    };
1042    let Some(value) = (unsafe { arg(val) }) else {
1043        runtime::throw_error(context, "TypeError", "not a value");
1044        return -1;
1045    };
1046    match context.with_current_interp(|interp| interp.to_js_number(&value)) {
1047        Ok(number) => {
1048            if !pres.is_null() {
1049                // SAFETY: the caller guarantees the pointer is writable.
1050                unsafe { *pres = number };
1051            }
1052            0
1053        }
1054        Err(signal) => {
1055            let _ = runtime::result_value(context, Err(signal));
1056            -1
1057        }
1058    }
1059}
1060
1061/// `JS_ToCStringLen2`: the value as a NUL-terminated UTF-8 string, allocated by
1062/// [`crate::js_mallocz`]'s allocator so `JS_FreeCString` can release it.
1063///
1064/// `cesu8` is ignored: the engine's strings carry WTF-8 (lone surrogates preserved as three
1065/// bytes), which is what the reference emits for `cesu8 = 0` as well.
1066///
1067/// # Safety
1068///
1069/// `ctx` must be a live context, `val` a live `JSValue`, and `plen` null or writable.
1070#[unsafe(no_mangle)]
1071pub unsafe extern "C" fn JS_ToCStringLen2(
1072    ctx: *mut JsContext,
1073    plen: *mut usize,
1074    val: JsValue,
1075    _cesu8: c_int,
1076) -> *mut c_char {
1077    let Some(context) = (unsafe { ctx.as_ref() }) else {
1078        return std::ptr::null_mut();
1079    };
1080    let Some(value) = (unsafe { arg(val) }) else {
1081        runtime::throw_error(context, "TypeError", "not a value");
1082        return std::ptr::null_mut();
1083    };
1084    let text = match context.with_current_interp(|interp| interp.to_js_string(&value)) {
1085        Ok(text) => text,
1086        Err(signal) => {
1087            let _ = runtime::result_value(context, Err(signal));
1088            return std::ptr::null_mut();
1089        }
1090    };
1091    let bytes = text.as_bytes();
1092    // SAFETY: `alloc_raw_zeroed` gives a zeroed block of the requested size, which is the
1093    // same allocator `js_mallocz` uses and therefore the one `js_free`/`JS_FreeCString`
1094    // expects.
1095    let buffer = unsafe { crate::alloc::alloc_raw_zeroed(bytes.len() + 1) };
1096    if buffer.is_null() {
1097        runtime::throw_error(context, "InternalError", "out of memory");
1098        return std::ptr::null_mut();
1099    }
1100    // SAFETY: the block holds `bytes.len() + 1` writable bytes, and the last one was zeroed.
1101    unsafe {
1102        std::ptr::copy_nonoverlapping(bytes.as_ptr(), buffer, bytes.len());
1103    }
1104    if !plen.is_null() {
1105        // SAFETY: the caller guarantees the pointer is writable.
1106        unsafe { *plen = bytes.len() };
1107    }
1108    buffer.cast()
1109}
1110
1111/// `JS_FreeCString`: release a string from [`JS_ToCStringLen2`].
1112///
1113/// # Safety
1114///
1115/// `ptr` must be null or a live pointer from `JS_ToCStringLen2`, and must not be used again.
1116#[unsafe(no_mangle)]
1117pub unsafe extern "C" fn JS_FreeCString(_ctx: *mut JsContext, ptr: *const c_char) {
1118    // SAFETY: the caller's contract; the allocator checks the header before freeing.
1119    unsafe { crate::alloc::free_raw(ptr.cast_mut().cast()) }
1120}