use core::ffi::{CStr, c_char, c_int, c_void};
use quickjs::cdefs::{
FunctionEntry, FunctionListUnion, JS_DEF_CFUNC, JS_DEF_CGETSET_MAGIC, JSCFunctionListEntry,
JSClassDef,
};
use quickjs::jsvalue::{EXCEPTION, JsValue, TAG_BOOL, TAG_EXCEPTION, TAG_INT, UNDEFINED};
use quickjs::runtime::{JsContext, JsRuntime};
struct Engine {
runtime: *mut JsRuntime,
context: *mut JsContext,
}
impl Engine {
fn new() -> Engine {
unsafe {
let runtime = quickjs::runtime::JS_NewRuntime();
assert!(!runtime.is_null());
let context = quickjs::runtime::JS_NewContext(runtime);
assert!(!context.is_null());
Engine { runtime, context }
}
}
fn eval(&self, source: &str) -> JsValue {
let mut text = source.as_bytes().to_vec();
text.push(0);
let name = b"<test>\0";
unsafe {
quickjs::runtime::JS_Eval(
self.context,
text.as_ptr().cast(),
source.len(),
name.as_ptr().cast(),
c_int::from(0),
)
}
}
fn eval_number(&self, source: &str) -> f64 {
let value = self.eval(source);
assert!(!value.is_exception(), "{source} threw");
if value.norm_tag() == TAG_INT {
return f64::from(value.to_int());
}
let number = value.to_float();
unsafe { quickjs::runtime::release(value) };
number
}
fn pending_text(&self) -> String {
unsafe {
let exception = quickjs::runtime::JS_GetException(self.context);
assert!(!exception.is_null(), "no pending exception");
let text = to_string(self.context, exception);
quickjs::runtime::release(exception);
text
}
}
}
impl Drop for Engine {
fn drop(&mut self) {
unsafe {
quickjs::runtime::JS_FreeContext(self.context);
quickjs::runtime::JS_FreeRuntime(self.runtime);
}
}
}
fn to_string(context: *mut JsContext, value: JsValue) -> String {
unsafe {
let context_ref = &*context;
let mut answer = String::new();
context_ref.with_interp(|interp| {
if let Some(value) = quickjs::convert::decode(value) {
answer = interp.to_js_string(&value).unwrap_or_default();
}
});
answer
}
}
#[repr(C)]
struct PointData {
x: i32,
y: i32,
}
static POINT_CLASS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
static SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());
fn serial() -> std::sync::MutexGuard<'static, ()> {
SERIAL.lock().unwrap_or_else(|poison| poison.into_inner())
}
fn point_class() -> u32 {
POINT_CLASS.load(std::sync::atomic::Ordering::SeqCst)
}
static FINALIZED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
unsafe extern "C" fn point_finalizer(_rt: *mut c_void, value: JsValue) {
let class = POINT_CLASS.load(std::sync::atomic::Ordering::SeqCst);
let pointer = unsafe { quickjs::objects::JS_GetOpaque(value, class) };
if pointer.is_null() {
return;
}
FINALIZED.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
unsafe { quickjs::js_free_rt(std::ptr::null_mut(), pointer) };
}
unsafe extern "C" fn point_ctor(
ctx: *mut JsContext,
new_target: JsValue,
argc: c_int,
argv: *const JsValue,
) -> JsValue {
unsafe {
let payload =
quickjs::js_mallocz(ctx, core::mem::size_of::<PointData>()).cast::<PointData>();
if payload.is_null() {
return EXCEPTION;
}
let first = *argv;
let second = if argc > 1 { *argv.add(1) } else { UNDEFINED };
if quickjs::conversions::JS_ToInt32(ctx, &raw mut (*payload).x, first) < 0 {
quickjs::js_free(ctx, payload.cast());
return EXCEPTION;
}
if quickjs::conversions::JS_ToInt32(ctx, &raw mut (*payload).y, second) < 0 {
quickjs::js_free(ctx, payload.cast());
return EXCEPTION;
}
let proto = quickjs::objects::JS_GetPropertyStr(ctx, new_target, c"prototype".as_ptr());
if proto.is_exception() {
quickjs::js_free(ctx, payload.cast());
return EXCEPTION;
}
let object = quickjs::objects::JS_NewObjectProtoClass(ctx, proto, point_class());
quickjs::runtime::release(proto);
if object.is_exception() {
quickjs::js_free(ctx, payload.cast());
return EXCEPTION;
}
quickjs::objects::JS_SetOpaque(object, payload.cast());
object
}
}
unsafe extern "C" fn point_get(ctx: *mut JsContext, this: JsValue, magic: c_int) -> JsValue {
unsafe {
let payload = quickjs::objects::JS_GetOpaque2(ctx, this, point_class()).cast::<PointData>();
if payload.is_null() {
return EXCEPTION;
}
let number = if magic == 0 {
(*payload).x
} else {
(*payload).y
};
quickjs::convert::encode(&engine::Value::Int(number))
}
}
unsafe extern "C" fn point_set(
ctx: *mut JsContext,
this: JsValue,
value: JsValue,
magic: c_int,
) -> JsValue {
unsafe {
let payload = quickjs::objects::JS_GetOpaque2(ctx, this, point_class()).cast::<PointData>();
if payload.is_null() {
return EXCEPTION;
}
let mut number: i32 = 0;
if quickjs::conversions::JS_ToInt32(ctx, &mut number, value) < 0 {
return EXCEPTION;
}
if magic == 0 {
(*payload).x = number;
} else {
(*payload).y = number;
}
UNDEFINED
}
}
unsafe extern "C" fn point_norm(
_ctx: *mut JsContext,
this: JsValue,
_argc: c_int,
_argv: *const JsValue,
) -> JsValue {
unsafe {
let payload = quickjs::objects::JS_GetOpaque(this, point_class()).cast::<PointData>();
if payload.is_null() {
return EXCEPTION;
}
let (x, y) = (f64::from((*payload).x), f64::from((*payload).y));
quickjs::convert::encode(&engine::Value::Float((x * x + y * y).sqrt()))
}
}
fn point_table() -> Vec<JSCFunctionListEntry> {
let cgetset = |name: &'static CStr, magic: i16| JSCFunctionListEntry {
name: name.as_ptr(),
prop_flags: quickjs::cdefs::prop::CONFIGURABLE,
def_type: JS_DEF_CGETSET_MAGIC,
magic,
_padding: [0; 4],
u: FunctionListUnion {
getset: core::mem::ManuallyDrop::new(quickjs::cdefs::GetSetEntry {
get: quickjs::cdefs::JSCFunctionType {
pointer: point_get as *const c_void,
},
set: quickjs::cdefs::JSCFunctionType {
pointer: point_set as *const c_void,
},
}),
},
};
vec![
cgetset(c"x", 0),
cgetset(c"y", 1),
JSCFunctionListEntry {
name: c"norm".as_ptr(),
prop_flags: quickjs::cdefs::prop::WRITABLE | quickjs::cdefs::prop::CONFIGURABLE,
def_type: JS_DEF_CFUNC,
magic: 0,
_padding: [0; 4],
u: FunctionListUnion {
func: core::mem::ManuallyDrop::new(FunctionEntry {
length: 0,
cproto: quickjs::cdefs::CFunctionEnum::Generic as u8,
_padding: [0; 6],
cfunc: quickjs::cdefs::JSCFunctionType {
pointer: point_norm as *const c_void,
},
}),
},
},
]
}
fn install_point(engine: &Engine) {
let table = point_table();
unsafe {
let context = engine.context;
let runtime = quickjs::objects::JS_GetRuntime(context);
assert!(!runtime.is_null(), "JS_GetRuntime answered null");
let mut id = 0u32;
quickjs::objects::JS_NewClassID(&raw mut id);
POINT_CLASS.store(id, std::sync::atomic::Ordering::SeqCst);
assert_ne!(id, 0, "JS_NewClassID answered an invalid id");
let definition = JSClassDef {
class_name: c"Point".as_ptr(),
finalizer: Some(point_finalizer),
gc_mark: None,
call: None,
exotic: std::ptr::null(),
};
assert_eq!(
quickjs::objects::JS_NewClass(runtime, id, &definition),
0,
"JS_NewClass failed"
);
assert_eq!(
quickjs::objects::JS_IsRegisteredClass(runtime, id),
1,
"the class did not register"
);
let proto = quickjs::objects::JS_NewObject(context);
assert!(!proto.is_exception(), "JS_NewObject failed");
assert_eq!(
quickjs::objects::JS_SetPropertyFunctionList(
context,
proto,
table.as_ptr(),
c_int::try_from(table.len()).unwrap(),
),
0,
"JS_SetPropertyFunctionList failed"
);
let constructor = quickjs::objects::JS_NewCFunction2(
context,
point_ctor as *const c_void,
c"Point".as_ptr(),
2,
quickjs::cdefs::CFunctionEnum::Constructor as c_int,
0,
);
assert!(!constructor.is_exception(), "JS_NewCFunction2 failed");
assert_eq!(
quickjs::objects::JS_SetConstructor(context, constructor, proto),
0,
"JS_SetConstructor failed"
);
let for_class = quickjs::convert::encode(
&quickjs::runtime::argument(constructor).expect("the constructor decodes"),
);
quickjs::objects::JS_SetClassProto(context, id, for_class);
let global = quickjs::objects::JS_GetGlobalObject(context);
assert!(!global.is_exception(), "JS_GetGlobalObject failed");
let for_global = quickjs::convert::encode(
&quickjs::runtime::argument(constructor).expect("the constructor decodes"),
);
assert_eq!(
quickjs::objects::JS_SetPropertyStr(context, global, c"Point".as_ptr(), for_global),
0,
"JS_SetPropertyStr failed"
);
quickjs::runtime::release(global);
quickjs::runtime::release(constructor);
quickjs::runtime::release(proto);
}
}
#[test]
fn the_point_class_works_from_c() {
let _serial = serial();
let engine = Engine::new();
install_point(&engine);
assert_eq!(engine.eval_number("var p = new Point(2, 3); p.x"), 2.0);
assert_eq!(engine.eval_number("p.y"), 3.0);
assert_eq!(engine.eval_number("p.x = 4; p.x"), 4.0);
assert_eq!(engine.eval_number("p.norm()"), 5.0);
assert_eq!(
engine.eval_number(
"class ColorPoint extends Point { constructor(x, y) { super(x, y); } }\n\
var cp = new ColorPoint(6, 8); cp.norm()"
),
10.0
);
assert_eq!(engine.eval_number("cp instanceof Point ? 1 : 0"), 1.0);
}
#[test]
fn a_getter_and_a_setter_both_use_magic() {
let _serial = serial();
let engine = Engine::new();
install_point(&engine);
engine.eval("var q = new Point(1, 2);");
assert_eq!(engine.eval_number("q.x"), 1.0);
assert_eq!(engine.eval_number("q.y"), 2.0);
engine.eval("q.y = 20;");
assert_eq!(engine.eval_number("q.y"), 20.0);
}
#[test]
fn the_opaque_is_per_class_and_typed() {
let _serial = serial();
let engine = Engine::new();
install_point(&engine);
engine.eval("var r = new Point(0, 0);");
let value = engine.eval("Point.prototype.x.call({})");
assert!(value.is_exception(), "a bare object answered an opaque");
let text = engine.pending_text();
assert!(text.contains("not a Point"), "{text}");
}
#[test]
fn the_finalizer_runs_exactly_once() {
let _serial = serial();
let engine = Engine::new();
install_point(&engine);
let before = FINALIZED.load(std::sync::atomic::Ordering::SeqCst);
engine.eval("for (var i = 0; i < 3; i++) { new Point(i, i); } 0");
let after = FINALIZED.load(std::sync::atomic::Ordering::SeqCst);
assert_eq!(
after - before,
3,
"the finalizer did not run once per instance"
);
}
#[test]
fn a_nulled_global_releases_its_instance() {
let _serial = serial();
let engine = Engine::new();
install_point(&engine);
let before = FINALIZED.load(std::sync::atomic::Ordering::SeqCst);
let mut counts = Vec::new();
for script in [
"var a = new Point(2, 3); a = null;",
"var b = new Point(2, 3); b.x; b = null;",
"var c = new Point(2, 3); c.tag = 1; c = null;",
"var d = new Point(2, 3); d.norm(); d = null;",
] {
engine.eval(script);
let now = FINALIZED.load(std::sync::atomic::Ordering::SeqCst);
counts.push(now - before);
assert_eq!(
counts.last().copied().unwrap_or(0),
counts.len(),
"{script}: an instance was retained"
);
}
}
#[test]
fn js_to_int32_coerces_and_reports_type_errors() {
let engine = Engine::new();
assert_eq!(engine.eval_number("new Number(7) | 0"), 7.0);
assert_eq!(engine.eval_number("('12' | 0) + ('0x10' | 0)"), 28.0);
assert_eq!(engine.eval_number("(1e30 | 0) === (1e30 | 0) ? 1 : 0"), 1.0);
}
#[test]
fn an_exception_from_c_keeps_its_object() {
let _serial = serial();
let engine = Engine::new();
install_point(&engine);
let thrown = engine.eval("try { new Point(Symbol('nope'), 0) } catch (e) { e.name }");
let text = to_string(engine.context, thrown);
assert_eq!(
text, "TypeError",
"the C function's exception lost its identity"
);
unsafe { quickjs::runtime::release(thrown) };
}
#[test]
fn eval_reports_syntax_errors_as_exception_objects() {
let _serial = serial();
let engine = Engine::new();
let value = engine.eval("var = ;");
assert!(value.is_exception());
let text = engine.pending_text();
assert!(text.contains("SyntaxError"), "{text}");
}
#[test]
fn a_boolean_and_an_index_convert() {
let _serial = serial();
let engine = Engine::new();
assert_eq!(engine.eval_number("[] ? 1 : 0"), 1.0);
assert_eq!(engine.eval_number("'' ? 1 : 0"), 0.0);
assert_eq!(engine.eval_number("NaN ? 1 : 0"), 0.0);
}
#[test]
fn the_value_tags_line_up_with_the_header() {
let _serial = serial();
assert_eq!(UNDEFINED.norm_tag(), quickjs::jsvalue::TAG_UNDEFINED);
assert_eq!(EXCEPTION.norm_tag(), TAG_EXCEPTION);
assert_eq!(TAG_BOOL, 1);
assert_eq!(TAG_INT, 0);
let _: *const c_char = c"x".as_ptr();
}