Run let/chardef and keep group definitions local

Runtime expansion only understood \def/\gdef. Add \let\alias=\target (a macro
body that expands to the target) and \chardef\name=<code> (a one-character
body), both honoring the current scope, so class-style aliases work and can be
shadowed inside a group.

Line-based capture also still pulled a definition line out of a group and made
it global. Track brace depth across body lines and only capture at depth zero,
and restrict strip_page_geometry's definition capture to the preamble before
\begin{document}; body lines now reach runtime expansion where the scope stack
applies.

Tests preview a group-local \def on its own line as "twoone" and
\let/\chardef as "HiandA".
This commit is contained in:
gloamxun committed 2026-10-27 00:15:20 +08:00
1 parent d1b66af251
commit 9aa743b601
3 files changed
+145 -13

No files matched your search

+1 -1
View File
@@ -48,7 +48,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`,
`\bottomnumber`, `\totalnumber`), insertion classes (`\skip`, fraction and `\bottomnumber`, `\totalnumber`), insertion classes (`\skip`, fraction and
absolute limits, splitting), marks, Rust output hook, multi-page PDF, and the 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 route-D service endpoints (`/api/route-d/preview|pdf|edit`, project preview and
PDF opt-in with `?engine=route-d`). 989 workspace tests are green and no oracle PDF opt-in with `?engine=route-d`). 990 workspace tests are green and no oracle
fixture is ignored. Preview JSON also carries a `warnings` array naming fixture is ignored. Preview JSON also carries a `warnings` array naming
environments route-D cannot lay out and control words that survived layout, so environments route-D cannot lay out and control words that survived layout, so
unsupported source is reported instead of being silently typeset. unsupported source is reported instead of being silently typeset.
+6 -3
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. 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 989 tests (437 route-D unit, 364 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 60 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path. 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 990 tests (437 route-D unit, 365 engine binary unit, 10 route-D integration, 42 oracle, 71 v1 integration, 60 server, 4 engine unit, 1 core unit), with none ignored. v1 remains the live server path.
### M0 incremental demo ### M0 incremental demo
@@ -532,8 +532,11 @@ honest open items against the "feature-complete LaTeX compiler" objective are:
expansion keeps a scope stack for `{}` and `\begingroup`/`\endgroup`: a expansion keeps a scope stack for `{}` and `\begingroup`/`\endgroup`: a
`\def` inside a group is local to it, while a top-level `\def` or any `\def` inside a group is local to it, while a top-level `\def` or any
`\gdef` updates the document table; grouping braces are removed after `\gdef` updates the document table; grouping braces are removed after
command parsing. There is still no catcode state and no token stream, so command parsing. Runtime `\let\alias=\target` and `\chardef\name=<code>`
class code that relies on those semantics degrades. also define (or locally shadow) commands, and the line-based capture only
runs before `\begin{document}` and outside braces, so a definition on its own
line inside a group stays local. There is still no catcode state and no token
stream, so class code that relies on those semantics degrades.
- **Boxes**: `\sbox`/`\savebox` content and `\mbox`/`\hbox`/`\makebox` - **Boxes**: `\sbox`/`\savebox` content and `\mbox`/`\hbox`/`\makebox`
bodies are inserted as one unbreakable inline box (interword spaces become bodies are inserted as one unbreakable inline box (interword spaces become
fixed-width boxes), so `\usebox` no longer reflows across lines. Savebox fixed-width boxes), so `\usebox` no longer reflows across lines. Savebox
+138 -9
View File
@@ -768,6 +768,87 @@ fn upsert_macro(table: &mut Vec<MacroDefinition>, definition: MacroDefinition) {
} }
} }
fn brace_depth_delta(line: &str) -> i32 {
let mut depth = 0_i32;
let mut escaped = false;
for character in line.chars() {
if escaped {
escaped = false;
continue;
}
match character {
'\\' => escaped = true,
'{' => depth += 1,
'}' => depth -= 1,
_ => {}
}
}
depth
}
/// Runtime `\let\alias=\target` and `\chardef\name=<code>` definitions.
fn runtime_plain_definition(text: &str) -> Option<(MacroDefinition, usize)> {
let (command, used) = control_sequence(text)?;
let rest = &text[used..];
let trimmed = rest.trim_start();
let skipped = rest.len() - trimmed.len();
let (name, name_used) = control_sequence(trimmed)?;
let after_name = trimmed[name_used..].trim_start();
let name_gap = trimmed[name_used..].len() - after_name.len();
match command.as_str() {
"\\let" => {
let after = after_name
.strip_prefix('=')
.map(str::trim_start)
.unwrap_or(after_name);
let eq_skipped = after_name.len() - after.len();
let (target, target_used) = if let Some((target, target_used)) = control_sequence(after)
{
(target, target_used)
} else {
let character = after.chars().next()?;
(character.to_string(), character.len_utf8())
};
Some((
MacroDefinition {
name: format!("\\{}", name.trim_start_matches('\\')),
args: 0,
default: None,
params: None,
body: target,
},
used + skipped + name_used + name_gap + eq_skipped + target_used,
))
}
"\\chardef" => {
let after = after_name
.strip_prefix('=')
.map(str::trim_start)
.unwrap_or(after_name);
let eq_skipped = after_name.len() - after.len();
let digits: String = after
.chars()
.take_while(|character| character.is_ascii_digit())
.collect();
if digits.is_empty() {
return None;
}
let value: u32 = digits.parse().ok()?;
Some((
MacroDefinition {
name: format!("\\{}", name.trim_start_matches('\\')),
args: 0,
default: None,
params: None,
body: char::from_u32(value)?.to_string(),
},
used + skipped + name_used + name_gap + eq_skipped + digits.len(),
))
}
_ => None,
}
}
/// Parse a simple runtime `\def\name{body}` / `\gdef\name{body}` and return /// Parse a simple runtime `\def\name{body}` / `\gdef\name{body}` and return
/// the definition, bytes consumed and whether it is global. /// the definition, bytes consumed and whether it is global.
fn runtime_definition(text: &str) -> Option<(MacroDefinition, usize, bool)> { fn runtime_definition(text: &str) -> Option<(MacroDefinition, usize, bool)> {
@@ -1283,6 +1364,16 @@ fn expand_macros(source: &str, macros: &[MacroDefinition]) -> String {
changed = true; changed = true;
continue; continue;
} }
if let Some((definition, used)) = runtime_plain_definition(rest) {
if scopes.is_empty() {
upsert_macro(&mut runtime, definition);
} else if let Some(scope) = scopes.last_mut() {
upsert_macro(scope, definition);
}
index += used;
changed = true;
continue;
}
if rest.starts_with(r"\begingroup") { if rest.starts_with(r"\begingroup") {
scopes.push(Vec::new()); scopes.push(Vec::new());
index += r"\begingroup".len(); index += r"\begingroup".len();
@@ -2231,8 +2322,12 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
let mut geometry = PageGeometry::default(); let mut geometry = PageGeometry::default();
let mut body = String::new(); let mut body = String::new();
let mut tabular: Option<(String, String, &'static str, Option<i64>, usize)> = None; let mut tabular: Option<(String, String, &'static str, Option<i64>, usize)> = None;
let mut in_document = false;
for line in source.lines() { for line in source.lines() {
let trimmed = line.trim(); let trimmed = line.trim();
if trimmed.contains("\\begin{document}") {
in_document = true;
}
if let Some((_, text, environment, _, depth)) = tabular.as_mut() { if let Some((_, text, environment, _, depth)) = tabular.as_mut() {
let end = format!("\\end{{{environment}}}"); let end = format!("\\end{{{environment}}}");
let closed = trimmed.strip_suffix(&end); let closed = trimmed.strip_suffix(&end);
@@ -2553,12 +2648,13 @@ fn strip_page_geometry(source: &str) -> (String, PageGeometry) {
|| rest.chars().next().is_some_and(char::is_whitespace) || rest.chars().next().is_some_and(char::is_whitespace)
}) })
}; };
if is_macro_command("\\newcommand") if !in_document
|| is_macro_command("\\renewcommand") && (is_macro_command("\\newcommand")
|| is_macro_command("\\DeclareRobustCommand") || is_macro_command("\\renewcommand")
|| is_macro_command("\\providecommand") || is_macro_command("\\DeclareRobustCommand")
|| is_macro_command("\\def") || is_macro_command("\\providecommand")
|| is_macro_command("\\gdef") || is_macro_command("\\def")
|| is_macro_command("\\gdef"))
{ {
if is_macro_command("\\renewcommand") if is_macro_command("\\renewcommand")
&& let Some(width) = renewcommand_length(definition_line, "headrulewidth") && let Some(width) = renewcommand_length(definition_line, "headrulewidth")
@@ -4803,7 +4899,13 @@ fn capture_body_definitions(
) { ) {
let mut kept = String::new(); let mut kept = String::new();
let mut changed = false; let mut changed = false;
let mut depth = 0_i32;
let mut depths = Vec::new();
for line in body.lines() { for line in body.lines() {
depths.push(depth);
depth += brace_depth_delta(line);
}
for (line, depth) in body.lines().zip(depths) {
let trimmed = line.trim_start(); let trimmed = line.trim_start();
let definition_line = strip_definition_prefixes(trimmed); let definition_line = strip_definition_prefixes(trimmed);
if trimmed.starts_with("\\newenvironment") || trimmed.starts_with("\\renewenvironment") { if trimmed.starts_with("\\newenvironment") || trimmed.starts_with("\\renewenvironment") {
@@ -4831,19 +4933,24 @@ fn capture_body_definitions(
changed = true; changed = true;
continue; continue;
} }
if let Some(definition) = macro_definition(definition_line) if depth == 0
&& let Some(definition) = macro_definition(definition_line)
&& definition_consumes_line(definition_line) && definition_consumes_line(definition_line)
{ {
macros.push(definition); macros.push(definition);
changed = true; changed = true;
continue; continue;
} }
if let Some(definition) = char_definition(definition_line) { if depth == 0
&& let Some(definition) = char_definition(definition_line)
{
macros.push(definition); macros.push(definition);
changed = true; changed = true;
continue; continue;
} }
if let Some((name, target)) = macro_alias(definition_line) { if depth == 0
&& let Some((name, target)) = macro_alias(definition_line)
{
let source = macros let source = macros
.iter() .iter()
.find(|definition| definition.name == target) .find(|definition| definition.name == target)
@@ -14884,6 +14991,28 @@ A definition.
assert!(grouped.contains("twoone"), "{grouped}"); assert!(grouped.contains("twoone"), "{grouped}");
} }
#[test]
fn group_lines_and_runtime_aliases() {
let text_of = |source: &str| -> String {
let json = preview_json(source).expect("preview");
let value: serde_json::Value = serde_json::from_str(&json).expect("JSON");
let svg = value["pages"][0]["svg"].as_str().expect("svg");
svg.split('>')
.filter_map(|piece| piece.split('<').next())
.collect::<String>()
.split_whitespace()
.collect()
};
let grouped = text_of(
"\\documentclass{article}\n\\begin{document}\n\n\\def\\a{one}\n{\n\\def\\a{two}\n\\a\n}\n\\a\n\n\\end{document}\n",
);
assert!(grouped.contains("twoone"), "{grouped}");
let aliased = text_of(
"\\documentclass{article}\n\\begin{document}\n\n\\def\\b{Hi}\\let\\c=\\b\\c and \\chardef\\d=65\\d\n\n\\end{document}\n",
);
assert!(aliased.contains("HiandA"), "{aliased}");
}
#[test] #[test]
fn inline_definitions_and_makeatletter_expand() { fn inline_definitions_and_makeatletter_expand() {
let source = "\\documentclass{article}\n\\begin{document}\n\n\\makeatletter\\def\\@foo{bar}\\makeatother\\@foo and \\def\\greet{Hello}\\greet.\n\n\\end{document}\n"; let source = "\\documentclass{article}\n\\begin{document}\n\n\\makeatletter\\def\\@foo{bar}\\makeatother\\@foo and \\def\\greet{Hello}\\greet.\n\n\\end{document}\n";