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> {
MESSAGES.with(|m| m.borrow_mut().clear());
BUILDING.with(|b| b.borrow_mut().clear());
let mut vm = VM::new(chunk);
vm.register_builtin(ops::MSG_APPEND, b_msg_append);
vm.register_builtin(ops::MSG_FLUSH, b_msg_flush);
match vm.run() {
VMResult::Ok(_) | VMResult::Halted => Ok(MESSAGES.with(|m| m.borrow().clone())),
VMResult::Error(e) => Err(e),
}
}