use crate::compiler::ops;
use fusevm::{VMResult, Value, VM};
use std::cell::RefCell;
thread_local! {
static MESSAGES: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
}
thread_local! {
static BUILDING: RefCell<String> = const { RefCell::new(String::new()) };
}
fn b_msg_append(vm: &mut VM, _argc: u8) -> Value {
let piece = render(&vm.pop());
BUILDING.with(|b| b.borrow_mut().push_str(&piece));
Value::Undef
}
fn b_msg_flush(_vm: &mut VM, _argc: u8) -> Value {
let done = BUILDING.with(|b| std::mem::take(&mut *b.borrow_mut()));
MESSAGES.with(|m| m.borrow_mut().push(done));
Value::Undef
}
fn render(v: &Value) -> String {
match v {
Value::Int(n) => n.to_string(),
Value::Str(s) => s.to_string(),
other => format!("{other:?}"),
}
}
pub fn run(chunk: fusevm::Chunk) -> Result<Vec<String>, String> {
run_with(chunk, None)
}
pub fn run_debug(
chunk: fusevm::Chunk,
on_line: fn(&mut VM, u8) -> Value,
) -> Result<Vec<String>, String> {
run_with(chunk, Some(on_line))
}
thread_local! {
static FAULT: RefCell<Option<String>> = const { RefCell::new(None) };
}
fn fault(vm: &mut VM, msg: impl Into<String>) -> Value {
FAULT.with(|f| *f.borrow_mut() = Some(msg.into()));
vm.request_halt();
Value::Undef
}
fn b_ffi_compile(vm: &mut VM, _argc: u8) -> Value {
let b64 = render(&vm.pop());
match fusevm::ffi::compile_and_register(&b64) {
Ok(()) => Value::Undef,
Err(e) => fault(vm, e),
}
}
fn b_ffi_call(vm: &mut VM, argc: u8) -> Value {
let mut args = Vec::with_capacity(argc.saturating_sub(1) as usize);
for _ in 1..argc {
args.push(vm.pop());
}
args.reverse();
let name = render(&vm.pop());
match fusevm::ffi::try_call(&name, &args) {
Some(Ok(v)) => v,
Some(Err(e)) => fault(vm, e),
None => fault(
vm,
format!("Undefined rust function {name} -- is its \\rust block above the call?"),
),
}
}
pub fn register_message_builtins(vm: &mut VM) {
vm.register_builtin(ops::MSG_APPEND, b_msg_append);
vm.register_builtin(ops::MSG_FLUSH, b_msg_flush);
vm.register_builtin(ops::FFI_COMPILE, b_ffi_compile);
vm.register_builtin(ops::FFI_CALL, b_ffi_call);
}
pub fn take_messages() -> Vec<String> {
MESSAGES.with(|m| std::mem::take(&mut *m.borrow_mut()))
}
fn run_with(
chunk: fusevm::Chunk,
on_line: Option<fn(&mut VM, u8) -> Value>,
) -> Result<Vec<String>, String> {
MESSAGES.with(|m| m.borrow_mut().clear());
BUILDING.with(|b| b.borrow_mut().clear());
FAULT.with(|f| *f.borrow_mut() = None);
let mut vm = VM::new(chunk);
register_message_builtins(&mut vm);
if let Some(f) = on_line {
vm.register_builtin(ops::DBG_LINE, f);
}
let result = vm.run();
if let Some(f) = FAULT.with(|f| f.borrow_mut().take()) {
return Err(f);
}
match result {
VMResult::Ok(_) | VMResult::Halted => Ok(MESSAGES.with(|m| m.borrow().clone())),
VMResult::Error(e) => Err(e),
}
}