quickjs-capi 0.14.0

C ABI compatibility layer: the QuickJS C API on top of the pure-Rust engine
Documentation
/* A host that embeds libquickjs and never runs qjs.
 *
 * The three acceptance drivers (test_fib.js, test_point.js, test_bjson.js) are *scripts* run
 * by `qjs -m`: they prove the C API works when the CLI has already built the runtime, the
 * context and the module loader. They say nothing about the path a Go or Python binding takes,
 * which is "I have a `main`, I link `-lquickjs`, and I build the engine myself". This file is
 * that path, and it is compiled twice — once against the reference `quickjs.h` + reference
 * library, once against ours — with the output compared byte for byte.
 *
 * Every line printed is a decision a host makes, in the order a host makes it:
 *
 *   1. runtime and context, from nothing;
 *   2. a memory limit, and a script that must fail instead of taking the machine down;
 *   3. a stack limit, and a recursion that must fail instead of overflowing the C stack;
 *   4. an interrupt handler, and a loop that must stop when the host says so;
 *   5. a normal evaluation, with its completion value handed back;
 *   6. a C function installed from C, called from JavaScript, returning into C;
 *   7. a host class, constructed from JavaScript, read from C through its opaque payload;
 *   8. JSON parsed and stringified through the C API;
 *   9. teardown, in the order the header requires (context before runtime).
 *
 * The failures are printed as `name: message` rather than as a boolean so that a divergence
 * in *which* error is raised is visible, not just that one was. The reference's answers for
 * these four are `InternalError: out of memory`, `InternalError: stack overflow`,
 * `InternalError: interrupted` and `SyntaxError: ...`.
 *
 * Not covered, deliberately: promises and jobs (the three.js job queue belongs to a host with
 * an event loop, and `JS_ExecutePendingJob` is covered by tests/symbols.rs), and modules (a
 * C-side module loader is a different driver's job — see docs/m15-plan.md S7).
 *
 * Build (the script does this for both libraries):
 *
 *     cc -O1 -o embed embed.c -I<quickjs> -L<libdir> -lquickjs
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#include "quickjs.h"

static int failures;

static void check(int ok, const char *what)
{
    if (!ok) {
        printf("  FAIL %s\n", what);
        failures++;
    } else {
        printf("  ok   %s\n", what);
    }
}

/* The text of a pending exception, as `name: message`. The exception is consumed. */
static void describe_exception(JSContext *ctx, char *out, size_t n, JSValue v)
{
    if (!JS_IsException(v)) {
        snprintf(out, n, "no exception");
        return;
    }
    JSValue e = JS_GetException(ctx);
    JSValue name = JS_GetPropertyStr(ctx, e, "name");
    JSValue message = JS_GetPropertyStr(ctx, e, "message");
    const char *name_text = JS_ToCString(ctx, name);
    const char *message_text = JS_ToCString(ctx, message);
    snprintf(out, n, "%s: %s", name_text ? name_text : "?", message_text ? message_text : "?");
    JS_FreeCString(ctx, name_text);
    JS_FreeCString(ctx, message_text);
    JS_FreeValue(ctx, name);
    JS_FreeValue(ctx, message);
    JS_FreeValue(ctx, e);
}

/* Evaluate and print the completion value, or the exception. Answers 1 on success. */
static int run(JSContext *ctx, const char *what, const char *source)
{
    JSValue v = JS_Eval(ctx, source, strlen(source), "<embed>", JS_EVAL_TYPE_GLOBAL);
    char text[256];
    if (JS_IsException(v)) {
        describe_exception(ctx, text, sizeof text, v);
        printf("  %-8s threw %s\n", what, text);
        return 0;
    }
    const char *value = JS_ToCString(ctx, v);
    printf("  %-8s %s\n", what, value ? value : "?");
    JS_FreeCString(ctx, value);
    JS_FreeValue(ctx, v);
    return 1;
}

/* ------------------------------------------------------------------------- */
/* An interrupt handler that stops the second poll, not the first            */
/* ------------------------------------------------------------------------- */

static int polls;

static int interrupt_handler(JSRuntime *rt, void *opaque)
{
    (void)rt;
    (void)opaque;
    polls++;
    /* Counting polls rather than instructions means the driver does not depend on the poll
     * interval — a detail this library and the reference are allowed to differ on, and
     * documents as such (JS_INTERRUPT_COUNTER_INIT is the same 10000 on both). */
    return polls >= 2;
}

/* ------------------------------------------------------------------------- */
/* A C function installed from C                                             */
/* ------------------------------------------------------------------------- */

static JSValue multiply(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)
{
    (void)this_val;
    int a, b;
    if (argc < 2)
        return JS_ThrowTypeError(ctx, "multiply needs two arguments");
    if (JS_ToInt32(ctx, &a, argv[0]) < 0 || JS_ToInt32(ctx, &b, argv[1]) < 0)
        return JS_EXCEPTION;
    return JS_NewInt32(ctx, a * b);
}

