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

+1 -1
View File
@@ -49,7 +49,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`,
absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the
route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and
PDF opt-in with `?engine=route-d`; flat `/preview` and project previews now
prefer route-D with a v1 fallback). 998 workspace tests are green and no oracle
prefer route-D with a v1 fallback). 999 workspace tests are green and no oracle
fixture is ignored. Preview JSON also carries a `warnings` array naming
environments route-D cannot lay out and control words that survived layout, so
unsupported source is reported instead of being silently typeset.
+5 -1
View File
@@ -370,7 +370,7 @@ Math coverage includes fractions/roots, scripts, `\left...\right` with body-scal
Paragraph units carry a `ParagraphFont`; `Unit::paragraph_with_face` and `Unit::paragraph_with_style_and_face` select Roman, bold, italic, mono, or sans. The corresponding Computer Modern TFM (`cmr10`, `cmbx10`, `cmti10`, `cmbxti10`, `cmtt10`, `cmss10`, `cmssbx10`, `cmssi10`, `cmcsc10`) supplies advances, kerns, ligatures, and italic correction for layout, the display list selects the matching face, and the PDF writes Computer Modern Type1 outlines for each built-in face (`cmr10`/`cmbx10`/`cmti10`/`cmbxti10`/`cmtt10`/`cmss10`/`cmssbx10`/`cmssi10`/`cmcsc10`, plus `cmmi10` for mathematical italic letters, `cmsy10` for math symbols and `cmex10` for big operators), falling back to Liberation subsets only for characters the Type1 encodings cannot address; those fallback glyphs keep their Unicode text under PDF extraction, so accented and Greek words round-trip; Type1 faces carry a ToUnicode CMap built from the requested characters, so glyphs whose names are ambiguous in the Adobe Glyph List (capital Omega, which would otherwise extract as U+2126) keep their intended code points. `Engine::edit` preserves the face when reflowing an edited paragraph.
The crate currently has 437 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 998 tests (437 route-D unit, 371 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 62 server, 4 engine unit, 1 core unit), with none ignored. The flat `/preview` endpoint and the project preview/PDF endpoints now try route-D first and fall back to v1 on error (`?engine=v1` or `TEXRRA_ENGINE=v1` forces v1; the flat response carries `X-Preview-Engine`, naming the engine used). A geometry-less project now defaults to Letter, matching pdfLaTeX, where the old v1 path used A4.
The crate currently has 437 unit tests plus ten route-D integration tests and forty-two oracle fixtures. Workspace verification: `cargo fmt --all -- --check`; `cargo test --workspace --offline` runs 999 tests (437 route-D unit, 372 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 62 server, 4 engine unit, 1 core unit), with none ignored. The flat `/preview` endpoint and the project preview/PDF endpoints now try route-D first and fall back to v1 on error (`?engine=v1` or `TEXRRA_ENGINE=v1` forces v1; the flat response carries `X-Preview-Engine`, naming the engine used). A geometry-less project now defaults to Letter, matching pdfLaTeX, where the old v1 path used A4.
### M0 incremental demo
@@ -550,6 +550,10 @@ are:
other character are still unmodelled, and there is no token stream. A runtime
`\csname ... \endcsname` (also inside ordinary macro bodies) expands its
contents and resolves the named macro, yielding nothing when undefined.
`\futurelet\alias\command <token>` binds the looked-ahead token to the
alias without consuming it; conditionals are evaluated after macro expansion
with their operand tokens protected from expansion, then before register
expansion.
- **Boxes**: `\sbox`/`\savebox` content and `\mbox`/`\hbox`/`\makebox`
bodies are inserted as one unbreakable inline box (interword spaces become
fixed-width boxes), so `\usebox` no longer reflows across lines. Savebox
+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";