Make @ a letter only inside makeatletter
The scanner treated @ as a letter everywhere, so \makeatletter was a no-op and \foo@bar parsed as one command even outside it. Canonicalise the source once, before captures: in the default state a control word stops at @ (and a marker keeps later scanners from re-joining the split), between \makeatletter and \makeatother the name is rewritten with a private-use placeholder that control_sequence and expand_macro_lookup accept as a letter and normalise back to @. Grouping saves and restores the state, and route-D's own \@... names plus the internal \p@/\z@/\protected@edef family stay literal so their handlers keep matching; markers are stripped from text before shaping. Tests cover \@foo inside makeatletter, \foo@bar splitting to \foo plus "@bar", \@ifundefined still working, and a group-local \makeatother.
This commit is contained in:
1 parent
d4de3a3f35
commit
621a8abb92
3 files changed
+226
-13
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`). 991 workspace tests are green and no oracle
|
||||
PDF opt-in with `?engine=route-d`). 992 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.
|
||||
|
||||
+9
-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 991 tests (437 route-D unit, 366 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 992 tests (437 route-D unit, 367 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
|
||||
|
||||
@@ -526,9 +526,12 @@ 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, and a
|
||||
line-based capture only consumes a definition when it ends the line. Runtime
|
||||
textually. `@` is a letter in a control word only between `\makeatletter`
|
||||
and `\makeatother` (grouping restores the state); user names containing it
|
||||
are canonicalised through a private-use placeholder, while route-D's own
|
||||
`\@...`/`\p@`-style names and a small internal list stay literal so their
|
||||
handlers keep matching. 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
|
||||
@@ -537,8 +540,8 @@ honest open items against the "feature-complete LaTeX compiler" objective are:
|
||||
runs before `\begin{document}` and outside braces, so a definition on its own
|
||||
line inside a group stays local. `\edef`/`\xdef` lines in the preamble and in
|
||||
the body expand their bodies (including `\csname`) when read, while a plain
|
||||
`\def` stays lazy. There is still no catcode state and no token stream, so
|
||||
class code that relies on those semantics degrades.
|
||||
`\def` stays lazy. There is still no catcode table beyond `@` 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
|
||||
|
||||
+216
-6
@@ -401,7 +401,9 @@ fn environment_definition(line: &str) -> Option<EnvironmentDefinition> {
|
||||
fn control_sequence(text: &str) -> Option<(String, usize)> {
|
||||
let after_slash = text.strip_prefix('\\')?;
|
||||
let first = after_slash.chars().next()?;
|
||||
let letter = |character: char| character.is_ascii_alphabetic() || character == '@';
|
||||
let letter = |character: char| {
|
||||
character.is_ascii_alphabetic() || character == '@' || character == '\u{E021}'
|
||||
};
|
||||
let length = if letter(first) {
|
||||
after_slash
|
||||
.find(|character: char| !letter(character))
|
||||
@@ -409,7 +411,10 @@ fn control_sequence(text: &str) -> Option<(String, usize)> {
|
||||
} else {
|
||||
first.len_utf8()
|
||||
};
|
||||
Some((format!("\\{}", &after_slash[..length]), length + 1))
|
||||
Some((
|
||||
format!("\\{}", &after_slash[..length]).replace('\u{E021}', "@"),
|
||||
length + 1,
|
||||
))
|
||||
}
|
||||
|
||||
fn definition_argument_count(params: &str) -> Option<u8> {
|
||||
@@ -900,12 +905,14 @@ fn expand_macro_lookup(
|
||||
) -> Option<(String, usize)> {
|
||||
let after_slash = text.strip_prefix('\\')?;
|
||||
let length = after_slash
|
||||
.find(|character: char| !character.is_ascii_alphabetic() && character != '@')
|
||||
.find(|character: char| {
|
||||
!character.is_ascii_alphabetic() && character != '@' && character != '\u{E021}'
|
||||
})
|
||||
.unwrap_or(after_slash.len());
|
||||
if length == 0 {
|
||||
return None;
|
||||
}
|
||||
let name = format!("\\{}", &after_slash[..length]);
|
||||
let name = format!("\\{}", &after_slash[..length]).replace('\u{E021}', "@");
|
||||
let definition = scopes
|
||||
.iter()
|
||||
.rev()
|
||||
@@ -5094,6 +5101,183 @@ fn brace_delta(text: &str) -> i64 {
|
||||
}
|
||||
|
||||
/// Move `\AtBeginDocument{...}` bodies in front of `\begin{document}`.
|
||||
const INTERNAL_AT_COMMANDS: &[&str] = &[
|
||||
"empty",
|
||||
"firstofone",
|
||||
"firstoftwo",
|
||||
"secondoftwo",
|
||||
"gobble",
|
||||
"gobbletwo",
|
||||
"ifmtarg",
|
||||
"ifnextchar",
|
||||
"ifstar",
|
||||
"ifundefined",
|
||||
"ifpackageloaded",
|
||||
"ifclassloaded",
|
||||
"ifdefinable",
|
||||
"namedef",
|
||||
"nameuse",
|
||||
"nopreamble",
|
||||
"onlypreamble",
|
||||
"setfontsize",
|
||||
"listi",
|
||||
"listiv",
|
||||
"title",
|
||||
"minus",
|
||||
"plus",
|
||||
];
|
||||
|
||||
const INTERNAL_AT_INFIX: &[&str] = &[
|
||||
"protected@edef",
|
||||
"protected@xdef",
|
||||
"protected@write",
|
||||
"sixt@@n",
|
||||
"e@ight",
|
||||
"thr@@",
|
||||
"m@ne",
|
||||
"tw@",
|
||||
"p@",
|
||||
"z@",
|
||||
];
|
||||
|
||||
fn is_internal_at_command(name: &str) -> bool {
|
||||
if INTERNAL_AT_INFIX.contains(&name) {
|
||||
return true;
|
||||
}
|
||||
name.strip_prefix('@')
|
||||
.is_some_and(|rest| INTERNAL_AT_COMMANDS.contains(&rest))
|
||||
}
|
||||
|
||||
/// Model the one catcode the engine understands: `@` is a letter only between
|
||||
/// `\makeatletter` and `\makeatother`, and grouping restores the state. User
|
||||
/// command names containing `@` are rewritten with a private-use placeholder
|
||||
/// so later scanners still see one control word; route-D's own `\@...` names
|
||||
/// stay literal for their handlers.
|
||||
fn canonicalize_at_catcodes(source: &str) -> String {
|
||||
let characters: Vec<char> = source.chars().collect();
|
||||
let mut out = String::with_capacity(source.len());
|
||||
let mut index = 0;
|
||||
let mut at_letter = false;
|
||||
let mut saved = Vec::new();
|
||||
while index < characters.len() {
|
||||
let character = characters[index];
|
||||
if character == '{' {
|
||||
saved.push(at_letter);
|
||||
out.push(character);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if character == '}' {
|
||||
at_letter = saved.pop().unwrap_or(false);
|
||||
out.push(character);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
if character != '\\' {
|
||||
out.push(character);
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
let start = index + 1;
|
||||
let mut end = start;
|
||||
while end < characters.len()
|
||||
&& (characters[end].is_ascii_alphabetic() || (at_letter && characters[end] == '@'))
|
||||
{
|
||||
end += 1;
|
||||
}
|
||||
if !at_letter {
|
||||
let mut matched = false;
|
||||
for name in INTERNAL_AT_INFIX {
|
||||
let candidate: Vec<char> = name.chars().collect();
|
||||
if characters[start..].starts_with(&candidate) {
|
||||
let next = start + candidate.len();
|
||||
let boundary = next >= characters.len()
|
||||
|| (!characters[next].is_ascii_alphabetic() && characters[next] != '@');
|
||||
if boundary {
|
||||
out.push('\\');
|
||||
for character in &candidate {
|
||||
out.push(*character);
|
||||
}
|
||||
index = next;
|
||||
matched = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if matched {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if end == start {
|
||||
if !at_letter && start < characters.len() && characters[start] == '@' {
|
||||
let mut matched = false;
|
||||
for name in INTERNAL_AT_COMMANDS {
|
||||
let candidate: Vec<char> = std::iter::once('@').chain(name.chars()).collect();
|
||||
if characters[start..].starts_with(&candidate) {
|
||||
let next = start + candidate.len();
|
||||
let boundary = next >= characters.len()
|
||||
|| (!characters[next].is_ascii_alphabetic() && characters[next] != '@');
|
||||
if boundary {
|
||||
out.push('\\');
|
||||
out.extend(candidate.iter());
|
||||
index = next;
|
||||
matched = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if matched {
|
||||
continue;
|
||||
}
|
||||
out.push('\\');
|
||||
out.push('@');
|
||||
out.push('\u{E022}');
|
||||
index = start + 1;
|
||||
continue;
|
||||
}
|
||||
out.push('\\');
|
||||
if start < characters.len() {
|
||||
out.push(characters[start]);
|
||||
index = start + 1;
|
||||
} else {
|
||||
index = start;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let name: String = characters[start..end].iter().collect();
|
||||
match name.as_str() {
|
||||
"makeatletter" => {
|
||||
at_letter = true;
|
||||
index = end;
|
||||
continue;
|
||||
}
|
||||
"makeatother" => {
|
||||
at_letter = false;
|
||||
index = end;
|
||||
continue;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
out.push('\\');
|
||||
if is_internal_at_command(&name) {
|
||||
out.push_str(&name);
|
||||
} else {
|
||||
for character in name.chars() {
|
||||
out.push(if character == '@' {
|
||||
'\u{E021}'
|
||||
} else {
|
||||
character
|
||||
});
|
||||
}
|
||||
if end < characters.len() && characters[end] == '@' && !at_letter {
|
||||
out.push('\u{E022}');
|
||||
}
|
||||
}
|
||||
index = end;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn lift_at_begin_document(source: &str) -> String {
|
||||
let mut hooks = String::new();
|
||||
let mut out = String::new();
|
||||
@@ -5160,6 +5344,7 @@ fn geometry_and_body(source: &str) -> (String, PageGeometry) {
|
||||
let source = lift_at_begin_document(source);
|
||||
let source = collapse_definition_bodies(&source);
|
||||
let source = strip_tex_comments(&source);
|
||||
let source = canonicalize_at_catcodes(&source);
|
||||
let source = collapse_braced_command(&source, "\\newgeometry");
|
||||
// Class files write the title metadata across lines, especially author
|
||||
// blocks with forced line breaks and thanks notes.
|
||||
@@ -8545,10 +8730,11 @@ fn strip_group_braces(text: &str) -> String {
|
||||
}
|
||||
out.push(character);
|
||||
}
|
||||
out
|
||||
out.replace('\u{E022}', "")
|
||||
}
|
||||
|
||||
fn strip_noop_commands(text: &str) -> String {
|
||||
let text = text.replace('\u{E022}', "");
|
||||
const COMMANDS: [&str; 17] = [
|
||||
"\\displaybreak",
|
||||
"\\protect",
|
||||
@@ -15015,6 +15201,30 @@ A definition.
|
||||
assert_eq!(value["warnings"].as_array().map(Vec::len), Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn at_is_a_letter_only_inside_makeatletter() {
|
||||
let text_of = |body: &str| -> String {
|
||||
let source = format!(
|
||||
"\\documentclass{{article}}\n\\begin{{document}}\n\n{body}\n\n\\end{{document}}\n"
|
||||
);
|
||||
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()
|
||||
};
|
||||
assert!(text_of("\\makeatletter\\def\\@foo{bar}\\@foo\\makeatother").contains("bar"));
|
||||
let split = text_of("\\def\\foo{Hi}\\foo@bar");
|
||||
assert!(split.contains("Hi@bar"), "{split}");
|
||||
assert!(text_of("\\@ifundefined{missing}{Yes}{No}").contains("Yes"));
|
||||
assert!(
|
||||
text_of("\\makeatletter{\\makeatother}\\def\\@x{Y}\\@x\\makeatother").contains('Y')
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_lines_and_runtime_aliases() {
|
||||
let text_of = |source: &str| -> String {
|
||||
@@ -15039,7 +15249,7 @@ A definition.
|
||||
|
||||
#[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";
|
||||
let source = "\\documentclass{article}\n\\begin{document}\n\n\\makeatletter\\def\\@foo{bar}\\@foo and \\def\\greet{Hello}\\greet.\\makeatother\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["status"], "ok");
|
||||
|
||||
Reference in new issue
Block a user