/* ------------------------------------------------------------------------- */
/* A host class, so the payload round-trips through an opaque pointer        */
/* ------------------------------------------------------------------------- */

static JSClassID counter_class_id;

typedef struct {
    int value;
} Counter;

static void counter_finalizer(JSRuntime *rt, JSValue obj)
{
    Counter *c = JS_GetOpaque(obj, counter_class_id);
    if (c)
        js_free_rt(rt, c);
}

static JSValue counter_ctor(JSContext *ctx, JSValueConst new_target, int argc, JSValueConst *argv)
{
    JSValue obj, proto;
    Counter *c;
    int start = 0;

    if (argc > 0 && JS_ToInt32(ctx, &start, argv[0]) < 0)
        return JS_EXCEPTION;
    obj = JS_NewObjectClass(ctx, counter_class_id);
    if (JS_IsException(obj))
        return obj;
    c = js_mallocz(ctx, sizeof *c);
    if (!c) {
        JS_FreeValue(ctx, obj);
        return JS_EXCEPTION;
    }
    c->value = start;
    JS_SetOpaque(obj, c);
    proto = JS_GetPropertyStr(ctx, new_target, "prototype");
    if (JS_IsException(proto)) {
        JS_FreeValue(ctx, obj);
        return JS_EXCEPTION;
    }
    JS_SetPrototype(ctx, obj, proto);
    JS_FreeValue(ctx, proto);
    return obj;
}

static JSValue counter_bump(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv)
{
    Counter *c = JS_GetOpaque2(ctx, this_val, counter_class_id);
    int by = 1;
    if (!c)
        return JS_EXCEPTION;
    if (argc > 0 && JS_ToInt32(ctx, &by, argv[0]) < 0)
        return JS_EXCEPTION;
    c->value += by;
    return JS_NewInt32(ctx, c->value);
}

