Add futurelet lookahead and defer conditionals

\futurelet\alias\command <token> now binds <token> to \alias without consuming
it: the expand loop parses the alias and command, stores the peeked token as the
alias body, and leaves the command plus token in the stream. Conditional
operands are protected from macro expansion, so \ifdefined and \ifx still see
the names they test, and a token-alias macro whose body is one character
compares equal to that character in \ifx.

Conditionals moved after macro expansion (and before register expansion):
running them first evaluated \ifx inside a not-yet-expanded \def body, and
register expansion turned the \a in \ifnum\a=3 into an assignment. The
expand_macros_mut variant writes its runtime table back so later passes see
\futurelet aliases and runtime definitions.

A test covers \futurelet\next\shownext x printing [x] and an \ifx dispatch that
chooses Y.
This commit is contained in:
gloamxun committed 2026-10-27 00:56:33 +08:00
1 parent e48a64da7a
commit 9d10def2f5
3 files changed
+181 -12

No files matched your search

+175 -10
View File
@@ -793,7 +793,106 @@ fn brace_depth_delta(line: &str) -> i32 {
depth
}
/// Copy a conditional command together with the operand tokens it inspects,
/// so macro expansion cannot consume them before the conditional is evaluated.
fn protected_conditional_prefix(text: &str) -> Option<(String, usize)> {
for (command, operands) in [
("\\ifdefined", 1_usize),
("\\ifx", 2),
("\\ifcat", 2),
("\\if", 2),
] {
let Some(after) = text.strip_prefix(command) else {
continue;
};
if after
.chars()
.next()
.is_some_and(|character| character.is_ascii_alphabetic())
{
continue;
}
let mut consumed = command.len();
for _ in 0..operands {
let (_, used) = next_token(&text[consumed..])?;
consumed += used;
}
return Some((text[..consumed].to_string(), consumed));
}
None
}
/// Whether the output currently ends with a conditional control word, where
/// splicing a letter directly would merge into a different control word.
fn output_ends_with_conditional(output: &str) -> bool {
const CONDITIONALS: &[&str] = &[
"ifx",
"if",
"ifnum",
"ifcat",
"ifdim",
"ifdefined",
"ifcsname",
"ifhmode",
"ifvmode",
"ifmmode",
"ifvoid",
"ifhbox",
"ifvbox",
"ifeof",
"iftrue",
"iffalse",
"else",
"fi",
"or",
"unless",
];
let bytes = output.as_bytes();
let mut start = bytes.len();
while start > 0 && bytes[start - 1].is_ascii_alphabetic() {
start -= 1;
}
if start == 0 || start == bytes.len() || bytes[start - 1] != b'\\' {
return false;
}
CONDITIONALS.contains(&&output[start..])
}
/// Parse `\futurelet\next\command <token>`: return the alias name, the peeked
/// token text and the byte offset where the command starts.
fn futurelet_lookahead(text: &str) -> Option<(String, String, usize)> {
let after = text.strip_prefix("\\futurelet")?;
if after
.chars()
.next()
.is_some_and(|character| character.is_ascii_alphabetic())
{
return None;
}
let trimmed = after.trim_start();
let (alias, alias_used) = control_sequence(trimmed)?;
let rest = &trimmed[alias_used..];
let command_text = rest.trim_start();
let (_, command_used) = next_token(command_text)?;
let target_text = &command_text[command_used..];
let (target, _) = next_token(target_text)?;
Some((alias, target, text.len() - command_text.len()))
}
fn next_token(text: &str) -> Option<(String, usize)> {
let trimmed = text.trim_start();
let skipped = text.len() - trimmed.len();
if trimmed.starts_with('\\') {
let (name, used) = control_sequence(trimmed)?;
Some((name, skipped + used))
} else {
let character = trimmed.chars().next()?;
Some((character.to_string(), skipped + character.len_utf8()))
}
}
/// Resolve a runtime `\csname ... \endcsname` into the macro it names.
fn csname_expansion(
text: &str,
runtime: &[MacroDefinition],
@@ -1399,8 +1498,13 @@ 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)
}
fn expand_macros_mut(source: &str, macros: &mut Vec<MacroDefinition>) -> String {
let mut text = source.to_string();
let mut runtime: Vec<MacroDefinition> = macros.to_vec();
let mut runtime: Vec<MacroDefinition> = macros.clone();
for _ in 0..8 {
let mut output = String::with_capacity(text.len());
let mut index = 0;
@@ -1408,6 +1512,12 @@ fn expand_macros(source: &str, macros: &[MacroDefinition]) -> String {
let mut scopes: Vec<Vec<MacroDefinition>> = Vec::new();
while index < text.len() {
let rest = &text[index..];
if let Some((prefix, used)) = protected_conditional_prefix(rest) {
output.push_str(&prefix);
index += used;
changed = true;
continue;
}
if let Some((definition, used, global)) = runtime_definition(rest) {
if global || scopes.is_empty() {
upsert_macro(&mut runtime, definition);
@@ -1428,7 +1538,32 @@ fn expand_macros(source: &str, macros: &[MacroDefinition]) -> String {
changed = true;
continue;
}
if let Some((alias, target, command_start)) = futurelet_lookahead(rest) {
let definition = MacroDefinition {
name: alias,
args: 0,
default: None,
params: None,
body: target,
};
if scopes.is_empty() {
upsert_macro(&mut runtime, definition);
} else if let Some(scope) = scopes.last_mut() {
upsert_macro(scope, definition);
}
index += command_start;
changed = true;
continue;
}
if let Some((expanded, used)) = csname_expansion(rest, &runtime, &scopes) {
if expanded
.chars()
.next()
.is_some_and(|character| character.is_ascii_alphabetic())
&& output_ends_with_conditional(&output)
{
output.push(' ');
}
output.push_str(&expanded);
index += used;
changed = true;
@@ -1507,6 +1642,14 @@ fn expand_macros(source: &str, macros: &[MacroDefinition]) -> String {
}
}
if let Some((expanded, used)) = expand_macro_at_scoped(rest, &runtime, &scopes) {
if expanded
.chars()
.next()
.is_some_and(|character| character.is_ascii_alphabetic())
&& output_ends_with_conditional(&output)
{
output.push(' ');
}
output.push_str(&expanded);
index += used;
changed = true;
@@ -1526,6 +1669,7 @@ fn expand_macros(source: &str, macros: &[MacroDefinition]) -> String {
break;
}
}
macros.clone_from(&runtime);
text.replace('\u{E000}', "\\")
}
@@ -1995,6 +2139,11 @@ fn conditional_at(
_ => false,
}
}
(ConditionalToken::Control(name), ConditionalToken::Character(character))
| (ConditionalToken::Character(character), ConditionalToken::Control(name)) => macros
.iter()
.find(|definition| &definition.name == name)
.is_some_and(|definition| definition.body == character.to_string()),
_ => false,
};
return Some((value, consumed + first_used + second_used));
@@ -5640,7 +5789,8 @@ fn geometry_and_body(source: &str) -> (String, PageGeometry) {
);
body = expand_box_dimensions(&body, &geometry.savebox_dimensions);
dedupe_macros(&mut geometry.macros);
let macros = geometry.macros.clone();
let mut macros = geometry.macros.clone();
body = expand_macros_mut(&body, &mut macros);
body = expand_conditionals(
&body,
&mut geometry.conditionals,
@@ -5648,7 +5798,6 @@ fn geometry_and_body(source: &str) -> (String, PageGeometry) {
&geometry.count_registers,
&geometry.counters,
);
body = expand_macros(&body, &macros);
let mut numbered_dimens = geometry.numbered_dimens;
body = expand_numbered_dimens(&body, &mut numbered_dimens);
geometry.numbered_dimens = numbered_dimens;
@@ -5668,13 +5817,6 @@ fn geometry_and_body(source: &str) -> (String, PageGeometry) {
body = expand_skip_registers(&body, &mut skip_registers);
geometry.skip_registers = skip_registers;
body = expand_links(&body);
body = expand_conditionals(
&body,
&mut geometry.conditionals,
&macros,
&geometry.count_registers,
&geometry.counters,
);
let today = today_string();
body = expand_today(&body, &today);
body = expand_lipsum(&body);
@@ -15527,6 +15669,29 @@ A definition.
assert!(!text.contains("makeatletter"), "{text}");
}
#[test]
fn futurelet_peeks_without_consuming() {
let source = "\\documentclass{article}\n\\begin{document}\n\n\\def\\shownext{[\\next]}\\futurelet\\next\\shownext x\n\n\\def\\yes{Y}\\def\\no{N}\\def\\pick{\\futurelet\\next\\pickii}\\def\\pickii{\\ifx\\next x\\yes\\else\\no\\fi}\n\n\\pick x\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("[x]"), "{text}");
assert!(text.contains("Y"), "{text}");
assert!(!text.contains("futurelet"), "{text}");
}
#[test]
fn runtime_csname_resolves_macros() {
let source = "\\documentclass{article}\n\\begin{document}\n\n\\def\\foo{Z}\n\\def\\a{\\csname foo\\endcsname}\n\n\\a and \\csname foo\\endcsname and \\csname missing\\endcsname.\n\n\\end{document}\n";