quickjs-pure 0.14.4

Embeddable JavaScript engine written in pure Rust (QuickJS-compatible)
Documentation
//! The memory report: `qjs -d` / `JS_ComputeMemoryUsage`.
//!
//! The numbers have to be **right**, not merely present. A report that says "571 objects"
//! because it counted boxes is a report nobody can act on, and the shape of this feature's
//! history is exactly that risk: the flag was parsed and dropped for the whole life of the
//! CLI (`docs/test262-status.md` §4.37), so the first version of it has to come with
//! assertions that fail when a counter is off by one — not with a screenshot.

fn context<'rt>(runtime: &'rt quickjs::Runtime) -> quickjs::Context<'rt> {
    quickjs::Context::new(runtime)
}

/// Run `source` and hand back the measurement taken before and after.
fn measure(source: &str) -> (quickjs::MemoryUsage, quickjs::MemoryUsage) {
    let rt = quickjs::Runtime::new();
    let mut ctx = context(&rt);
    let (before, _) = ctx.memory_usage();
    ctx.eval(source)
        .unwrap_or_else(|error| panic!("{source:?} failed: {error}"));
    let (after, _) = ctx.memory_usage();
    (before, after)
}

/// Two objects and three properties: the delta has to be exactly that.
///
/// This is the assertion that matters. A counter that is off by one, or one that counts
/// property *slots* where the rest of the world counts properties, fails here and nowhere
/// else.
///
/// `let` rather than `var`, and the reason is worth knowing: a top-level `var` in a *script*
/// becomes a property of the global object, so `var a = {}; var b = {}` reports five
/// properties where three were written on purpose. That is not a bug in the report — it is
/// the language — and the next test pins it down so this one can stay exact.
#[test]
fn objects_and_properties_are_counted_exactly() {
    let (before, after) = measure("let a = {}; let b = {}; a.x = 1; a.y = 2; b.z = 3;");
    assert_eq!(
        after.obj_count - before.obj_count,
        2,
        "two objects were created; report says {}",
        after.obj_count - before.obj_count
    );
    assert_eq!(
        after.prop_count - before.prop_count,
        3,
        "three properties were defined; report says {}",
        after.prop_count - before.prop_count
    );
}

/// A top-level `var` is a global object property; a top-level `let` is not.
///
/// Encoded as a test because it is the two-property difference that made the assertion above
/// fail at first, and "the report is off by two" is a much more alarming symptom than "the
/// language is doing what it says". If this ever stops holding, the report is not what
/// changed.
#[test]
fn a_top_level_var_is_a_global_property() {
    let (before, with_var) = measure("var only_var = 1;");
    let (_, with_let) = measure("let only_let = 1;");
    assert_eq!(
        with_var.prop_count - before.prop_count,
        1,
        "`var` in a script defines a property on the global object"
    );
    assert_eq!(
        with_let.prop_count - before.prop_count,
        0,
        "`let` in a script defines a lexical binding, which is not an object property"
    );
}

/// An array's elements are elements, not properties.
///
/// The two live in different places in this engine (`ObjectKind::Array`'s vector versus the
/// property table), and `Array.prototype.push` grows the first without touching the second.
/// Counting elements as properties is the mistake this catches.
#[test]
fn array_elements_are_not_properties() {
    let (before, after) = measure("let a = [1, 2, 3];");
    assert_eq!(after.array_count - before.array_count, 1);
    assert_eq!(after.fast_array_count - before.fast_array_count, 1);
    assert_eq!(
        after.fast_array_elements - before.fast_array_elements,
        3,
        "three elements were stored; report says {}",
        after.fast_array_elements - before.fast_array_elements
    );
    // `length` is not stored in the property table for a dense array, so the only property
    // growth is whatever the eval itself created.
    assert_eq!(
        after.prop_count - before.prop_count,
        0,
        "a dense array's elements must not appear as properties"
    );
}

/// A string that is never interned is still a string, and its bytes are its bytes.
#[test]
fn strings_are_counted_with_their_bytes() {
    let (before, after) = measure("var s = '0123456789';");
    assert_eq!(after.str_count - before.str_count, 1);
    let grew = after.str_size - before.str_size;
    assert!(
        grew >= 10,
        "a ten-character string must add at least ten bytes, added {grew}"
    );
}

/// A function compiled from source is a bytecode function; a builtin is a C function.
///
/// Getting these two the wrong way round is easy — both are `ObjectKind::Function` — and the
/// report would silently say "0 bytecode functions" for a program full of them.
#[test]
fn bytecode_and_native_functions_are_told_apart() {
    let (before, after) = measure("function f(a, b) { return a + b; } f(1, 2);");
    assert_eq!(
        after.js_func_count - before.js_func_count,
        1,
        "one function was compiled; report says {}",
        after.js_func_count - before.js_func_count
    );
    assert!(after.js_func_code_size > before.js_func_code_size);
    // The realm's builtins are already there before the script runs, so the *delta* is what
    // is asserted: a script must not be credited with inventing them.
    assert_eq!(
        after.c_func_count, before.c_func_count,
        "a script that defines a function must not create C functions"
    );
    assert!(
        after.c_func_count > 100,
        "the realm has hundreds of builtins; report says {}",
        after.c_func_count
    );
}

