use crate::catcode::Cat;
use crate::expand::{Engine, Meaning, TexError};
use crate::ir::{Cmd, Num};
use crate::lexer::Lexer;
use crate::token::Token;
use mlua::{Lua, Table, Value, Variadic};
use std::cell::{Cell, RefCell};
use std::collections::{BTreeMap, HashMap};
use std::rc::Rc;
pub mod callback;
mod ctx;
mod extraprimitives;
mod fio;
pub mod font;
mod kpse;
mod libs;
mod lualib;
mod node;
pub mod pdf;
mod tex;
mod token;
pub use font::{LuaChar, LuaFont};
pub use kpse::set_progname;
type R<T> = Result<T, TexError>;
fn is_primitive(name: &str) -> bool {
matches!(
name,
"directlua"
| "luadirect"
| "latelua"
| "luaescapestring"
| "luafunction"
| "luafunctioncall"
| "lateluafunction"
| "luadef"
| "luabytecode"
| "luabytecodecall"
| "luatexrevision"
)
}
thread_local! {
static RUNTIME: RefCell<Option<Runtime>> = const { RefCell::new(None) };
static LUADEFS: RefCell<HashMap<String, i64>> = RefCell::new(HashMap::new());
static ANY_LUADEF: Cell<bool> = const { Cell::new(false) };
static EXPANDABLE_LUADEFS: RefCell<std::collections::HashSet<String>> =
RefCell::new(std::collections::HashSet::new());
static JOBNAME: RefCell<Option<String>> = const { RefCell::new(None) };
}
struct Runtime {
lua: Lua,
bridge: Rc<RefCell<Bridge>>,
owner: usize,
}
#[derive(Default)]
struct Bridge {
prints: Vec<Print>,
counts: HashMap<i64, i64>,
counts_written: BTreeMap<i64, i64>,
count_names: HashMap<String, i64>,
toks: HashMap<i64, String>,
toks_written: BTreeMap<i64, String>,
toks_names: HashMap<String, i64>,
error: Option<String>,
messages: Vec<Message>,
fallbacks: Option<Vec<String>>,
}
struct Message {
text: String,
nl: bool,
}
struct Print {
text: String,
cats: Regime,
line: LineMode,
}
#[derive(Clone, Copy, PartialEq)]
enum Regime {
Current,
Verbatim,
All(Cat),
}
#[derive(Clone, Copy, PartialEq)]
enum LineMode {
Line,
Partial,
}
pub fn claims(name: &str) -> bool {
if is_primitive(name) {
return true;
}
ANY_LUADEF.with(Cell::get) && LUADEFS.with(|m| m.borrow().contains_key(name))
}
pub fn expands_in_gullet(name: &str) -> bool {
ANY_LUADEF.with(Cell::get) && EXPANDABLE_LUADEFS.with(|m| m.borrow().contains(name))
}
pub(super) fn luacall(name: &str) -> Option<(i64, bool)> {
if !ANY_LUADEF.with(Cell::get) {
return None;
}
let id = LUADEFS.with(|m| m.borrow().get(name).copied())?;
Some((id, EXPANDABLE_LUADEFS.with(|m| m.borrow().contains(name))))
}
pub(super) fn define_luacall(name: &str, id: i64, expandable: bool) {
LUADEFS.with(|m| m.borrow_mut().insert(name.to_string(), id));
EXPANDABLE_LUADEFS.with(|m| match expandable {
true => m.borrow_mut().insert(name.to_string()),
false => m.borrow_mut().remove(name),
});
ANY_LUADEF.with(|f| f.set(true));
}
fn take_fallbacks() -> Option<Vec<String>> {
RUNTIME.with(|slot| {
slot.borrow()
.as_ref()
.and_then(|rt| rt.bridge.borrow_mut().fallbacks.take())
})
}
fn warn(text: &str) {
let bridge = RUNTIME.with(|slot| slot.borrow().as_ref().map(|rt| Rc::clone(&rt.bridge)));
if let Some(b) = bridge {
say(
&b,
Message {
text: text.to_string(),
nl: true,
},
);
}
}
fn say(bridge: &Rc<RefCell<Bridge>>, m: Message) {
if ctx::depth() > 0 {
bridge.borrow_mut().messages.push(m);
return;
}
crate::runtime::tell(vec![crate::stomach::Said::Terminal(m.text)], false);
}
fn notes_to_engine(eng: &mut Engine) {
let bridge = RUNTIME.with(|slot| slot.borrow().as_ref().map(|rt| Rc::clone(&rt.bridge)));
let Some(b) = bridge else { return };
let said = std::mem::take(&mut b.borrow_mut().messages);
for m in said {
eng.terminal_note(&m.text);
}
}
fn with_lua<T>(f: impl FnOnce(&Lua) -> T) -> Option<T> {
let lua = RUNTIME.with(|slot| slot.borrow().as_ref().map(|rt| rt.lua.clone()))?;
Some(f(&lua))
}
fn current_attributes() -> Vec<(i64, i64)> {
RUNTIME.with(|slot| {
let slot = slot.borrow();
let Some(rt) = slot.as_ref() else {
return Vec::new();
};
let b = rt.bridge.borrow();
let mut out: Vec<(i64, i64)> = b
.counts
.iter()
.filter(|(k, v)| **k >= ATTRIBUTE_BASE && **v != node::UNUSED_ATTRIBUTE)
.map(|(k, v)| (*k - ATTRIBUTE_BASE, *v))
.collect();
out.sort();
out
})
}
pub fn reset() {
RUNTIME.with(|r| *r.borrow_mut() = None);
LUADEFS.with(|m| m.borrow_mut().clear());
EXPANDABLE_LUADEFS.with(|m| m.borrow_mut().clear());
ANY_LUADEF.with(|f| f.set(false));
}
pub fn set_jobname(name: &str) {
JOBNAME.with(|j| *j.borrow_mut() = Some(name.to_string()));
}
pub fn lower(
eng: &mut Engine,
lx: &mut Lexer,
name: &str,
out: &mut Vec<Cmd>,
fonts: &mut crate::typeset::Families,
) -> R<()> {
match name {
"directlua" | "luadirect" => {
let (name, chunk) = read_chunk(eng, lx)?;
let chain = crate::typeset::fallback_chain(&chunk);
if !chain.is_empty() {
fonts.fallbacks = chain;
}
let result = run(eng, lx, out, name.as_deref(), &chunk, Yield::ToInput);
if let Some(chain) = take_fallbacks() {
fonts.fallbacks = chain;
}
result
}
"latelua" => {
let (name, chunk) = read_chunk(eng, lx)?;
run(eng, lx, out, name.as_deref(), &chunk, Yield::Discard)
}
"luaescapestring" => {
let text = read_group(eng, lx)?;
let escaped = escape_string(&text);
let toks = tokenize(&escaped, Regime::Verbatim, LineMode::Partial, &eng.cats);
lx.push_back(&toks);
Ok(())
}
"luafunction" | "luafunctioncall" => {
let n = eng.scan_number_file(lx)?;
call_function(eng, lx, out, n, Yield::ToInput)
}
"lateluafunction" => {
let n = eng.scan_number_file(lx)?;
call_function(eng, lx, out, n, Yield::Discard)
}
"luabytecode" | "luabytecodecall" => {
let n = eng.scan_number_file(lx)?;
let (lua, bridge) = runtime(eng)?;
snapshot(eng, &bridge);
let result = ctx::enter(eng, lx, || lualib::call(&lua, n));
finish(eng, lx, out, &bridge, Yield::ToInput, result)
}
"luatexrevision" => {
lx.push_back(&[Token::Char('0', Cat::Other)]);
Ok(())
}
"luadef" => {
let Some(Token::Cs(cs)) = eng.take_file(lx) else {
return Err(TexError("Missing control sequence after \\luadef".into()));
};
let n = eng.scan_number_file(lx)?;
define_luacall(cs.name(), n, false);
Ok(())
}
_ => {
let Some(n) = LUADEFS.with(|m| m.borrow().get(name).copied()) else {
return Err(TexError(format!("Undefined control sequence \\{name}")));
};
call_function(eng, lx, out, n, Yield::ToInput)
}
}
}
#[derive(Clone, Copy, PartialEq)]
enum Yield {
ToInput,
Discard,
}
fn read_chunk(eng: &mut Engine, lx: &mut Lexer) -> R<(Option<String>, String)> {
let name = scan_lua_state(eng, lx)?;
Ok((name, read_group(eng, lx)?))
}
fn read_group(eng: &mut Engine, lx: &mut Lexer) -> R<String> {
let toks = eng.read_balanced_group(lx)?;
let expanded = eng.expand_edef_body(&toks)?;
let escaped = apply_escapestring(eng, &expanded);
let shown: Vec<Token> = escaped
.iter()
.filter(|t| !t.is_cs("par"))
.flat_map(|t| match t {
Token::Char(_, Cat::Param) => vec![*t, *t],
_ => vec![*t],
})
.collect();
Ok(eng.tokens_text(&shown))
}
fn apply_escapestring(eng: &Engine, toks: &[Token]) -> Vec<Token> {
if !toks.iter().any(|t| t.is_cs("luaescapestring")) {
return toks.to_vec();
}
let mut out = Vec::with_capacity(toks.len());
let mut i = 0;
while i < toks.len() {
if !toks[i].is_cs("luaescapestring") {
out.push(toks[i]);
i += 1;
continue;
}
let Some((body, next)) = group_after(toks, i + 1) else {
out.push(toks[i]);
i += 1;
continue;
};
let inner = apply_escapestring(eng, &body);
for c in escape_string(&eng.tokens_text(&inner)).chars() {
out.push(match c == ' ' {
true => Token::Char(' ', Cat::Space),
false => Token::Char(c, Cat::Other),
});
}
i = next;
}
out
}
fn group_after(toks: &[Token], at: usize) -> Option<(Vec<Token>, usize)> {
let mut i = at;
while matches!(toks.get(i), Some(t) if t.is_space()) {
i += 1;
}
if !matches!(toks.get(i), Some(Token::Char(_, Cat::BeginGroup))) {
return None;
}
i += 1;
let mut depth = 1usize;
let mut body = Vec::new();
while let Some(t) = toks.get(i) {
match t {
Token::Char(_, Cat::BeginGroup) => depth += 1,
Token::Char(_, Cat::EndGroup) => {
depth -= 1;
if depth == 0 {
return Some((body, i + 1));
}
}
_ => {}
}
body.push(*t);
i += 1;
}
None
}
fn scan_lua_state(eng: &mut Engine, lx: &mut Lexer) -> R<Option<String>> {
let next = loop {
match eng.take_file(lx) {
Some(t) if t.is_space() || t.is_cs("relax") => continue,
other => break other,
}
};
let Some(tok) = next else {
return Ok(None);
};
lx.push_back(std::slice::from_ref(&tok));
if matches!(tok, Token::Char(_, Cat::BeginGroup)) {
return Ok(None);
}
if eng.scan_keyword(lx, "name", false)? {
return read_group(eng, lx).map(Some);
}
let n = eng.scan_number_file(lx)?;
Ok(lualib::chunk_name(n))
}
fn escape_string(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for c in text.chars() {
match c {
'\\' | '"' | '\'' => {
out.push('\\');
out.push(c);
}
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
_ => out.push(c),
}
}
out
}
fn run(
eng: &mut Engine,
lx: &mut Lexer,
out: &mut Vec<Cmd>,
name: Option<&str>,
chunk: &str,
yield_to: Yield,
) -> R<()> {
let (lua, bridge) = runtime(eng)?;
snapshot(eng, &bridge);
let default = match yield_to {
Yield::ToInput => "=[\\directlua]",
Yield::Discard => "=[\\latelua]",
};
let name = name.unwrap_or(default);
let result = ctx::enter(eng, lx, || lua.load(chunk).set_name(name).exec());
finish(eng, lx, out, &bridge, yield_to, result)
}
fn call_function(
eng: &mut Engine,
lx: &mut Lexer,
out: &mut Vec<Cmd>,
n: i64,
yield_to: Yield,
) -> R<()> {
let (lua, bridge) = runtime(eng)?;
snapshot(eng, &bridge);
let result = ctx::enter(eng, lx, || {
functions_table(&lua)
.and_then(|t| t.get::<mlua::Function>(n))
.and_then(|f| f.call::<()>(n))
});
finish(eng, lx, out, &bridge, yield_to, result)
}
fn finish(
eng: &mut Engine,
lx: &mut Lexer,
out: &mut Vec<Cmd>,
bridge: &Rc<RefCell<Bridge>>,
yield_to: Yield,
result: mlua::Result<()>,
) -> R<()> {
let mut b = bridge.borrow_mut();
for (®, &v) in &b.counts_written {
eng.known.set(reg, Some(v));
out.push(Cmd::SetCount(reg, Num::Literal(v)));
}
let toks_written = std::mem::take(&mut b.toks_written);
for (reg, text) in toks_written {
let toks = tokenize(&text, Regime::Verbatim, LineMode::Partial, &eng.cats);
eng.toks.insert(reg, toks);
}
for m in std::mem::take(&mut b.messages) {
let op = match m.nl {
true => crate::ir::MsgOp::Report(format!("{}\n{}", crate::expand::DIAGNOSTIC, m.text)),
false => crate::ir::MsgOp::Text(m.text),
};
out.push(Cmd::Message(vec![op]));
}
if let Some(e) = b.error.take() {
return Err(TexError(e));
}
if let Err(e) = result {
return Err(TexError(lua_error_text(&e)));
}
if yield_to == Yield::Discard {
b.prints.clear();
return Ok(());
}
let prints = std::mem::take(&mut b.prints);
let mut toks = Vec::new();
let last = prints.len().saturating_sub(1);
for (i, p) in prints.iter().enumerate() {
let line = match p.line == LineMode::Line && i == last {
true => LineMode::Partial,
false => p.line,
};
toks.extend(tokenize(&p.text, p.cats, line, &eng.cats));
}
lx.push_back(&toks);
Ok(())
}
fn lua_error_text(e: &mlua::Error) -> String {
let text = match e {
mlua::Error::CallbackError { cause, .. } => return lua_error_text(cause),
mlua::Error::SyntaxError { message, .. } => format!("Lua syntax error: {message}"),
other => format!("Lua error: {other}"),
};
let text = match text.split_once("\nstack traceback:") {
Some((head, _)) => head.to_string(),
None => text,
};
text.replace('\n', " ").trim_end().to_string()
}
const OWNER_CS: &str = "\u{0}lua-document";
fn document_id(eng: &mut Engine) -> i64 {
let cs = crate::token::CsId::intern(OWNER_CS);
if let Some(Meaning::CharDef(id)) = eng.meanings.get(&cs) {
return *id;
}
static NEXT: once_cell::sync::Lazy<std::sync::atomic::AtomicI64> =
once_cell::sync::Lazy::new(|| {
let seed = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| i64::from(d.subsec_nanos()))
.unwrap_or(1);
std::sync::atomic::AtomicI64::new(seed * 1_000_000 + 1)
});
let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
eng.meanings.insert(cs, Meaning::CharDef(id));
id
}
fn runtime(eng: &mut Engine) -> R<(Lua, Rc<RefCell<Bridge>>)> {
let owner = document_id(eng) as usize;
RUNTIME.with(|slot| {
let mut slot = slot.borrow_mut();
let fresh = match slot.as_ref() {
Some(rt) => rt.owner != owner,
None => true,
};
if fresh {
*slot = Some(build(owner).map_err(|e| TexError(lua_error_text(&e)))?);
LUADEFS.with(|m| m.borrow_mut().clear());
EXPANDABLE_LUADEFS.with(|m| m.borrow_mut().clear());
ANY_LUADEF.with(|f| f.set(false));
}
let rt = slot.as_ref().expect("just built");
Ok((rt.lua.clone(), Rc::clone(&rt.bridge)))
})
}
fn snapshot(eng: &Engine, bridge: &Rc<RefCell<Bridge>>) {
let mut b = bridge.borrow_mut();
b.prints.clear();
b.error = None;
b.counts = eng.known.values();
b.counts_written.clear();
b.toks_written.clear();
b.count_names.clear();
b.toks_names.clear();
b.toks.clear();
for ® in eng.toks.keys() {
b.toks.insert(reg, eng.toks_text(reg));
}
for (name, meaning) in eng.meanings.iter() {
match meaning {
Meaning::CountDef(r) => {
b.count_names.insert(name.name().to_string(), *r);
}
Meaning::ToksDef(r) => {
b.toks_names.insert(name.name().to_string(), *r);
}
_ => {}
}
}
}
pub fn explicit_jobname() -> Option<String> {
if let Some(j) = JOBNAME.with(|j| j.borrow().clone()) {
return Some(j);
}
let mut args = std::env::args().skip(1);
while let Some(a) = args.next() {
if let Some(v) = a
.strip_prefix("-jobname=")
.or_else(|| a.strip_prefix("--jobname="))
{
return Some(v.to_string());
}
if a == "-jobname" || a == "--jobname" {
return args.next();
}
}
None
}
pub(crate) fn jobname() -> String {
if let Some(j) = explicit_jobname() {
return j;
}
let mut file = None;
for a in std::env::args().skip(1) {
if file.is_none() && !a.starts_with('-') && !a.starts_with('\\') && !a.starts_with('&') {
file = Some(a);
}
}
file.map(|f| {
std::path::Path::new(&f)
.file_stem()
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_else(|| f.clone())
})
.unwrap_or_else(|| "texput".to_string())
}
fn tokenize(
text: &str,
regime: Regime,
line: LineMode,
cats: &crate::catcode::CatTable,
) -> Vec<Token> {
match regime {
Regime::Verbatim => text
.chars()
.map(|c| match c == ' ' {
true => Token::Char(' ', Cat::Space),
false => Token::Char(c, Cat::Other),
})
.collect(),
Regime::All(cat) => {
let mut table = crate::catcode::CatTable::new();
for c in text.chars() {
table.set(c, cat);
}
scan(text, LineMode::Partial, &table)
}
Regime::Current => scan(text, line, cats),
}
}
fn scan(text: &str, line: LineMode, cats: &crate::catcode::CatTable) -> Vec<Token> {
let mut out = Vec::new();
let body = match line {
LineMode::Line => format!("{}\n", text.trim_end_matches(' ')),
LineMode::Partial => {
let rest = text.trim_start_matches(' ');
if rest.len() != text.len() {
out.push(Token::Char(' ', Cat::Space));
}
rest.to_string()
}
};
let mut lx = Lexer::new(&body);
while let Some(t) = lx.next_token(cats) {
out.push(t);
}
out
}
fn functions_table(lua: &Lua) -> mlua::Result<Table> {
lua.named_registry_value::<Table>(lualib::FUNCTIONS)
}
fn build(owner: usize) -> mlua::Result<Runtime> {
let lua = libs::new_state()?;
callback::reset();
let bridge = Rc::new(RefCell::new(Bridge::default()));
let arena = Rc::new(RefCell::new(node::Arena::default()));
let globals = lua.globals();
let register = |name: &str, t: Table| -> mlua::Result<()> {
let loaded: Table = globals.get::<Table>("package")?.get("loaded")?;
loaded.set(name, t.clone())?;
globals.set(name, t)
};
register("tex", tex_table(&lua, &bridge, &arena)?)?;
register("token", token::table(&lua, &arena)?)?;
register("node", node::table(&lua, &arena)?)?;
register("texio", texio_table(&lua, &bridge)?)?;
register("kpse", kpse::table(&lua)?)?;
register("callback", callback::table(&lua, &arena)?)?;
register("lua", lualib::table(&lua)?)?;
register("status", status_table(&lua)?)?;
register("font", font::table(&lua)?)?;
register("pdf", pdf::table(&lua, &bridge)?)?;
register(
"pdfe",
unported(
&lua,
"pdfe",
PDFE,
"reads PDF files through pplib, which is not ported",
)?,
)?;
globals.set("texconfig", lua.create_table()?)?;
kpse::install_searcher(&lua)?;
libs::core(&lua)?;
globals.set("luatexbase", luatexbase_table(&lua)?)?;
globals.set("luaotfload", luaotfload_table(&lua, &bridge)?)?;
Ok(Runtime { lua, bridge, owner })
}
const PDFE: &[&str] = &[
"arraytotable",
"close",
"closestream",
"dictionarytotable",
"getarray",
"getboolean",
"getbox",
"getcatalog",
"getdictionary",
"getfromarray",
"getfromdictionary",
"getfromreference",
"getfromstream",
"getinfo",
"getinteger",
"getmemoryusage",
"getname",
"getnofobjects",
"getnofpages",
"getnumber",
"getpage",
"getpages",
"getsize",
"getstatus",
"getstream",
"getstring",
"gettrailer",
"getversion",
"new",
"open",
"openstream",
"pagestotable",
"readfromstream",
"readwholestream",
"type",
"unencrypt",
];
fn unported(
lua: &Lua,
lib: &'static str,
names: &[&'static str],
why: &'static str,
) -> mlua::Result<Table> {
let t = lua.create_table()?;
for name in names {
let name: &'static str = name;
t.set(
name,
lua.create_function(move |_, _: Variadic<Value>| {
Err::<(), _>(mlua::Error::runtime(format!("{lib}.{name}: {lib} {why}")))
})?,
)?;
}
Ok(t)
}
fn lua_tostring(lua: &Lua, v: &Value) -> mlua::Result<String> {
match v {
Value::String(s) => Ok(s.to_str()?.to_string()),
other => lua
.globals()
.get::<mlua::Function>("tostring")?
.call::<String>(other.clone()),
}
}
fn print_args(lua: &Lua, args: &Variadic<Value>) -> mlua::Result<(Option<i64>, Vec<String>)> {
let mut rest = &args[..];
let mut selector = None;
if rest.len() > 1 {
if let Some(n) = rest[0].as_integer() {
selector = Some(n);
rest = &rest[1..];
}
}
let mut texts = Vec::new();
if let [Value::Table(t)] = rest {
let len = t.raw_len();
for i in 1..=len {
match t.raw_get::<Value>(i)? {
Value::String(s) => texts.push(s.to_str()?.to_string()),
Value::Integer(n) => texts.push(n.to_string()),
Value::Number(_) => texts.push(lua_tostring(lua, &t.raw_get::<Value>(i)?)?),
_ => break,
}
}
return Ok((selector, texts));
}
for v in rest {
match v {
Value::Nil | Value::Boolean(_) | Value::Table(_) | Value::Function(_) => break,
other => texts.push(lua_tostring(lua, other)?),
}
}
Ok((selector, texts))
}
fn drop_global(args: &Variadic<Value>) -> Vec<Value> {
match args.first() {
Some(Value::String(s)) if s.to_str().map(|s| s == "global").unwrap_or(false) => {
args.iter().skip(1).cloned().collect()
}
_ => args.iter().cloned().collect(),
}
}
fn regime_of(selector: Option<i64>) -> Regime {
match selector {
Some(-2) => Regime::Verbatim,
_ => Regime::Current,
}
}
fn tex_table(
lua: &Lua,
bridge: &Rc<RefCell<Bridge>>,
arena: &Rc<RefCell<node::Arena>>,
) -> mlua::Result<Table> {
let tex = lua.create_table()?;
for (name, line) in [("print", LineMode::Line), ("sprint", LineMode::Partial)] {
let b = Rc::clone(bridge);
tex.set(
name,
lua.create_function(move |lua, args: Variadic<Value>| {
let (selector, texts) = print_args(lua, &args)?;
let cats = regime_of(selector);
let mut b = b.borrow_mut();
for text in texts {
b.prints.push(Print { text, cats, line });
}
Ok(())
})?,
)?;
}
let b = Rc::clone(bridge);
tex.set(
"write",
lua.create_function(move |lua, args: Variadic<Value>| {
let (_, texts) = print_args(lua, &args)?;
let mut b = b.borrow_mut();
for text in texts {
b.prints.push(Print {
text,
cats: Regime::Verbatim,
line: LineMode::Partial,
});
}
Ok(())
})?,
)?;
let b = Rc::clone(bridge);
tex.set(
"cprint",
lua.create_function(move |lua, args: Variadic<Value>| {
let n = args
.first()
.and_then(|v| v.as_integer())
.ok_or_else(|| mlua::Error::runtime("tex.cprint wants a catcode"))?;
let cat = crate::catcode::cat_from_i64(n)
.ok_or_else(|| mlua::Error::runtime(format!("bad catcode {n}")))?;
let rest = Variadic::from_iter(args.iter().skip(1).cloned());
let (_, texts) = print_args(lua, &rest)?;
let mut b = b.borrow_mut();
for text in texts {
b.prints.push(Print {
text,
cats: Regime::All(cat),
line: LineMode::Partial,
});
}
Ok(())
})?,
)?;
let b = Rc::clone(bridge);
tex.set(
"tprint",
lua.create_function(move |lua, args: Variadic<Value>| {
for arg in args.iter() {
let Value::Table(t) = arg else { continue };
let inner = Variadic::from_iter(t.clone().sequence_values::<Value>().flatten());
let (selector, texts) = print_args(lua, &inner)?;
let cats = regime_of(selector);
let mut b = b.borrow_mut();
for text in texts {
b.prints.push(Print {
text,
cats,
line: LineMode::Partial,
});
}
}
Ok(())
})?,
)?;
tex.set("count", register_table(lua, bridge, Kind::Count)?)?;
tex.set("dimen", register_table(lua, bridge, Kind::Dimen)?)?;
tex.set("toks", register_table(lua, bridge, Kind::Toks)?)?;
tex.set("attribute", register_table(lua, bridge, Kind::Attribute)?)?;
for (name, kind) in [
("getcount", Kind::Count),
("getdimen", Kind::Dimen),
("getattribute", Kind::Attribute),
] {
let b = Rc::clone(bridge);
tex.set(
name,
lua.create_function(move |_, key: Value| {
let b = b.borrow();
let reg = resolve(&b, kind, &key)?;
Ok(register_value(&b, kind, reg))
})?,
)?;
}
for (name, kind) in [
("setcount", Kind::Count),
("setdimen", Kind::Dimen),
("setattribute", Kind::Attribute),
] {
let b = Rc::clone(bridge);
tex.set(
name,
lua.create_function(move |_, args: Variadic<Value>| {
let args = drop_global(&args);
let [key, value] = &args[..] else {
return Err(mlua::Error::runtime(
"tex.set* wants a register and a value",
));
};
let mut b = b.borrow_mut();
let reg = resolve(&b, kind, key)?;
let v = scaled_value(kind, value)?;
b.counts.insert(reg, v);
b.counts_written.insert(reg, v);
Ok(())
})?,
)?;
}
tex.set("glue", register_table(lua, bridge, Kind::Glue)?)?;
let b = Rc::clone(bridge);
tex.set(
"getglue",
lua.create_function(move |_, args: Variadic<Value>| {
let key = args.first().cloned().unwrap_or(Value::Nil);
let b = b.borrow();
let base = resolve(&b, Kind::Glue, &key)?;
let (w, st, sh, sto, sho) = glue_get(&b, base);
match args.get(1) {
Some(Value::Boolean(false)) => Ok(Variadic::from_iter([Value::Integer(w)])),
_ => Ok(Variadic::from_iter(
[w, st, sh, sto, sho].map(Value::Integer),
)),
}
})?,
)?;
let b = Rc::clone(bridge);
tex.set(
"setglue",
lua.create_function(move |_, args: Variadic<Value>| {
let args = drop_global(&args);
let Some(key) = args.first() else {
return Err(mlua::Error::runtime("tex.setglue wants a register"));
};
let n = |i: usize| args.get(i).and_then(|v| v.as_integer()).unwrap_or(0);
let mut b = b.borrow_mut();
let base = resolve(&b, Kind::Glue, key)?;
glue_set(&mut b, base, (n(1), n(2), n(3), n(4), n(5)))?;
Ok(())
})?,
)?;
let b = Rc::clone(bridge);
let a = Rc::clone(arena);
tex.set(
"getskip",
lua.create_function(move |lua, key: Value| {
let base = {
let b = b.borrow();
resolve(&b, Kind::Glue, &key)?
};
let glue = glue_get(&b.borrow(), base);
node::spec_node(lua, &a, glue)
})?,
)?;
let b = Rc::clone(bridge);
let a = Rc::clone(arena);
tex.set(
"setskip",
lua.create_function(move |_, args: Variadic<Value>| {
let args = drop_global(&args);
let [key, value] = &args[..] else {
return Err(mlua::Error::runtime(
"tex.setskip wants a register and a glue_spec node",
));
};
let glue = node::spec_values(&a, value)?;
let mut b = b.borrow_mut();
let base = resolve(&b, Kind::Glue, key)?;
glue_set(&mut b, base, glue)
})?,
)?;
let b = Rc::clone(bridge);
let a = Rc::clone(arena);
tex.set(
"getmuskip",
lua.create_function(move |lua, key: Value| {
let base = {
let b = b.borrow();
resolve(&b, Kind::MuGlue, &key)?
};
let glue = glue_get(&b.borrow(), base);
node::spec_node(lua, &a, glue)
})?,
)?;
let b = Rc::clone(bridge);
let a = Rc::clone(arena);
tex.set(
"setmuskip",
lua.create_function(move |_, args: Variadic<Value>| {
let args = drop_global(&args);
let [key, value] = &args[..] else {
return Err(mlua::Error::runtime(
"tex.setmuskip wants a register and a glue_spec node",
));
};
let glue = node::spec_values(&a, value)?;
let mut b = b.borrow_mut();
let base = resolve(&b, Kind::MuGlue, key)?;
glue_set(&mut b, base, glue)
})?,
)?;
let b = Rc::clone(bridge);
tex.set(
"getmuglue",
lua.create_function(move |_, args: Variadic<Value>| {
let key = args.first().cloned().unwrap_or(Value::Nil);
let b = b.borrow();
let base = resolve(&b, Kind::MuGlue, &key)?;
let (w, st, sh, sto, sho) = glue_get(&b, base);
match args.get(1) {
Some(Value::Boolean(false)) => Ok(Variadic::from_iter([Value::Integer(w)])),
_ => Ok(Variadic::from_iter(
[w, st, sh, sto, sho].map(Value::Integer),
)),
}
})?,
)?;
let b = Rc::clone(bridge);
tex.set(
"setmuglue",
lua.create_function(move |_, args: Variadic<Value>| {
let args = drop_global(&args);
let Some(key) = args.first() else {
return Err(mlua::Error::runtime("tex.setmuglue wants a register"));
};
let n = |i: usize| args.get(i).and_then(|v| v.as_integer()).unwrap_or(0);
let mut b = b.borrow_mut();
let base = resolve(&b, Kind::MuGlue, key)?;
glue_set(&mut b, base, (n(1), n(2), n(3), n(4), n(5)))?;
Ok(())
})?,
)?;
tex.set("muglue", register_table(lua, bridge, Kind::MuGlue)?)?;
let muskip = lua.create_table()?;
let mt = lua.create_table()?;
let b = Rc::clone(bridge);
let a = Rc::clone(arena);
mt.set(
"__index",
lua.create_function(move |lua, (_, key): (Table, Value)| {
let base = {
let b = b.borrow();
resolve(&b, Kind::MuGlue, &key)?
};
let glue = glue_get(&b.borrow(), base);
node::spec_node(lua, &a, glue)
})?,
)?;
let b = Rc::clone(bridge);
let a = Rc::clone(arena);
mt.set(
"__newindex",
lua.create_function(move |_, (_, key, value): (Table, Value, Value)| {
let glue = node::spec_values(&a, &value)?;
let mut b = b.borrow_mut();
let base = resolve(&b, Kind::MuGlue, &key)?;
glue_set(&mut b, base, glue)
})?,
)?;
muskip.set_metatable(Some(mt))?;
tex.set("muskip", muskip)?;
for name in [
"getbox", "setbox", "splitbox", "getlist", "setlist", "getnest", "getmath", "setmath",
] {
tex.set(
name,
lua.create_function(move |_, _: Variadic<Value>| {
Err::<(), _>(mlua::Error::runtime(format!(
"tex.{name} works on the stomach's node lists, which exist while the program runs and not while a chunk is lowered"
)))
})?,
)?;
}
let skip = lua.create_table()?;
let mt = lua.create_table()?;
let b = Rc::clone(bridge);
let a = Rc::clone(arena);
mt.set(
"__index",
lua.create_function(move |lua, (_, key): (Table, Value)| {
let base = {
let b = b.borrow();
resolve(&b, Kind::Glue, &key)?
};
let glue = glue_get(&b.borrow(), base);
node::spec_node(lua, &a, glue)
})?,
)?;
let b = Rc::clone(bridge);
let a = Rc::clone(arena);
mt.set(
"__newindex",
lua.create_function(move |_, (_, key, value): (Table, Value, Value)| {
let glue = node::spec_values(&a, &value)?;
let mut b = b.borrow_mut();
let base = resolve(&b, Kind::Glue, &key)?;
glue_set(&mut b, base, glue)
})?,
)?;
skip.set_metatable(Some(mt))?;
tex.set("skip", skip)?;
for (name, kind) in [
("iscount", Kind::Count),
("isdimen", Kind::Dimen),
("isskip", Kind::Glue),
("isglue", Kind::Glue),
("ismuskip", Kind::MuGlue),
("ismuglue", Kind::MuGlue),
("istoks", Kind::Toks),
("isattribute", Kind::Attribute),
] {
let b = Rc::clone(bridge);
tex.set(
name,
lua.create_function(move |_, key: Value| {
let b = b.borrow();
let Ok(slot) = resolve(&b, kind, &key) else {
return Ok(Value::Boolean(false));
};
if let Ok(Some((_, n))) =
ctx::with("tex.is", |eng, _| Ok(eng.pooled_register(slot)))
{
return Ok(Value::Integer(n));
}
let base = match kind {
Kind::Count | Kind::Toks => 0,
Kind::Dimen => crate::compiler::DIMEN_BASE,
Kind::Glue => crate::compiler::SKIP_BASE,
Kind::MuGlue => crate::compiler::MUSKIP_BASE,
Kind::Attribute => ATTRIBUTE_BASE,
};
let stride = match kind {
Kind::Glue | Kind::MuGlue => crate::compiler::SKIP_STRIDE,
_ => 1,
};
Ok(Value::Integer((slot - base) / stride))
})?,
)?;
}
let b = Rc::clone(bridge);
tex.set(
"gettoks",
lua.create_function(move |_, key: Value| {
let b = b.borrow();
let reg = resolve(&b, Kind::Toks, &key)?;
Ok(b.toks.get(®).cloned().unwrap_or_default())
})?,
)?;
let b = Rc::clone(bridge);
tex.set(
"settoks",
lua.create_function(move |_, args: Variadic<Value>| {
let args = drop_global(&args);
let [key, value] = &args[..] else {
return Err(mlua::Error::runtime(
"tex.settoks wants a register and a string",
));
};
let mut b = b.borrow_mut();
let reg = resolve(&b, Kind::Toks, key)?;
let text = value.to_string()?;
b.toks.insert(reg, text.clone());
b.toks_written.insert(reg, text);
Ok(())
})?,
)?;
tex.set("jobname", jobname())?;
tex.set("luatexversion", 124)?;
tex.set("luatexrevision", "0")?;
let b = Rc::clone(bridge);
tex.set(
"error",
lua.create_function(move |_, (msg, _help): (String, Option<Table>)| {
b.borrow_mut().error = Some(msg);
Ok(())
})?,
)?;
tex.set(
"sp",
lua.create_function(|_, v: Value| {
scaled_value(Kind::Dimen, &v).map_err(|e| mlua::Error::runtime(e.to_string()))
})?,
)?;
tex.set(
"round",
lua.create_function(|_, v: f64| Ok(clamp_register(v.round() as i64)))?,
)?;
tex.set(
"scale",
lua.create_function(|_, (v, delta): (f64, f64)| {
Ok(clamp_register((v * delta).round() as i64))
})?,
)?;
tex.set(
"number",
lua.create_function(|_, n: i64| Ok(n.to_string()))?,
)?;
let b = Rc::clone(bridge);
tex.set(
"runtoks",
lua.create_function(
move |_, (what, _force, _grouped): (Value, Option<bool>, Option<bool>)| {
let stop = ctx::with("tex.runtoks", |_, lx| Ok(lx.pending.len()))?;
match what {
Value::Function(f) => {
let printed_before = b.borrow().prints.len();
f.call::<()>(())?;
let prints: Vec<Print> =
b.borrow_mut().prints.drain(printed_before..).collect();
ctx::with("tex.runtoks", |eng, lx| {
let mut toks = Vec::new();
for p in &prints {
toks.extend(tokenize(&p.text, p.cats, p.line, &eng.cats));
}
lx.push_back(&toks);
Ok(())
})?;
}
Value::Integer(_) | Value::String(_) => {
let reg = match &what {
Value::Integer(n) => *n,
Value::String(s) => {
let name = s.to_str()?.to_string();
b.borrow().toks_names.get(&name).copied().ok_or_else(|| {
mlua::Error::runtime(format!(
"tex.runtoks: no token register named {name}"
))
})?
}
_ => unreachable!(),
};
ctx::with("tex.runtoks", |eng, lx| {
let list = eng.toks.get(®).cloned().unwrap_or_default();
lx.push_back(&list);
Ok(())
})?;
}
_ => return Err(mlua::Error::runtime("invalid argument to tex.runtoks")),
}
ctx::with("tex.runtoks", |eng, lx| {
eng.local_control(lx, stop)
.map_err(|e| mlua::Error::runtime(e.0))
})
},
)?,
)?;
tex.set(
"romannumeral",
lua.create_function(|_, n: i64| Ok(roman(n)))?,
)?;
tex.set(
"extraprimitives",
lua.create_function(|lua, args: Variadic<Value>| {
use extraprimitives::{Origin, PRIMITIVES};
let mut mask = Vec::new();
if args.is_empty() {
mask = vec![Origin::Etex, Origin::Luatex];
}
for a in args.iter() {
if let Value::String(s) = a {
match &*s.to_str()? {
"etex" => mask.push(Origin::Etex),
"tex" => mask.push(Origin::Tex),
"core" => mask.push(Origin::Core),
"luatex" => mask.push(Origin::Luatex),
_ => {}
}
}
}
lua.create_sequence_from(
PRIMITIVES
.iter()
.filter(|(origin, _)| mask.contains(origin))
.map(|(_, name)| *name),
)
})?,
)?;
tex.set(
"enableprimitives",
lua.create_function(|_, args: Variadic<Value>| {
let [Value::String(prefix), names] = &args[..] else {
return Err(mlua::Error::runtime("wrong number of arguments"));
};
let Value::Table(names) = names else {
return Err(mlua::Error::runtime(
"Expected an array of names as second argument",
));
};
let prefix = prefix.to_str()?.to_string();
let mut prims = Vec::new();
for v in names.sequence_values::<Value>() {
let Value::String(s) = v? else { break };
prims.push(s.to_str()?.to_string());
}
ctx::with("tex.enableprimitives", |eng, _| {
for prim in prims {
if !token::is_primitive_name(&prim) {
continue;
}
let name = match prim.starts_with(&prefix) {
true => prim.clone(),
false => format!("{prefix}{prim}"),
};
if token::means_something(eng, &name) {
continue;
}
eng.meanings.insert(
crate::token::CsId::intern(&name),
Meaning::Primitive(crate::token::CsId::intern(&prim)),
);
}
Ok(())
})
})?,
)?;
tex::install(lua, &tex, bridge, arena)?;
Ok(tex)
}
fn parameter_reason(key: &Value) -> mlua::Result<Option<String>> {
let Value::String(s) = key else {
return Ok(None);
};
Ok(parameter_reason_text(&s.to_str()?))
}
fn parameter_reason_text(name: &str) -> Option<String> {
let name = name.to_string();
const GEOMETRY: &[&str] = &[
"hsize",
"vsize",
"parindent",
"hoffset",
"voffset",
"pagewidth",
"pageheight",
"pagetopoffset",
"pagebottomoffset",
"pageleftoffset",
"pagerightoffset",
"baselineskip",
"lineskip",
"lineskiplimit",
"parskip",
"leftskip",
"rightskip",
"parfillskip",
"topskip",
"splittopskip",
"spaceskip",
"xspaceskip",
"hangindent",
"hangafter",
];
const BREAKER: &[&str] = &[
"tolerance",
"pretolerance",
"hbadness",
"vbadness",
"hfuzz",
"vfuzz",
"adjdemerits",
"linepenalty",
"doublehyphendemerits",
"finalhyphendemerits",
"exhyphenpenalty",
"hyphenpenalty",
"interlinepenalty",
"clubpenalty",
"widowpenalty",
"displaywidowpenalty",
"brokenpenalty",
"looseness",
"emergencystretch",
"lefthyphenmin",
"righthyphenmin",
"uchyph",
"lastlinefit",
"language",
"overfullrule",
];
const REST: &[&str] = &[
"abovedisplayshortskip",
"abovedisplayskip",
"belowdisplayshortskip",
"belowdisplayskip",
"binoppenalty",
"bodydir",
"boxmaxdepth",
"catcodetable",
"clubpenalties",
"day",
"deadcycles",
"defaulthyphenchar",
"defaultskewchar",
"delimiterfactor",
"delimitershortfall",
"displayindent",
"displaywidowpenalties",
"displaywidth",
"endlinechar",
"errhelp",
"errorcontextlines",
"escapechar",
"everycr",
"everydisplay",
"everyeof",
"everyhbox",
"everyjob",
"everymath",
"everypar",
"everyvbox",
"fam",
"floatingpenalty",
"globaldefs",
"holdinginserts",
"insertpenalties",
"interlinepenalties",
"lastkern",
"lastnodetype",
"lastpenalty",
"lastskip",
"localbrokenpenalty",
"localinterlinepenalty",
"mag",
"mathdir",
"mathsurround",
"maxdeadcycles",
"maxdepth",
"medmuskip",
"month",
"nest",
"newlinechar",
"nulldelimiterspace",
"output",
"outputpenalty",
"pagebottomoffset",
"pagedepth",
"pagedir",
"pagefilllstretch",
"pagefillstretch",
"pagefilstretch",
"pagegoal",
"pageshrink",
"pagestretch",
"pagetotal",
"pardir",
"parshape",
"pausing",
"postdisplaypenalty",
"predisplaydirection",
"predisplaypenalty",
"predisplaysize",
"prevdepth",
"prevgraf",
"relpenalty",
"savinghyphcodes",
"savingvdiscards",
"scriptspace",
"showboxbreadth",
"showboxdepth",
"spacefactor",
"splitmaxdepth",
"tabskip",
"textdir",
"thickmuskip",
"thinmuskip",
"time",
"tracingassigns",
"tracingcommands",
"tracinggroups",
"tracingifs",
"tracinglostchars",
"tracingmacros",
"tracingnesting",
"tracingonline",
"tracingoutput",
"tracingpages",
"tracingparagraphs",
"tracingrestores",
"tracingscantokens",
"tracingstats",
"widowpenalties",
"year",
];
let name = name.as_str();
if crate::intpar::index(name).is_some()
|| crate::params::register_slot(name).is_some()
|| crate::params::toks_register(name).is_some()
{
return None;
}
if GEOMETRY.contains(&name) {
return Some(format!(
"tex.{name} is one of LuaTeX's internal parameters, and the page \
geometry lives in crate::typeset::Layout, decided from the class and \
geometry options rather than read from what the document assigned, \
and it is not decided yet where a chunk stands"
));
}
if BREAKER.contains(&name) {
return Some(format!(
"tex.{name} is one of LuaTeX's internal parameters, and the line \
breaker uses a constant in crate::linebreak rather than reading it"
));
}
if REST.contains(&name) {
return Some(format!(
"tex.{name} is one of LuaTeX's internal parameters, and texrs does not \
hold it at all: it belongs to the stomach, the output routine or the \
maths, none of which is on the path a run takes"
));
}
None
}
#[derive(Clone, Copy, PartialEq)]
enum Kind {
Count,
Dimen,
Glue,
MuGlue,
Toks,
Attribute,
}
impl Kind {
fn primitive(self) -> &'static str {
match self {
Kind::Count => "count",
Kind::Dimen => "dimen",
Kind::Glue => "skip",
Kind::MuGlue => "muskip",
Kind::Toks => "toks",
Kind::Attribute => "attribute",
}
}
}
fn register_value(b: &Bridge, kind: Kind, reg: i64) -> i64 {
match kind {
Kind::Attribute => b
.counts
.get(®)
.copied()
.unwrap_or(node::UNUSED_ATTRIBUTE),
_ => slot_value(b, reg),
}
}
fn slot_value(b: &Bridge, slot: i64) -> i64 {
if let Some(v) = b.counts.get(&slot) {
return *v;
}
if ctx::depth() > 0 {
if let Ok(Some(v)) = ctx::with("tex", |eng, _| Ok(eng.known.get(slot))) {
return v;
}
}
crate::params::initial_value(slot)
}
const ATTRIBUTE_BASE: i64 = 1 << 20;
const REGISTERS: i64 = 65536;
fn resolve(b: &Bridge, kind: Kind, key: &Value) -> mlua::Result<i64> {
let base = match kind {
Kind::Count | Kind::Toks => 0,
Kind::Dimen => crate::compiler::DIMEN_BASE,
Kind::Glue => crate::compiler::SKIP_BASE,
Kind::MuGlue => crate::compiler::MUSKIP_BASE,
Kind::Attribute => ATTRIBUTE_BASE,
};
let stride = match kind {
Kind::Glue | Kind::MuGlue => crate::compiler::SKIP_STRIDE,
_ => 1,
};
if let Some(n) = key.as_integer() {
let file = match kind {
Kind::Count => Some(crate::compiler::RegFile::Count),
Kind::Dimen => Some(crate::compiler::RegFile::Dimen),
Kind::Glue => Some(crate::compiler::RegFile::Skip),
Kind::MuGlue => Some(crate::compiler::RegFile::MuSkip),
_ => None,
};
let Some(file) = file else {
return Ok(base + n * stride);
};
if !(0..REGISTERS).contains(&n) {
return Err(mlua::Error::runtime(format!(
"\\{}{n} is out of range: there are {REGISTERS} {} registers",
kind.primitive(),
kind.primitive(),
)));
}
if n < 256 {
return Ok(base + n * stride);
}
return ctx::with("tex", |eng, _| {
eng.register_address(file, n)
.map_err(|e| mlua::Error::runtime(e.0))
});
}
let Value::String(s) = key else {
return Err(mlua::Error::runtime(
"register index must be a number or a name",
));
};
let name = s.to_str()?.to_string();
let found = match kind {
Kind::Toks => b.toks_names.get(&name).copied(),
_ => b.count_names.get(&name).copied(),
};
found.ok_or_else(|| mlua::Error::runtime(format!("no register named {name}")))
}
fn glue_get(b: &Bridge, base: i64) -> (i64, i64, i64, i64, i64) {
let at = |i: i64| slot_value(b, base + i);
let packed = at(3);
(
at(0),
at(1),
at(2),
to_luatex_order(packed / 4),
to_luatex_order(packed % 4),
)
}
fn glue_set(b: &mut Bridge, base: i64, glue: (i64, i64, i64, i64, i64)) -> mlua::Result<()> {
let (w, st, sh, sto, sho) = glue;
let packed = from_luatex_order(sto)? * 4 + from_luatex_order(sho)?;
for (i, v) in [w, st, sh, packed].into_iter().enumerate() {
let v = clamp_register(v);
b.counts.insert(base + i as i64, v);
b.counts_written.insert(base + i as i64, v);
}
Ok(())
}
fn to_luatex_order(order: i64) -> i64 {
match order {
0 => 0,
n => n + 1,
}
}
fn from_luatex_order(order: i64) -> mlua::Result<i64> {
match order {
0 => Ok(0),
1 => Err(mlua::Error::runtime(
"stretch order 1 is LuaTeX's `fi`, which texrs has no unit for",
)),
n if (2..=4).contains(&n) => Ok(n - 1),
n => Err(mlua::Error::runtime(format!("bad glue order {n}"))),
}
}
fn scaled_value(kind: Kind, v: &Value) -> mlua::Result<i64> {
if let Some(n) = v.as_integer() {
return Ok(clamp_register(n));
}
if let Some(n) = v.as_number() {
return Ok(clamp_register(n.round() as i64));
}
let Value::String(s) = v else {
return Err(mlua::Error::runtime(
"register value must be a number or a dimension",
));
};
if kind != Kind::Dimen {
return Err(mlua::Error::runtime("register value must be a number"));
}
parse_dimen(s.to_str()?.trim()).ok_or_else(|| mlua::Error::runtime("bad dimension"))
}
fn parse_dimen(text: &str) -> Option<i64> {
let mut chars = text.chars().peekable();
let mut sign = 1i64;
while let Some(&c) = chars.peek() {
match c {
'-' => {
sign = -sign;
chars.next();
}
'+' | ' ' => {
chars.next();
}
_ => break,
}
}
let mut int = String::new();
while let Some(&c) = chars.peek() {
if !c.is_ascii_digit() {
break;
}
int.push(c);
chars.next();
}
let mut frac = String::new();
if matches!(chars.peek(), Some('.') | Some(',')) {
chars.next();
while let Some(&c) = chars.peek() {
if !c.is_ascii_digit() {
break;
}
frac.push(c);
chars.next();
}
}
if int.is_empty() && frac.is_empty() {
return None;
}
let unit: String = chars.collect::<String>().trim().to_lowercase();
if unit.starts_with("fil") || unit == "em" || unit == "ex" || unit == "px" {
return None;
}
let sp = crate::dimen::to_scaled(
int.parse::<i64>().unwrap_or(0),
crate::dimen::round_decimals(&frac),
&unit,
)?;
Some(clamp_register(sign * sp))
}
fn clamp_register(n: i64) -> i64 {
n.clamp(-crate::dimen::MAX_DIMEN, crate::dimen::MAX_DIMEN)
}
fn roman(mut n: i64) -> String {
if n <= 0 {
return String::new();
}
let table = [
(1000, "m"),
(900, "cm"),
(500, "d"),
(400, "cd"),
(100, "c"),
(90, "xc"),
(50, "l"),
(40, "xl"),
(10, "x"),
(9, "ix"),
(5, "v"),
(4, "iv"),
(1, "i"),
];
let mut out = String::new();
for (v, s) in table {
while n >= v {
out.push_str(s);
n -= v;
}
}
out
}
fn register_table(lua: &Lua, bridge: &Rc<RefCell<Bridge>>, kind: Kind) -> mlua::Result<Table> {
let t = lua.create_table()?;
let mt = lua.create_table()?;
let b = Rc::clone(bridge);
mt.set(
"__index",
lua.create_function(move |lua, (_t, key): (Table, Value)| {
let b = b.borrow();
let reg = resolve(&b, kind, &key)?;
match kind {
Kind::Toks => lua
.create_string(b.toks.get(®).cloned().unwrap_or_default())
.map(Value::String),
Kind::Glue | Kind::MuGlue => Ok(Value::Integer(glue_get(&b, reg).0)),
_ => Ok(Value::Integer(register_value(&b, kind, reg))),
}
})?,
)?;
let b = Rc::clone(bridge);
mt.set(
"__newindex",
lua.create_function(move |_, (_t, key, value): (Table, Value, Value)| {
let mut b = b.borrow_mut();
let reg = resolve(&b, kind, &key)?;
match kind {
Kind::Toks => {
let text = value.to_string()?;
b.toks.insert(reg, text.clone());
b.toks_written.insert(reg, text);
}
Kind::Glue | Kind::MuGlue => {
let g = match &value {
Value::Table(t) => {
let n = |i| t.raw_get::<Option<i64>>(i).unwrap_or(None).unwrap_or(0);
(n(1), n(2), n(3), n(4), n(5))
}
other => (scaled_value(Kind::Dimen, other)?, 0, 0, 0, 0),
};
glue_set(&mut b, reg, g)?;
}
_ => {
let v = scaled_value(kind, &value)?;
b.counts.insert(reg, v);
b.counts_written.insert(reg, v);
}
}
Ok(())
})?,
)?;
t.set_metatable(Some(mt))?;
Ok(t)
}
fn texio_table(lua: &Lua, bridge: &Rc<RefCell<Bridge>>) -> mlua::Result<Table> {
let t = lua.create_table()?;
for (name, nl) in [("write", false), ("write_nl", true)] {
let b = Rc::clone(bridge);
t.set(
name,
lua.create_function(move |lua, args: Variadic<Value>| {
let printable = |v: &Value| {
matches!(v, Value::String(_) | Value::Integer(_) | Value::Number(_))
};
if args.is_empty() || !printable(&args[args.len() - 1]) {
return Err(mlua::Error::runtime("no string to print"));
}
let mut rest = &args[..];
let mut to_terminal = true;
if args.len() > 1 {
match &args[0] {
Value::String(s) => to_terminal = &*s.to_str()? != "log",
Value::Integer(_) | Value::Number(_) => {}
_ => {
return Err(mlua::Error::runtime(
"first argument is not 'term and log', 'term', 'log' or a number",
))
}
}
rest = &args[1..];
}
let mut text = String::new();
for v in rest {
if !printable(v) {
return Err(mlua::Error::runtime("argument is not a string"));
}
text.push_str(&lua_tostring(lua, v)?);
}
if to_terminal {
say(&b, Message { text, nl });
}
Ok(())
})?,
)?;
}
t.set("setescape", lua.create_function(|_, _: Value| Ok(()))?)?;
t.set(
"closeinput",
lua.create_function(|_, ()| {
Err::<(), _>(mlua::Error::runtime(
"texio.closeinput ends the input file TeX is reading, which texrs's mouth \
does not let a chunk close",
))
})?,
)?;
Ok(t)
}
fn status_table(lua: &Lua) -> mlua::Result<Table> {
let t = lua.create_table()?;
let fields = |lua: &Lua| -> mlua::Result<Table> {
let f = lua.create_table()?;
f.set(
"banner",
format!("This is texrs, Version {}", env!("CARGO_PKG_VERSION")),
)?;
f.set("luatex_version", 124)?;
f.set("luatex_revision", "0")?;
f.set("luatex_engine", "luatex")?;
f.set("development_id", 7724)?;
f.set("luatex_hashtype", "lua")?;
f.set("luatex_hashchars", 6)?;
f.set("ini_version", false)?;
f.set("shell_escape", libs::SHELL_ESCAPE)?;
f.set("safer_option", 0)?;
f.set("luadebug_option", 0)?;
f.set("kpse_used", 1)?;
f.set("output_active", false)?;
f.set("jobname", jobname())?;
f.set("log_name", format!("{}.log", jobname()))?;
f.set("callbacks", 0)?;
for (name, var) in [
("lc_ctype", "LC_CTYPE"),
("lc_collate", "LC_COLLATE"),
("lc_numeric", "LC_NUMERIC"),
] {
let v = std::env::var(var)
.or_else(|_| std::env::var("LC_ALL"))
.or_else(|_| std::env::var("LANG"))
.unwrap_or_else(|_| "C".to_string());
f.set(name, v)?;
}
if let Ok(line) = ctx::with("status", |_, lx| Ok(lx.line())) {
f.set("linenumber", line as i64)?;
}
Ok(f)
};
let mt = lua.create_table()?;
mt.set(
"__index",
lua.create_function(move |lua, (_, key): (Table, Value)| fields(lua)?.get::<Value>(key))?,
)?;
t.set_metatable(Some(mt))?;
t.set("list", lua.create_function(move |lua, ()| fields(lua))?)?;
t.set("resetmessages", lua.create_function(|_, ()| Ok(()))?)?;
t.set("setexitcode", lua.create_function(|_, _: i64| Ok(()))?)?;
Ok(t)
}
fn luaotfload_table(lua: &Lua, bridge: &Rc<RefCell<Bridge>>) -> mlua::Result<Table> {
let t = lua.create_table()?;
let b = Rc::clone(bridge);
t.set(
"add_fallback",
lua.create_function(move |_, args: Variadic<Value>| {
let list = args.iter().find_map(|v| match v {
Value::Table(t) => Some(t.clone()),
_ => None,
});
let Some(list) = list else {
return Err(mlua::Error::runtime(
"luaotfload.add_fallback wants a table of font specifications",
));
};
let chain: Vec<String> = list
.sequence_values::<String>()
.flatten()
.map(|s| s.split(':').next().unwrap_or_default().trim().to_string())
.filter(|s| !s.is_empty())
.collect();
if !chain.is_empty() {
b.borrow_mut().fallbacks = Some(chain);
}
Ok(())
})?,
)?;
Ok(t)
}
fn luatexbase_table(lua: &Lua) -> mlua::Result<Table> {
let t = lua.create_table()?;
t.set(
"provides_module",
lua.create_function(|_, _: Variadic<Value>| Ok(()))?,
)?;
t.set(
"add_to_callback",
lua.create_function(|_, args: Variadic<Value>| {
Ok(args.first().and_then(|v| v.as_integer()).unwrap_or(0))
})?,
)?;
t.set(
"remove_from_callback",
lua.create_function(|_, _: Variadic<Value>| Ok(()))?,
)?;
t.set(
"callback_descriptions",
lua.create_function(|lua, _: Variadic<Value>| lua.create_table())?,
)?;
t.set(
"registernumber",
lua.create_function(|_, _: Variadic<Value>| Ok(Value::Nil))?,
)?;
t.set(
"module_warning",
lua.create_function(|_, _: Variadic<Value>| Ok(()))?,
)?;
t.set(
"module_error",
lua.create_function(|_, (module, msg): (String, String)| {
Err::<(), _>(mlua::Error::runtime(format!("{module}: {msg}")))
})?,
)?;
Ok(t)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_dimension_string_reaches_the_scaled_points_tex_computes() {
assert_eq!(parse_dimen("1pt"), Some(65536));
assert_eq!(parse_dimen("1in"), Some(4736286));
assert_eq!(parse_dimen("-0.5pt"), Some(-32768));
assert_eq!(parse_dimen("5sp"), Some(5));
assert_eq!(parse_dimen("1fil"), None);
assert_eq!(parse_dimen("1em"), None);
}
#[test]
fn escaping_is_what_luaescapestring_does() {
assert_eq!(escape_string(r#"a\b"c'd"#), r#"a\\b\"c\'d"#);
assert_eq!(escape_string("a\nb"), "a\\nb");
}
#[test]
fn romannumeral_matches_tex() {
assert_eq!(roman(1987), "mcmlxxxvii");
assert_eq!(roman(4), "iv");
assert_eq!(roman(0), "");
}
}