int main(void)
{
    JSRuntime *rt;
    JSContext *ctx;
    JSValue global, fn, instance, result;
    char text[256];

    /* Line-buffered: a host that integrates an embedder usually wants its transcript to
     * survive a crash, and every `check` below is a line. */
    setvbuf(stdout, NULL, _IOLBF, 0);

    printf("1. runtime and context\n");
    rt = JS_NewRuntime();
    check(rt != NULL, "JS_NewRuntime");
    ctx = JS_NewContext(rt);
    check(ctx != NULL, "JS_NewContext");
    if (!rt || !ctx)
        return 1;

    /* A host that installs nothing still gets the intrinsics: a context is born with them. */
    check(run(ctx, "intr", "typeof Object + ' ' + typeof JSON + ' ' + typeof Promise"), "a raw context has the intrinsics");

    printf("2. memory limit\n");
    /* 8 MiB is enough for the engine and not enough for the script below, which asks for
     * 64 MiB in one allocation. The reference fails in js_malloc; this library fails at its
     * per-instruction checkpoint. Both produce InternalError: out of memory. */
    JS_SetMemoryLimit(rt, 8 * 1024 * 1024);
    if (run(ctx, "limit", "try { new Array(64 << 20).fill(0).length } catch (e) { throw e }") == 0)
        check(1, "the allocation limit stops the script");
    /* `(size_t)-1` removes the limit, and `0` does *not*: the reference's limit is a size_t
     * whose "unlimited" value is -1, so a limit of 0 refuses every allocation. Getting that
     * backwards makes the rest of this program fail, which is how it was found. */
    JS_SetMemoryLimit(rt, (size_t)-1);

    printf("3. stack limit\n");
    JS_SetMaxStackSize(rt, 256 * 1024);
    {
        JSValue v = JS_Eval(ctx,
                            "(function depth(n){ try { return depth(n + 1); } "
                            "catch (e) { return n; } })(0)",
                            strlen("(function depth(n){ try { return depth(n + 1); } "
                                   "catch (e) { return n; } })(0)"),
                            "<embed>", JS_EVAL_TYPE_GLOBAL);
        /* The exact depth depends on how much stack each implementation spends per frame,
         * which the two documents as different (a C frame vs a heap frame). So this asserts
         * the *shape*: it stopped, and it stopped after reaching a real depth. */
        double depth = 0;
        JS_ToFloat64(ctx, &depth, v);
        check(!JS_IsException(v) && depth > 100, "deep recursion stops instead of crashing");
        JS_FreeValue(ctx, v);
    }
    /* ... and an unbounded one reports the error a script can see. The reference makes this
     * uncatchable *only* for an interrupt; a stack overflow is catchable. */
    {
        JSValue v = JS_Eval(ctx, "function f(){ return f() } f()",
                            strlen("function f(){ return f() } f()"), "<embed>",
                            JS_EVAL_TYPE_GLOBAL);
        describe_exception(ctx, text, sizeof text, v);
        printf("  %-8s threw %s\n", "overflow", text);
        check(strstr(text, "stack overflow") != NULL, "stack overflow is InternalError");
    }
    JS_SetMaxStackSize(rt, 0);

    printf("4. interrupt\n");
    polls = 0;
    JS_SetInterruptHandler(rt, interrupt_handler, NULL);
    {
        JSValue v = JS_Eval(ctx, "for(;;){}", strlen("for(;;){}"), "<embed>",
                            JS_EVAL_TYPE_GLOBAL);
        describe_exception(ctx, text, sizeof text, v);
        printf("  %-8s threw %s (%d poll(s))\n", "loop", text, polls);
        check(strstr(text, "interrupted") != NULL, "a runaway loop is interrupted");
    }
    JS_SetInterruptHandler(rt, NULL, NULL);
    /* With the handler gone the same shape of loop must run to completion. */
    check(run(ctx, "loop", "var n = 0; for (var i = 0; i < 100000; i++) n++; n"),
          "a loop finishes when no handler is installed");

    printf("5. globals and properties\n");
    global = JS_GetGlobalObject(ctx);
    fn = JS_NewCFunction(ctx, multiply, "multiply", 2);
    JS_SetPropertyStr(ctx, global, "multiply", fn); /* consumes fn */
    JS_FreeValue(ctx, global);
    check(run(ctx, "call", "multiply(6, 7)"), "a C function installed from C is callable");

    printf("6. a host class\n");
    JS_NewClassID(&counter_class_id);
    {
        JSClassDef def = { "Counter", .finalizer = counter_finalizer };
        check(JS_NewClass(rt, counter_class_id, &def) == 0, "JS_NewClass");
    }
    {
        JSValue proto = JS_NewObject(ctx);
        JS_SetPropertyStr(ctx, proto, "bump",
                          JS_NewCFunction(ctx, counter_bump, "bump", 1));
        JS_SetClassProto(ctx, counter_class_id, proto); /* consumes proto */
    }
    global = JS_GetGlobalObject(ctx);
    {
        JSValue ctor = JS_NewCFunction2(ctx, counter_ctor, "Counter", 1,
                                        JS_CFUNC_constructor, 0);
        JSValue proto = JS_GetClassProto(ctx, counter_class_id);
        JS_SetPropertyStr(ctx, ctor, "prototype", proto); /* consumes proto */
        JS_SetPropertyStr(ctx, global, "Counter", ctor);
    }
    JS_FreeValue(ctx, global);
    instance = JS_Eval(ctx, "var c = new Counter(10); c.bump(5)",
                       strlen("var c = new Counter(10); c.bump(5)"), "<embed>",
                       JS_EVAL_TYPE_GLOBAL);
    {
        const char *bumped = JS_ToCString(ctx, instance);
        printf("  %-8s %s\n", "class", bumped ? bumped : "?");
        JS_FreeCString(ctx, bumped);
        JS_FreeValue(ctx, instance);
    }
    /* Read the payload back from C: this is the round trip a binding's object wrapper needs,
     * and the only thing that proves the opaque pointer and the finalizer agree. */
    global = JS_GetGlobalObject(ctx);
    {
        JSValue c = JS_GetPropertyStr(ctx, global, "c");
        Counter *payload = JS_GetOpaque(c, counter_class_id);
        check(payload != NULL && payload->value == 15, "the opaque payload round-trips");
        JS_FreeValue(ctx, c);
    }
    JS_FreeValue(ctx, global);

    printf("7. JSON\n");
    {
        const char *json = "{\"a\":[1,2,{\"b\":null}],\"c\":\"text\"}";
        JSValue parsed = JS_ParseJSON(ctx, json, strlen(json), "<embed>");
        check(!JS_IsException(parsed), "JS_ParseJSON");
        {
            JSValue stringified = JS_JSONStringify(ctx, parsed, JS_UNDEFINED, JS_UNDEFINED);
            const char *again = JS_ToCString(ctx, stringified);
            check(again != NULL && strcmp(again, json) == 0, "round trips through the C API");
            JS_FreeCString(ctx, again);
            JS_FreeValue(ctx, stringified);
        }
        JS_FreeValue(ctx, parsed);
    }

    printf("8. memory report\n");
    {
        JSMemoryUsage usage;
        memset(&usage, 0, sizeof usage);
        JS_ComputeMemoryUsage(rt, &usage);
        /* Only the two fields both implementations can answer are asserted, and they are
         * asserted as a shape rather than a number: the exact counts differ by design. */
        check(usage.obj_count > 0, "obj_count is populated");
        check(usage.atom_count > 0, "atom_count is populated");
    }

    printf("9. teardown\n");
    result = JS_Eval(ctx, "c.bump()", strlen("c.bump()"), "<embed>", JS_EVAL_TYPE_GLOBAL);
    JS_FreeValue(ctx, result); /* the instance is still reachable from the global */
    JS_FreeContext(ctx);
    JS_RunGC(rt);
    JS_FreeRuntime(rt);
    check(1, "context and runtime freed in the header's order");

    printf(failures ? "embed: %d failure(s)\n" : "embed: %d failure(s)\n", failures);
    return failures ? 1 : 0;
}