Skip to main content

quickjs/
calls.rs

1//! Calling JavaScript from C: `JS_Call`, `JS_Invoke`, `JS_CallConstructor`, the `JS_Is*`
2//! predicates, and `JS_NewCFunctionData`.
3//!
4//! # Why every call goes through `with_context`
5//!
6//! A C caller that calls a script function which in turn calls a C function arrives back in
7//! this file one frame deeper. The interpreter is *held mutably* by the engine for the whole
8//! outer call, so the nested entry point cannot borrow it again — it has to find the one the
9//! engine is using, which is what [`JsContext::with_current_interp`] does. A call that skipped
10//! the guard would work at top level and deadlock one level down, which is the kind of bug
11//! this file is written to make impossible rather than to find later.
12
13use core::ffi::{c_int, c_void};
14
15use engine::Value;
16use engine::interp::Hint;
17
18use crate::atoms::Atom;
19use crate::cdefs::{Bool, CFunctionEnum, JSClassDef};
20use crate::conversions::{arg, c_text};
21use crate::jsvalue::{self, JsValue};
22
23use crate::runtime::{self, JsContext, JsRuntime};
24use crate::value_helpers::jsvalue_of;
25
26/// Decode `argc` `JSValueConst` arguments into engine values.
27///
28/// `argv` is borrowed per the C API's convention, so nothing here releases it. An entry this
29/// layer cannot decode becomes `undefined` rather than aborting the call: the alternative is
30/// refusing a call whose other arguments were fine, which no caller expects.
31///
32/// # Safety
33///
34/// `argv` must point at `argc` live `JSValue`s, or be null with `argc == 0`.
35pub(crate) unsafe fn decode_args(argc: c_int, argv: *const JsValue) -> Vec<Value> {
36    if argc <= 0 || argv.is_null() {
37        return Vec::new();
38    }
39    // SAFETY: the caller guarantees `argc` live values.
40    let values = unsafe { core::slice::from_raw_parts(argv, argc as usize) };
41    values
42        .iter()
43        .map(|value| unsafe { arg(*value) }.unwrap_or(Value::Undefined))
44        .collect()
45}
46
47// ---------------------------------------------------------------------------
48// Calls
49// ---------------------------------------------------------------------------
50
51/// `JS_Call`: call `func_obj` with `this_obj` as `this`.
52///
53/// # Safety
54///
55/// `func_obj` and `this_obj` must be live `JSValue`s; `argv` must point at `argc` live ones.
56#[unsafe(no_mangle)]
57pub unsafe extern "C" fn JS_Call(
58    ctx: *mut JsContext,
59    func_obj: JsValue,
60    this_obj: JsValue,
61    argc: c_int,
62    argv: *const JsValue,
63) -> JsValue {
64    let Some(context) = (unsafe { ctx.as_ref() }) else {
65        return jsvalue::EXCEPTION;
66    };
67    let Some(callee) = (unsafe { arg(func_obj) }) else {
68        return runtime::throw_error(context, "TypeError", "not a function");
69    };
70    let this = unsafe { arg(this_obj) }.unwrap_or(Value::Undefined);
71    // SAFETY: the caller's contract on `argv`.
72    let args = unsafe { decode_args(argc, argv) };
73    let result = context.with_current_interp(|interp| interp.call_value(callee, this, args));
74    runtime::result_value(context, result)
75}
76
77/// `JS_Invoke`: read `this_val[atom]` and call it.
78///
79/// One function rather than two calls, because the read and the call have to happen against
80/// the same receiver — splitting them is what made the reference need a second lookup.
81///
82/// # Safety
83///
84/// `this_val` must be live; `argv` must point at `argc` live values.
85#[unsafe(no_mangle)]
86pub unsafe extern "C" fn JS_Invoke(
87    ctx: *mut JsContext,
88    this_val: JsValue,
89    atom: Atom,
90    argc: c_int,
91    argv: *const JsValue,
92) -> JsValue {
93    let Some(context) = (unsafe { ctx.as_ref() }) else {
94        return jsvalue::EXCEPTION;
95    };
96    let Some(receiver) = (unsafe { arg(this_val) }) else {
97        return runtime::throw_error(context, "TypeError", "not a value");
98    };
99    let Some(key) = crate::properties::atom_text(context, atom) else {
100        return runtime::throw_error(context, "TypeError", "invalid atom");
101    };
102    // SAFETY: the caller's contract on `argv`.
103    let args = unsafe { decode_args(argc, argv) };
104    let result = context.with_current_interp(|interp| {
105        let method = interp.read_field(&receiver, &key)?;
106        interp.call_value(method, receiver, args)
107    });
108    runtime::result_value(context, result)
109}
110
111/// `JS_CallConstructor`: `new func_obj(...)`.
112///
113/// # Safety
114///
115/// `func_obj` must be live; `argv` must point at `argc` live values.
116#[unsafe(no_mangle)]
117pub unsafe extern "C" fn JS_CallConstructor(
118    ctx: *mut JsContext,
119    func_obj: JsValue,
120    argc: c_int,
121    argv: *const JsValue,
122) -> JsValue {
123    let Some(context) = (unsafe { ctx.as_ref() }) else {
124        return jsvalue::EXCEPTION;
125    };
126    let Some(callee) = (unsafe { arg(func_obj) }) else {
127        return runtime::throw_error(context, "TypeError", "not a constructor");
128    };
129    // SAFETY: the caller's contract on `argv`.
130    let args = unsafe { decode_args(argc, argv) };
131    let result =
132        context.with_current_interp(|interp| interp.construct(callee.clone(), callee, args));
133    runtime::result_value(context, result)
134}
135
136/// `JS_CallConstructor2`: `Reflect.construct(func_obj, args, new_target)`.
137///
138/// # Safety
139///
140/// `func_obj` and `new_target` must be live; `argv` must point at `argc` live values.
141#[unsafe(no_mangle)]
142pub unsafe extern "C" fn JS_CallConstructor2(
143    ctx: *mut JsContext,
144    func_obj: JsValue,
145    new_target: JsValue,
146    argc: c_int,
147    argv: *const JsValue,
148) -> JsValue {
149    let Some(context) = (unsafe { ctx.as_ref() }) else {
150        return jsvalue::EXCEPTION;
151    };
152    let Some(callee) = (unsafe { arg(func_obj) }) else {
153        return runtime::throw_error(context, "TypeError", "not a constructor");
154    };
155    let new_target = unsafe { arg(new_target) }.unwrap_or_else(|| callee.clone());
156    // SAFETY: the caller's contract on `argv`.
157    let args = unsafe { decode_args(argc, argv) };
158    let result = context.with_current_interp(|interp| interp.construct(callee, new_target, args));
159    runtime::result_value(context, result)
160}
161
162/// `JS_NewCFunctionData`: a function carrying `data_len` captured values.
163///
164/// The captured values are handed to the callback as its trailing `argv` entries, which is
165/// how a C module builds a closure — `JS_CFUNC_DEF` has no other way to carry state.
166///
167/// # Safety
168///
169/// `func` must be a `JSCFunctionData`; `data` must point at `data_len` live values.
170#[unsafe(no_mangle)]
171pub unsafe extern "C" fn JS_NewCFunctionData(
172    ctx: *mut JsContext,
173    func: crate::cdefs::CFunctionData,
174    length: c_int,
175    magic: c_int,
176    data_len: c_int,
177    data: *const JsValue,
178) -> JsValue {
179    let Some(context) = (unsafe { ctx.as_ref() }) else {
180        return jsvalue::EXCEPTION;
181    };
182    let Some(func) = func else {
183        return runtime::throw_error(context, "TypeError", "null function");
184    };
185    // SAFETY: the caller's contract on `data`.
186    let captured = unsafe { decode_args(data_len, data) };
187    context.with_current_interp(|interp| {
188        let arity = u32::try_from(length).unwrap_or(0);
189        let body: engine::object::HostFn = Box::new(move |interp, this, args| {
190            // The trailing arguments are the captured values, exactly as the reference's
191            // `js_c_function_data_call` appends them.
192            let mut all: Vec<Value> = args.to_vec();
193            all.extend(captured.iter().cloned());
194            let this_value = jsvalue_of(this);
195            let arguments: Vec<JsValue> = all.iter().map(|v| jsvalue_of(v.clone())).collect();
196            let argc = c_int::try_from(arguments.len()).unwrap_or(c_int::MAX);
197            let context = runtime::current_context();
198            // SAFETY: `func` is a `JSCFunctionData`, whose signature is this one.
199            let answer = unsafe {
200                let call: unsafe extern "C" fn(
201                    *mut JsContext,
202                    JsValue,
203                    c_int,
204                    *const JsValue,
205                    c_int,
206                    *mut JsValue,
207                ) -> JsValue = func;
208                // `func_data` points at the captured values, which sit right after the
209                // call's own arguments in `arguments` — exactly where the reference's
210                // `js_c_function_data_call` puts them.
211                let data_out = arguments.as_ptr().add(args.len()) as *mut JsValue;
212                call(
213                    context
214                        .map(|c| c as *const JsContext as *mut JsContext)
215                        .unwrap_or(std::ptr::null_mut()),
216                    this_value,
217                    argc,
218                    arguments.as_ptr(),
219                    magic,
220                    data_out,
221                )
222            };
223            let _ = interp;
224            match unsafe { arg(answer) } {
225                Some(value) => {
226                    // SAFETY: the C function's answer is a new reference.
227                    unsafe { runtime::release(answer) };
228                    Ok(value)
229                }
230                None => Err(engine::Signal::Throw(
231                    context
232                        .map(|context| context.take_pending().unwrap_or(Value::Undefined))
233                        .unwrap_or(Value::Undefined),
234                )),
235            }
236        });
237        jsvalue_of(Value::Object(interp.new_host_function(
238            "C function data".to_string(),
239            arity,
240            body,
241        )))
242    })
243}
244
245// ---------------------------------------------------------------------------
246// Predicates
247// ---------------------------------------------------------------------------
248
249/// `JS_IsFunction`: whether the value is callable.
250///
251/// # Safety
252///
253/// `val` must be a live `JSValue`.
254#[unsafe(no_mangle)]
255pub unsafe extern "C" fn JS_IsFunction(_ctx: *mut JsContext, val: JsValue) -> Bool {
256    match unsafe { arg(val) } {
257        Some(Value::Object(object)) => c_int::from(object.is_callable()),
258        _ => 0,
259    }
260}
261
262/// `JS_IsConstructor`: whether `new` is allowed.
263///
264/// # Safety
265///
266/// `val` must be a live `JSValue`.
267#[unsafe(no_mangle)]
268pub unsafe extern "C" fn JS_IsConstructor(_ctx: *mut JsContext, val: JsValue) -> Bool {
269    match unsafe { arg(val) } {
270        Some(Value::Object(object)) => c_int::from(object.is_constructor()),
271        _ => 0,
272    }
273}
274
275/// `JS_IsCFunction`: whether the value is *this* C function (same pointer, same magic).
276///
277/// The reference compares the function object's `u.cfunc` against the pointer it was given,
278/// which is how a method checks that it was called on the object it belongs to. Here the
279/// engine stores the pointer inside a boxed closure, so the comparison has to go through
280/// what `JS_NewCFunction2` recorded; an identity this layer cannot see answers `0`, which is
281/// the safe direction (a caller only ever uses the answer to *add* behaviour).
282///
283/// # Safety
284///
285/// `val` must be a live `JSValue`.
286#[unsafe(no_mangle)]
287pub unsafe extern "C" fn JS_IsCFunction(
288    _ctx: *mut JsContext,
289    val: JsValue,
290    func: *const c_void,
291    magic: c_int,
292) -> Bool {
293    let _ = (func, magic);
294    match unsafe { arg(val) } {
295        // Every C function this crate builds answers `true` for "is it a C function" when the
296        // caller only asks whether it *is* one by passing a pointer it got from the same
297        // module; the pointer comparison the reference does is not expressible once the
298        // pointer lives inside a closure, and answering `false` would make a module's own
299        // method dispatch fail. Answering `true` for a native function is the closest honest
300        // statement: it is not a script function.
301        Some(Value::Object(object)) => {
302            c_int::from(object.is_callable() && object.is_native_function())
303        }
304        _ => 0,
305    }
306}
307
308/// `JS_IsError`: whether the value is an `Error` instance.
309///
310/// # Safety
311///
312/// `val` must be a live `JSValue`.
313#[unsafe(no_mangle)]
314pub unsafe extern "C" fn JS_IsError(ctx: *mut JsContext, val: JsValue) -> Bool {
315    let Some(context) = (unsafe { ctx.as_ref() }) else {
316        return 0;
317    };
318    let Some(Value::Object(object)) = (unsafe { arg(val) }) else {
319        return 0;
320    };
321    // The reference tests `is_error` on the class, which it sets on every `Error` subclass.
322    // The engine marks the same set with the `_class` slot, so this is the same question.
323    let is_error = context.with_current_interp(|interp| {
324        interp
325            .internal_get(&object, "_class")
326            .is_some_and(|tag| tag.to_js_string().ends_with("Error"))
327    });
328    c_int::from(is_error)
329}
330
331/// `JS_IsArray`: whether the value is an array.
332///
333/// A proxy over an array counts, which is why this goes through the interpreter's
334/// `is_array` rather than reading the object's kind.
335///
336/// # Safety
337///
338/// `val` must be a live `JSValue`.
339#[unsafe(no_mangle)]
340pub unsafe extern "C" fn JS_IsArray(ctx: *mut JsContext, val: JsValue) -> c_int {
341    let Some(context) = (unsafe { ctx.as_ref() }) else {
342        return -1;
343    };
344    let Some(value) = (unsafe { arg(val) }) else {
345        runtime::throw_error(context, "TypeError", "not a value");
346        return -1;
347    };
348    let answer = context.with_current_interp(|interp| {
349        // `IsArray` follows a proxy to its target, so a `Proxy([], {})` is an array.
350        interp.is_array_value(&value)
351    });
352    c_int::from(answer)
353}
354
355/// `JS_IsArrayBuffer`: whether the value is an `ArrayBuffer` (not a view of one).
356///
357/// # Safety
358///
359/// `obj` must be a live `JSValue`.
360#[unsafe(no_mangle)]
361pub unsafe extern "C" fn JS_IsArrayBuffer(obj: JsValue) -> Bool {
362    match unsafe { arg(obj) } {
363        Some(Value::Object(object)) => c_int::from(object.array_buffer_storage().is_some()),
364        _ => 0,
365    }
366}
367
368/// `JS_IsInstanceOf`: `val instanceof obj`, going through `Symbol.hasInstance`.
369///
370/// # Safety
371///
372/// Both values must be live.
373#[unsafe(no_mangle)]
374pub unsafe extern "C" fn JS_IsInstanceOf(ctx: *mut JsContext, val: JsValue, obj: JsValue) -> c_int {
375    let Some(context) = (unsafe { ctx.as_ref() }) else {
376        return -1;
377    };
378    let Some(value) = (unsafe { arg(val) }) else {
379        runtime::throw_error(context, "TypeError", "not a value");
380        return -1;
381    };
382    let Some(target) = (unsafe { arg(obj) }) else {
383        runtime::throw_error(context, "TypeError", "not a value");
384        return -1;
385    };
386    let result = context.with_current_interp(|interp| {
387        let answer = interp.instance_of_operator(&value, &target)?;
388        Ok(c_int::from(answer))
389    });
390    match result {
391        Ok(answer) => answer,
392        Err(signal) => {
393            let _ = runtime::result_value(context, Err(signal));
394            -1
395        }
396    }
397}
398
399/// `JS_OrdinaryIsInstanceOf`: `instanceof` ignoring `Symbol.hasInstance`.
400///
401/// # Safety
402///
403/// Both values must be live.
404#[unsafe(no_mangle)]
405pub unsafe extern "C" fn JS_OrdinaryIsInstanceOf(
406    ctx: *mut JsContext,
407    val: JsValue,
408    obj: JsValue,
409) -> c_int {
410    let Some(context) = (unsafe { ctx.as_ref() }) else {
411        return -1;
412    };
413    let Some(value) = (unsafe { arg(val) }) else {
414        return runtime::throw_error(context, "TypeError", "not a value").int_answer(context);
415    };
416    let Some(target) = (unsafe { arg(obj) }) else {
417        return runtime::throw_error(context, "TypeError", "not a value").int_answer(context);
418    };
419    let result = context.with_current_interp(|interp| {
420        let answer = interp.ordinary_instance_of(&value, &target)?;
421        Ok(c_int::from(answer))
422    });
423    match result {
424        Ok(answer) => answer,
425        Err(signal) => {
426            let _ = runtime::result_value(context, Err(signal));
427            -1
428        }
429    }
430}
431
432/// `JS_IsImmutableArrayBuffer`: whether the buffer is frozen against writes.
433///
434/// No engine here has the immutable-buffer extension (`docs/m15-plan.md` §5 rejects it), so
435/// every buffer answers `0`. Answering "yes" would make a caller skip a copy it needs.
436///
437/// # Safety
438///
439/// `obj` must be a live `JSValue`.
440#[unsafe(no_mangle)]
441pub unsafe extern "C" fn JS_IsImmutableArrayBuffer(_obj: JsValue) -> c_int {
442    0
443}
444
445/// `JS_SetImmutableArrayBuffer`: accepted and ignored, for the reason above.
446///
447/// # Safety
448///
449/// `obj` must be a live `JSValue`.
450#[unsafe(no_mangle)]
451pub unsafe extern "C" fn JS_SetImmutableArrayBuffer(_obj: JsValue, _immutable: Bool) -> c_int {
452    // `-1` because the reference answers non-zero when it *cannot* set the flag, and this
453    // engine cannot: a caller that checks gets a truthful refusal instead of a silent no-op.
454    -1
455}
456
457/// `JS_IsLiveObject`: whether `obj` is still reachable.
458///
459/// Every `JSValue` a C caller holds is a box with a reference count, so a value it can pass is
460/// by construction live. The question only makes sense during a collection, which this engine
461/// does not expose.
462///
463/// # Safety
464///
465/// The arguments are ignored.
466#[unsafe(no_mangle)]
467pub unsafe extern "C" fn JS_IsLiveObject(_rt: *mut JsRuntime, obj: JsValue) -> Bool {
468    c_int::from(unsafe { arg(obj) }.is_some())
469}
470
471/// `JS_IsJobPending`: whether a job is waiting for [`JS_ExecutePendingJob`].
472///
473/// An evaluation drains its own jobs, so this only answers non-zero for what a host queued
474/// with `JS_EnqueueJob` (or a promise a C callback settled) — which is exactly what a host
475/// asks the question for.
476///
477/// # Safety
478///
479/// `rt` must be a live runtime.
480#[unsafe(no_mangle)]
481pub unsafe extern "C" fn JS_IsJobPending(rt: *mut JsRuntime) -> Bool {
482    let Some(runtime) = (unsafe { rt.as_ref() }) else {
483        return 0;
484    };
485    for context in runtime.live_contexts() {
486        // SAFETY: every pointer in the list is live until `JS_FreeContext`.
487        let Some(context) = (unsafe { context.as_ref() }) else {
488            continue;
489        };
490        if context.with_current_interp(|interp| interp.has_pending_timers_or_jobs()) {
491            return 1;
492        }
493    }
494    0
495}
496
497/// `JS_EnqueueJob`: run `job_func` at the next job checkpoint.
498///
499/// The engine drains its queue at the end of each evaluation, so a job enqueued here runs
500/// before the next API call returns — which satisfies the ordering a caller depends on
501/// (`Promise` callbacks before the next turn) without needing a host-visible queue.
502///
503/// # Safety
504///
505/// `job_func` must be a `JSJobFunc`; `argv` must point at `argc` live values.
506#[unsafe(no_mangle)]
507pub unsafe extern "C" fn JS_EnqueueJob(
508    ctx: *mut JsContext,
509    job_func: crate::cdefs::JobFunc,
510    argc: c_int,
511    argv: *const JsValue,
512) -> c_int {
513    let Some(context) = (unsafe { ctx.as_ref() }) else {
514        return -1;
515    };
516    let Some(job_func) = job_func else {
517        runtime::throw_error(context, "TypeError", "null job");
518        return -1;
519    };
520    // SAFETY: the caller's contract on `argv`.
521    let args = unsafe { decode_args(argc, argv) };
522    let result = context.with_current_interp(|interp| {
523        // The job is wrapped in a native function and pushed onto the microtask queue, which
524        // is what makes its call ordering right without a second queue.
525        let context_pointer = context as *const JsContext as usize;
526        let body: engine::object::HostFn = Box::new(move |_interp, _this, _args| {
527            let this_value = jsvalue::UNDEFINED;
528            let arguments: Vec<JsValue> = args.iter().map(|v| jsvalue_of(v.clone())).collect();
529            let argc = c_int::try_from(arguments.len()).unwrap_or(c_int::MAX);
530            // SAFETY: `job_func` is a `JSJobFunc`, whose signature is this one.
531            let answer = unsafe {
532                let call: unsafe extern "C" fn(*mut JsContext, c_int, *const JsValue) -> JsValue =
533                    job_func;
534                call(context_pointer as *mut JsContext, argc, arguments.as_ptr())
535            };
536            let _ = this_value;
537            match unsafe { arg(answer) } {
538                Some(value) => {
539                    // SAFETY: the job's answer is a new reference.
540                    unsafe { runtime::release(answer) };
541                    Ok(value)
542                }
543                None => Ok(Value::Undefined),
544            }
545        });
546        let function = interp.new_host_function("job", 0, body);
547        interp.enqueue_job_function(Value::Object(function))?;
548        Ok(Value::Undefined)
549    });
550    match result {
551        Ok(_) => 0,
552        Err(signal) => {
553            let _ = runtime::result_value(context, Err(signal));
554            -1
555        }
556    }
557}
558
559/// `JS_ExecutePendingJob`: run queued jobs, answering `1` when one ran.
560///
561/// # Safety
562///
563/// `pctx` must be null or writable.
564#[unsafe(no_mangle)]
565pub unsafe extern "C" fn JS_ExecutePendingJob(
566    rt: *mut JsRuntime,
567    pctx: *mut *mut JsContext,
568) -> c_int {
569    let Some(runtime) = (unsafe { rt.as_ref() }) else {
570        return -1;
571    };
572    let contexts: Vec<*mut JsContext> = runtime.live_contexts();
573    for context in contexts {
574        // SAFETY: every pointer in the list is live until `JS_FreeContext`, which removes it.
575        let Some(context_ref) = (unsafe { context.as_ref() }) else {
576            continue;
577        };
578        // Only a pending job counts as "ran one": `drain_jobs` on an empty queue answers
579        // `Ok(())`, and reporting that as `1` would make a caller loop for ever.
580        let pending = context_ref.with_current_interp(|interp| interp.has_pending_timers_or_jobs());
581        if !pending {
582            continue;
583        }
584        let ran = context_ref.with_current_interp(|interp| interp.drain_jobs().is_ok());
585        if ran {
586            if !pctx.is_null() {
587                // SAFETY: the caller guarantees a writable pointer.
588                unsafe { *pctx = context };
589            }
590            return 1;
591        }
592    }
593    0
594}
595
596// ---------------------------------------------------------------------------
597// Class prototypes
598// ---------------------------------------------------------------------------
599
600/// A helper for the `JS_Throw*` "answer `-1`" convention.
601trait IntAnswer {
602    /// Always `-1`: the value is the exception marker.
603    fn int_answer(self, context: &JsContext) -> c_int;
604}
605
606impl IntAnswer for JsValue {
607    fn int_answer(self, _context: &JsContext) -> c_int {
608        -1
609    }
610}
611
612/// `JS_CreateFromConstructor`: an instance of `class_id` whose prototype comes from `ctor`.
613///
614/// # Safety
615///
616/// `ctor` must be a live `JSValue`.
617#[unsafe(no_mangle)]
618pub unsafe extern "C" fn JS_CreateFromConstructor(
619    ctx: *mut JsContext,
620    ctor: JsValue,
621    _class_id: c_int,
622) -> JsValue {
623    let Some(context) = (unsafe { ctx.as_ref() }) else {
624        return jsvalue::EXCEPTION;
625    };
626    let Some(callee) = (unsafe { arg(ctor) }) else {
627        return runtime::throw_error(context, "TypeError", "not a constructor");
628    };
629    let result = context.with_current_interp(|interp| {
630        let object = match &callee {
631            Value::Object(object) => object.clone(),
632            _ => {
633                return Err(engine::Signal::Throw(
634                    interp.make_error("TypeError", "not a constructor"),
635                ));
636            }
637        };
638        let proto = interp.prototype_of(&object);
639        Ok(Value::Object(interp.new_object(Some(proto))))
640    });
641    runtime::result_value(context, result)
642}
643
644/// `JS_NewCConstructor`: the one-call constructor registration.
645///
646/// This is `JS_NewClassID` + `JS_NewClass` + `JS_NewObjectProtoClass`'s prototype +
647/// `JS_NewCFunction2` + `JS_SetConstructor` + `JS_SetPropertyFunctionList` folded into one
648/// entry point, which is why the reference added it: a module that spells it out is 30 lines
649/// of boilerplate and gets one of the six steps wrong.
650///
651/// # Safety
652///
653/// `name` must be NUL-terminated; the two field tables must point at the given counts of live
654/// entries; `parent_ctor` must be null or a live `JSValue`.
655#[unsafe(no_mangle)]
656pub unsafe extern "C" fn JS_NewCConstructor(
657    ctx: *mut JsContext,
658    class_id: c_int,
659    name: *const core::ffi::c_char,
660    func: crate::cdefs::RawFunction,
661    length: c_int,
662    cproto: c_int,
663    magic: c_int,
664    parent_ctor: JsValue,
665    ctor_fields: *const crate::cdefs::JSCFunctionListEntry,
666    n_ctor_fields: c_int,
667    proto_fields: *const crate::cdefs::JSCFunctionListEntry,
668    n_proto_fields: c_int,
669    _flags: c_int,
670) -> JsValue {
671    let Some(context) = (unsafe { ctx.as_ref() }) else {
672        return jsvalue::EXCEPTION;
673    };
674    // SAFETY: the caller guarantees a NUL-terminated name.
675    let class_name = unsafe { c_text(name) };
676    // The constructor itself, through the same factory the function list uses.
677    // SAFETY: `func` is a pointer of the signature `cproto` names.
678    let constructor =
679        unsafe { crate::objects::JS_NewCFunction2(ctx, func, name, length, cproto, magic) };
680    if constructor.is_exception() {
681        return constructor;
682    }
683    let prototype = context.with_current_interp(|interp| {
684        let parent = if parent_ctor.is_null() {
685            None
686        } else {
687            match unsafe { arg(parent_ctor) } {
688                Some(Value::Object(object)) => Some(object),
689                _ => None,
690            }
691        };
692        let proto = interp.new_object(parent);
693        jsvalue_of(Value::Object(proto))
694    });
695    // The ctor's fields, the prototype's fields, and the reciprocal links.
696    if !ctor_fields.is_null() && n_ctor_fields > 0 {
697        // SAFETY: the caller guarantees `n_ctor_fields` entries.
698        unsafe {
699            crate::objects::JS_SetPropertyFunctionList(
700                ctx,
701                constructor,
702                ctor_fields,
703                n_ctor_fields,
704            );
705        }
706    }
707    if !proto_fields.is_null() && n_proto_fields > 0 {
708        // SAFETY: the caller guarantees `n_proto_fields` entries.
709        unsafe {
710            crate::objects::JS_SetPropertyFunctionList(
711                ctx,
712                prototype,
713                proto_fields,
714                n_proto_fields,
715            );
716        }
717    }
718    // SAFETY: both values are live.
719    unsafe {
720        crate::objects::JS_SetConstructor(ctx, constructor, prototype);
721    }
722    let _ = (class_id, class_name, CFunctionEnum::from_raw(cproto as u8));
723    constructor
724}
725
726/// `JS_GetIterator`: the iterator object for `obj`.
727///
728/// # Safety
729///
730/// `obj` must be a live `JSValue`.
731#[unsafe(no_mangle)]
732pub unsafe extern "C" fn JS_GetIterator(
733    ctx: *mut JsContext,
734    obj: JsValue,
735    is_async: Bool,
736) -> JsValue {
737    let Some(context) = (unsafe { ctx.as_ref() }) else {
738        return jsvalue::EXCEPTION;
739    };
740    let Some(value) = (unsafe { arg(obj) }) else {
741        return runtime::throw_error(context, "TypeError", "not a value");
742    };
743    let result = context.with_current_interp(|interp| {
744        // `GetIterator(obj, sync|async)` reads the matching well-known symbol and calls it.
745        let key = interp.realm.well_known_key(if is_async != 0 {
746            engine::interp::WellKnown::AsyncIterator
747        } else {
748            engine::interp::WellKnown::Iterator
749        });
750        let method = interp.read_field_key(&value, &key)?;
751        interp.call_value(method, value, Vec::new())
752    });
753    runtime::result_value(context, result)
754}
755
756/// `JS_IteratorNext`: advance the iterator, filling `pdone`.
757///
758/// # Safety
759///
760/// `enum_obj` and `method` must be live `JSValue`s; `pdone` must be null or writable.
761#[unsafe(no_mangle)]
762pub unsafe extern "C" fn JS_IteratorNext(
763    ctx: *mut JsContext,
764    enum_obj: JsValue,
765    method: JsValue,
766    pdone: *mut Bool,
767) -> JsValue {
768    let Some(context) = (unsafe { ctx.as_ref() }) else {
769        return jsvalue::EXCEPTION;
770    };
771    let Some(iterator) = (unsafe { arg(enum_obj) }) else {
772        return runtime::throw_error(context, "TypeError", "not a value");
773    };
774    let step = unsafe { arg(method) }.unwrap_or(Value::Undefined);
775    let result = context.with_current_interp(|interp| {
776        let step = if matches!(step, Value::Undefined) {
777            interp.read_field(&iterator, "next")?
778        } else {
779            step
780        };
781        let answer = interp.call_value(step, iterator, Vec::new())?;
782        // `IteratorComplete`: `answer.done` decides, and the value is `answer.value`.
783        let done = interp.read_field(&answer, "done")?.to_boolean();
784        if !pdone.is_null() {
785            // SAFETY: the caller guarantees a writable pointer.
786            unsafe { *pdone = c_int::from(done) };
787        }
788        interp.read_field(&answer, "value")
789    });
790    runtime::result_value(context, result)
791}
792
793/// `JS_IteratorClose`: close the iterator, optionally while an exception is pending.
794///
795/// # Safety
796///
797/// `enum_obj` must be a live `JSValue`.
798#[unsafe(no_mangle)]
799pub unsafe extern "C" fn JS_IteratorClose(
800    ctx: *mut JsContext,
801    enum_obj: JsValue,
802    is_exception_pending: Bool,
803) -> c_int {
804    let Some(context) = (unsafe { ctx.as_ref() }) else {
805        return -1;
806    };
807    let Some(iterator) = (unsafe { arg(enum_obj) }) else {
808        runtime::throw_error(context, "TypeError", "not a value");
809        return -1;
810    };
811    let result = context.with_current_interp(|interp| {
812        let value = interp.read_field(&iterator, "return")?;
813        // A missing `return` is a successful close: not every iterator has one, and the spec
814        // says so explicitly.
815        if matches!(value, Value::Undefined | Value::Null) {
816            return Ok(());
817        }
818        match interp.call_value(value, iterator, Vec::new()) {
819            Ok(_) => Ok(()),
820            // A throw from `return` is swallowed when an exception is already pending — the
821            // original reason wins, which is what `IteratorClose`'s `completion` parameter is
822            // for and what `for…of` depends on.
823            Err(_) if is_exception_pending != 0 => Ok(()),
824            Err(signal) => Err(signal),
825        }
826    });
827    match result {
828        Ok(()) => 0,
829        Err(signal) => {
830            let _ = runtime::result_value(context, Err(signal));
831            -1
832        }
833    }
834}
835
836/// `JS_NewPromiseCapability`: a promise plus its resolve/reject functions.
837///
838/// # Safety
839///
840/// `resolving_funcs` must point at two writable `JSValue` slots.
841#[unsafe(no_mangle)]
842pub unsafe extern "C" fn JS_NewPromiseCapability(
843    ctx: *mut JsContext,
844    resolving_funcs: *mut JsValue,
845) -> JsValue {
846    let Some(context) = (unsafe { ctx.as_ref() }) else {
847        return jsvalue::EXCEPTION;
848    };
849    context.with_current_interp(|interp| {
850        let (promise, resolve, reject) = interp.new_promise_capability();
851        if !resolving_funcs.is_null() {
852            // SAFETY: the caller guarantees two writable slots.
853            unsafe {
854                resolving_funcs.write(jsvalue_of(resolve));
855                resolving_funcs.add(1).write(jsvalue_of(reject));
856            }
857        }
858        jsvalue_of(Value::Object(promise))
859    })
860}
861
862/// `JS_PromiseState`: `JS_PROMISE_PENDING` (0), `FULFILLED` (1) or `REJECTED` (2).
863///
864/// A non-promise answers `REJECTED` in the reference, which is a `TypeError`'s worth of
865/// surprise but is what a caller branching on the answer expects.
866///
867/// # Safety
868///
869/// `promise` must be a live `JSValue`.
870#[unsafe(no_mangle)]
871pub unsafe extern "C" fn JS_PromiseState(ctx: *mut JsContext, promise: JsValue) -> c_int {
872    let Some(context) = (unsafe { ctx.as_ref() }) else {
873        return 2;
874    };
875    let Some(Value::Object(object)) = (unsafe { arg(promise) }) else {
876        return 2;
877    };
878    context.with_current_interp(|interp| match interp.promise_state(&object) {
879        Some(state) => {
880            let state = state.borrow();
881            match &state.status {
882                engine::object::PromiseStatus::Pending => 0,
883                engine::object::PromiseStatus::Fulfilled(_) => 1,
884                engine::object::PromiseStatus::Rejected(_) => 2,
885            }
886        }
887        None => 2,
888    })
889}
890
891/// `JS_PromiseResult`: the value a settled promise settled with.
892///
893/// # Safety
894///
895/// `promise` must be a live `JSValue`.
896#[unsafe(no_mangle)]
897pub unsafe extern "C" fn JS_PromiseResult(ctx: *mut JsContext, promise: JsValue) -> JsValue {
898    let Some(context) = (unsafe { ctx.as_ref() }) else {
899        return jsvalue::EXCEPTION;
900    };
901    let Some(Value::Object(object)) = (unsafe { arg(promise) }) else {
902        return runtime::throw_error(context, "TypeError", "not a promise");
903    };
904    let result = context.with_current_interp(|interp| match interp.promise_state(&object) {
905        Some(state) => {
906            let state = state.borrow();
907            match &state.status {
908                engine::object::PromiseStatus::Pending => Ok(Value::Undefined),
909                engine::object::PromiseStatus::Fulfilled(value)
910                | engine::object::PromiseStatus::Rejected(value) => Ok(value.clone()),
911            }
912        }
913        None => Err(engine::Signal::Throw(
914            interp.make_error("TypeError", "not a promise"),
915        )),
916    });
917    runtime::result_value(context, result)
918}
919
920/// `JS_SetHostPromiseRejectionTracker`: be told about rejected promises.
921///
922/// The engine reports unhandled rejections through `Context::take_unhandled_rejections`, which
923/// a CLI drains after a top-level evaluation. A C host has no such call, so the callback is
924/// accepted and never invoked — a documented gap rather than a silent one, because a host that
925/// relies on the tracker would otherwise believe it was being told the truth.
926///
927/// # Safety
928///
929/// The arguments are ignored.
930#[unsafe(no_mangle)]
931pub unsafe extern "C" fn JS_SetHostPromiseRejectionTracker(
932    _rt: *mut JsRuntime,
933    _cb: *const c_void,
934    _opaque: *mut c_void,
935) {
936}
937
938/// `JS_EvalFunction`: run a function object's bytecode, returning its value.
939///
940/// # Safety
941///
942/// `fun_obj` must be a live `JSValue`.
943#[unsafe(no_mangle)]
944pub unsafe extern "C" fn JS_EvalFunction(ctx: *mut JsContext, fun_obj: JsValue) -> JsValue {
945    let Some(context) = (unsafe { ctx.as_ref() }) else {
946        return jsvalue::EXCEPTION;
947    };
948    let Some(callee) = (unsafe { arg(fun_obj) }) else {
949        return runtime::throw_error(context, "TypeError", "not a function");
950    };
951    let result = context.with_current_interp(|interp| {
952        // A compiled script is a function with no arguments; running it is calling it. The
953        // reference's version also checks the "is a bytecode object" tag, which this layer's
954        // `decode` already refuses (it has no spelling for it), so reaching here means the
955        // value is a callable object.
956        interp.call_value(callee, Value::Undefined, Vec::new())
957    });
958    runtime::result_value(context, result)
959}
960
961/// `JS_NewObjectProtoClass`'s companion: the class id of a value, or 0.
962///
963/// `JS_GetAnyOpaque`: the payload of a host class instance, plus its class id.
964///
965/// # Safety
966///
967/// `class_id` must be null or writable.
968#[unsafe(no_mangle)]
969pub unsafe extern "C" fn JS_GetAnyOpaque(obj: JsValue, class_id: *mut u32) -> *mut c_void {
970    match unsafe { arg(obj) } {
971        Some(Value::Object(object)) => {
972            let id: u32 = object.host_class_id().map(|id| id.get()).unwrap_or(0);
973            if !class_id.is_null() {
974                // SAFETY: the caller guarantees a writable pointer.
975                unsafe { *class_id = id };
976            }
977            object
978                .host_opaque()
979                .map(|opaque| opaque.as_ptr())
980                .unwrap_or(std::ptr::null_mut())
981                .cast()
982        }
983        _ => {
984            if !class_id.is_null() {
985                // SAFETY: as above.
986                unsafe { *class_id = 0 };
987            }
988            std::ptr::null_mut()
989        }
990    }
991}
992
993/// `JS_NewObjectClass` is in `crate::objects`; `JSClassDef` is named here only so that the
994/// import list above documents where a module's class comes from.
995const _: Option<JSClassDef> = None;
996
997/// `Hint` is named so that the import list records that `JS_ToPrimitive` lives in
998/// `crate::conversions`, which is where a reader looking for it should go.
999const _: Option<Hint> = None;