Add token registers

\toks was unsupported, so \newtoks/\toks0={...}/\the\toks0 leaked. Expansion
now carries a token-register table next to the macro table: \newtoks declares a
named register, \toks0={...} and a declared \name={...} store text, and
\the\toks0 or \the\name splice the stored text back into the stream.

A preview test stores Hello in a named register and A in \toks0, then renders
"\the\greet and \the\toks0 B" as "Hello and A B" with no warnings.
This commit is contained in:
gloamxun committed 2026-10-27 01:08:56 +08:00
1 parent 9005194c54
commit 2ef284e585
3 files changed
+159 -6

No files matched your search

+154 -3
View File
@@ -231,6 +231,8 @@ struct PageGeometry {
savebox_dimensions: Vec<(String, (i64, i64, i64))>,
/// Nested `tabular` sources referenced by `\texrranested{index}` tokens.
nested_tables: Vec<String>,
/// Token registers: `\toks0`/named registers mapped to their text.
token_registers: Vec<(String, String)>,
head_sep: Option<i64>,
head_height: Option<i64>,
foot_skip: Option<i64>,
@@ -793,6 +795,95 @@ fn brace_depth_delta(line: &str) -> i32 {
depth
}
fn toks_register(text: &str) -> Option<(String, usize)> {
let after = text.strip_prefix("\\toks")?;
if after
.chars()
.next()
.is_some_and(|character| character.is_ascii_alphabetic())
{
return None;
}
let digits: String = after
.chars()
.take_while(|character| character.is_ascii_digit())
.collect();
if !digits.is_empty() {
return Some((digits.clone(), "\\toks".len() + digits.len()));
}
let (name, used) = control_sequence(after)?;
Some((name, "\\toks".len() + used))
}
fn newtoks_declaration(text: &str) -> Option<(String, usize)> {
let after = text.strip_prefix("\\newtoks")?;
if after
.chars()
.next()
.is_some_and(|character| character.is_ascii_alphabetic())
{
return None;
}
let trimmed = after.trim_start();
let skipped = after.len() - trimmed.len();
let (name, used) = control_sequence(trimmed)?;
Some((name, "\\newtoks".len() + skipped + used))
}
fn named_toks_assignment(
text: &str,
tokens: &[(String, String)],
) -> Option<(String, String, usize)> {
let (name, name_used) = control_sequence(text)?;
if !tokens.iter().any(|(known, _)| known == &name) {
return None;
}
let rest = text[name_used..].trim_start();
let mut used = name_used + (text[name_used..].len() - rest.len());
let rest = rest.strip_prefix('=')?;
let value = rest.trim_start();
used += text[used..].len() - value.len();
let (content, group_used) = braced_group(value)?;
Some((name, content.to_string(), used + group_used))
}
fn toks_assignment(text: &str) -> Option<(String, String, usize)> {
let (key, mut used) = toks_register(text)?;
let rest = text[used..].trim_start();
used += text[used..].len() - rest.len();
let rest = rest.strip_prefix('=')?;
let value = rest.trim_start();
used += text[used..].len() - value.len();
let (content, group_used) = braced_group(value)?;
Some((key, content.to_string(), used + group_used))
}
fn the_toks(text: &str, tokens: &[(String, String)]) -> Option<(String, usize)> {
let after = text.strip_prefix("\\the")?;
if after
.chars()
.next()
.is_some_and(|character| character.is_ascii_alphabetic())
{
return None;
}
let trimmed = after.trim_start();
let skipped = after.len() - trimmed.len();
if let Some((key, used)) = toks_register(trimmed) {
let content = tokens
.iter()
.find(|(known, _)| known == &key)
.map(|(_, value)| value.clone())?;
return Some((content, "\\the".len() + skipped + used));
}
let (name, used) = control_sequence(trimmed)?;
let content = tokens
.iter()
.find(|(known, _)| known == &name)
.map(|(_, value)| value.clone())?;
Some((content, "\\the".len() + skipped + used))
}
/// Replace `\scantokens{...}` with the text it re-tokenises; later expansion
/// passes then process the content as usual.
fn scantokens_body(text: &str) -> Option<(String, usize)> {
@@ -1539,10 +1630,15 @@ fn expandafter_chain(text: &str, macros: &[MacroDefinition]) -> Option<(String,
fn expand_macros(source: &str, macros: &[MacroDefinition]) -> String {
let mut table = macros.to_vec();
expand_macros_mut(source, &mut table)
let mut tokens = Vec::new();
expand_macros_mut(source, &mut table, &mut tokens)
}
fn expand_macros_mut(source: &str, macros: &mut Vec<MacroDefinition>) -> String {
fn expand_macros_mut(
source: &str,
macros: &mut Vec<MacroDefinition>,
tokens: &mut Vec<(String, String)>,
) -> String {
let mut text = source.to_string();
let mut runtime: Vec<MacroDefinition> = macros.clone();
for _ in 0..8 {
@@ -1579,6 +1675,39 @@ fn expand_macros_mut(source: &str, macros: &mut Vec<MacroDefinition>) -> String
changed = true;
continue;
}
if let Some((content, used)) = newtoks_declaration(rest) {
if !tokens.iter().any(|(key, _)| key == &content) {
tokens.push((content, String::new()));
}
index += used;
changed = true;
continue;
}
if let Some((key, value, used)) = named_toks_assignment(rest, tokens) {
if let Some(slot) = tokens.iter_mut().find(|(known, _)| known == &key) {
slot.1 = value;
}
index += used;
changed = true;
continue;
}
if let Some((key, value, used)) = toks_assignment(rest) {
if let Some(slot) = tokens.iter_mut().find(|(known, _)| known == &key) {
slot.1 = value;
} else {
tokens.push((key, value));
}
index += used;
changed = true;
continue;
}
if let Some((content, used)) = the_toks(rest, tokens) {
output.push('\u{E022}');
output.push_str(&content);
index += used;
changed = true;
continue;
}
if let Some((content, used)) = scantokens_body(rest) {
output.push('\u{E022}');
output.push_str(&content);
@@ -5914,7 +6043,7 @@ fn geometry_and_body(source: &str) -> (String, PageGeometry) {
body = expand_box_dimensions(&body, &geometry.savebox_dimensions);
dedupe_macros(&mut geometry.macros);
let mut macros = geometry.macros.clone();
body = expand_macros_mut(&body, &mut macros);
body = expand_macros_mut(&body, &mut macros, &mut geometry.token_registers);
body = expand_conditionals(
&body,
&mut geometry.conditionals,
@@ -15793,6 +15922,28 @@ A definition.
assert!(!text.contains("makeatletter"), "{text}");
}
#[test]
fn token_registers_store_and_expand() {
let source = "\\documentclass{article}\n\\begin{document}\n\n\\newtoks\\greet\n\\greet={Hello}\n\\toks0={A}\n\n\\the\\greet and \\the\\toks0 B\n\n\\end{document}\n";
let json = preview_json(source).expect("preview");
let value: serde_json::Value = serde_json::from_str(&json).expect("JSON");
assert_eq!(
value["warnings"].as_array().map(Vec::len),
Some(0),
"{}",
value["warnings"]
);
let svg = value["pages"][0]["svg"].as_str().expect("svg");
let text: String = svg
.split('>')
.filter_map(|piece| piece.split('<').next())
.collect::<String>()
.split_whitespace()
.collect();
assert!(text.contains("HelloandAB"), "{text}");
assert!(!text.contains("toks"), "{text}");
}
#[test]
fn scantokens_reprocesses_its_content() {
let source = "\\documentclass{article}\n\\begin{document}\n\n\\def\\greet{Hello}\\scantokens{\\greet world}.\n\n\\end{document}\n";