/// An `ArrayBuffer`'s bytes are counted once, on the buffer.
///
/// Views own nothing in this engine — the bytes live behind the buffer — so counting a
/// `TypedArray`'s length *again* would double every byte of every binary program. The report
/// has to agree with the heap's own accounting, so this asserts the exact byte delta.
#[test]
fn a_buffers_bytes_are_counted_once() {
    let (before, after) = measure("var b = new ArrayBuffer(1024); var v = new Uint8Array(b);");
    assert_eq!(
        after.binary_object_count - before.binary_object_count,
        2,
        "the buffer and its view are two binary objects"
    );
    assert_eq!(
        after.binary_object_size - before.binary_object_size,
        1024,
        "only the buffer owns bytes; the view must add nothing"
    );
}

/// The rows have to add up to the total they are part of.
///
/// This is the assertion that caught the first version: it reported a `properties` row of
/// 248 KB inside a `memory allocated` total of 270 KB, because the heap's own accounting
/// deliberately excludes the property vector (see `impl Trace for JsObject` — reporting a
/// payload whose growth nothing charges for would subtract it twice at free time). The rows
/// are what a reader uses to decide where the memory went, so a row larger than its own
/// total is not a rounding difference, it is a broken table.
#[test]
fn the_rows_add_up_to_the_total() {
    let rt = quickjs::Runtime::new();
    let mut ctx = context(&rt);
    ctx.eval("let o = { a: 1, b: 2 }; let v = [1, 2, 3]; let s = 'x'.repeat(100);")
        .unwrap();
    let (usage, _) = ctx.memory_usage();

    assert!(
        usage.malloc_size >= usage.prop_size + usage.obj_size,
        "objects ({}) plus their property tables ({}) cannot exceed the total ({})",
        usage.obj_size,
        usage.prop_size,
        usage.malloc_size
    );
    // Every categorised row, summed, has to fit in the total too. The gap is what no row
    // claims: box headers, captured bindings, closure environments — real bytes with no
    // category, which is the state this engine's object model is actually in.
    let named = usage.obj_size
        + usage.prop_size
        + usage.str_size
        + usage.js_func_size
        + usage.js_func_code_size
        + usage.binary_object_size;
    assert!(
        named <= usage.malloc_size,
        "categorised rows sum to {named}, more than the total {}",
        usage.malloc_size
    );
    assert!(
        named * 4 > usage.malloc_size,
        "the rows should name most of the footprint: {named} of {}",
        usage.malloc_size
    );
}

/// The rendered report is the reference's table shape, and it says what it cannot measure.
///
/// The rows are compared by name rather than by number because the numbers are this engine's;
/// the *shape* is what a reader diffing against `qjs -d` needs, and the trailing note is what
/// stops a missing row from reading as a zero.
#[test]
fn the_report_has_the_reference_shape() {
    let rt = quickjs::Runtime::new();
    let mut ctx = context(&rt);
    ctx.eval("var a = [1, 2, 3], o = { p: 1 };").unwrap();
    let report = ctx.dump_memory_usage();

    assert!(
        report.starts_with("QuickJS memory usage -- "),
        "the header line is what a side-by-side diff aligns on:\n{report}"
    );
    assert!(report.contains(", 64-bit, malloc limit: -1"));
    assert!(report.contains("JSObject classes"));
    assert!(report.contains("NAME                    COUNT     SIZE"));
    for row in [
        "memory allocated",
        "strings",
        "objects",
        "  properties",
        "  shapes",
        "bytecode functions",
        "  bytecode",
        "C functions",
        "arrays",
        "  fast arrays",
        "  elements",
    ] {
        assert!(
            report.contains(row),
            "the report is missing the `{row}` row:\n{report}"
        );
    }
    assert!(
        report.contains("not accounted for by this engine"),
        "a row this engine does not have must be named, not silently absent:\n{report}"
    );
}

/// `--memory-limit` shows up in the header, because that is the number the report is judged
/// against.
#[test]
fn the_header_reports_the_memory_limit() {
    let mut rt = quickjs::Runtime::new();
    rt.set_memory_limit(Some(64 * 1024 * 1024));
    let mut ctx = context(&rt);
    let report = ctx.dump_memory_usage();
    assert!(
        report.contains("malloc limit: 67108864"),
        "the limit has to reach the header:\n{report}"
    );
}

/// A limit of zero is a limit, not the absence of one.
///
/// The reference's field is a `size_t` initialised to `-1`, so "unlimited" and "zero bytes"
/// are different values — and `JS_SetMemoryLimit(rt, 0)` means the latter
/// (`docs/m15-plan.md`). A renderer that reads 0 as "no limit" would print `-1` for the one
/// setting that refuses every allocation.
#[test]
fn a_zero_limit_is_not_an_absent_limit() {
    let mut rt = quickjs::Runtime::new();
    rt.set_memory_limit(Some(0));
    // Measured on the empty heap rather than through a context, because a realm cannot be
    // built under a zero-byte limit at all — `InternalError: out of memory` from the first
    // builtin installed. That refusal is the semantics the field has to report.
    let (usage, census) = quickjs::memory::compute(rt.heap());
    assert_eq!(usage.malloc_limit, 0);
    let report = quickjs::memory::dump(&usage, &census);
    assert!(
        report.contains(", malloc limit: 0\n"),
        "zero means zero, not -1:\n{report}"
    );
}