quickjs-capi 0.13.0

C ABI compatibility layer: the QuickJS C API on top of the pure-Rust engine
Documentation
//! The bridge: engine [`Value`] ⇄ C [`JsValue`].
//!
//! Two directions, both total for the values that can cross the boundary:
//!
//! * [`encode`] never fails. Primitives become their bit pattern; anything with a
//!   reference count is boxed (see [`crate::alloc`]), because C will eventually decrement
//!   the count through a pointer it only knows because we allocated one.
//! * [`decode`] answers `None` for a tag the engine has no value for — an internal tag the
//!   reference uses for its own containers (`JS_TAG_FUNCTION_BYTECODE`, `JS_TAG_MODULE`)
//!   or a `JS_TAG_SHORT_BIG_INT`, which this engine does not produce because a `BigInt`
//!   here is always a heap allocation.
//!
//! # What is deliberately not here
//!
//! The engine's internal markers (`CatchOffset`, `ReturnAddress`, `Hole`, `Uninitialized`)
//! never cross this boundary in either direction: they live on the operand stack and in
//! object slots, and a host never sees one. [`encode`] maps the two that have a spelling in
//! C (`Uninitialized` is `JS_UNINITIALIZED`) and treats the rest as a programming error
//! rather than inventing a tag.

use engine::Value;

use crate::alloc;
use crate::jsvalue::{self, JsValue};

/// Engine value → C value.
///
/// # The box, and who owns it
///
/// A reference-counted value is boxed with a count of one. That count *is* the answer's
/// ownership: the caller owns the single reference, `JS_DupValue` makes more of them, and
/// the last `JS_FreeValue` drops the box and with it the engine's handle. Boxes are not
/// shared between calls — two `encode`s of the same object give two boxes — which is
/// invisible to C for values, and observable only through `JS_VALUE_GET_PTR` equality,
/// which the C API uses for object identity. That identity is S3's interning table; until
/// then two encodings of one object are two pointers.
pub fn encode(value: &Value) -> JsValue {
    match value {
        Value::Undefined => jsvalue::UNDEFINED,
        Value::Null => jsvalue::NULL,
        Value::Bool(flag) => jsvalue::new_bool(*flag),
        Value::Int(number) => jsvalue::new_int32(*number),
        Value::Float(number) => jsvalue::new_float64(*number),
        Value::Uninitialized => jsvalue::UNINITIALIZED,
        // Everything below owns a heap allocation, so it needs a reference count C can
        // write through. `Hole` is an array's hole marker: it never comes out of a
        // property read (`undefined` does), and boxing it would hand C a value with no
        // meaning in the C API.
        Value::String(_) | Value::Object(_) | Value::Symbol(_) | Value::BigInt(_) => {
            alloc::box_value(value.clone())
        }
        // Operand-stack markers. A value that reaches here is a bug in the caller, and a
        // debug assertion is the loudest available answer: the alternative is inventing a
        // tag for something no C program can interpret.
        Value::CatchOffset(_) | Value::ReturnAddress(_) | Value::Hole => {
            debug_assert!(false, "an engine-internal marker cannot cross the C ABI");
            jsvalue::UNDEFINED
        }
    }
}

/// C value → engine value.
///
/// `None` means the tag names nothing this engine can produce. It is not an error path for
/// well-behaved callers: a `JSValue` from a host is always one of ours.
///
/// # Safety
///
/// A reference-counted `value` must be a live box from this crate whose count is at least
/// one — the returned [`Value`] is a *clone* whose handle keeps the payload alive on its
/// own, but reading the box at all requires it to exist.
pub unsafe fn decode(value: JsValue) -> Option<Value> {
    match value.norm_tag() {
        jsvalue::TAG_UNDEFINED => Some(Value::Undefined),
        jsvalue::TAG_NULL => Some(Value::Null),
        jsvalue::TAG_BOOL => Some(Value::Bool(value.to_bool())),
        jsvalue::TAG_INT => Some(Value::Int(value.to_int())),
        jsvalue::TAG_FLOAT64 => Some(Value::Float(value.to_float())),
        jsvalue::TAG_UNINITIALIZED => Some(Value::Uninitialized),
        // `TAG_EXCEPTION` is not a value: it is the marker `JS_IsException` tests, and
        // decoding it into anything would let a caller store it in an object.
        tag if jsvalue::is_engine_tag(tag) => {
            let payload = value.as_ptr()?;
            // SAFETY: the caller guarantees the payload is a live box.
            Some(unsafe { alloc::value_of(payload) })
        }
        _ => None,
    }
}

