[oden][oden-js] Rework modules

Damn this is a lot
This commit is contained in:
John Doty 2023-06-24 08:45:39 -07:00
parent aa90cea4a3
commit db8a5f8eed
12 changed files with 280 additions and 105 deletions

View file

@ -1,8 +1,29 @@
use crate::module::loader::{load_module, DefaultModuleLoader, ModuleLoader};
use crate::ContextRef;
use oden_js_sys as sys;
use std::cell::RefCell;
use std::ffi::CStr;
struct PrivateState {
refs: u64,
loader: Box<dyn ModuleLoader>,
}
impl PrivateState {
unsafe extern "C" fn module_loader(
ctx: *mut sys::JSContext,
path: *const i8,
opaque: *mut std::os::raw::c_void,
) -> *mut sys::JSModuleDef {
let path = match CStr::from_ptr(path).to_str() {
Ok(s) => s,
Err(_) => return std::ptr::null_mut(),
};
let state = opaque as *mut PrivateState;
let context = ContextRef::from_raw(ctx);
load_module(&context, path, &mut (*state).loader)
}
}
#[derive(Debug)]
@ -12,10 +33,19 @@ pub struct Runtime {
impl Runtime {
pub fn new() -> Runtime {
let state = Box::new(RefCell::new(PrivateState { refs: 1 }));
Self::with_loader(DefaultModuleLoader::new())
}
pub fn with_loader<TLoader: ModuleLoader + 'static>(loader: TLoader) -> Runtime {
let state = Box::new(RefCell::new(PrivateState {
refs: 1,
loader: Box::new(loader),
}));
let rt = unsafe {
let rt = sys::JS_NewRuntime();
sys::JS_SetRuntimeOpaque(rt, Box::into_raw(state) as *mut _);
let state = Box::into_raw(state) as *mut _;
sys::JS_SetRuntimeOpaque(rt, state);
sys::JS_SetModuleLoaderFunc(rt, None, Some(PrivateState::module_loader), state);
rt
};
Runtime { rt }