///| Running a component with wasmtime (its C API, linked as a prebuilt library; see wt_stub.c). /// /// The host registers its functions by interface with `define`, each under an id; calls from the /// component reach the one handler given to `set_handler` as (id, arguments). ///| extern "C" fn c_set_dispatch(f : FuncRef[(Int, Bytes) -> Bytes]) = "wt_set_dispatch" ///| extern "C" fn c_last_error() -> Bytes = "wt_last_error" ///| extern "C" fn c_init() -> Int = "wt_init" ///| #borrow(path) extern "C" fn c_load(path : Bytes) -> Int = "wt_load" ///| #borrow(iface, names) extern "C" fn c_define(iface : Bytes, names : Bytes, first_id : Int) -> Int = "wt_define" ///| extern "C" fn c_instantiate() -> Int = "wt_instantiate" ///| #borrow(iface, name, args) extern "C" fn c_call(iface : Bytes, name : Bytes, args : Bytes) -> Bytes = "wt_call" ///| What a host function returns: its results (zero or one value). let handler : Ref[(Int, Array[Val]) -> Array[Val]] = Ref(fn(id, _) { abort("no handler for host function \{id}") }) ///| fn dispatch(id : Int, args : Bytes) -> Bytes { encode((handler.val)(id, decode(args))) } ///| fn last_error() -> String { @utf8.decode_lossy(c_last_error()) } ///| fn cstr(s : String) -> Bytes { @utf8.encode(s) } ///| Create the engine and load the component at `path`. pub fn load(path : String) -> Result[Unit, String] { if c_init() != 0 { return Err(last_error()) } c_set_dispatch(fn(id, args) { dispatch(id, args) }) if c_load(cstr(path)) != 0 { return Err(last_error()) } Ok(()) } ///| The function that serves every host import. pub fn set_handler(f : (Int, Array[Val]) -> Array[Val]) -> Unit { handler.val = f } ///| Define functions `names` of interface `iface` ("" for root imports) with ids `first_id`, /// `first_id + 1`, ... pub fn define_funcs( iface : String, names : Array[String], first_id : Int, ) -> Result[Unit, String] { let joined = names.iter().fold(init="", fn(acc, n) { if acc == "" { n } else { acc + "\n" + n } }) if c_define(cstr(iface), cstr(joined), first_id) != 0 { Err(last_error()) } else { Ok(()) } } ///| pub fn instantiate() -> Result[Unit, String] { if c_instantiate() != 0 { Err(last_error()) } else { Ok(()) } } ///| Call export `name` (of interface `iface`, "" for a root export). pub fn call( iface : String, name : String, args : Array[Val], ) -> Result[Array[Val], String] { let out = c_call(cstr(iface), cstr(name), encode(args)) if out.length() == 0 { Err(last_error()) } else { Ok(decode(out)) } }