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()) };
}
thread_local! {
static TEXT: RefCell<String> = const { RefCell::new(String::new()) };
}
thread_local! {
static ERROR_SITE: RefCell<String> = const { RefCell::new(String::new()) };
static REPORTED: RefCell<bool> = const { RefCell::new(false) };
}
fn b_text(vm: &mut VM, _argc: u8) -> Value {
let piece = render(&vm.pop());
TEXT.with(|t| t.borrow_mut().push_str(&piece));
Value::Undef
}
fn b_color_push(vm: &mut VM, _argc: u8) -> Value {
let b = render(&vm.pop());
let g = render(&vm.pop());
let r = render(&vm.pop());
TEXT.with(|t| t.borrow_mut().push_str(&format!("\u{1}{r},{g},{b}\u{2}")));
Value::Undef
}
fn b_color_pop(_vm: &mut VM, _argc: u8) -> Value {
TEXT.with(|t| t.borrow_mut().push('\u{3}'));
Value::Undef
}
pub fn take_text() -> String {
TEXT.with(|t| std::mem::take(&mut *t.borrow_mut()))
}
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 report(msg: &str) {
let site = ERROR_SITE.with(|s| s.borrow().clone());
REPORTED.with(|r| *r.borrow_mut() = true);
BUILDING.with(|b| {
b.borrow_mut()
.push_str(&format!("! {msg}.{}", site.replace('\n', "")))
});
}
fn b_err_site(vm: &mut VM, _argc: u8) -> Value {
let site = render(&vm.pop());
ERROR_SITE.with(|s| *s.borrow_mut() = site);
Value::Int(0)
}
fn b_transcript_notice(_vm: &mut VM, _argc: u8) -> Value {
if REPORTED.with(|r| *r.borrow()) {
let held = BUILDING.with(|b| std::mem::take(&mut *b.borrow_mut()));
MESSAGES.with(|m| {
m.borrow_mut().push(format!(
"{held})(see the transcript file for additional information"
))
});
}
Value::Int(0)
}
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?"),
),
}
}
fn b_arith_checked(vm: &mut VM, _argc: u8) -> Value {
let which = vm.pop().to_int();
let operand = vm.pop().to_int();
let old = vm.pop().to_int();
let result = match which {
0 => old.checked_mul(operand),
_ => match operand {
0 => None,
d => old.checked_div(d),
},
};
match result {
Some(v) if (i32::MIN as i64..=i32::MAX as i64).contains(&v) => Value::Int(v),
_ => {
report("Arithmetic overflow");
Value::Int(old)
}
}
}
fn b_scale_dimen(vm: &mut VM, _argc: u8) -> Value {
let frac = vm.pop().to_int();
let int = vm.pop().to_int();
let v = vm.pop().to_int();
Value::Int(crate::dimen::scale_by_factor(int, frac, v))
}
fn b_msg_close(_vm: &mut VM, _argc: u8) -> Value {
MESSAGES.with(|m| {
let mut m = m.borrow_mut();
match m.last_mut() {
Some(last) => last.push(')'),
None => m.push(")".to_string()),
}
});
Value::Int(0)
}
fn b_msg_dimen(vm: &mut VM, _argc: u8) -> Value {
let sp = vm.pop().to_int();
let text = format!("{}pt", crate::dimen::print_scaled(sp));
BUILDING.with(|b| b.borrow_mut().push_str(&text));
Value::Int(0)
}
fn b_msg_roman(vm: &mut VM, _argc: u8) -> Value {
let n = vm.pop().to_int();
let text = crate::expand::roman_int(n);
BUILDING.with(|b| b.borrow_mut().push_str(&text));
Value::Int(0)
}
fn b_msg_glue(vm: &mut VM, _argc: u8) -> Value {
append_glue(vm, "pt")
}
fn b_msg_muglue(vm: &mut VM, _argc: u8) -> Value {
append_glue(vm, "mu")
}
fn append_glue(vm: &mut VM, unit: &str) -> Value {
let orders = vm.pop().to_int();
let shrink = vm.pop().to_int();
let stretch = vm.pop().to_int();
let natural = vm.pop().to_int();
let text = crate::glue::print_glue_in(unit, natural, stretch, orders / 4, shrink, orders % 4);
BUILDING.with(|b| b.borrow_mut().push_str(&text));
Value::Int(0)
}
pub fn register_message_builtins(vm: &mut VM) {
vm.register_builtin(ops::TEXT, b_text);
vm.register_builtin(ops::COLOR_PUSH, b_color_push);
vm.register_builtin(ops::COLOR_POP, b_color_pop);
vm.register_builtin(ops::MSG_APPEND, b_msg_append);
vm.register_builtin(ops::MSG_FLUSH, b_msg_flush);
vm.register_builtin(ops::MSG_CLOSE, b_msg_close);
vm.register_builtin(ops::MSG_DIMEN, b_msg_dimen);
vm.register_builtin(ops::MSG_ROMAN, b_msg_roman);
vm.register_builtin(ops::MSG_GLUE, b_msg_glue);
vm.register_builtin(ops::ARITH_CHECKED, b_arith_checked);
vm.register_builtin(ops::SCALE_DIMEN, b_scale_dimen);
vm.register_builtin(ops::MSG_MUGLUE, b_msg_muglue);
vm.register_builtin(ops::ERR_SITE, b_err_site);
vm.register_builtin(ops::TRANSCRIPT_NOTICE, b_transcript_notice);
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);
ERROR_SITE.with(|s| s.borrow_mut().clear());
REPORTED.with(|r| *r.borrow_mut() = false);
let chunk_for_jit = chunk.clone();
let mut vm = VM::new(chunk);
register_message_builtins(&mut vm);
match on_line {
Some(f) => vm.register_builtin(ops::DBG_LINE, f),
None if crate::tiers::has_loop(&chunk_for_jit) => vm.enable_tracing_jit(),
None => {}
}
let result = vm.run();
let held = BUILDING.with(|b| std::mem::take(&mut *b.borrow_mut()));
if !held.is_empty() {
MESSAGES.with(|m| m.borrow_mut().push(held));
}
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),
}
}