use crate::expand::Engine;
use crate::lexer::Lexer;
use std::cell::Cell;
#[derive(Clone, Copy)]
struct Frame {
eng: *mut Engine,
lx: *mut Lexer,
}
thread_local! {
static CURRENT: Cell<Option<Frame>> = const { Cell::new(None) };
static DEPTH: Cell<usize> = const { Cell::new(0) };
}
pub(super) fn depth() -> usize {
DEPTH.with(Cell::get)
}
pub(super) fn enter<T>(eng: &mut Engine, lx: &mut Lexer, body: impl FnOnce() -> T) -> T {
struct Restore(Option<Frame>);
impl Drop for Restore {
fn drop(&mut self) {
CURRENT.with(|c| c.set(self.0));
DEPTH.with(|d| d.set(d.get() - 1));
}
}
DEPTH.with(|d| d.set(d.get() + 1));
let frame = Frame {
eng: eng as *mut Engine,
lx: lx as *mut Lexer,
};
let _restore = Restore(CURRENT.with(|c| c.replace(Some(frame))));
body()
}
pub(super) fn with<T>(
what: &str,
f: impl FnOnce(&mut Engine, &mut Lexer) -> mlua::Result<T>,
) -> mlua::Result<T> {
let Some(frame) = CURRENT.with(|c| c.get()) else {
return Err(mlua::Error::runtime(format!(
"{what} reads TeX's input, and it was called when no TeX input \
was running it"
)));
};
let (eng, lx) = unsafe { (&mut *frame.eng, &mut *frame.lx) };
f(eng, lx)
}