MoonBit host for the compositor component on prebuilt libwasmtime (sys, font, raster)
CI / test (push) Failing after 17s

wasmhost/ runs build/compositor.wasm with wasmtime linked as the upstream C API
library (fetched by setup-toolchain.sh) instead of compiling it: a cold build is
about 4 s against about 2 min for host-wasm. sys and font reuse the native
compositor's packages; the rasteriser is a port of host-wasm/src/raster.rs with the
pixel work in C, SVG through nanosvg. Panel modules, --drm and --window come next;
host-wasm stays the working host until then.

wit: sys.append-file. The C API moves list<u8> as one dynamic value per byte and
wasmtime caps what one call may copy, so the component writes files over 1 MiB as
write-file plus appends (host-wasm implements it too).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hiNfjrw2edja7LiRLB
This commit is contained in:
Claude committed 2026-11-25 19:42:20 +00:00
1 parent 2636373a4f
commit 2f4ce827c3
26 files changed
+7592 -2

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
import {
"moonbitlang/core/builtin",
"moonbitlang/core/buffer" @buffer,
"moonbitlang/core/encoding/utf8" @utf8,
}
supported_targets = "-all+native"
// The wasmtime C API comes prebuilt from setup-toolchain.sh (.tools/wasmtime-c-api); build with
// scripts/build-wasmhost.sh, which points the C compiler and linker at it.
options(
"native-stub": [ "wt_stub.c" ],
)
+365
View File
@@ -0,0 +1,365 @@
///| A component-model value as it crosses to and from wasmtime (encoding in wt_stub.c).
pub(all) enum Val {
Bool(Bool)
S8(Int)
U8(Int)
S16(Int)
U16(Int)
S32(Int)
U32(UInt)
S64(Int64)
U64(UInt64)
F32(Float)
F64(Double)
Char(Char)
Str(String)
List(Array[Val])
Record(Array[(String, Val)])
Tuple(Array[Val])
Variant(String, Val?)
Enum(String)
Option(Val?)
Result(Bool, Val?)
Flags(Array[String])
/// A `list<u8>` (encoded as one blob rather than a value per byte).
Blob(Bytes)
} derive(Show, Eq)
///| A list of u8 (`list<u8>`) from bytes.
pub fn Val::bytes(b : Bytes) -> Val {
Blob(b)
}
///| A `list<string>`.
pub fn Val::strings(a : Array[String]) -> Val {
List(a.map(Str(_)))
}
///| Record field `name` (records are looked up by name, not position).
pub fn Val::field(self : Val, name : String) -> Val {
match self {
Record(fs) => {
for f in fs {
if f.0 == name {
return f.1
}
}
abort("record has no field \{name}")
}
_ => abort("not a record: field \{name}")
}
}
///|
pub fn Val::to_int(self : Val) -> Int {
match self {
S8(v) | U8(v) | S16(v) | U16(v) | S32(v) => v
U32(v) => v.reinterpret_as_int()
S64(v) => v.to_int()
U64(v) => v.to_int()
Bool(b) => if b { 1 } else { 0 }
Char(c) => c.to_int()
_ => abort("not an integer: \{self}")
}
}
///|
pub fn Val::to_uint(self : Val) -> UInt {
match self {
U32(v) => v
_ => self.to_int().reinterpret_as_uint()
}
}
///|
pub fn Val::to_bool(self : Val) -> Bool {
match self {
Bool(b) => b
_ => self.to_int() != 0
}
}
///|
pub fn Val::to_double(self : Val) -> Double {
match self {
F64(d) => d
F32(f) => f.to_double()
_ => self.to_int().to_double()
}
}
///|
pub fn Val::to_string(self : Val) -> String {
match self {
Str(s) | Enum(s) => s
_ => abort("not a string: \{self}")
}
}
///|
pub fn Val::to_list(self : Val) -> Array[Val] {
match self {
List(a) | Tuple(a) => a
_ => abort("not a list: \{self}")
}
}
///| A `list<u8>` as bytes.
pub fn Val::to_bytes(self : Val) -> Bytes {
if self is Blob(b) {
return b
}
let a = self.to_list()
let out = FixedArray::make(a.length(), b'\x00')
for i, v in a {
out[i] = v.to_int().to_byte()
}
Bytes::from_fixedarray(out)
}
///|
pub fn Val::to_option(self : Val) -> Val? {
match self {
Option(o) => o
_ => abort("not an option: \{self}")
}
}
// ---- encoding ----
///|
fn put_u32(buf : @buffer.Buffer, v : Int) -> Unit {
buf.write_int_le(v)
}
///|
fn put_str(buf : @buffer.Buffer, s : String) -> Unit {
let b = @utf8.encode(s)
put_u32(buf, b.length())
buf.write_bytes(b)
}
///|
fn kind(v : Val) -> Byte {
match v {
Bool(_) => 0
S8(_) => 1
U8(_) => 2
S16(_) => 3
U16(_) => 4
S32(_) => 5
U32(_) => 6
S64(_) => 7
U64(_) => 8
F32(_) => 9
F64(_) => 10
Char(_) => 11
Str(_) => 12
List(_) => 13
Record(_) => 14
Tuple(_) => 15
Variant(_, _) => 16
Enum(_) => 17
Option(_) => 18
Result(_, _) => 19
Flags(_) => 20
Blob(_) => 0x80
}
}
///|
fn enc(buf : @buffer.Buffer, v : Val) -> Unit {
buf.write_byte(kind(v))
match v {
Bool(b) => buf.write_byte(if b { b'\x01' } else { b'\x00' })
S8(x) | U8(x) => buf.write_byte(x.to_byte())
S16(x) | U16(x) => {
buf.write_byte(x.to_byte())
buf.write_byte((x >> 8).to_byte())
}
S32(x) => buf.write_int_le(x)
U32(x) => buf.write_uint_le(x)
S64(x) => buf.write_int64_le(x)
U64(x) => buf.write_uint64_le(x)
F32(x) => buf.write_float_le(x)
F64(x) => buf.write_double_le(x)
Char(c) => buf.write_int_le(c.to_int())
Str(s) | Enum(s) => put_str(buf, s)
List(a) | Tuple(a) => {
put_u32(buf, a.length())
for x in a {
enc(buf, x)
}
}
Record(fs) => {
put_u32(buf, fs.length())
for f in fs {
put_str(buf, f.0)
enc(buf, f.1)
}
}
Variant(name, p) => {
put_str(buf, name)
match p {
Some(x) => {
buf.write_byte(b'\x01')
enc(buf, x)
}
None => buf.write_byte(b'\x00')
}
}
Option(p) =>
match p {
Some(x) => {
buf.write_byte(b'\x01')
enc(buf, x)
}
None => buf.write_byte(b'\x00')
}
Result(ok, p) => {
buf.write_byte(if ok { b'\x01' } else { b'\x00' })
match p {
Some(x) => {
buf.write_byte(b'\x01')
enc(buf, x)
}
None => buf.write_byte(b'\x00')
}
}
Flags(names) => {
put_u32(buf, names.length())
for n in names {
put_str(buf, n)
}
}
Blob(b) => {
put_u32(buf, b.length())
buf.write_bytes(b)
}
}
}
///| Encode a message (a list of values: arguments or results).
pub fn encode(vals : Array[Val]) -> Bytes {
let buf = @buffer.new(size_hint=64)
put_u32(buf, vals.length())
for v in vals {
enc(buf, v)
}
buf.to_bytes()
}
// ---- decoding ----
///|
struct Reader {
b : Bytes
mut pos : Int
}
///|
fn Reader::u8(self : Reader) -> Int {
let v = self.b[self.pos].to_int()
self.pos += 1
v
}
///|
fn Reader::u32(self : Reader) -> UInt {
let p = self.pos
let v = self.b[p].to_uint() |
(self.b[p + 1].to_uint() << 8) |
(self.b[p + 2].to_uint() << 16) |
(self.b[p + 3].to_uint() << 24)
self.pos += 4
v
}
///|
fn Reader::u64(self : Reader) -> UInt64 {
let lo = self.u32().to_uint64()
let hi = self.u32().to_uint64()
lo | (hi << 32)
}
///|
fn Reader::str(self : Reader) -> String {
let n = self.u32().reinterpret_as_int()
let s = @utf8.decode_lossy(self.b[self.pos:self.pos + n])
self.pos += n
s
}
///|
fn Reader::val(self : Reader) -> Val {
match self.u8() {
0 => Bool(self.u8() != 0)
1 => {
let x = self.u8()
S8(if x >= 128 { x - 256 } else { x })
}
2 => U8(self.u8())
3 => {
let x = self.u8() | (self.u8() << 8)
S16(if x >= 32768 { x - 65536 } else { x })
}
4 => U16(self.u8() | (self.u8() << 8))
5 => S32(self.u32().reinterpret_as_int())
6 => U32(self.u32())
7 => S64(self.u64().reinterpret_as_int64())
8 => U64(self.u64())
9 => F32(Float::reinterpret_from_uint(self.u32()))
10 => F64(self.u64().reinterpret_as_double())
11 => Char(Int::unsafe_to_char(self.u32().reinterpret_as_int()))
12 => Str(self.str())
13 | 15 as k => {
let n = self.u32().reinterpret_as_int()
let a = Array::new(capacity=n)
for _ in 0..<n {
a.push(self.val())
}
if k == 13 {
List(a)
} else {
Tuple(a)
}
}
14 => {
let n = self.u32().reinterpret_as_int()
let a = Array::new(capacity=n)
for _ in 0..<n {
let name = self.str()
a.push((name, self.val()))
}
Record(a)
}
16 => {
let name = self.str()
Variant(name, if self.u8() != 0 { Some(self.val()) } else { None })
}
17 => Enum(self.str())
18 => Option(if self.u8() != 0 { Some(self.val()) } else { None })
19 => {
let ok = self.u8() != 0
Result(ok, if self.u8() != 0 { Some(self.val()) } else { None })
}
20 => {
let n = self.u32().reinterpret_as_int()
Flags(Array::makei(n, _ => self.str()))
}
0x80 => {
let n = self.u32().reinterpret_as_int()
let b = self.b[self.pos:self.pos + n].to_owned()
self.pos += n
Blob(b)
}
k => abort("unknown value kind \{k}")
}
}
///| Decode a message.
pub fn decode(b : Bytes) -> Array[Val] {
let r = { b, pos: 0 }
let n = r.u32().reinterpret_as_int()
Array::makei(n, _ => r.val())
}
+109
View File
@@ -0,0 +1,109 @@
///| 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))
}
}
+414
View File
@@ -0,0 +1,414 @@
/* The wasmtime C API (component model) for the MoonBit host.
*
* One engine, store and linker. Host functions are registered by interface; every call from the
* component lands in one callback that encodes the arguments into bytes, calls the MoonBit
* dispatcher with them and decodes the bytes it returns into the results. Calling an export works
* the same way in reverse. MoonBit never sees a wasmtime value, only this encoding (see val.mbt):
*
* value = kind:u8 payload (kind is WASMTIME_COMPONENT_*)
* bool/s8/u8: 1 byte; s16/u16: 2; s32/u32/f32/char: 4; s64/u64/f64: 8 (little endian)
* string/enum: u32 length + UTF-8
* list/tuple: u32 n + n values
* record: u32 n + n (string name, value)
* variant: string case + u8 has-payload + [value]
* option: u8 is-some + [value]
* result: u8 is-ok + u8 has-payload + [value]
* flags: u32 n + n strings
* blob: u32 n + n bytes (kind 0x80: a list<u8>, both ways)
* message = u32 count + count values
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wasmtime.h>
#include "moonbit.h"
#define KIND_BLOB 0x80
typedef moonbit_bytes_t (*wt_dispatch_t)(int32_t id, moonbit_bytes_t args);
static wasm_engine_t *engine;
static wasmtime_store_t *store;
static wasmtime_context_t *ctx;
static wasmtime_component_linker_t *linker;
static wasmtime_component_t *component;
static wasmtime_component_instance_t instance;
static int have_instance;
static wt_dispatch_t dispatch;
static char last_error[1024];
static void set_error(const char *what, wasmtime_error_t *e) {
if (!e) {
snprintf(last_error, sizeof last_error, "%s", what);
return;
}
wasm_byte_vec_t m;
wasmtime_error_message(e, &m);
snprintf(last_error, sizeof last_error, "%s: %.*s", what, (int)m.size, m.data);
wasm_byte_vec_delete(&m);
wasmtime_error_delete(e);
}
/* ---- encoding ---- */
typedef struct { uint8_t *p; size_t len, cap; } Buf;
static void put(Buf *b, const void *src, size_t n) {
if (b->len + n > b->cap) {
size_t c = b->cap ? b->cap * 2 : 256;
while (c < b->len + n) c *= 2;
b->p = realloc(b->p, c);
b->cap = c;
}
memcpy(b->p + b->len, src, n);
b->len += n;
}
static void put_u8(Buf *b, uint8_t v) { put(b, &v, 1); }
static void put_u32(Buf *b, uint32_t v) { put(b, &v, 4); }
static void put_name(Buf *b, const wasm_name_t *s) {
put_u32(b, (uint32_t)s->size);
if (s->size) put(b, s->data, s->size);
}
static void enc(Buf *b, const wasmtime_component_val_t *v) {
put_u8(b, v->kind);
switch (v->kind) {
case WASMTIME_COMPONENT_BOOL: put_u8(b, v->of.boolean ? 1 : 0); break;
case WASMTIME_COMPONENT_S8: put(b, &v->of.s8, 1); break;
case WASMTIME_COMPONENT_U8: put(b, &v->of.u8, 1); break;
case WASMTIME_COMPONENT_S16: put(b, &v->of.s16, 2); break;
case WASMTIME_COMPONENT_U16: put(b, &v->of.u16, 2); break;
case WASMTIME_COMPONENT_S32: put(b, &v->of.s32, 4); break;
case WASMTIME_COMPONENT_U32: put(b, &v->of.u32, 4); break;
case WASMTIME_COMPONENT_S64: put(b, &v->of.s64, 8); break;
case WASMTIME_COMPONENT_U64: put(b, &v->of.u64, 8); break;
case WASMTIME_COMPONENT_F32: put(b, &v->of.f32, 4); break;
case WASMTIME_COMPONENT_F64: put(b, &v->of.f64, 8); break;
case WASMTIME_COMPONENT_CHAR: put(b, &v->of.character, 4); break;
case WASMTIME_COMPONENT_STRING: put_name(b, &v->of.string); break;
case WASMTIME_COMPONENT_ENUM: put_name(b, &v->of.enumeration); break;
case WASMTIME_COMPONENT_LIST:
if (v->of.list.size && v->of.list.data[0].kind == WASMTIME_COMPONENT_U8) {
b->p[b->len - 1] = KIND_BLOB;
put_u32(b, (uint32_t)v->of.list.size);
for (size_t i = 0; i < v->of.list.size; i++) put_u8(b, v->of.list.data[i].of.u8);
break;
}
put_u32(b, (uint32_t)v->of.list.size);
for (size_t i = 0; i < v->of.list.size; i++) enc(b, &v->of.list.data[i]);
break;
case WASMTIME_COMPONENT_TUPLE:
put_u32(b, (uint32_t)v->of.tuple.size);
for (size_t i = 0; i < v->of.tuple.size; i++) enc(b, &v->of.tuple.data[i]);
break;
case WASMTIME_COMPONENT_RECORD:
put_u32(b, (uint32_t)v->of.record.size);
for (size_t i = 0; i < v->of.record.size; i++) {
put_name(b, &v->of.record.data[i].name);
enc(b, &v->of.record.data[i].val);
}
break;
case WASMTIME_COMPONENT_VARIANT:
put_name(b, &v->of.variant.discriminant);
put_u8(b, v->of.variant.val ? 1 : 0);
if (v->of.variant.val) enc(b, v->of.variant.val);
break;
case WASMTIME_COMPONENT_OPTION:
put_u8(b, v->of.option ? 1 : 0);
if (v->of.option) enc(b, v->of.option);
break;
case WASMTIME_COMPONENT_RESULT:
put_u8(b, v->of.result.is_ok ? 1 : 0);
put_u8(b, v->of.result.val ? 1 : 0);
if (v->of.result.val) enc(b, v->of.result.val);
break;
case WASMTIME_COMPONENT_FLAGS:
put_u32(b, (uint32_t)v->of.flags.size);
for (size_t i = 0; i < v->of.flags.size; i++) put_name(b, &v->of.flags.data[i]);
break;
default:
break; /* resources and maps: our WIT has none */
}
}
static moonbit_bytes_t to_moonbit(const Buf *b) {
moonbit_bytes_t out = moonbit_make_bytes((int32_t)b->len, 0);
if (b->len) memcpy(out, b->p, b->len);
return out;
}
static moonbit_bytes_t enc_message(const wasmtime_component_val_t *vals, size_t n) {
Buf b = {0};
put_u32(&b, (uint32_t)n);
for (size_t i = 0; i < n; i++) enc(&b, &vals[i]);
moonbit_bytes_t out = to_moonbit(&b);
free(b.p);
return out;
}
/* ---- decoding ---- */
typedef struct { const uint8_t *p; size_t len, pos; int bad; } Rd;
static int take(Rd *r, void *dst, size_t n) {
if (r->bad || r->pos + n > r->len) { r->bad = 1; memset(dst, 0, n); return 0; }
memcpy(dst, r->p + r->pos, n);
r->pos += n;
return 1;
}
static uint8_t get_u8(Rd *r) { uint8_t v; take(r, &v, 1); return v; }
static uint32_t get_u32(Rd *r) { uint32_t v; take(r, &v, 4); return v; }
static void get_name(Rd *r, wasm_name_t *out) {
uint32_t n = get_u32(r);
if (r->bad || r->pos + n > r->len) { r->bad = 1; wasm_byte_vec_new_empty(out); return; }
wasm_byte_vec_new(out, n, (const wasm_byte_t *)(r->p + r->pos));
r->pos += n;
}
static void dec(Rd *r, wasmtime_component_val_t *v);
static wasmtime_component_val_t *dec_boxed(Rd *r) {
wasmtime_component_val_t tmp;
dec(r, &tmp);
return wasmtime_component_val_new(&tmp);
}
static void dec(Rd *r, wasmtime_component_val_t *v) {
memset(v, 0, sizeof *v);
uint8_t kind = get_u8(r);
if (r->bad) { v->kind = WASMTIME_COMPONENT_BOOL; return; }
v->kind = kind;
switch (kind) {
case WASMTIME_COMPONENT_BOOL: v->of.boolean = get_u8(r) != 0; break;
case WASMTIME_COMPONENT_S8: take(r, &v->of.s8, 1); break;
case WASMTIME_COMPONENT_U8: take(r, &v->of.u8, 1); break;
case WASMTIME_COMPONENT_S16: take(r, &v->of.s16, 2); break;
case WASMTIME_COMPONENT_U16: take(r, &v->of.u16, 2); break;
case WASMTIME_COMPONENT_S32: take(r, &v->of.s32, 4); break;
case WASMTIME_COMPONENT_U32: take(r, &v->of.u32, 4); break;
case WASMTIME_COMPONENT_S64: take(r, &v->of.s64, 8); break;
case WASMTIME_COMPONENT_U64: take(r, &v->of.u64, 8); break;
case WASMTIME_COMPONENT_F32: take(r, &v->of.f32, 4); break;
case WASMTIME_COMPONENT_F64: take(r, &v->of.f64, 8); break;
case WASMTIME_COMPONENT_CHAR: take(r, &v->of.character, 4); break;
case WASMTIME_COMPONENT_STRING: get_name(r, &v->of.string); break;
case WASMTIME_COMPONENT_ENUM: get_name(r, &v->of.enumeration); break;
case WASMTIME_COMPONENT_LIST:
case WASMTIME_COMPONENT_TUPLE: {
uint32_t n = get_u32(r);
if (r->bad || n > r->len) { r->bad = 1; n = 0; }
wasmtime_component_vallist_t *l = kind == WASMTIME_COMPONENT_LIST
? &v->of.list : (wasmtime_component_vallist_t *)&v->of.tuple;
wasmtime_component_vallist_new_uninit(l, n);
for (uint32_t i = 0; i < n; i++) dec(r, &l->data[i]);
break;
}
case KIND_BLOB: {
uint32_t n = get_u32(r);
if (r->bad || r->pos + n > r->len) { r->bad = 1; n = 0; }
v->kind = WASMTIME_COMPONENT_LIST;
wasmtime_component_vallist_new_uninit(&v->of.list, n);
for (uint32_t i = 0; i < n; i++) {
memset(&v->of.list.data[i], 0, sizeof v->of.list.data[i]);
v->of.list.data[i].kind = WASMTIME_COMPONENT_U8;
v->of.list.data[i].of.u8 = r->p[r->pos + i];
}
r->pos += n;
break;
}
case WASMTIME_COMPONENT_RECORD: {
uint32_t n = get_u32(r);
if (r->bad || n > r->len) { r->bad = 1; n = 0; }
wasmtime_component_valrecord_new_uninit(&v->of.record, n);
for (uint32_t i = 0; i < n; i++) {
get_name(r, &v->of.record.data[i].name);
dec(r, &v->of.record.data[i].val);
}
break;
}
case WASMTIME_COMPONENT_VARIANT:
get_name(r, &v->of.variant.discriminant);
v->of.variant.val = get_u8(r) ? dec_boxed(r) : NULL;
break;
case WASMTIME_COMPONENT_OPTION:
v->of.option = get_u8(r) ? dec_boxed(r) : NULL;
break;
case WASMTIME_COMPONENT_RESULT:
v->of.result.is_ok = get_u8(r) != 0;
v->of.result.val = get_u8(r) ? dec_boxed(r) : NULL;
break;
case WASMTIME_COMPONENT_FLAGS: {
uint32_t n = get_u32(r);
if (r->bad || n > r->len) { r->bad = 1; n = 0; }
wasmtime_component_valflags_new_uninit(&v->of.flags, n);
for (uint32_t i = 0; i < n; i++) get_name(r, &v->of.flags.data[i]);
break;
}
default:
r->bad = 1;
v->kind = WASMTIME_COMPONENT_BOOL;
break;
}
}
/* Decode a message into `out` (n slots). 0 on success. */
static int dec_message(moonbit_bytes_t bytes, wasmtime_component_val_t *out, size_t n) {
Rd r = { (const uint8_t *)bytes, (size_t)Moonbit_array_length(bytes), 0, 0 };
uint32_t count = get_u32(&r);
if (r.bad || count != n) {
for (size_t i = 0; i < n; i++) { memset(&out[i], 0, sizeof out[i]); out[i].kind = WASMTIME_COMPONENT_BOOL; }
return -1;
}
for (size_t i = 0; i < n; i++) dec(&r, &out[i]);
return r.bad ? -1 : 0;
}
/* ---- host functions ---- */
static wasmtime_error_t *host_call(void *env, wasmtime_context_t *c, const wasmtime_component_func_type_t *ty,
wasmtime_component_val_t *args, size_t nargs,
wasmtime_component_val_t *results, size_t nresults) {
(void)c; (void)ty;
int32_t id = (int32_t)(intptr_t)env;
moonbit_bytes_t in = enc_message(args, nargs);
moonbit_bytes_t out = dispatch(id, in); /* takes `in` */
int bad = dec_message(out, results, nresults);
moonbit_decref(out);
if (bad) {
char msg[96];
snprintf(msg, sizeof msg, "host function %d returned a malformed result", id);
return wasmtime_error_new(msg);
}
return NULL;
}
void wt_set_dispatch(wt_dispatch_t f) { dispatch = f; }
moonbit_bytes_t wt_last_error(void) {
size_t n = strlen(last_error);
moonbit_bytes_t out = moonbit_make_bytes((int32_t)n, 0);
memcpy(out, last_error, n);
return out;
}
int32_t wt_init(void) {
if (engine) return 0;
wasm_config_t *cfg = wasm_config_new();
wasmtime_config_wasm_component_model_set(cfg, true);
engine = wasm_engine_new_with_config(cfg);
if (!engine) { set_error("cannot create the wasmtime engine", NULL); return -1; }
store = wasmtime_store_new(engine, NULL, NULL);
ctx = wasmtime_store_context(store);
linker = wasmtime_component_linker_new(engine);
return 0;
}
int32_t wt_load(moonbit_bytes_t path) {
char p[4096];
size_t n = (size_t)Moonbit_array_length(path);
if (n >= sizeof p) n = sizeof p - 1;
memcpy(p, path, n);
p[n] = 0;
FILE *f = fopen(p, "rb");
if (!f) { snprintf(last_error, sizeof last_error, "cannot open %s", p); return -1; }
fseek(f, 0, SEEK_END);
long len = ftell(f);
rewind(f);
uint8_t *data = malloc(len > 0 ? (size_t)len : 1);
size_t got = fread(data, 1, (size_t)len, f);
fclose(f);
wasmtime_error_t *e = wasmtime_component_new(engine, data, got, &component);
free(data);
if (e) { set_error("cannot compile the component", e); return -1; }
return 0;
}
/* Define the functions `names` (newline separated) of interface `iface` ("" for the root), with
* ids first_id, first_id + 1, ... in order. */
int32_t wt_define(moonbit_bytes_t iface, moonbit_bytes_t names, int32_t first_id) {
wasmtime_component_linker_instance_t *root = wasmtime_component_linker_root(linker);
wasmtime_component_linker_instance_t *li = root;
size_t ilen = (size_t)Moonbit_array_length(iface);
wasmtime_error_t *e = NULL;
if (ilen) {
e = wasmtime_component_linker_instance_add_instance(root, (const char *)iface, ilen, &li);
if (e) { set_error("cannot define the instance", e); wasmtime_component_linker_instance_delete(root); return -1; }
}
const char *s = (const char *)names;
size_t len = (size_t)Moonbit_array_length(names), start = 0;
int32_t id = first_id;
for (size_t i = 0; i <= len; i++) {
if (i == len || s[i] == '\n') {
if (i > start) {
e = wasmtime_component_linker_instance_add_func(li, s + start, i - start, host_call,
(void *)(intptr_t)id, NULL);
if (e) {
char what[160];
snprintf(what, sizeof what, "cannot define %.*s", (int)(i - start), s + start);
set_error(what, e);
break;
}
id++;
}
start = i + 1;
}
}
if (li != root) wasmtime_component_linker_instance_delete(li);
wasmtime_component_linker_instance_delete(root);
return e ? -1 : 0;
}
int32_t wt_instantiate(void) {
wasmtime_error_t *e = wasmtime_component_linker_instantiate(linker, ctx, component, &instance);
if (e) { set_error("cannot instantiate the component", e); return -1; }
have_instance = 1;
return 0;
}
/* Call export `name` of interface `iface` ("" for a root export) with the encoded `args`. The
* encoded results, or an empty byte string on failure (wt_last_error says why). */
moonbit_bytes_t wt_call(moonbit_bytes_t iface, moonbit_bytes_t name, moonbit_bytes_t args) {
moonbit_bytes_t fail = moonbit_make_bytes(0, 0);
if (!have_instance) { set_error("no instance", NULL); return fail; }
wasmtime_component_export_index_t *parent = NULL;
size_t ilen = (size_t)Moonbit_array_length(iface);
if (ilen) {
parent = wasmtime_component_instance_get_export_index(&instance, ctx, NULL, (const char *)iface, ilen);
if (!parent) { set_error("no such exported interface", NULL); return fail; }
}
wasmtime_component_export_index_t *idx = wasmtime_component_instance_get_export_index(
&instance, ctx, parent, (const char *)name, (size_t)Moonbit_array_length(name));
if (parent) wasmtime_component_export_index_delete(parent);
if (!idx) { set_error("no such export", NULL); return fail; }
wasmtime_component_func_t func;
int ok = wasmtime_component_instance_get_func(&instance, ctx, idx, &func);
wasmtime_component_export_index_delete(idx);
if (!ok) { set_error("the export is not a function", NULL); return fail; }
wasmtime_component_func_type_t *ty = wasmtime_component_func_type(&func, ctx);
size_t nparams = wasmtime_component_func_type_param_count(ty);
wasmtime_component_valtype_t rty;
size_t nresults = wasmtime_component_func_type_result(ty, &rty) ? 1 : 0;
if (nresults) wasmtime_component_valtype_delete(&rty);
wasmtime_component_func_type_delete(ty);
wasmtime_component_val_t *a = calloc(nparams ? nparams : 1, sizeof *a);
if (dec_message(args, a, nparams)) {
for (size_t i = 0; i < nparams; i++) wasmtime_component_val_delete(&a[i]);
free(a);
set_error("malformed arguments", NULL);
return fail;
}
wasmtime_component_val_t res[1];
memset(res, 0, sizeof res);
wasmtime_error_t *e = wasmtime_component_func_call(&func, ctx, a, nparams, res, nresults);
for (size_t i = 0; i < nparams; i++) wasmtime_component_val_delete(&a[i]);
free(a);
if (e) { set_error("call failed", e); return fail; }
moonbit_bytes_t out = enc_message(res, nresults);
for (size_t i = 0; i < nresults; i++) wasmtime_component_val_delete(&res[i]);
wasmtime_component_func_post_return(&func, ctx);
moonbit_decref(fail);
return out;
}