quickjs-capi 0.13.0

C ABI compatibility layer: the QuickJS C API on top of the pure-Rust engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! The module API's remaining half: private values, names, namespaces, the loader hooks, and
//! `JS_EvalThis`/`JS_DetectModule`/`JS_WriteObject2`.
//!
//! # What a `JSModuleDef *` can be
//!
//! Two things, and they are different allocations:
//!
//! * a **C module's** definition, built by [`crate::modules::JS_NewCModule`] — a `JsModuleDef`
//!   with a name, declared exports and values;
//! * an **engine module's** record, for a `.js` file the loader read — the engine owns that one
//!   and the C API only ever sees it as the pointer it recorded.
//!
//! Every function here therefore has to decide which it has. The discriminator is the
//! module's own table: a pointer the context's `module_table` knows is a C module; anything
//! else is an engine module the context has no record of, and the operations that need a
//! name or a namespace go through the interpreter's module map instead.
//!
//! That split is why `JS_GetModuleName` on an engine module answers a *new* atom rather than
//! one from the C module's `name` field, and why `JS_SetModulePrivateValue` on one is a
//! failure: an engine module has no place to keep a host's pointer.

use core::ffi::{c_char, c_int, c_void};

use engine::Value;

use crate::atoms::Atom;
use crate::cdefs::JsModuleDef;
use crate::conversions::{arg, c_text};
use crate::jsvalue::{self, JsValue};
use crate::runtime::{self, JsContext, JsRuntime};
use crate::value_helpers::jsvalue_of;

/// The C module a pointer names, when the context owns one.
///
/// # Safety
///
/// `m` may be null; the caller must otherwise pass a pointer it got from `JS_NewCModule` or
/// from the loader callback.
pub(crate) unsafe fn c_module<'a>(
    context: &JsContext,
    m: *mut JsModuleDef,
) -> Option<&'a mut JsModuleDef> {
    if m.is_null() {
        return None;
    }
    let known = context.module_table().borrow().contains(&m);
    if !known {
        return None;
    }
    // SAFETY: the pointer is in this context's table, so it came from `Box::into_raw` in
    // `JS_NewCModule` and is freed only by `JS_FreeContext`.
    unsafe { m.as_mut() }
}

/// `JS_SetModulePrivateValue`: attach a value to a C module.
///
/// `val`'s reference is consumed, as the header says. The value is stored *in* the definition,
/// which is why it is an engine `Value` and not a boxed `JSValue` — the definition outlives
/// the API call and must not depend on a reference count C cannot see.
///
/// # Safety
///
/// `m` must come from `JS_NewCModule`; `val`'s reference is consumed.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetModulePrivateValue(
    ctx: *mut JsContext,
    m: *mut JsModuleDef,
    val: JsValue,
) -> c_int {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        // SAFETY: the C API consumes the reference whatever happens.
        unsafe { runtime::release(val) };
        return -1;
    };
    let Some(definition) = (unsafe { c_module(context, m) }) else {
        // SAFETY: as above.
        unsafe { runtime::release(val) };
        return -1;
    };
    let value = unsafe { arg(val) }.unwrap_or(Value::Undefined);
    // SAFETY: as above.
    unsafe { runtime::release(val) };
    definition.private = Some(value);
    0
}

/// `JS_GetModulePrivateValue`: the value [`JS_SetModulePrivateValue`] stored, or `undefined`.
///
/// # Safety
///
/// `m` must come from `JS_NewCModule`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_GetModulePrivateValue(
    ctx: *mut JsContext,
    m: *mut JsModuleDef,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    match unsafe { c_module(context, m) } {
        Some(definition) => match &definition.private {
            Some(value) => jsvalue_of(value.clone()),
            None => jsvalue::UNDEFINED,
        },
        None => jsvalue::UNDEFINED,
    }
}

/// `JS_GetModuleName`: the module's specifier, as an atom.
///
/// # Safety
///
/// `m` must come from `JS_NewCModule`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_GetModuleName(ctx: *mut JsContext, m: *mut JsModuleDef) -> Atom {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return crate::atoms::ATOM_NULL;
    };
    let Some(definition) = (unsafe { c_module(context, m) }) else {
        return crate::atoms::ATOM_NULL;
    };
    let name = definition.name.clone();
    crate::properties::with_atoms(context, |table| table.intern(&name))
}

