Scope runtime definitions to their group
Expansion kept a single flat macro table, so a \def inside {...} replaced the
outer definition for the rest of the document. Keep a scope stack in
expand_macros instead: '{' and \begingroup push a scope, '}' and \endgroup pop
it, and lookup walks the scopes newest-first before the document table. A
top-level \def and every \gdef update the document table; a \def inside a group
only shadows until the group closes.
Runtime \def\name{body} is now parsed during expansion (the pre-expansion inline
capture is gone), and grouping braces are dropped after command parsing so the
scope braces do not print: plain pieces, link labels, inline runs and the
fallback face path all strip them at that point.
A test previews \def\a{one}{\def\a{two}\a}\a as "twoone" and the
\begingroup form likewise; the existing inline-definition test still passes.
Catcode state and a real token stream remain open.
This commit is contained in:
1 parent
7547c0abc4
commit
d1b66af251
3 files changed
+169
-75
No files matched your search
@@ -48,7 +48,7 @@ floats (`\floatsep`, `\textfloatsep`, `\intextsep`, `\topfraction`,
|
||||
`\bottomnumber`, `\totalnumber`), insertion classes (`\skip`, fraction and
|
||||
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`). 988 workspace tests are green and no oracle
|
||||
PDF opt-in with `?engine=route-d`). 989 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.
|
||||
|
||||
+8
-6
@@ -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 988 tests (437 route-D unit, 363 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 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.
|
||||
|
||||
### M0 incremental demo
|
||||
|
||||
@@ -527,11 +527,13 @@ honest open items against the "feature-complete LaTeX compiler" objective are:
|
||||
- **Macro engine scope**: `\def`-style definitions, registers, conditionals,
|
||||
`\csname`, `\expandafter`, delimited parameters and `\edef` are executed
|
||||
textually. `@` counts as a letter in control words (so `\@foo` is one
|
||||
command), `\makeatletter`/`\makeatother` are consumed as no-ops, a
|
||||
line-based capture only consumes a definition when it ends the line, and a
|
||||
simple `\def\name{body}` embedded in running text is captured too. There is
|
||||
still no real group scoping, no catcode state, and no token stream; class
|
||||
code that relies on those semantics degrades.
|
||||
command), `\makeatletter`/`\makeatother` are consumed as no-ops, and a
|
||||
line-based capture only consumes a definition when it ends the line. Runtime
|
||||
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
|
||||
`\gdef` updates the document table; grouping braces are removed after
|
||||
command parsing. 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`
|
||||
bodies are inserted as one unbreakable inline box (interword spaces become
|
||||
fixed-width boxes), so `\usebox` no longer reflows across lines. Savebox
|
||||
|
||||
+160
-68
@@ -760,7 +760,63 @@ fn expand_links_line(line: &str) -> String {
|
||||
output
|
||||
}
|
||||
|
||||
fn upsert_macro(table: &mut Vec<MacroDefinition>, definition: MacroDefinition) {
|
||||
if let Some(existing) = table.iter_mut().find(|known| known.name == definition.name) {
|
||||
*existing = definition;
|
||||
} else {
|
||||
table.push(definition);
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a simple runtime `\def\name{body}` / `\gdef\name{body}` and return
|
||||
/// the definition, bytes consumed and whether it is global.
|
||||
fn runtime_definition(text: &str) -> Option<(MacroDefinition, usize, bool)> {
|
||||
let (command, used) = control_sequence(text)?;
|
||||
let global = match command.as_str() {
|
||||
"\\def" => false,
|
||||
"\\gdef" => true,
|
||||
_ => return None,
|
||||
};
|
||||
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 brace_skipped = trimmed[name_used..].len() - after_name.len();
|
||||
if !after_name.starts_with('{') {
|
||||
return None;
|
||||
}
|
||||
let (body, body_used) = braced_group(after_name)?;
|
||||
Some((
|
||||
MacroDefinition {
|
||||
name: format!("\\{}", name.trim_start_matches('\\')),
|
||||
args: 0,
|
||||
default: None,
|
||||
params: None,
|
||||
body: body.to_string(),
|
||||
},
|
||||
used + skipped + name_used + brace_skipped + body_used,
|
||||
global,
|
||||
))
|
||||
}
|
||||
|
||||
fn expand_macro_at(text: &str, macros: &[MacroDefinition]) -> Option<(String, usize)> {
|
||||
expand_macro_lookup(text, macros, &[])
|
||||
}
|
||||
|
||||
fn expand_macro_at_scoped(
|
||||
text: &str,
|
||||
macros: &[MacroDefinition],
|
||||
scopes: &[Vec<MacroDefinition>],
|
||||
) -> Option<(String, usize)> {
|
||||
expand_macro_lookup(text, macros, scopes)
|
||||
}
|
||||
|
||||
fn expand_macro_lookup(
|
||||
text: &str,
|
||||
macros: &[MacroDefinition],
|
||||
scopes: &[Vec<MacroDefinition>],
|
||||
) -> Option<(String, usize)> {
|
||||
let after_slash = text.strip_prefix('\\')?;
|
||||
let length = after_slash
|
||||
.find(|character: char| !character.is_ascii_alphabetic() && character != '@')
|
||||
@@ -769,7 +825,11 @@ fn expand_macro_at(text: &str, macros: &[MacroDefinition]) -> Option<(String, us
|
||||
return None;
|
||||
}
|
||||
let name = format!("\\{}", &after_slash[..length]);
|
||||
let definition = macros.iter().find(|macro_| macro_.name == name)?;
|
||||
let definition = scopes
|
||||
.iter()
|
||||
.rev()
|
||||
.find_map(|scope| scope.iter().rev().find(|macro_| macro_.name == name))
|
||||
.or_else(|| macros.iter().find(|macro_| macro_.name == name))?;
|
||||
if let Some(params) = &definition.params {
|
||||
return expand_delimited(text, definition, params);
|
||||
}
|
||||
@@ -1205,12 +1265,36 @@ fn expandafter_chain(text: &str, macros: &[MacroDefinition]) -> Option<(String,
|
||||
|
||||
fn expand_macros(source: &str, macros: &[MacroDefinition]) -> String {
|
||||
let mut text = source.to_string();
|
||||
let mut runtime: Vec<MacroDefinition> = macros.to_vec();
|
||||
for _ in 0..8 {
|
||||
let mut output = String::with_capacity(text.len());
|
||||
let mut index = 0;
|
||||
let mut changed = false;
|
||||
let mut scopes: Vec<Vec<MacroDefinition>> = Vec::new();
|
||||
while index < text.len() {
|
||||
let rest = &text[index..];
|
||||
if let Some((definition, used, global)) = runtime_definition(rest) {
|
||||
if global || 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") {
|
||||
scopes.push(Vec::new());
|
||||
index += r"\begingroup".len();
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
if rest.starts_with(r"\endgroup") {
|
||||
scopes.pop();
|
||||
index += r"\endgroup".len();
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
if let Some(after) = rest.strip_prefix(r"\noexpand") {
|
||||
let boundary = after
|
||||
.chars()
|
||||
@@ -1238,14 +1322,14 @@ fn expand_macros(source: &str, macros: &[MacroDefinition]) -> String {
|
||||
}
|
||||
}
|
||||
if rest.starts_with(r"\expandafter") {
|
||||
if let Some((expanded, used)) = expandafter_chain(rest, macros) {
|
||||
if let Some((expanded, used)) = expandafter_chain(rest, &runtime) {
|
||||
output.push_str(&expanded);
|
||||
index += used;
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if let Some((expanded, used)) = latex_internal_at(rest, macros) {
|
||||
if let Some((expanded, used)) = latex_internal_at(rest, &runtime) {
|
||||
output.push_str(&expanded);
|
||||
index += used;
|
||||
changed = true;
|
||||
@@ -1271,13 +1355,18 @@ fn expand_macros(source: &str, macros: &[MacroDefinition]) -> String {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if let Some((expanded, used)) = expand_macro_at(rest, macros) {
|
||||
if let Some((expanded, used)) = expand_macro_at_scoped(rest, &runtime, &scopes) {
|
||||
output.push_str(&expanded);
|
||||
index += used;
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
let character = rest.chars().next().expect("non-empty tail");
|
||||
if character == '{' {
|
||||
scopes.push(Vec::new());
|
||||
} else if character == '}' {
|
||||
scopes.pop();
|
||||
}
|
||||
output.push(character);
|
||||
index += character.len_utf8();
|
||||
}
|
||||
@@ -4648,65 +4737,6 @@ fn capture_body_registers(
|
||||
}
|
||||
}
|
||||
|
||||
/// Capture simple `\def\name{body}` definitions that appear in running body
|
||||
/// text (not at the start of a line). Parameterised forms stay with the
|
||||
/// line-based capture until the token engine models grouping.
|
||||
fn capture_inline_definitions(body: &mut String, macros: &mut Vec<MacroDefinition>) {
|
||||
let mut out = String::new();
|
||||
let mut rest = body.as_str();
|
||||
let mut changed = false;
|
||||
while let Some(position) = rest.find("\\def") {
|
||||
let after = &rest[position + "\\def".len()..];
|
||||
let boundary = after
|
||||
.chars()
|
||||
.next()
|
||||
.is_none_or(|character| !character.is_ascii_alphabetic());
|
||||
if !boundary {
|
||||
out.push_str(&rest[..position + "\\def".len()]);
|
||||
rest = after;
|
||||
continue;
|
||||
}
|
||||
let trimmed = after.trim_start();
|
||||
let Some((name, used)) = control_sequence(trimmed) else {
|
||||
out.push_str(&rest[..position + "\\def".len()]);
|
||||
rest = after;
|
||||
continue;
|
||||
};
|
||||
let after_name = trimmed[used..].trim_start();
|
||||
if !after_name.starts_with('{') {
|
||||
out.push_str(&rest[..position + "\\def".len()]);
|
||||
rest = after;
|
||||
continue;
|
||||
}
|
||||
let Some((content, body_used)) = braced_group(after_name) else {
|
||||
out.push_str(&rest[..position + "\\def".len()]);
|
||||
rest = after;
|
||||
continue;
|
||||
};
|
||||
out.push_str(&rest[..position]);
|
||||
let name = format!("\\{}", name.trim_start_matches('\\'));
|
||||
if let Some(existing) = macros.iter_mut().find(|m| m.name == name) {
|
||||
existing.body = content.to_string();
|
||||
existing.params = None;
|
||||
existing.args = 0;
|
||||
} else {
|
||||
macros.push(MacroDefinition {
|
||||
name,
|
||||
args: 0,
|
||||
default: None,
|
||||
params: None,
|
||||
body: content.to_string(),
|
||||
});
|
||||
}
|
||||
rest = &after_name[body_used..];
|
||||
changed = true;
|
||||
}
|
||||
out.push_str(rest);
|
||||
if changed {
|
||||
*body = out;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a definition command consumes its whole line (ignoring trailing
|
||||
/// whitespace). Embedded definitions are left for the inline pass.
|
||||
fn definition_consumes_line(line: &str) -> bool {
|
||||
@@ -4801,7 +4831,9 @@ fn capture_body_definitions(
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
if let Some(definition) = macro_definition(definition_line) {
|
||||
if let Some(definition) = macro_definition(definition_line)
|
||||
&& definition_consumes_line(definition_line)
|
||||
{
|
||||
macros.push(definition);
|
||||
changed = true;
|
||||
continue;
|
||||
@@ -5038,7 +5070,6 @@ fn geometry_and_body(source: &str) -> (String, PageGeometry) {
|
||||
&mut geometry.theorem_definitions,
|
||||
&mut geometry.environments,
|
||||
);
|
||||
capture_inline_definitions(&mut body, &mut geometry.macros);
|
||||
body = body
|
||||
.replace("\\makeatletter", "")
|
||||
.replace("\\makeatother", "");
|
||||
@@ -8367,6 +8398,41 @@ fn expand_character_commands(text: &str) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
/// Drop grouping braces outside math mode; `\{`/`\}` stay literal. Command
|
||||
/// arguments that matter have already been consumed by this stage.
|
||||
fn strip_group_braces(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
let mut math = false;
|
||||
let mut chars = text.chars().peekable();
|
||||
while let Some(character) = chars.next() {
|
||||
if character == '$' {
|
||||
math = !math;
|
||||
out.push(character);
|
||||
continue;
|
||||
}
|
||||
if math {
|
||||
out.push(character);
|
||||
continue;
|
||||
}
|
||||
if character == '\\' {
|
||||
if let Some(&next) = chars.peek() {
|
||||
if next == '{' || next == '}' {
|
||||
out.push(next);
|
||||
chars.next();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out.push(character);
|
||||
continue;
|
||||
}
|
||||
if character == '{' || character == '}' {
|
||||
continue;
|
||||
}
|
||||
out.push(character);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn strip_noop_commands(text: &str) -> String {
|
||||
const COMMANDS: [&str; 17] = [
|
||||
"\\displaybreak",
|
||||
@@ -8751,6 +8817,10 @@ fn inline_math_segments(
|
||||
parse_math(&piece),
|
||||
));
|
||||
} else if !piece.is_empty() {
|
||||
let piece = strip_group_braces(&piece);
|
||||
if piece.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if background || frame.is_some() {
|
||||
found_color = true;
|
||||
segments.push(
|
||||
@@ -8796,7 +8866,7 @@ fn inline_math_segments(
|
||||
segments.push(texrra_tex_core::paragraph::InlineSegment::Link {
|
||||
font,
|
||||
url: url.clone(),
|
||||
text,
|
||||
text: strip_group_braces(&text),
|
||||
color: link_color,
|
||||
});
|
||||
}
|
||||
@@ -8817,7 +8887,7 @@ fn inline_runs(text: &str, base: ParagraphFont) -> Option<Vec<(ParagraphFont, St
|
||||
Some(
|
||||
inline_sized_runs(text, base)?
|
||||
.into_iter()
|
||||
.map(|(font, _, text)| (font, text))
|
||||
.map(|(font, _, text)| (font, strip_group_braces(&text)))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
@@ -11084,7 +11154,7 @@ fn build_document_with_labels(
|
||||
),
|
||||
None => Unit::paragraph_with_style_and_face(
|
||||
index as u64,
|
||||
plain,
|
||||
strip_group_braces(&plain),
|
||||
style,
|
||||
paragraph.font,
|
||||
),
|
||||
@@ -14792,6 +14862,28 @@ A definition.
|
||||
assert!(!text.contains('?'), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_definitions_are_local() {
|
||||
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 braced = text_of(
|
||||
"\\documentclass{article}\n\\begin{document}\n\n\\def\\a{one}{\\def\\a{two}\\a}\\a\n\n\\end{document}\n",
|
||||
);
|
||||
assert!(braced.contains("twoone"), "{braced}");
|
||||
let grouped = text_of(
|
||||
"\\documentclass{article}\n\\begin{document}\n\n\\def\\a{one}\\begingroup\\def\\a{two}\\a\\endgroup\\a\n\n\\end{document}\n",
|
||||
);
|
||||
assert!(grouped.contains("twoone"), "{grouped}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
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";
|
||||
|
||||
Reference in new issue
Block a user