quickjs-capi
The QuickJS C API, on top of the pure-Rust engine. This is M15 in
docs/m15-plan.md:
the library that makes libquickjs.so replaceable at link time, so the existing Go, Python
and Rust bindings — and every C module written against quickjs.h — keep working.
Status: M15 done (S1–S7). All 211 symbols the reference exports are exported here, plus the
11 js_* allocator entry points and JS_IsException (the header's static inline, exported
so Rust tests can take its address) — 223 in all. A real C class — Point, with an
opaque payload, magic accessors and a finalizer — compiles against the reference header and
links against this library, and
qjs -m loads fib.so/point.so/bjson.so with output byte-identical to the reference.
"All 223 exported" is not "all 223 behave identically": 194 are exact, 17 are partial and 12
are present and refuse, and each one says so in tests/symbols.rs — a
literal 223-row table of symbol plus a one-line verdict (yes, partly, no), with a test
that fails when a symbol is added without a row or a row outlives its symbol. The gaps are named and reasoned
below. The crate stays publish = false until S7's from-scratch embedding path is exercised
from C.
Why this is not a shim
quickjs.h ships 119 of its "functions" as static inline, and they run in the caller's
translation unit:
static inline void
Compiled C never asks the library how a JSValue is laid out — it decodes the bits and
writes through a raw pointer. So the boundary cannot be a conversion layer, and a handle
table (a JSValue that is really an index) segfaults on the first JS_DupValue. Two things
have to be bit-compatible:
| what it is | where | |
|---|---|---|
JSValue |
8 bytes, NaN-boxed: tag in bits 47..64, payload below | src/jsvalue.rs |
| reference counts | an int at payload - 4, written by the caller |
src/alloc.rs |
The parts
src/jsvalue.rs— tags,encode/decodeof the bit patterns, and the constructors. Pure integer arithmetic, nounsafe.tests/abi.rspins every constant against whatgccprinted for the same expression in the reference header.src/alloc.rs— the magic-header allocator. Every block is[u32 kind+size][i32 ref_count][payload], sopayload - 4is the count andpayloadis whatJS_VALUE_GET_PTRreturns.js_malloc/js_freeuse the same allocator as the value boxes, becausebjson.cfrees aJS_WriteObjectbuffer we allocated.src/convert.rs— engineValue⇄JsValue. Primitives map to bits; anything with a reference count is boxed with a count of one, and the lastJS_FreeValuedrops the box and with it the engine's handle. That is where a host class'sfinalizerruns.src/cdefs.rs— the C structs C fills in and we read (JSCFunctionListEntry,JSClassDef, the exotic traps), every offset asserted againstoffsetofon this platform.src/runtime.rs—JSRuntime/JSContext,JS_Eval, pending exceptions, and the thread-local that lets a C callback find the live interpreter it was called from.src/objects.rs— the object/property/function/class API.src/modules.rs—JS_NewCModuleand friends, and thedlopen/dlsymthat finds a.so'sjs_init_module.src/host.rs— the host session: publishes the running interpreter so a C function called from a script can reach the API.src/bjson.rs—JS_WriteObject/JS_ReadObject(a format of this crate's own; see the module docs for why that is legitimate) and theArrayBufferbridge.src/calls.rs— calls and construction, promises, jobs,instanceof, iterators.src/properties.rs,src/conversions.rs,src/atoms.rs— the property/coercion/atom families, which are the bulk of the surface a binding touches first.src/buffers.rs,src/builtins_typed.rs—ArrayBuffer, the views,JSON,SameValue/StrictEq, and theJSTypedArrayEnumtranslation.src/intrinsics.rs— the sixteenJS_AddIntrinsic*calls. A context here is born with every intrinsic installed, so they answer0;IntlandTemporalare the two the engine does not have and they answer-1rather than lying.src/module_api.rs—JS_LoadModule, the loader hooks, module private values and names,JS_DetectModule,JS_EvalThis,JS_WriteObject2.src/state.rs— limits (JS_SetMemoryLimit/JS_SetMaxStackSize/JS_SetGCThreshold), GC, opaque pointers, context values, memory reporting andJS_PrintValue.
The one test that matters for "all 223"
tests/symbols.rs opens with a literal table — one row per exported symbol, each row a
verdict (yes, partly, no) and one line of behaviour — and
every_reference_symbol_has_a_documented_behaviour reads the reference's own nm -D output
and fails when a row and a symbol disagree in either direction. scripts/verify-claims.py
re-checks the same three counts against README.md, so the published numbers cannot drift
from the table the way "56 of 211" did.
The re-entrancy channel
A C function installed by a module is called with nothing but a JSContext *, and the
engine is inside a call while it runs — it holds the &mut Interp that JS_ToInt32 has
to use. There is no second interpreter to hand out, so a callback reaches the live one
through a thread-local raw pointer that every entry point installs and every API function
reads. Miss that and the failure looks like a broken module: each API call answers an
exception with no message, because there is no current context to describe it.
Limitations
Twenty-nine symbols are exported so a binding links, and either refuse or do a documented subset rather than pretend. Grouped by why:
- Not in the engine at all —
JS_AddIntrinsicIntl,JS_SetLocaleCallbacks(noIntl, no locale database;toLocaleStringistoString),JS_AddIntrinsicTemporal(M13, unstarted),JS_SetSharedArrayBufferFunctions,JS_AtomicsSetAsyncWaker(no threads, so nothing waits),JS_SetHostPromiseRejectionTracker(the engine reports unhandled rejections itself),JS_SetIsHTMLDDA. - A representation this engine does not have —
JS_IsImmutableArrayBuffer(always0) andJS_SetImmutableArrayBuffer(-1),JS_NewUint8ArrayCopy2(refusesis_immutable),JS_NewRuntime2(a per-runtime C allocator would have to be threaded through the GC, so the default allocator is used),JS_GetImportMeta(undefined: a C module was never parsed),JS_ParseJSON3(parses, writes no source-position record). - Accepted and recorded, no observable effect —
JS_SetCanBlock,JS_SetStripInfo(debug info is never stripped),JS_SetRuntimeInfo,JS_UpdateStackTop(depth is measured in frames, not bytes),JS_MarkValue(reference counting, not tracing). - Partial by design, documented at the call site —
JS_NewArrayBuffer/JS_NewUint8Arraycopy the C block (so writes the host makes afterwards are invisible to script) thoughfree_funcnow runs at collection, as the header says;JS_SetInterruptHandleris polled at loop back-edges and calls, which is where the reference polls too;JS_NewContextRawisJS_NewContext(a context here is born with every intrinsic, so a host that adds them gets a superset);JS_ComputeMemoryUsagefills the fields it can account for and zeroes the rest;JS_PrintValuehonours all three limits but renders a class the engine's printer does not walk as its class name;JS_IsLiveObject/JS_IsCFunctionanswer for values the caller can legitimately hold;JS_ValueToAtomrefuses a symbol, whose atom would have to keep its symbolness;JS_WriteObject2always answers an empty shared-buffer table.
Checking it
--abi is the one that matters for the ABI: it compiles a C file against the reference
quickjs.h and links it against our library, so the header's inline constructors expand in
that translation unit and js_mallocz resolves from our .so. --exports is the one that
matters for a binding: a Go or Python binding links against whatever its cgo/cffi preamble
names, and the only honest proof that one can work is that our nm -D listing is a superset
of the reference's. Both are part of scripts/check.sh, and both skip loudly when the
reference build is absent.
--embed is the one that matters for an embedder: tests/c/embed.c
builds the runtime itself instead of running a script through qjs, and the script compiles it
twice — once against the reference's own object files, once against our .so — then compares
stdout and stderr byte for byte. Read that file if you are writing a binding; it is the
shortest complete host.
Embedding it
A Go/Python/Rust binding and this file are the same program shape. The whole thing, minus the
error handling tests/c/embed.c demonstrates:
int
Three rules that are not obvious from quickjs.h and that cost the most to discover:
JS_SetPropertyStrandJS_DefineProperty*consume the value's reference. Passing a value and thenJS_FreeValue-ing it yourself is a double free — it corrupts the heap and the crash lands somewhere else, often after the test suite has passed.- A
JSValuereturned by any API function is a new reference.JS_GetPropertyStr,JS_Eval,JS_GetException— all of them. The header'sstatic inlineJS_FreeValuedecrements the count in the caller's translation unit, so an engine that did not box exactly the way the header expects would corrupt memory on the first free. - A C function called from script may re-enter the API.
JS_ToInt32,JS_GetPropertyStrand friends all work inside a callback; they go through the interpreter the engine is already running. What does not work is callingJS_Evalfrom a callback and expecting a separate interpreter — it evaluates in the same global scope, on the same stack.
For an interrupt — "this script has run too long" — install the handler with
JS_SetInterruptHandler(rt, cb, opaque) then return non-zero from cb. It is polled every
10000 instructions and at every loop back-edge; the script fails with
InternalError: interrupted. Two differences from the reference, both visible: the error is
catchable here (the reference makes it uncatchable), and a catch around the call therefore
behaves differently. JS_SetUncatchableException is accepted and does nothing, which is
honest rather than silent: a pending exception is already past every script catch.