Print macro bodies with meaning

\meaning<token> was unsupported. Expansion now reads the following token and
prints its meaning literally: for a known macro, "macro:" plus its parameter
text (or #1..#n from the argument count) and "->" plus the stored body; for an
undefined control sequence, \relax; for a character, "the character <c>". The
text goes through the same private-use escaping as \string so later passes
cannot re-tokenise it.

A preview test defines \greet#1 and prints \meaning\greet plus
\meaning\missing, checking "macro:#1->Hello #1" and "\relax" with no warnings.
This commit is contained in:
gloamxun committed 2026-10-27 01:18:49 +08:00
1 parent 47dcdfec47
commit d791e3a0f2
3 files changed
+77 -7

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). 1006 workspace tests are green and no oracle
prefer route-D with a v1 fallback). 1007 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.
+4 -2
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 1006 tests (437 route-D unit, 379 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 1007 tests (437 route-D unit, 380 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
@@ -570,7 +570,9 @@ are:
`\newtoks\name`, `\name={...}`, `\toks0={...}` and `\the\toks0` /
`\the\name` store and splice the register text. `\string<token>` prints the
token without expanding it, with backslash/braces carried through private-use
placeholders so they render but never re-tokenise.
placeholders so they render but never re-tokenise. `\meaning<token>` prints
`macro:<params>-><body>` for a macro (or `\relax` for an undefined control
sequence) with the same literal escaping.
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`
+72 -4
View File
@@ -805,11 +805,51 @@ fn string_token(text: &str) -> Option<(String, usize)> {
return None;
}
let (token, used) = next_token(after)?;
let escaped = token
.replace('\\', "\u{E023}")
Some((escape_literal(&token), "\\string".len() + used))
}
fn escape_literal(text: &str) -> String {
text.replace('\\', "\u{E023}")
.replace('{', "\u{E024}")
.replace('}', "\u{E025}");
Some((escaped, "\\string".len() + used))
.replace('}', "\u{E025}")
}
/// `\meaning<token>` prints the macro body (or a primitive stand-in) literally.
fn meaning_token(
text: &str,
runtime: &[MacroDefinition],
scopes: &[Vec<MacroDefinition>],
) -> Option<(String, usize)> {
let after = text.strip_prefix("\\meaning")?;
if after
.chars()
.next()
.is_some_and(|character| character.is_ascii_alphabetic())
{
return None;
}
let (token, used) = next_token(after)?;
let meaning = if token.starts_with('\\') {
let definition = scopes
.iter()
.rev()
.find_map(|scope| scope.iter().rev().find(|known| known.name == token))
.or_else(|| runtime.iter().find(|known| known.name == token));
match definition {
Some(definition) => {
let params = definition.params.clone().unwrap_or_else(|| {
(1..=definition.args)
.map(|index| format!("#{index}"))
.collect()
});
format!("macro:{}->{}", params, definition.body)
}
None => "\\relax".to_string(),
}
} else {
format!("the character {}", token)
};
Some((escape_literal(&meaning), "\\meaning".len() + used))
}
fn toks_register(text: &str) -> Option<(String, usize)> {
@@ -1698,6 +1738,12 @@ fn expand_macros_mut(
changed = true;
continue;
}
if let Some((text, used)) = meaning_token(rest, &runtime, &scopes) {
output.push_str(&text);
index += used;
changed = true;
continue;
}
if let Some((content, used)) = newtoks_declaration(rest) {
if !tokens.iter().any(|(key, _)| key == &content) {
tokens.push((content, String::new()));
@@ -16027,6 +16073,28 @@ A definition.
assert!(!text.contains("makeatletter"), "{text}");
}
#[test]
fn meaning_prints_macro_bodies() {
let source = "\\documentclass{article}\n\\begin{document}\n\n\\def\\greet#1{Hello #1}\n\n\\meaning\\greet and \\meaning\\missing.\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("macro:#1-&gt;Hello#1"), "{text}");
assert!(text.contains("\\relax"), "{text}");
}
#[test]
fn string_prints_tokens_literally() {
let source = "\\documentclass{article}\n\\begin{document}\n\n\\def\\foo{bar}\n\n\\string\\foo and \\string{ and \\string}.\n\n\\end{document}\n";