Resolve csname targets with arguments

\csname foo\endcsname stopped after looking up a zero-argument macro; a
parameterised target was left unresolved. After the zero-argument fast path,
build a synthetic command from the resolved name plus the text following
\endcsname and run the normal macro lookup, so arguments/defaults/delimited
parameter text are consumed exactly as for a literal \foo, and only the bytes
belonging to the csname construct are charged to the caller.

A test defines \foo#1{[#1]} and prints both \csname foo\endcsname{x} and
\csname foo\endcsname{y} as "[x] and [y]" with no warnings.
This commit is contained in:
gloamxun committed 2026-10-27 01:51:29 +08:00
1 parent c3e02f0586
commit c3ae52452d
4 files changed
+41 -11

No files matched your search

+34 -5
View File
@@ -1152,11 +1152,19 @@ fn csname_expansion(
.rev()
.find_map(|scope| scope.iter().rev().find(|known| known.name == name))
.or_else(|| runtime.iter().find(|known| known.name == name));
let body = definition
.filter(|known| known.args == 0 && known.params.is_none())
.map(|known| known.body.clone())
.unwrap_or_default();
Some((body, consumed))
if let Some(definition) = definition {
if definition.args == 0 && definition.params.is_none() {
return Some((definition.body.clone(), consumed));
}
}
// A parameterised target takes its arguments from after \endcsname.
let tail = &after[end + "\\endcsname".len()..];
let fake = format!("\\{}{}", expanded, tail);
if let Some((body, used)) = expand_macro_lookup(&fake, runtime, scopes) {
let prefix = 1 + expanded.len();
return Some((body, consumed + used.saturating_sub(prefix)));
}
Some((String::new(), consumed))
}
/// Runtime `\let\alias=\target` and `\chardef\name=<code>` definitions.
@@ -16367,6 +16375,27 @@ A definition.
assert!(!text.contains("makeatletter"), "{text}");
}
#[test]
fn csname_resolves_parameterised_targets() {
let source = "\\documentclass{article}\n\\begin{document}\n\n\\def\\foo#1{[#1]}\n\n\\csname foo\\endcsname{x} and \\csname foo\\endcsname{y}\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]and[y]"), "{text}");
}
#[test]
fn global_definitions_win_over_group_locals() {
let source = "\\documentclass{article}\n\\begin{document}\n\n\\def\\a{A}{\\def\\a{L}\\gdef\\a{G}\\a}\\a and \\global\\def\\b{B}\\b\n\n\\end{document}\n";