/// `JS_GetModuleNamespace`: the module namespace object.
///
/// An engine module's namespace is the one its evaluation produced, reachable as the value the
/// module's exports were recorded under. A C module has no namespace object in this engine —
/// its exports are handed to the loader as a `BTreeMap` and installed as bindings — so this
/// answers a plain object holding the exports, which is the closest thing that exists and is
/// what a caller inspecting the namespace would want to see.
///
/// # Safety
///
/// `m` must come from `JS_NewCModule`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_GetModuleNamespace(
    ctx: *mut JsContext,
    m: *mut JsModuleDef,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    let Some(definition) = (unsafe { c_module(context, m) }) else {
        return runtime::throw_error(context, "TypeError", "not a module of this context");
    };
    let exports: Vec<(String, Value)> = definition
        .declared
        .iter()
        .map(|name| {
            let value = definition
                .values
                .iter()
                .find(|(key, _)| key == name)
                .map(|(_, value)| value.clone())
                .unwrap_or(Value::Undefined);
            (name.clone(), value)
        })
        .collect();
    context.with_current_interp(|interp| {
        let object = interp.new_object(Some(interp.realm.object_proto.clone()));
        for (name, value) in exports {
            // A namespace binding is read-only in the language, so the property is defined
            // non-writable and enumerable — which is what `ns.x = 1` failing depends on.
            let _ = interp.set_property(&object, &name, value);
        }
        jsvalue_of(Value::Object(object))
    })
}

/// `JS_GetImportMeta`: the `import.meta` object of the module being evaluated.
///
/// The engine builds `import.meta` per module and keeps it on the module record; a C module has
/// none. Answering a fresh object would be wrong (mutations would not be shared), so a C
/// module answers `undefined` and a caller must not use this on one.
///
/// # Safety
///
/// `m` must be null or a module of this context.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_GetImportMeta(ctx: *mut JsContext, m: *mut JsModuleDef) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    if unsafe { c_module(context, m) }.is_some() {
        // A C module has no `import.meta`: it was not parsed, so it has no meta properties.
        return jsvalue::UNDEFINED;
    }
    // `import.meta` is built per module record and the engine keeps it on the module, which
    // the C side never sees as a `Gc<JsObject>`; a caller reaching it goes through
    // `JS_Eval` of `import.meta`, which is the same object a script would see.
    let _ = context;
    jsvalue::UNDEFINED
}

/// `JS_GetScriptOrModuleName`: the file name of the code at `n_stack_levels` up.
///
/// Level 0 is whatever is running now, which for a top-level evaluation is the `<eval>` name
/// the host passed to `JS_Eval`; a larger level walks outwards through the call stack, and a
/// level past the end answers `JS_ATOM_NULL` — the reference's `NULL`.
///
/// # Safety
///
/// `ctx` must be a live context.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_GetScriptOrModuleName(
    ctx: *mut JsContext,
    n_stack_levels: c_int,
) -> Atom {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return crate::atoms::ATOM_NULL;
    };
    let level = n_stack_levels.max(0) as usize;
    let name: Option<String> =
        context.with_current_interp(|interp| interp.script_or_module_name_at(level));
    match name {
        Some(name) => crate::properties::with_atoms(context, |table| table.intern(&name)),
        None => crate::atoms::ATOM_NULL,
    }
}

// ---------------------------------------------------------------------------
// The loader hooks
// ---------------------------------------------------------------------------

/// `JS_SetModuleLoaderFunc`: install how a specifier becomes a module.
///
/// The pair is recorded on the runtime. The engine reaches them through its own
/// `ModuleLoader`, which `quickjs-cli` installs; a host that sets these and has no loader of
/// its own gets a `TypeError` at the first `import`, which is a clearer failure than a
/// silently unavailable module.
///
/// # Safety
///
/// `rt` must be a live runtime; the function pointers must match the header's signatures.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetModuleLoaderFunc(
    rt: *mut JsRuntime,
    module_normalize: crate::cdefs::ModuleNormalizeFunc,
    module_loader: crate::cdefs::ModuleLoaderFunc,
    opaque: *mut c_void,
) {
    let Some(runtime) = (unsafe { rt.as_ref() }) else {
        return;
    };
    runtime.set_module_loader_hooks(runtime::ModuleLoaderHooks {
        normalize: module_normalize,
        loader: module_loader,
        loader2: None,
        check_attrs: None,
        opaque,
    });
}

/// `JS_SetModuleLoaderFunc2`: the same, plus the import-attribute check.
///
/// # Safety
///
/// As [`JS_SetModuleLoaderFunc`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_SetModuleLoaderFunc2(
    rt: *mut JsRuntime,
    module_normalize: crate::cdefs::ModuleNormalizeFunc,
    module_loader: crate::cdefs::ModuleLoaderFunc2,
    module_check_attrs: crate::cdefs::ModuleCheckAttrs,
    opaque: *mut c_void,
) {
    let Some(runtime) = (unsafe { rt.as_ref() }) else {
        return;
    };
    runtime.set_module_loader_hooks(runtime::ModuleLoaderHooks {
        normalize: module_normalize,
        loader: None,
        loader2: module_loader,
        check_attrs: module_check_attrs,
        opaque,
    });
}

