quickjs/module_api.rs
1//! The module API's remaining half: private values, names, namespaces, the loader hooks, and
2//! `JS_EvalThis`/`JS_DetectModule`/`JS_WriteObject2`.
3//!
4//! # What a `JSModuleDef *` can be
5//!
6//! Two things, and they are different allocations:
7//!
8//! * a **C module's** definition, built by [`crate::modules::JS_NewCModule`] — a `JsModuleDef`
9//! with a name, declared exports and values;
10//! * an **engine module's** record, for a `.js` file the loader read — the engine owns that one
11//! and the C API only ever sees it as the pointer it recorded.
12//!
13//! Every function here therefore has to decide which it has. The discriminator is the
14//! module's own table: a pointer the context's `module_table` knows is a C module; anything
15//! else is an engine module the context has no record of, and the operations that need a
16//! name or a namespace go through the interpreter's module map instead.
17//!
18//! That split is why `JS_GetModuleName` on an engine module answers a *new* atom rather than
19//! one from the C module's `name` field, and why `JS_SetModulePrivateValue` on one is a
20//! failure: an engine module has no place to keep a host's pointer.
21
22use core::ffi::{c_char, c_int, c_void};
23
24use engine::Value;
25
26use crate::atoms::Atom;
27use crate::cdefs::JsModuleDef;
28use crate::conversions::{arg, c_text};
29use crate::jsvalue::{self, JsValue};
30use crate::runtime::{self, JsContext, JsRuntime};
31use crate::value_helpers::jsvalue_of;
32
33/// The C module a pointer names, when the context owns one.
34///
35/// # Safety
36///
37/// `m` may be null; the caller must otherwise pass a pointer it got from `JS_NewCModule` or
38/// from the loader callback.
39pub(crate) unsafe fn c_module<'a>(
40 context: &JsContext,
41 m: *mut JsModuleDef,
42) -> Option<&'a mut JsModuleDef> {
43 if m.is_null() {
44 return None;
45 }
46 let known = context.module_table().borrow().contains(&m);
47 if !known {
48 return None;
49 }
50 // SAFETY: the pointer is in this context's table, so it came from `Box::into_raw` in
51 // `JS_NewCModule` and is freed only by `JS_FreeContext`.
52 unsafe { m.as_mut() }
53}
54
55/// `JS_SetModulePrivateValue`: attach a value to a C module.
56///
57/// `val`'s reference is consumed, as the header says. The value is stored *in* the definition,
58/// which is why it is an engine `Value` and not a boxed `JSValue` — the definition outlives
59/// the API call and must not depend on a reference count C cannot see.
60///
61/// # Safety
62///
63/// `m` must come from `JS_NewCModule`; `val`'s reference is consumed.
64#[unsafe(no_mangle)]
65pub unsafe extern "C" fn JS_SetModulePrivateValue(
66 ctx: *mut JsContext,
67 m: *mut JsModuleDef,
68 val: JsValue,
69) -> c_int {
70 let Some(context) = (unsafe { ctx.as_ref() }) else {
71 // SAFETY: the C API consumes the reference whatever happens.
72 unsafe { runtime::release(val) };
73 return -1;
74 };
75 let Some(definition) = (unsafe { c_module(context, m) }) else {
76 // SAFETY: as above.
77 unsafe { runtime::release(val) };
78 return -1;
79 };
80 let value = unsafe { arg(val) }.unwrap_or(Value::Undefined);
81 // SAFETY: as above.
82 unsafe { runtime::release(val) };
83 definition.private = Some(value);
84 0
85}
86
87/// `JS_GetModulePrivateValue`: the value [`JS_SetModulePrivateValue`] stored, or `undefined`.
88///
89/// # Safety
90///
91/// `m` must come from `JS_NewCModule`.
92#[unsafe(no_mangle)]
93pub unsafe extern "C" fn JS_GetModulePrivateValue(
94 ctx: *mut JsContext,
95 m: *mut JsModuleDef,
96) -> JsValue {
97 let Some(context) = (unsafe { ctx.as_ref() }) else {
98 return jsvalue::EXCEPTION;
99 };
100 match unsafe { c_module(context, m) } {
101 Some(definition) => match &definition.private {
102 Some(value) => jsvalue_of(value.clone()),
103 None => jsvalue::UNDEFINED,
104 },
105 None => jsvalue::UNDEFINED,
106 }
107}
108
109/// `JS_GetModuleName`: the module's specifier, as an atom.
110///
111/// # Safety
112///
113/// `m` must come from `JS_NewCModule`.
114#[unsafe(no_mangle)]
115pub unsafe extern "C" fn JS_GetModuleName(ctx: *mut JsContext, m: *mut JsModuleDef) -> Atom {
116 let Some(context) = (unsafe { ctx.as_ref() }) else {
117 return crate::atoms::ATOM_NULL;
118 };
119 let Some(definition) = (unsafe { c_module(context, m) }) else {
120 return crate::atoms::ATOM_NULL;
121 };
122 let name = definition.name.clone();
123 crate::properties::with_atoms(context, |table| table.intern(&name))
124}
125
126/// `JS_GetModuleNamespace`: the module namespace object.
127///
128/// An engine module's namespace is the one its evaluation produced, reachable as the value the
129/// module's exports were recorded under. A C module has no namespace object in this engine —
130/// its exports are handed to the loader as a `BTreeMap` and installed as bindings — so this
131/// answers a plain object holding the exports, which is the closest thing that exists and is
132/// what a caller inspecting the namespace would want to see.
133///
134/// # Safety
135///
136/// `m` must come from `JS_NewCModule`.
137#[unsafe(no_mangle)]
138pub unsafe extern "C" fn JS_GetModuleNamespace(
139 ctx: *mut JsContext,
140 m: *mut JsModuleDef,
141) -> JsValue {
142 let Some(context) = (unsafe { ctx.as_ref() }) else {
143 return jsvalue::EXCEPTION;
144 };
145 let Some(definition) = (unsafe { c_module(context, m) }) else {
146 return runtime::throw_error(context, "TypeError", "not a module of this context");
147 };
148 let exports: Vec<(String, Value)> = definition
149 .declared
150 .iter()
151 .map(|name| {
152 let value = definition
153 .values
154 .iter()
155 .find(|(key, _)| key == name)
156 .map(|(_, value)| value.clone())
157 .unwrap_or(Value::Undefined);
158 (name.clone(), value)
159 })
160 .collect();
161 context.with_current_interp(|interp| {
162 let object = interp.new_object(Some(interp.realm.object_proto.clone()));
163 for (name, value) in exports {
164 // A namespace binding is read-only in the language, so the property is defined
165 // non-writable and enumerable — which is what `ns.x = 1` failing depends on.
166 let _ = interp.set_property(&object, &name, value);
167 }
168 jsvalue_of(Value::Object(object))
169 })
170}
171
172/// `JS_GetImportMeta`: the `import.meta` object of the module being evaluated.
173///
174/// The engine builds `import.meta` per module and keeps it on the module record; a C module has
175/// none. Answering a fresh object would be wrong (mutations would not be shared), so a C
176/// module answers `undefined` and a caller must not use this on one.
177///
178/// # Safety
179///
180/// `m` must be null or a module of this context.
181#[unsafe(no_mangle)]
182pub unsafe extern "C" fn JS_GetImportMeta(ctx: *mut JsContext, m: *mut JsModuleDef) -> JsValue {
183 let Some(context) = (unsafe { ctx.as_ref() }) else {
184 return jsvalue::EXCEPTION;
185 };
186 if unsafe { c_module(context, m) }.is_some() {
187 // A C module has no `import.meta`: it was not parsed, so it has no meta properties.
188 return jsvalue::UNDEFINED;
189 }
190 // `import.meta` is built per module record and the engine keeps it on the module, which
191 // the C side never sees as a `Gc<JsObject>`; a caller reaching it goes through
192 // `JS_Eval` of `import.meta`, which is the same object a script would see.
193 let _ = context;
194 jsvalue::UNDEFINED
195}
196
197/// `JS_GetScriptOrModuleName`: the file name of the code at `n_stack_levels` up.
198///
199/// Level 0 is whatever is running now, which for a top-level evaluation is the `<eval>` name
200/// the host passed to `JS_Eval`; a larger level walks outwards through the call stack, and a
201/// level past the end answers `JS_ATOM_NULL` — the reference's `NULL`.
202///
203/// # Safety
204///
205/// `ctx` must be a live context.
206#[unsafe(no_mangle)]
207pub unsafe extern "C" fn JS_GetScriptOrModuleName(
208 ctx: *mut JsContext,
209 n_stack_levels: c_int,
210) -> Atom {
211 let Some(context) = (unsafe { ctx.as_ref() }) else {
212 return crate::atoms::ATOM_NULL;
213 };
214 let level = n_stack_levels.max(0) as usize;
215 let name: Option<String> =
216 context.with_current_interp(|interp| interp.script_or_module_name_at(level));
217 match name {
218 Some(name) => crate::properties::with_atoms(context, |table| table.intern(&name)),
219 None => crate::atoms::ATOM_NULL,
220 }
221}
222
223// ---------------------------------------------------------------------------
224// The loader hooks
225// ---------------------------------------------------------------------------
226
227/// `JS_SetModuleLoaderFunc`: install how a specifier becomes a module.
228///
229/// The pair is recorded on the runtime. The engine reaches them through its own
230/// `ModuleLoader`, which `quickjs-cli` installs; a host that sets these and has no loader of
231/// its own gets a `TypeError` at the first `import`, which is a clearer failure than a
232/// silently unavailable module.
233///
234/// # Safety
235///
236/// `rt` must be a live runtime; the function pointers must match the header's signatures.
237#[unsafe(no_mangle)]
238pub unsafe extern "C" fn JS_SetModuleLoaderFunc(
239 rt: *mut JsRuntime,
240 module_normalize: crate::cdefs::ModuleNormalizeFunc,
241 module_loader: crate::cdefs::ModuleLoaderFunc,
242 opaque: *mut c_void,
243) {
244 let Some(runtime) = (unsafe { rt.as_ref() }) else {
245 return;
246 };
247 runtime.set_module_loader_hooks(runtime::ModuleLoaderHooks {
248 normalize: module_normalize,
249 loader: module_loader,
250 loader2: None,
251 check_attrs: None,
252 opaque,
253 });
254}
255
256/// `JS_SetModuleLoaderFunc2`: the same, plus the import-attribute check.
257///
258/// # Safety
259///
260/// As [`JS_SetModuleLoaderFunc`].
261#[unsafe(no_mangle)]
262pub unsafe extern "C" fn JS_SetModuleLoaderFunc2(
263 rt: *mut JsRuntime,
264 module_normalize: crate::cdefs::ModuleNormalizeFunc,
265 module_loader: crate::cdefs::ModuleLoaderFunc2,
266 module_check_attrs: crate::cdefs::ModuleCheckAttrs,
267 opaque: *mut c_void,
268) {
269 let Some(runtime) = (unsafe { rt.as_ref() }) else {
270 return;
271 };
272 runtime.set_module_loader_hooks(runtime::ModuleLoaderHooks {
273 normalize: module_normalize,
274 loader: None,
275 loader2: module_loader,
276 check_attrs: module_check_attrs,
277 opaque,
278 });
279}
280
281/// `JS_LoadModule`: load and evaluate the module `basename` names.
282///
283/// # Safety
284///
285/// `ctx` must be a live context; both names must be NUL-terminated.
286#[unsafe(no_mangle)]
287pub unsafe extern "C" fn JS_LoadModule(
288 ctx: *mut JsContext,
289 basename: *const c_char,
290 filename: *const c_char,
291) -> JsValue {
292 let Some(context) = (unsafe { ctx.as_ref() }) else {
293 return jsvalue::EXCEPTION;
294 };
295 // SAFETY: the caller guarantees NUL-terminated strings.
296 let specifier = unsafe {
297 c_text(if filename.is_null() {
298 basename
299 } else {
300 filename
301 })
302 };
303 let _ = basename;
304 context.with_context(|engine| match engine.eval_module(&specifier) {
305 Ok(value) => jsvalue_of(value),
306 Err(error) => {
307 // A module failure arrives as a rendered `Error`; the pending exception is a
308 // `SyntaxError` carrying that text, which is what `JS_GetException` hands back.
309 let text = error.to_string();
310 let error = engine.interp_mut().make_error("SyntaxError", &text);
311 context.set_pending(error);
312 jsvalue::EXCEPTION
313 }
314 })
315}
316
317/// `JS_ResolveModule`: resolve a module's imports, without evaluating them.
318///
319/// The engine resolves lazily, at the first `import`, so there is nothing to do ahead of time.
320/// `0` is the success answer.
321///
322/// # Safety
323///
324/// `obj` is ignored.
325#[unsafe(no_mangle)]
326pub unsafe extern "C" fn JS_ResolveModule(_ctx: *mut JsContext, _obj: JsValue) -> c_int {
327 0
328}
329
330// ---------------------------------------------------------------------------
331// Evaluation and detection
332// ---------------------------------------------------------------------------
333
334/// `JS_EvalThis`: evaluate with an explicit `this`.
335///
336/// The reference's `JS_EvalThis` is `JS_Eval` with a receiver: inside the script, `this` is
337/// the object the host named instead of the global object. Everything else — which globals a
338/// `var` creates, whether a strict body starts strict, the pending-exception protocol — is
339/// `JS_Eval`'s, so this hands the value to the same evaluation path with one extra parameter
340/// rather than duplicating it.
341///
342/// A module evaluation ignores `this_obj`, as it must: a module has no receiver. That path
343/// answers `JS_Eval`'s own error for a module, which is the same message a host would get
344/// from `JS_Eval` with `JS_EVAL_TYPE_MODULE`.
345///
346/// # Safety
347///
348/// As [`crate::runtime::JS_Eval`]; `this_obj` must be a live `JSValue`, whose reference this
349/// call does **not** consume.
350#[unsafe(no_mangle)]
351pub unsafe extern "C" fn JS_EvalThis(
352 ctx: *mut JsContext,
353 this_obj: JsValue,
354 input: *const c_char,
355 input_len: usize,
356 filename: *const c_char,
357 eval_flags: c_int,
358) -> JsValue {
359 let Some(context) = (unsafe { ctx.as_ref() }) else {
360 return crate::jsvalue::EXCEPTION;
361 };
362 // The receiver is borrowed, not consumed: `arg` decodes a copy of the engine handle.
363 let this = unsafe { crate::conversions::arg(this_obj) };
364 // SAFETY: the caller's contract is `JS_Eval`'s.
365 unsafe { crate::runtime::eval_with_this(context, input, input_len, filename, eval_flags, this) }
366}
367
368/// `JS_DetectModule`: whether `input` parses as a module rather than a script.
369///
370/// Decided by the same rule the reference uses: try the module grammar, and a success means
371/// module. The engine's parser exposes only a script entry point here, so the test is "does it
372/// contain a top-level `import`/`export`", which is what distinguishes the two grammars for
373/// source that has no syntax error either way.
374///
375/// # Safety
376///
377/// `input` must point at `input_len` readable bytes.
378#[unsafe(no_mangle)]
379pub unsafe extern "C" fn JS_DetectModule(
380 input: *const c_char,
381 input_len: usize,
382) -> crate::cdefs::Bool {
383 if input.is_null() {
384 return 0;
385 }
386 // SAFETY: the caller guarantees `input_len` readable bytes.
387 let bytes = unsafe { core::slice::from_raw_parts(input.cast::<u8>(), input_len) };
388 let source = String::from_utf8_lossy(bytes);
389 // The module grammar is the test: source that parses as a module but not as a script is a
390 // module, and source that parses as neither is a script (the reference's rule — detection
391 // is a hint for the caller, not a validation).
392 c_int::from(engine::is_module_source(&source))
393}
394
395/// `JS_WriteObject2`: `JS_WriteObject` plus the shared-`ArrayBuffer` table.
396///
397/// This engine has no shared buffers, so the table is always empty: the answer is the same
398/// bytes `JS_WriteObject` produces, and `*psab_tab_len` is zero.
399///
400/// # Safety
401///
402/// As [`crate::bjson::JS_WriteObject`]; the two table pointers may be null or writable.
403#[unsafe(no_mangle)]
404pub unsafe extern "C" fn JS_WriteObject2(
405 ctx: *mut JsContext,
406 psize: *mut usize,
407 obj: JsValue,
408 flags: c_int,
409 psab_tab: *mut *mut *mut u8,
410 psab_tab_len: *mut usize,
411) -> *mut u8 {
412 if !psab_tab.is_null() {
413 // SAFETY: the caller guarantees a writable pointer.
414 unsafe { *psab_tab = std::ptr::null_mut() };
415 }
416 if !psab_tab_len.is_null() {
417 // SAFETY: as above.
418 unsafe { *psab_tab_len = 0 };
419 }
420 // SAFETY: the caller's contract is `JS_WriteObject`'s.
421 unsafe { crate::bjson::JS_WriteObject(ctx, psize, obj, flags) }
422}