use super::*;
use crate::expand::Macro;
use crate::token::CsId;
struct Ctx<'a> {
eng: &'a mut Engine,
lx: &'a mut Lexer,
}
type Shared<'a> = Rc<RefCell<Ctx<'a>>>;
pub(super) fn with<T>(
lua: &Lua,
eng: &mut Engine,
lx: &mut Lexer,
body: impl FnOnce(&Lua) -> T,
) -> mlua::Result<T> {
let ctx: Shared = Rc::new(RefCell::new(Ctx { eng, lx }));
let out = lua.scope(|scope| {
lua.globals().set("token", table(lua, scope, &ctx)?)?;
Ok(body(lua))
});
lua.globals().raw_remove("token")?;
out
}
fn tex_err(e: TexError) -> mlua::Error {
mlua::Error::runtime(e.0)
}
fn table<'scope, 'env: 'scope>(
lua: &Lua,
scope: &'scope mlua::Scope<'scope, 'env>,
ctx: &'env Shared<'env>,
) -> mlua::Result<Table> {
let t = lua.create_table()?;
let c = Rc::clone(ctx);
t.set(
"scan_int",
scope.create_function(move |_, ()| {
let mut c = c.borrow_mut();
let Ctx { eng, lx } = &mut *c;
eng.scan_number_file(lx).map_err(tex_err)
})?,
)?;
let c = Rc::clone(ctx);
t.set(
"scan_dimen",
scope.create_function(move |_, ()| {
let mut c = c.borrow_mut();
let Ctx { eng, lx } = &mut *c;
eng.scan_dimen_file(lx).map_err(tex_err)
})?,
)?;
let c = Rc::clone(ctx);
t.set(
"scan_keyword",
scope.create_function(move |_, word: String| {
let mut c = c.borrow_mut();
let Ctx { eng, lx } = &mut *c;
eng.scan_keyword(lx, &word, false)
.map_err(|e| mlua::Error::runtime(e.0))
})?,
)?;
let c = Rc::clone(ctx);
t.set(
"scan_keyword_cs",
scope.create_function(move |_, word: String| {
let mut c = c.borrow_mut();
let Ctx { eng, lx } = &mut *c;
let mut seen = Vec::new();
for want in word.chars() {
match eng.take_file(lx) {
Some(Token::Char(c, _)) if c == want => seen.push(Token::Char(c, Cat::Other)),
other => {
if let Some(t) = other {
lx.push_back(std::slice::from_ref(&t));
}
seen.reverse();
lx.push_back(&seen);
return Ok(false);
}
}
}
Ok(true)
})?,
)?;
let c = Rc::clone(ctx);
t.set(
"scan_word",
scope.create_function(move |_, ()| {
let mut c = c.borrow_mut();
let Ctx { eng, lx } = &mut *c;
Ok(scan_word(eng, lx))
})?,
)?;
let c = Rc::clone(ctx);
t.set(
"scan_csname",
scope.create_function(move |_, ()| {
let mut c = c.borrow_mut();
let Ctx { eng, lx } = &mut *c;
match eng.take_file(lx) {
Some(Token::Cs(n)) => Ok(Some(n.name().to_string())),
Some(other) => {
lx.push_back(std::slice::from_ref(&other));
Ok(None)
}
None => Ok(None),
}
})?,
)?;
for name in ["scan_string", "scan_argument"] {
let c = Rc::clone(ctx);
t.set(
name,
scope.create_function(move |_, _: Variadic<Value>| {
let mut c = c.borrow_mut();
let Ctx { eng, lx } = &mut *c;
scan_string(eng, lx).map_err(tex_err)
})?,
)?;
}
let c = Rc::clone(ctx);
t.set(
"get_macro",
scope.create_function(move |lua, name: String| {
let c = c.borrow();
let Some(Meaning::Macro(m)) = c.eng.meanings.get(&CsId::intern(&name)) else {
return Ok(Variadic::new());
};
let body = lua.create_string(c.eng.tokens_text(&m.body))?;
Ok(Variadic::from_iter([Value::String(body)]))
})?,
)?;
let c = Rc::clone(ctx);
t.set(
"get_meaning",
scope.create_function(move |lua, name: String| {
let c = c.borrow();
let Some(Meaning::Macro(m)) = c.eng.meanings.get(&CsId::intern(&name)) else {
return Ok(Variadic::new());
};
let text = lua.create_string(format!(
"{}->{}",
c.eng.tokens_text(&m.params),
c.eng.tokens_text(&m.body)
))?;
Ok(Variadic::from_iter([Value::String(text)]))
})?,
)?;
let c = Rc::clone(ctx);
t.set(
"set_macro",
scope.create_function(move |_, args: Variadic<Value>| {
let args: Vec<Value> = args
.iter()
.filter(|v| !matches!(v, Value::Integer(_) | Value::Number(_)))
.cloned()
.collect();
let text = |v: Option<&Value>| match v {
Some(Value::String(s)) => s.to_str().map(|s| s.to_string()).ok(),
_ => None,
};
let (Some(name), Some(body)) = (text(args.first()), text(args.get(1))) else {
return Err(mlua::Error::runtime(
"token.set_macro wants a name and a body, both strings",
));
};
let mut c = c.borrow_mut();
let toks = super::scan(&body, LineMode::Partial, &c.eng.cats);
c.eng.meanings.insert(
CsId::intern(&name),
Meaning::Macro(Macro {
params: Vec::new(),
body: toks,
long: false,
protected: false,
outer: false,
}),
);
Ok(())
})?,
)?;
let c = Rc::clone(ctx);
t.set(
"is_defined",
scope.create_function(move |_, name: String| {
let c = c.borrow();
Ok(c.eng.meanings.contains_key(&CsId::intern(&name)) || super::claims(&name))
})?,
)?;
t.set("biggest_char", 0x10FFFF)?;
for (name, instead) in [
("create", "token userdata"),
("new", "token userdata"),
("get_next", "token userdata"),
("scan_token", "token userdata"),
("expand", "token userdata"),
(
"scan_glue",
"a glue_spec node; token.scan_dimen reads its width",
),
("scan_toks", "a token table"),
("scan_list", "a hlist or vlist node"),
] {
t.set(
name,
lua.create_function(move |_, _: Variadic<Value>| {
Err::<(), _>(mlua::Error::runtime(format!(
"token.{name} answers with {instead}, which texrs has no interface for"
)))
})?,
)?;
}
Ok(t)
}
fn skip_spaces(eng: &mut Engine, lx: &mut Lexer) -> Option<Token> {
loop {
match eng.take_file(lx) {
Some(t) if t.is_space() => continue,
other => return other,
}
}
}
fn scan_word(eng: &mut Engine, lx: &mut Lexer) -> String {
let mut out = String::new();
let Some(first) = skip_spaces(eng, lx) else {
return out;
};
let mut tok = Some(first);
while let Some(t) = tok {
match t {
Token::Char(c, Cat::Letter | Cat::Other) => out.push(c),
other => {
lx.push_back(std::slice::from_ref(&other));
break;
}
}
tok = eng.take_file(lx);
}
out
}
fn scan_string(eng: &mut Engine, lx: &mut Lexer) -> R<String> {
let Some(tok) = skip_spaces(eng, lx) else {
return Ok(String::new());
};
match tok {
Token::Char(_, Cat::BeginGroup) => {
lx.push_back(std::slice::from_ref(&tok));
super::read_group(eng, lx)
}
Token::Cs(name) => Ok(match eng.meanings.get(&name) {
Some(Meaning::Macro(m)) => eng.tokens_text(&m.body),
_ => eng.meaning_text(&Token::Cs(name)),
}),
other => {
lx.push_back(std::slice::from_ref(&other));
Ok(scan_word(eng, lx))
}
}
}