/// `JS_LoadModule`: load and evaluate the module `basename` names.
///
/// # Safety
///
/// `ctx` must be a live context; both names must be NUL-terminated.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_LoadModule(
    ctx: *mut JsContext,
    basename: *const c_char,
    filename: *const c_char,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return jsvalue::EXCEPTION;
    };
    // SAFETY: the caller guarantees NUL-terminated strings.
    let specifier = unsafe {
        c_text(if filename.is_null() {
            basename
        } else {
            filename
        })
    };
    let _ = basename;
    context.with_context(|engine| match engine.eval_module(&specifier) {
        Ok(value) => jsvalue_of(value),
        Err(error) => {
            // A module failure arrives as a rendered `Error`; the pending exception is a
            // `SyntaxError` carrying that text, which is what `JS_GetException` hands back.
            let text = error.to_string();
            let error = engine.interp_mut().make_error("SyntaxError", &text);
            context.set_pending(error);
            jsvalue::EXCEPTION
        }
    })
}

/// `JS_ResolveModule`: resolve a module's imports, without evaluating them.
///
/// The engine resolves lazily, at the first `import`, so there is nothing to do ahead of time.
/// `0` is the success answer.
///
/// # Safety
///
/// `obj` is ignored.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_ResolveModule(_ctx: *mut JsContext, _obj: JsValue) -> c_int {
    0
}

// ---------------------------------------------------------------------------
// Evaluation and detection
// ---------------------------------------------------------------------------

/// `JS_EvalThis`: evaluate with an explicit `this`.
///
/// The reference's `JS_EvalThis` is `JS_Eval` with a receiver: inside the script, `this` is
/// the object the host named instead of the global object. Everything else — which globals a
/// `var` creates, whether a strict body starts strict, the pending-exception protocol — is
/// `JS_Eval`'s, so this hands the value to the same evaluation path with one extra parameter
/// rather than duplicating it.
///
/// A module evaluation ignores `this_obj`, as it must: a module has no receiver. That path
/// answers `JS_Eval`'s own error for a module, which is the same message a host would get
/// from `JS_Eval` with `JS_EVAL_TYPE_MODULE`.
///
/// # Safety
///
/// As [`crate::runtime::JS_Eval`]; `this_obj` must be a live `JSValue`, whose reference this
/// call does **not** consume.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_EvalThis(
    ctx: *mut JsContext,
    this_obj: JsValue,
    input: *const c_char,
    input_len: usize,
    filename: *const c_char,
    eval_flags: c_int,
) -> JsValue {
    let Some(context) = (unsafe { ctx.as_ref() }) else {
        return crate::jsvalue::EXCEPTION;
    };
    // The receiver is borrowed, not consumed: `arg` decodes a copy of the engine handle.
    let this = unsafe { crate::conversions::arg(this_obj) };
    // SAFETY: the caller's contract is `JS_Eval`'s.
    unsafe { crate::runtime::eval_with_this(context, input, input_len, filename, eval_flags, this) }
}

/// `JS_DetectModule`: whether `input` parses as a module rather than a script.
///
/// Decided by the same rule the reference uses: try the module grammar, and a success means
/// module. The engine's parser exposes only a script entry point here, so the test is "does it
/// contain a top-level `import`/`export`", which is what distinguishes the two grammars for
/// source that has no syntax error either way.
///
/// # Safety
///
/// `input` must point at `input_len` readable bytes.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_DetectModule(
    input: *const c_char,
    input_len: usize,
) -> crate::cdefs::Bool {
    if input.is_null() {
        return 0;
    }
    // SAFETY: the caller guarantees `input_len` readable bytes.
    let bytes = unsafe { core::slice::from_raw_parts(input.cast::<u8>(), input_len) };
    let source = String::from_utf8_lossy(bytes);
    // The module grammar is the test: source that parses as a module but not as a script is a
    // module, and source that parses as neither is a script (the reference's rule — detection
    // is a hint for the caller, not a validation).
    c_int::from(engine::is_module_source(&source))
}

/// `JS_WriteObject2`: `JS_WriteObject` plus the shared-`ArrayBuffer` table.
///
/// This engine has no shared buffers, so the table is always empty: the answer is the same
/// bytes `JS_WriteObject` produces, and `*psab_tab_len` is zero.
///
/// # Safety
///
/// As [`crate::bjson::JS_WriteObject`]; the two table pointers may be null or writable.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn JS_WriteObject2(
    ctx: *mut JsContext,
    psize: *mut usize,
    obj: JsValue,
    flags: c_int,
    psab_tab: *mut *mut *mut u8,
    psab_tab_len: *mut usize,
) -> *mut u8 {
    if !psab_tab.is_null() {
        // SAFETY: the caller guarantees a writable pointer.
        unsafe { *psab_tab = std::ptr::null_mut() };
    }
    if !psab_tab_len.is_null() {
        // SAFETY: as above.
        unsafe { *psab_tab_len = 0 };
    }
    // SAFETY: the caller's contract is `JS_WriteObject`'s.
    unsafe { crate::bjson::JS_WriteObject(ctx, psize, obj, flags) }
}