use std::collections::{BTreeMap, BTreeSet};
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Pool {
Count,
Dimen,
Skip,
Toks,
Char,
}
impl Pool {
fn primitive(self) -> &'static str {
match self {
Pool::Count => "countdef",
Pool::Dimen => "dimendef",
Pool::Skip => "skipdef",
Pool::Toks => "toksdef",
Pool::Char => "chardef",
}
}
fn last(self) -> usize {
match self {
Pool::Count => 99,
_ => 255,
}
}
}
const FIRST: usize = 10;
const COMMANDS: [(&str, Pool); 12] = [
("\\newcount", Pool::Count),
("\\newdimen", Pool::Dimen),
("\\newlength", Pool::Skip),
("\\newskip", Pool::Skip),
("\\newmuskip", Pool::Skip),
("\\newtoks", Pool::Toks),
("\\newbox", Pool::Char),
("\\newinsert", Pool::Char),
("\\newread", Pool::Char),
("\\newwrite", Pool::Char),
("\\newlanguage", Pool::Char),
("\\newfam", Pool::Char),
];
pub fn declared(text: &str) -> Vec<(String, &'static str)> {
let mut seen = BTreeSet::new();
let mut out = Vec::new();
let mut found: Vec<(usize, String, Pool)> =
crate::parallel::map_ordered(&COMMANDS, text.len(), |&(command, pool)| {
let mut found = Vec::new();
let mut rest = text;
let mut base = 0usize;
while let Some(at) = rest.find(command) {
let after = &rest[at + command.len()..];
let at_abs = base + at;
base = at_abs + command.len();
rest = after;
if after.starts_with(|c: char| c.is_ascii_alphabetic()) {
continue;
}
let Some(name) = name_after(after) else {
continue;
};
found.push((at_abs, name, pool));
}
found
})
.into_iter()
.flatten()
.collect();
found.sort_by_key(|(at, _, _)| *at);
for (_, name, pool) in found {
if seen.insert(name.clone()) {
out.push((name, pool.primitive()));
}
}
out
}
fn name_after(after: &str) -> Option<String> {
let after = after.trim_start_matches([' ', '\t', '\r', '\n']);
let after = after.strip_prefix('{').unwrap_or(after).trim_start();
let after = after.strip_prefix('\\')?;
let end = after
.find(|c: char| !(c.is_ascii_alphabetic() || c == '@'))
.unwrap_or(after.len());
let name = &after[..end];
match name.is_empty() || name == "csname" || name == "expandafter" {
true => None,
false => Some(name.to_string()),
}
}
pub fn definitions(text: &str) -> String {
let names = declared(text);
if names.is_empty() {
return String::new();
}
let mut next: BTreeMap<&'static str, usize> = BTreeMap::new();
let mut out = String::from(
"% The registers this file allocates -- see src/latex/allocate.rs.\n\\catcode`\\@=11\n",
);
for (name, primitive) in names {
let pool = match primitive {
"countdef" => Pool::Count,
"dimendef" => Pool::Dimen,
"skipdef" => Pool::Skip,
"toksdef" => Pool::Toks,
_ => Pool::Char,
};
let slot = next.entry(primitive).or_insert(FIRST);
if *slot > pool.last() {
out.push_str(&format!(
"% \\{name}: no {primitive} register left (the last is {}).\n",
pool.last()
));
continue;
}
out.push_str(&format!("\\{primitive}\\{name}={slot}\n"));
*slot += 1;
}
out.push_str("\\catcode`\\@=12\n");
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn each_command_allocates_out_of_its_own_file() {
let got = declared("\\newcount\\a\\newdimen\\b\\newskip\\c\\newtoks\\d\\newbox\\e");
assert_eq!(
got,
[
("a".to_string(), "countdef"),
("b".to_string(), "dimendef"),
("c".to_string(), "skipdef"),
("d".to_string(), "toksdef"),
("e".to_string(), "chardef"),
]
);
}
#[test]
fn a_longer_command_is_not_this_one() {
assert!(declared("\\newcounter{step}").is_empty());
}
#[test]
fn latex_writes_a_length_with_braces_and_it_is_a_skip() {
assert_eq!(
declared("\\newlength{\\parskip@indent}"),
[("parskip@indent".to_string(), "skipdef")]
);
}
#[test]
fn a_name_the_engine_would_have_to_build_is_passed_over() {
assert!(declared("\\expandafter\\newcount\\csname c@x\\endcsname").is_empty());
}
#[test]
fn the_same_name_declared_twice_gets_one_register() {
let out = definitions("\\newdimen\\@tempdima\n\\newdimen\\@tempdima\n");
assert_eq!(out.matches("\\dimendef").count(), 1);
assert!(out.contains("\\dimendef\\@tempdima=10"), "{out}");
}
#[test]
fn the_pools_are_counted_apart_and_start_clear_of_a_documents_own() {
let out = definitions("\\newcount\\a\\newcount\\b\\newdimen\\c");
assert!(out.contains("\\countdef\\a=10"), "{out}");
assert!(out.contains("\\countdef\\b=11"), "{out}");
assert!(out.contains("\\dimendef\\c=10"), "{out}");
}
#[test]
fn running_out_of_count_registers_is_said_rather_than_wrapped() {
let name = |i: usize| {
format!(
"n{}{}",
(b'a' + (i / 26) as u8) as char,
(b'a' + (i % 26) as u8) as char
)
};
let src: String = (0..120)
.map(|i| format!("\\newcount\\{}\n", name(i)))
.collect();
let out = definitions(&src);
assert!(
out.contains(&format!("\\countdef\\{}=99", name(89))),
"the ninetieth fills the last register: {out}"
);
assert!(
out.contains(&format!(
"% \\{}: no countdef register left (the last is 99).",
name(90)
)),
"{out}"
);
}
#[test]
fn the_block_makes_the_at_sign_a_letter_and_puts_it_back() {
let out = definitions("\\newcount\\c@foo");
assert!(out.starts_with("% The registers"), "{out}");
assert!(
out.contains("\\catcode`\\@=11\n\\countdef\\c@foo=10"),
"{out}"
);
assert!(out.trim_end().ends_with("\\catcode`\\@=12"), "{out}");
}
}