/// Whether a C value is one this layer produced.
///
/// Cheap enough to call on every incoming argument, and the answer to "is this a
/// `JSValue` from a foreign implementation", which mixing two `libquickjs`s would produce.
pub fn is_ours(value: JsValue) -> bool {
    match value.norm_tag() {
        jsvalue::TAG_UNDEFINED
        | jsvalue::TAG_NULL
        | jsvalue::TAG_BOOL
        | jsvalue::TAG_INT
        | jsvalue::TAG_FLOAT64
        | jsvalue::TAG_UNINITIALIZED
        | jsvalue::TAG_EXCEPTION => true,
        tag => jsvalue::is_engine_tag(tag),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn primitives_round_trip_without_a_box() {
        for value in [
            Value::Undefined,
            Value::Null,
            Value::Bool(true),
            Value::Bool(false),
            Value::Int(0),
            Value::Int(-7),
            Value::Float(1.5),
            Value::Float(-0.0),
        ] {
            let encoded = encode(&value);
            assert!(!encoded.has_ref_count(), "{value:?} needed a box");
            // SAFETY: no reference count means no box to read.
            let decoded = unsafe { decode(encoded) }.expect("a primitive decodes");
            // `Value` has no `PartialEq` on purpose (a `Gc` handle compares by identity,
            // not by contents); `same_value` is the language's own equality.
            assert!(decoded.same_value(&value), "{value:?} round-tripped wrong");
        }
    }

    #[test]
    fn uninitiailised_has_a_tag_of_its_own() {
        let encoded = encode(&Value::Uninitialized);
        assert_eq!(encoded.norm_tag(), jsvalue::TAG_UNINITIALIZED);
        // SAFETY: no reference count.
        assert!(matches!(
            unsafe { decode(encoded) },
            Some(Value::Uninitialized)
        ));
    }

    #[test]
    fn a_boxed_string_round_trips() {
        let runtime = engine::Runtime::new();
        let mut ctx = engine::Context::new(&runtime);
        let string = ctx.new_string("boxed");
        let encoded = encode(&string);
        assert!(encoded.has_ref_count(), "a string needs a count for C");
        assert_eq!(
            encoded.norm_tag(),
            jsvalue::TAG_STRING,
            "JS_IsString reads the tag"
        );
        // SAFETY: `encoded` is a live box with a count of one.
        let decoded = unsafe { decode(encoded) }.expect("a box decodes");
        assert!(decoded.same_value(&string), "the string survived the box");
        // SAFETY: the count is still one, so this is the only reference.
        unsafe { crate::alloc::free_value(encoded.as_ptr().unwrap()) };
    }

    #[test]
    fn a_boxed_object_round_trips_and_keeps_the_engine_handle() {
        let runtime = engine::Runtime::new();
        let mut ctx = engine::Context::new(&runtime);
        let object = ctx.new_object();
        let engine::Value::Object(handle) = &object else {
            panic!("new_object must answer an object");
        };
        let before = handle.strong_count();

        let encoded = encode(&object);
        assert_eq!(encoded.norm_tag(), jsvalue::TAG_OBJECT);
        assert_eq!(
            handle.strong_count(),
            before + 1,
            "the box holds a reference"
        );

        // SAFETY: the box is live and this is its only reference.
        unsafe { crate::alloc::free_value(encoded.as_ptr().unwrap()) };
        assert_eq!(handle.strong_count(), before, "freeing the box released it");
    }

    #[test]
    fn an_exception_is_not_a_decodable_value() {
        // `JS_EXCEPTION` is a marker, not a value: `JS_IsException` tests the bits, and
        // nothing may store it in an object.
        // SAFETY: no reference count.
        assert!(unsafe { decode(jsvalue::EXCEPTION) }.is_none());
        assert!(is_ours(jsvalue::EXCEPTION));
    }

    #[test]
    fn foreign_tags_are_not_ours() {
        // The reference's own containers: a string rope and a bytecode object. Neither has
        // a spelling in this engine, so a value carrying one did not come from here.
        assert!(!is_ours(jsvalue::JsValue::mkval(
            jsvalue::TAG_STRING_ROPE,
            0
        )));
        assert!(!is_ours(jsvalue::JsValue::mkval(
            jsvalue::TAG_FUNCTION_BYTECODE,
            0
        )));
        assert!(!is_ours(jsvalue::JsValue::mkval(jsvalue::TAG_MODULE, 0)));
    }

    #[test]
    fn a_nan_is_a_double_like_any_other() {
        // `JS_NAN` is not a foreign tag: it is the canonical NaN, and `JS_IsNumber` is
        // true for it. `is_ours` has to agree, or every `NaN` a script passes back would
        // look like another implementation's value.
        let nan = JsValue::new(jsvalue::NAN);
        assert!(is_ours(nan));
        assert!(nan.is_number());
        // SAFETY: no reference count.
        let decoded = unsafe { decode(nan) }.expect("NaN decodes");
        assert!(matches!(decoded, Value::Float(number) if number.is_nan()));
    }
}