quickjs/state.rs
1//! Runtime and context state: limits, GC, opaque pointers, context values, memory reporting
2//! and `JS_PrintValue`.
3//!
4//! # Which of these are real and which are "accepted and recorded"
5//!
6//! A limit that the engine does not enforce must not pretend to. `JS_SetMemoryLimit` and
7//! `JS_SetMaxStackSize` map onto `Runtime::set_memory_limit`/`set_stack_size`, which the
8//! allocator and the call-depth check already consult — so those are real.
9//! `JS_SetGCThreshold` maps onto the heap's threshold, also real.
10//! `JS_SetInterruptHandler` is real but only checked where the engine already yields
11//! (`docs/m15-plan.md` §5: not between every opcode), and that limit is stated in the README.
12//! `JS_SetCanBlock`, `JS_SetStripInfo` and `JS_SetRuntimeInfo` are recorded and have no
13//! observable effect, which is stated at each one.
14//!
15//! # Why the memory report is not a fabrication
16//!
17//! `JS_ComputeMemoryUsage` fills a `JSMemoryUsage` whose fields a C program prints. Filling
18//! them with plausible-looking zeros would be worse than filling the two that are actually
19//! known: a host that logs `malloc_size` and sees `0` knows the number is unavailable, whereas
20//! one that sees an invented `4096` believes it. So the live-box count and its bytes are real,
21//! and the fields this engine cannot account for are zero with a comment naming which.
22
23use core::ffi::{c_char, c_int, c_void};
24
25use engine::Value;
26
27use crate::cdefs::{Bool, JSMemoryUsage, JSPrintValueOptions, PrintValueWrite};
28use crate::conversions::arg;
29use crate::jsvalue::{self, JsValue};
30use crate::runtime::{self, JsContext, JsRuntime};
31use crate::value_helpers::jsvalue_of;
32
33// ---------------------------------------------------------------------------
34// Limits
35// ---------------------------------------------------------------------------
36
37/// `JS_SetMemoryLimit`: refuse an allocation that would take the heap past `limit` bytes.
38///
39/// **`0` means "no memory at all", not "no limit".** The reference's `malloc_limit` is a
40/// `size_t` initialised to `-1`, and `js_malloc` fails when `malloc_size + size > limit`, so
41/// a host that wants to remove a limit passes `(size_t)-1`. That is worth stating because it
42/// is the opposite of what a "0 disables it" instinct expects, and getting it wrong here
43/// would have made every allocation after the call fail — which is exactly what happened
44/// when this layer first mapped `0` onto "unlimited" and `tests/c/embed.c` caught it.
45///
46/// # Safety
47///
48/// `rt` must be a live runtime.
49#[unsafe(no_mangle)]
50pub unsafe extern "C" fn JS_SetMemoryLimit(rt: *mut JsRuntime, limit: usize) {
51 let Some(runtime) = (unsafe { rt.as_ref() }) else {
52 return;
53 };
54 // SAFETY: the engine runtime is boxed and this pointer is the only writer; the C API is
55 // single-threaded per runtime by contract, and `&mut` through a raw pointer is how a
56 // `*mut JSRuntime` reaches it.
57 let engine = unsafe { &mut *(runtime.engine_ptr() as *mut engine::Runtime) };
58 // `Some(limit)`, always: a limit of zero is a real limit (nothing may be allocated),
59 // which is what the reference does. The engine's `Option` is only for "no limit", and
60 // that arrives as `(size_t)-1` from the host.
61 engine.set_memory_limit(if limit == usize::MAX {
62 None
63 } else {
64 Some(limit)
65 });
66}
67
68/// `JS_SetMaxStackSize`: cap the call depth, `0` to disable the check.
69///
70/// # Safety
71///
72/// `rt` must be a live runtime.
73#[unsafe(no_mangle)]
74pub unsafe extern "C" fn JS_SetMaxStackSize(rt: *mut JsRuntime, stack_size: usize) {
75 let Some(runtime) = (unsafe { rt.as_ref() }) else {
76 return;
77 };
78 // SAFETY: as `JS_SetMemoryLimit`.
79 let engine = unsafe { &mut *(runtime.engine_ptr() as *mut engine::Runtime) };
80 let limit = if stack_size == 0 {
81 None
82 } else {
83 Some(stack_size)
84 };
85 engine.set_stack_size(limit);
86 // The engine's field is what a *later* context picks up; a context that already ran
87 // something owns its interpreter, and it has to be told now — the same ordering problem
88 // [`JS_SetMemoryLimit`] had, which the heap solves for memory and the interpreter cannot.
89 if let Some(limit) = limit {
90 for context in runtime.live_contexts() {
91 // SAFETY: every pointer in the list is live until `JS_FreeContext`.
92 if let Some(context) = unsafe { context.as_ref() } {
93 context.set_stack_limit(limit);
94 }
95 }
96 }
97}
98
99/// `JS_SetGCThreshold`: collect once the heap holds `threshold` bytes.
100///
101/// # Safety
102///
103/// `rt` must be a live runtime.
104#[unsafe(no_mangle)]
105pub unsafe extern "C" fn JS_SetGCThreshold(rt: *mut JsRuntime, gc_threshold: usize) {
106 let Some(runtime) = (unsafe { rt.as_ref() }) else {
107 return;
108 };
109 runtime.set_gc_threshold(gc_threshold);
110 runtime.engine.heap().set_threshold(gc_threshold);
111}
112
113/// `JS_SetInterruptHandler`: call `cb` periodically while a script runs.
114///
115/// Returning non-zero from the callback aborts the script. The engine checks the handler at
116/// the sites it already yields at (loop back-edges and calls), which is enough for "stop this
117/// runaway script" and *not* enough for single-stepping — see the README's limitations
118/// section, where that is stated as the reason `debugger` is not implemented on top of it.
119///
120/// # Safety
121///
122/// `rt` must be a live runtime and `cb`, if non-null, a `JSInterruptHandler`.
123#[unsafe(no_mangle)]
124pub unsafe extern "C" fn JS_SetInterruptHandler(
125 rt: *mut JsRuntime,
126 cb: crate::cdefs::InterruptHandler,
127 opaque: *mut c_void,
128) {
129 let Some(runtime) = (unsafe { rt.as_ref() }) else {
130 return;
131 };
132 runtime.set_interrupt_handler(cb, opaque);
133 // A context that already ran something has a live interpreter, and it has to learn about
134 // the handler now rather than at its next entry point: `JS_SetInterruptHandler` is
135 // documented as taking effect for the *next* evaluation, which is also the next poll.
136 for context in runtime.live_contexts() {
137 // SAFETY: every pointer in the list is live until `JS_FreeContext`.
138 if let Some(context) = unsafe { context.as_ref() } {
139 context.install_interrupt_hook();
140 }
141 }
142}
143
144/// `JS_RunGC`: collect now.
145///
146/// # Safety
147///
148/// `rt` must be a live runtime.
149#[unsafe(no_mangle)]
150pub unsafe extern "C" fn JS_RunGC(rt: *mut JsRuntime) {
151 let Some(runtime) = (unsafe { rt.as_ref() }) else {
152 return;
153 };
154 runtime.engine.run_gc();
155}
156
157/// `JS_UpdateStackTop`: tell the engine where this thread's stack starts.
158///
159/// The engine measures depth in frames rather than bytes, so there is no stack top to update.
160/// The reference needs this after a thread switch; a C host that moves a runtime between
161/// threads still gets the frame-based check, which is thread-independent.
162///
163/// # Safety
164///
165/// The argument is ignored.
166#[unsafe(no_mangle)]
167pub unsafe extern "C" fn JS_UpdateStackTop(_rt: *mut JsRuntime) {}
168
169/// `JS_SetCanBlock`: whether a blocking operation (a synchronous `Atomics.wait`) is allowed.
170///
171/// # Safety
172///
173/// `rt` must be a live runtime.
174#[unsafe(no_mangle)]
175pub unsafe extern "C" fn JS_SetCanBlock(rt: *mut JsRuntime, can_block: Bool) {
176 let Some(runtime) = (unsafe { rt.as_ref() }) else {
177 return;
178 };
179 runtime.set_can_block(can_block != 0);
180}
181
182/// `JS_SetStripInfo`: record how much debug info to keep.
183///
184/// The engine never compiles debug info away, so the flag is stored and has no effect. A host
185/// that sets it still gets full stack traces, which is the safe direction (more information,
186/// not less).
187///
188/// # Safety
189///
190/// `rt` must be a live runtime.
191#[unsafe(no_mangle)]
192pub unsafe extern "C" fn JS_SetStripInfo(rt: *mut JsRuntime, flags: c_int) {
193 if let Some(runtime) = unsafe { rt.as_ref() } {
194 runtime.set_strip_info(flags);
195 }
196}
197
198/// `JS_GetStripInfo`: the value last given to [`JS_SetStripInfo`].
199///
200/// # Safety
201///
202/// `rt` must be a live runtime.
203#[unsafe(no_mangle)]
204pub unsafe extern "C" fn JS_GetStripInfo(rt: *mut JsRuntime) -> c_int {
205 match unsafe { rt.as_ref() } {
206 Some(runtime) => runtime.strip_info(),
207 None => 0,
208 }
209}
210
211/// `JS_SetRuntimeInfo`: a label for diagnostics.
212///
213/// # Safety
214///
215/// `info` must be null or NUL-terminated, and outlive the runtime as the header requires.
216#[unsafe(no_mangle)]
217pub unsafe extern "C" fn JS_SetRuntimeInfo(rt: *mut JsRuntime, info: *const c_char) {
218 if let Some(runtime) = unsafe { rt.as_ref() } {
219 runtime.set_info(info);
220 }
221}
222
223/// `JS_GetRuntimeOpaque`: the host's pointer.
224///
225/// # Safety
226///
227/// `rt` must be a live runtime.
228#[unsafe(no_mangle)]
229pub unsafe extern "C" fn JS_GetRuntimeOpaque(rt: *mut JsRuntime) -> *mut c_void {
230 match unsafe { rt.as_ref() } {
231 Some(runtime) => runtime.opaque(),
232 None => std::ptr::null_mut(),
233 }
234}
235
236/// `JS_SetRuntimeOpaque`.
237///
238/// # Safety
239///
240/// `rt` must be a live runtime.
241#[unsafe(no_mangle)]
242pub unsafe extern "C" fn JS_SetRuntimeOpaque(rt: *mut JsRuntime, opaque: *mut c_void) {
243 if let Some(runtime) = unsafe { rt.as_ref() } {
244 runtime.set_opaque(opaque);
245 }
246}
247
248/// `JS_NewRuntime2`: a runtime with the host's allocator.
249///
250/// The engine's allocations go through Rust's global allocator, which a C-supplied
251/// `JSMallocFunctions` cannot replace without a per-runtime allocator threaded through `Gc`.
252/// The runtime is created with the default allocator and the functions are ignored; a caller
253/// that needs its own allocator must not use this library. Recorded in the README.
254///
255/// # Safety
256///
257/// `mf` is ignored; the answer is a live runtime, or null when allocation fails.
258#[unsafe(no_mangle)]
259pub unsafe extern "C" fn JS_NewRuntime2(
260 _mf: *const crate::cdefs::JSMallocFunctions,
261 _opaque: *mut c_void,
262) -> *mut JsRuntime {
263 Box::into_raw(JsRuntime::new())
264}
265
266// ---------------------------------------------------------------------------
267// Contexts
268// ---------------------------------------------------------------------------
269
270/// `JS_DupContext`: raise the context's reference count and answer the same pointer.
271///
272/// The reference does exactly this — a context is not copyable, only reference-counted — and
273/// the count is what makes the documented idiom safe: hand a context to a callback, release
274/// it when the callback returns, and the host's own release still finds it alive.
275///
276/// # Safety
277///
278/// `ctx` must be a live context.
279#[unsafe(no_mangle)]
280pub unsafe extern "C" fn JS_DupContext(ctx: *mut JsContext) -> *mut JsContext {
281 if let Some(context) = unsafe { ctx.as_ref() } {
282 context.raise_refs();
283 }
284 ctx
285}
286
287/// `JS_GetContextOpaque`.
288///
289/// # Safety
290///
291/// `ctx` must be a live context.
292#[unsafe(no_mangle)]
293pub unsafe extern "C" fn JS_GetContextOpaque(ctx: *mut JsContext) -> *mut c_void {
294 match unsafe { ctx.as_ref() } {
295 Some(context) => context.opaque(),
296 None => std::ptr::null_mut(),
297 }
298}
299
300/// `JS_SetContextOpaque`.
301///
302/// # Safety
303///
304/// `ctx` must be a live context.
305#[unsafe(no_mangle)]
306pub unsafe extern "C" fn JS_SetContextOpaque(ctx: *mut JsContext, opaque: *mut c_void) {
307 if let Some(context) = unsafe { ctx.as_ref() } {
308 context.set_opaque(opaque);
309 }
310}
311
312/// `JS_SetContextValue`: store a value at one of the context's private slots.
313///
314/// # Safety
315///
316/// `ctx` must be a live context; `val`'s reference is consumed.
317#[unsafe(no_mangle)]
318pub unsafe extern "C" fn JS_SetContextValue(ctx: *mut JsContext, idx: c_int, val: JsValue) {
319 let Some(context) = (unsafe { ctx.as_ref() }) else {
320 // SAFETY: the C API consumes the reference whatever happens.
321 unsafe { runtime::release(val) };
322 return;
323 };
324 let value = unsafe { arg(val) }.unwrap_or(Value::Undefined);
325 // SAFETY: the C API consumes it.
326 unsafe { runtime::release(val) };
327 context.set_value(idx, value);
328}
329
330/// `JS_GetContextValue`: the value at slot `idx`, or `undefined`.
331///
332/// # Safety
333///
334/// `ctx` must be a live context.
335#[unsafe(no_mangle)]
336pub unsafe extern "C" fn JS_GetContextValue(ctx: *mut JsContext, idx: c_int) -> JsValue {
337 let Some(context) = (unsafe { ctx.as_ref() }) else {
338 return jsvalue::EXCEPTION;
339 };
340 match context.value(idx) {
341 Some(value) => jsvalue_of(value),
342 None => jsvalue::UNDEFINED,
343 }
344}
345
346/// `JS_NewContextRaw`: a context with no intrinsics installed.
347///
348/// The engine installs its builtins when it builds an interpreter, at which point a context
349/// *has* an interpreter and the intrinsic set is no longer a choice. So this is
350/// `JS_NewContext`: a raw context here still has `Object` and `Array`. A caller that wanted
351/// the reduced context must not use this library; the README says so next to
352/// `JS_AddIntrinsicIntl`.
353///
354/// # Safety
355///
356/// `rt` must be a live runtime.
357#[unsafe(no_mangle)]
358pub unsafe extern "C" fn JS_NewContextRaw(rt: *mut JsRuntime) -> *mut JsContext {
359 // SAFETY: the caller's contract is `JS_NewContext`'s.
360 unsafe { crate::runtime::JS_NewContext(rt) }
361}
362
363// ---------------------------------------------------------------------------
364// Memory usage
365// ---------------------------------------------------------------------------
366
367/// `JS_ComputeMemoryUsage`: fill `s` with what this runtime occupies.
368///
369/// Two fields are real (the live box count and its bytes); the rest are zero, because the
370/// engine does not account for them separately. See the module docs for why zero rather than
371/// a plausible number.
372///
373/// # Safety
374///
375/// `rt` must be a live runtime and `s` writable.
376#[unsafe(no_mangle)]
377pub unsafe extern "C" fn JS_ComputeMemoryUsage(rt: *mut JsRuntime, s: *mut JSMemoryUsage) {
378 if s.is_null() {
379 return;
380 }
381 let mut usage = JSMemoryUsage::default();
382 if let Some(runtime) = unsafe { rt.as_ref() } {
383 let heap = runtime.engine.heap();
384 let live = heap.live_count();
385 let bytes = heap.allocated_bytes();
386 // `obj_count`/`obj_size` are the only pair the engine can answer: every live box is
387 // an object, a string, a symbol or a cell, and the heap does not distinguish them.
388 usage.obj_count = i64::try_from(live).unwrap_or(i64::MAX);
389 usage.obj_size = i64::try_from(bytes).unwrap_or(i64::MAX);
390 usage.malloc_size = usage.obj_size;
391 usage.malloc_count = usage.obj_count;
392 // The limit, when the host set one, is what "can still be handed out" is relative to.
393 if let Some(limit) = runtime.engine.memory_limit() {
394 usage.malloc_limit = i64::try_from(limit).unwrap_or(i64::MAX);
395 let used = runtime.engine.heap().allocated_bytes();
396 usage.memory_used_size = i64::try_from(limit.saturating_sub(used)).unwrap_or(0);
397 }
398 usage.atom_count = i64::try_from(runtime.atoms.borrow().len()).unwrap_or(i64::MAX);
399 }
400 // SAFETY: the caller guarantees a writable pointer.
401 unsafe { s.write(usage) };
402}
403
404/// `JS_DumpMemoryUsage`: print the report to `fp`.
405///
406/// Rendered as `key: value` lines rather than the reference's formatted table, because the
407/// numbers behind the table do not exist here; the two that do are named exactly.
408///
409/// # Safety
410///
411/// `fp` must be a writable `FILE *` and `s` a filled `JSMemoryUsage`.
412#[unsafe(no_mangle)]
413pub unsafe extern "C" fn JS_DumpMemoryUsage(
414 fp: *mut c_void,
415 s: *const JSMemoryUsage,
416 _rt: *mut JsRuntime,
417) {
418 if fp.is_null() || s.is_null() {
419 return;
420 }
421 // SAFETY: the caller guarantees a live `FILE *` and a filled structure.
422 let usage = unsafe { &*s };
423 let report = format!(
424 "objects: {}\nobject bytes: {}\natoms: {}\nmalloc limit: {}\n",
425 usage.obj_count, usage.obj_size, usage.atom_count, usage.malloc_limit
426 );
427 // SAFETY: `fp` is a `FILE *` the caller opened; `fwrite` reads `len` bytes from `report`.
428 unsafe {
429 let write: unsafe extern "C" fn(*const c_void, usize, usize, *mut c_void) -> usize =
430 core::mem::transmute(libc::fwrite as unsafe extern "C" fn(_, _, _, _) -> _);
431 write(report.as_ptr().cast(), 1, report.len(), fp);
432 }
433}
434
435// ---------------------------------------------------------------------------
436// Printing a value
437// ---------------------------------------------------------------------------
438
439/// `JS_PrintValueSetDefaultOptions`: the options a fresh `JSPrintValueOptions` should hold.
440///
441/// **Not** zeros: the reference fills in `max_depth = 2`, `max_string_length = 1000` and
442/// `max_item_count = 100`. This function used to write zeros and the symbol table said that
443/// was "the header's default" — the header says nothing of the kind, and its implementation
444/// in `quickjs.c` is five lines of explicit assignment. A host that called this and then
445/// `JS_PrintValue` got an unbounded dump where the reference truncates at depth 2.
446///
447/// # Safety
448///
449/// `options` must be writable.
450#[unsafe(no_mangle)]
451pub unsafe extern "C" fn JS_PrintValueSetDefaultOptions(options: *mut JSPrintValueOptions) {
452 if options.is_null() {
453 return;
454 }
455 // SAFETY: the caller guarantees a writable pointer.
456 unsafe {
457 options.write(JSPrintValueOptions {
458 show_hidden: 0,
459 raw_dump: 0,
460 max_depth: 2,
461 max_string_length: 1000,
462 max_item_count: 100,
463 });
464 }
465}
466
467/// `JS_PrintValue`: render `val` through `write_func`.
468///
469/// The rendering is the engine's own `describe` (the one a REPL uses), which prints strings
470/// quoted, objects as `{ a: 1 }` and functions as `[Function: f]`. The options are accepted
471/// but only `show_hidden` is honoured, by way of the same describe; the three limits are not,
472/// and a caller relying on `max_depth` gets an unbounded rendering — stated in the README.
473///
474/// # Safety
475///
476/// `write_func` must be a `JSPrintValueWrite`; `val` a live `JSValue`.
477#[unsafe(no_mangle)]
478pub unsafe extern "C" fn JS_PrintValue(
479 ctx: *mut JsContext,
480 write_func: PrintValueWrite,
481 write_opaque: *mut c_void,
482 val: JsValue,
483 options: *const JSPrintValueOptions,
484) {
485 let Some(context) = (unsafe { ctx.as_ref() }) else {
486 return;
487 };
488 let Some(value) = (unsafe { arg(val) }) else {
489 return;
490 };
491 // `options` may be null, and then the reference's defaults apply (depth 2, 1000
492 // characters, 100 items) — the same numbers `JS_PrintValueSetDefaultOptions` writes.
493 let limits = if options.is_null() {
494 engine::print::PrintLimits::default()
495 } else {
496 // SAFETY: the caller guarantees the pointer is readable for the duration of the call.
497 let options = unsafe { &*options };
498 engine::print::PrintLimits {
499 // Zero does **not** mean "print nothing": the header says "0 = no limit", so it
500 // has to become a number large enough to never trigger. The fields are
501 // `uint32_t` in the header, which is why `as usize` is a widening conversion.
502 max_depth: if options.max_depth == 0 {
503 usize::MAX
504 } else {
505 options.max_depth as usize
506 },
507 max_string_length: if options.max_string_length == 0 {
508 usize::MAX
509 } else {
510 options.max_string_length as usize
511 },
512 max_item_count: if options.max_item_count == 0 {
513 usize::MAX
514 } else {
515 options.max_item_count as usize
516 },
517 }
518 };
519 let text = context.with_current_interp(|interp| {
520 match engine::print::sprint_limited(interp, &value, limits) {
521 Ok(text) => text,
522 // A printer that fails must not take the reporter down with it; the reference falls
523 // back to the class name, and so does this.
524 Err(_) => format!("[{}]", value.type_of()),
525 }
526 });
527 emit(write_func, write_opaque, &text);
528}
529
530/// `JS_PrintValueRT`: the same, found through a runtime rather than a context.
531///
532/// # Safety
533///
534/// `write_func` must be a `JS_PrintValueWrite`; `val` a live `JSValue`.
535#[unsafe(no_mangle)]
536pub unsafe extern "C" fn JS_PrintValueRT(
537 rt: *mut JsRuntime,
538 write_func: PrintValueWrite,
539 write_opaque: *mut c_void,
540 val: JsValue,
541 options: *const JSPrintValueOptions,
542) {
543 let Some(runtime) = (unsafe { rt.as_ref() }) else {
544 return;
545 };
546 // Whichever context exists is the one whose realm the value belongs to; a value with no
547 // context is printed by the first one, which is right because every context in a runtime
548 // shares its atoms and its class table.
549 let contexts = runtime.live_contexts();
550 if let Some(&context) = contexts.first() {
551 // SAFETY: the pointer is live until `JS_FreeContext`.
552 unsafe { JS_PrintValue(context, write_func, write_opaque, val, options) }
553 }
554}
555
556/// Hand `text` to a C write callback.
557fn emit(write_func: PrintValueWrite, write_opaque: *mut c_void, text: &str) {
558 let Some(write_func) = write_func else {
559 return;
560 };
561 // SAFETY: the caller guarantees the callback matches the header's signature, and the
562 // slice outlives the call.
563 unsafe { write_func(write_opaque, text.as_ptr().cast(), text.len()) };
564}
565
566/// `JS_HasException`: whether a call left an exception behind.
567///
568/// # Safety
569///
570/// `ctx` must be a live context.
571#[unsafe(no_mangle)]
572pub unsafe extern "C" fn JS_HasException(ctx: *mut JsContext) -> Bool {
573 match unsafe { ctx.as_ref() } {
574 Some(context) => c_int::from(context.has_pending()),
575 None => 0,
576 }
577}
578
579/// `JS_ThrowOutOfMemory`: raise the engine's out-of-memory error.
580///
581/// # Safety
582///
583/// `ctx` must be a live context.
584#[unsafe(no_mangle)]
585pub unsafe extern "C" fn JS_ThrowOutOfMemory(ctx: *mut JsContext) -> JsValue {
586 let Some(context) = (unsafe { ctx.as_ref() }) else {
587 return jsvalue::EXCEPTION;
588 };
589 let value = context.throw_out_of_memory();
590 context.set_pending(value);
591 jsvalue::EXCEPTION
592}
593
594/// `JS_ThrowSyntaxError`, `JS_ThrowTypeError`, `JS_ThrowReferenceError`,
595/// `JS_ThrowInternalError`: the four `JS_Throw*` spellings not already exported.
596///
597/// Each one is variadic in the header. Ours reads only `fmt`, for the reason
598/// `JS_ThrowRangeError` documents: a variadic Rust function is not expressible on stable, and
599/// a wrong-arity call would be worse than one that ignores surplus arguments.
600///
601/// # Safety
602///
603/// `ctx` must be a live context, `fmt` null or NUL-terminated.
604#[unsafe(no_mangle)]
605pub unsafe extern "C" fn JS_ThrowSyntaxError(ctx: *mut JsContext, fmt: *const c_char) -> JsValue {
606 // SAFETY: the caller's contract is `throw_named`'s.
607 unsafe { throw_named(ctx, "SyntaxError", fmt) }
608}
609
610/// `JS_ThrowTypeError`. See [`JS_ThrowSyntaxError`].
611///
612/// # Safety
613///
614/// As [`JS_ThrowSyntaxError`].
615#[unsafe(no_mangle)]
616pub unsafe extern "C" fn JS_ThrowTypeError(ctx: *mut JsContext, fmt: *const c_char) -> JsValue {
617 // SAFETY: the caller's contract is `throw_named`'s.
618 unsafe { throw_named(ctx, "TypeError", fmt) }
619}
620
621/// `JS_ThrowReferenceError`. See [`JS_ThrowSyntaxError`].
622///
623/// # Safety
624///
625/// As [`JS_ThrowSyntaxError`].
626#[unsafe(no_mangle)]
627pub unsafe extern "C" fn JS_ThrowReferenceError(
628 ctx: *mut JsContext,
629 fmt: *const c_char,
630) -> JsValue {
631 // SAFETY: the caller's contract is `throw_named`'s.
632 unsafe { throw_named(ctx, "ReferenceError", fmt) }
633}
634
635/// `JS_ThrowInternalError`. See [`JS_ThrowSyntaxError`].
636///
637/// # Safety
638///
639/// As [`JS_ThrowSyntaxError`].
640#[unsafe(no_mangle)]
641pub unsafe extern "C" fn JS_ThrowInternalError(ctx: *mut JsContext, fmt: *const c_char) -> JsValue {
642 // SAFETY: the caller's contract is `throw_named`'s.
643 unsafe { throw_named(ctx, "InternalError", fmt) }
644}
645
646/// The shared body of the four above.
647unsafe fn throw_named(ctx: *mut JsContext, name: &str, fmt: *const c_char) -> JsValue {
648 let Some(context) = (unsafe { ctx.as_ref() }) else {
649 return jsvalue::EXCEPTION;
650 };
651 // SAFETY: the caller guarantees a NUL-terminated format string.
652 let message = unsafe { crate::conversions::c_text(fmt) };
653 runtime::throw_error(context, name, &message)
654}