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()) };
static REPORTS_END: RefCell<usize> = const { RefCell::new(0) };
static TAKEN_ENDS_LINE: RefCell<bool> = const { RefCell::new(false) };
static REPORT_TAIL: RefCell<usize> = const { RefCell::new(0) };
static RECORDED_ENDS_LINE: RefCell<bool> = const { RefCell::new(false) };
}
thread_local! {
static GLUED: RefCell<bool> = const { RefCell::new(false) };
}
thread_local! {
static GLUE_NEXT: RefCell<bool> = const { RefCell::new(false) };
}
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) };
static ARITH_ERROR: 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 record(done: String) {
let glued = GLUED.with(|g| std::mem::take(&mut *g.borrow_mut()))
| GLUE_NEXT.with(|g| std::mem::take(&mut *g.borrow_mut()));
MESSAGES.with(|m| {
let mut m = m.borrow_mut();
match (glued, m.last_mut()) {
(true, Some(last)) => last.push_str(&done),
_ => m.push(done),
}
});
let ends = TAKEN_ENDS_LINE.with(|t| std::mem::take(&mut *t.borrow_mut()));
RECORDED_ENDS_LINE.with(|r| *r.borrow_mut() = ends);
}
pub(crate) fn tell(said: Vec<crate::stomach::Said>, online: bool) {
use crate::stomach::Said;
for s in said {
match s {
Said::Error(msg) => report(&msg),
Said::Diagnostic(text) => match online {
true => push_report(&text.replace('\n', "")),
false => REPORTED.with(|r| *r.borrow_mut() = true),
},
Said::Report(text) => push_report(&text.replace('\n', "")),
Said::ReportOpen(text) => {
push_report(&text.replace('\n', ""));
REPORT_TAIL.with(|t| *t.borrow_mut() = usize::MAX);
}
Said::Terminal(text) => {
let held = take_building();
let after_report = match held.is_empty() {
true => RECORDED_ENDS_LINE.with(|r| *r.borrow()),
false => TAKEN_ENDS_LINE.with(|t| *t.borrow()),
};
if !held.is_empty() {
record(held);
}
if after_report {
GLUED.with(|g| *g.borrow_mut() = true);
}
record(text);
}
Said::Glued(text) => {
let held = take_building();
if !held.is_empty() {
record(held);
}
GLUED.with(|g| *g.borrow_mut() = true);
record(text);
}
}
}
}
pub(crate) fn append_to_message(text: &str) {
BUILDING.with(|b| b.borrow_mut().push_str(text));
}
fn push_report(text: &str) {
BUILDING.with(|b| {
let mut b = b.borrow_mut();
if b.is_empty() {
GLUED.with(|g| *g.borrow_mut() = true);
}
REPORTS_END.with(|end| {
let mut end = end.borrow_mut();
if *end == b.len() {
*end += text.len();
}
});
b.push_str(text);
REPORT_TAIL.with(|t| *t.borrow_mut() = b.len());
});
}
fn report_before_text(text: &str) {
REPORTED.with(|r| *r.borrow_mut() = true);
BUILDING.with(|b| {
let mut b = b.borrow_mut();
REPORTS_END.with(|end| {
let mut end = end.borrow_mut();
let at = (*end).min(b.len());
if at == 0 {
GLUED.with(|g| *g.borrow_mut() = true);
}
b.insert_str(at, text);
*end = at + text.len();
});
});
}
fn take_building() -> String {
REPORTS_END.with(|end| *end.borrow_mut() = 0);
let tail = REPORT_TAIL.with(|t| std::mem::take(&mut *t.borrow_mut()));
let held = BUILDING.with(|b| std::mem::take(&mut *b.borrow_mut()));
TAKEN_ENDS_LINE.with(|t| *t.borrow_mut() = !held.is_empty() && tail == held.len());
held
}
fn b_expr_step(vm: &mut VM, argc: u8) -> Value {
let max = vm.pop().to_int();
let code = vm.pop().to_int();
let mut args: Vec<i64> = (2..argc).map(|_| vm.pop().to_int()).collect();
args.reverse();
match crate::etex_arith::Op::from_code(code) {
Some(op) => Value::Int(crate::etex_arith::apply(op, max, &args)),
None => Value::Int(crate::etex_arith::ERROR),
}
}
fn b_expr_end(vm: &mut VM, _argc: u8) -> Value {
let site = render(&vm.pop());
match vm.pop().to_int() {
crate::etex_arith::ERROR => {
report_before_text(&site);
Value::Int(0)
}
v => Value::Int(v),
}
}
fn b_msg_report(vm: &mut VM, _argc: u8) -> Value {
let text = render(&vm.pop());
match text.strip_prefix(crate::expand::DIAGNOSTIC) {
Some(shown) => push_report(shown),
None if text == crate::expand::WARNING_ISSUED => {
REPORTED.with(|r| *r.borrow_mut() = true);
}
None => {
REPORTED.with(|r| *r.borrow_mut() = true);
push_report(&text);
}
}
Value::Undef
}
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 = take_building();
record(done);
Value::Undef
}
fn b_write_flush(_vm: &mut VM, _argc: u8) -> Value {
let done = take_building();
GLUED.with(|g| *g.borrow_mut() = true);
record(done);
GLUE_NEXT.with(|g| *g.borrow_mut() = true);
Value::Undef
}
fn b_out_write(vm: &mut VM, _argc: u8) -> Value {
let stream = vm.pop().to_int();
let done = BUILDING.with(|b| std::mem::take(&mut *b.borrow_mut()));
crate::write::write_line(stream, &done);
Value::Undef
}
fn b_msg_take(_vm: &mut VM, _argc: u8) -> Value {
let text = BUILDING.with(|b| std::mem::take(&mut *b.borrow_mut()));
Value::str(text)
}
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
}
pub(crate) fn fault_now(vm: &mut VM, msg: impl Into<String>) -> Value {
fault(vm, msg)
}
fn report(msg: &str) {
let site = ERROR_SITE.with(|s| s.borrow().clone());
REPORTED.with(|r| *r.borrow_mut() = true);
push_report(&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 {
let glued = vm.pop().to_int() != 0;
let notes = render(&vm.pop());
let reported = REPORTED.with(|r| *r.borrow());
if !reported && notes.is_empty() {
return Value::Int(0);
}
let held = take_building();
if !held.is_empty() {
record(held);
}
let mut text = format!("){notes}");
match reported {
true => text.push_str("(see the transcript file for additional information"),
false => {
if let Some(at) = text.rfind(')') {
text.truncate(at);
}
}
}
MESSAGES.with(|m| {
let mut m = m.borrow_mut();
match (glued, m.last_mut()) {
(true, Some(last)) => last.push_str(&text),
_ => m.push(text),
}
});
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();
match arith_checked(old, operand, which) {
Some(v) => Value::Int(v),
None => {
report("Arithmetic overflow");
Value::Int(old)
}
}
}
pub fn arith_checked(old: i64, operand: i64, which: i64) -> Option<i64> {
let result = match which {
0 => old.checked_mul(operand),
2 => old
.checked_mul(operand)
.filter(|v| v.abs() <= crate::dimen::MAX_DIMEN),
_ => match operand {
0 => None,
d => old.checked_div(d),
},
};
result.filter(|v| (i32::MIN as i64..=i32::MAX as i64).contains(v))
}
fn b_arith_glue(vm: &mut VM, _argc: u8) -> Value {
let which = vm.pop().to_int();
let operand = vm.pop().to_int();
let old = vm.pop().to_int();
match arith_checked(old, operand, which) {
Some(v) => Value::Int(v),
None => {
ARITH_ERROR.with(|e| *e.borrow_mut() = true);
Value::Int(old)
}
}
}
fn b_arith_keep(vm: &mut VM, _argc: u8) -> Value {
let old = vm.pop();
let new = vm.pop();
match ARITH_ERROR.with(|e| *e.borrow()) {
true => old,
false => new,
}
}
fn b_arith_settle(_vm: &mut VM, _argc: u8) -> Value {
if ARITH_ERROR.with(|e| std::mem::take(&mut *e.borrow_mut())) {
report("Arithmetic overflow");
}
Value::Int(0)
}
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();
match crate::dimen::scale_by_factor_checked(int, frac, v) {
Ok(product) => Value::Int(product),
Err(clamped) => {
report("Dimension too large");
Value::Int(clamped)
}
}
}
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::WRITE_FLUSH, b_write_flush);
vm.register_builtin(ops::MSG_REPORT, b_msg_report);
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::ARITH_GLUE, b_arith_glue);
vm.register_builtin(ops::ARITH_KEEP, b_arith_keep);
vm.register_builtin(ops::ARITH_SETTLE, b_arith_settle);
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::EXPR_STEP, b_expr_step);
vm.register_builtin(ops::EXPR_END, b_expr_end);
vm.register_builtin(ops::MSG_TAKE, b_msg_take);
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);
vm.register_builtin(ops::LIST, crate::stomach::run::b_list);
vm.register_builtin(ops::LIST_SHOWBOX, crate::stomach::run::b_list_showbox);
vm.register_builtin(ops::LIST_SHOWLISTS, crate::stomach::run::b_list_showlists);
vm.register_builtin(ops::OUT_OPEN, crate::write::b_out_open);
vm.register_builtin(ops::OUT_WRITE, b_out_write);
vm.register_builtin(ops::OUT_CLOSE, crate::write::b_out_close);
vm.register_builtin(ops::OUT_IS_OPEN, crate::write::b_out_is_open);
}
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());
take_building();
GLUED.with(|g| *g.borrow_mut() = false);
GLUE_NEXT.with(|g| *g.borrow_mut() = false);
FAULT.with(|f| *f.borrow_mut() = None);
ERROR_SITE.with(|s| s.borrow_mut().clear());
REPORTED.with(|r| *r.borrow_mut() = false);
ARITH_ERROR.with(|e| *e.borrow_mut() = false);
crate::stomach::run::reset();
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();
finish_run()?;
match result {
VMResult::Ok(_) | VMResult::Halted => Ok(MESSAGES.with(|m| m.borrow().clone())),
VMResult::Error(e) => Err(e),
}
}
pub(crate) fn finish_run() -> Result<(), String> {
let held = take_building();
if !held.is_empty() {
record(held);
}
crate::write::close_all();
match FAULT.with(|f| f.borrow_mut().take()) {
Some(f) => Err(f),
None => Ok(()),
}
}