use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq)]
pub struct MacroDef {
pub name: String,
pub param_count: usize,
pub body: String,
}
#[derive(Debug, Default)]
pub struct MacroStore {
defs: HashMap<String, MacroDef>,
aliases: HashMap<String, String>,
}
impl MacroStore {
pub fn new() -> Self {
Self::default()
}
pub fn extract_definitions(&mut self, text: &str) -> String {
let mut result = String::with_capacity(text.len());
let mut i = 0;
while i < text.len() {
let remaining = &text[i..];
if (remaining.starts_with("\\newcommand")
|| remaining.starts_with("\\renewcommand")
|| remaining.starts_with("\\providecommand"))
&& let Some(skip) = self.parse_newcommand(remaining)
{
i += skip;
continue;
}
if remaining.starts_with("\\def")
&& let Some(skip) = self.parse_def(remaining)
{
i += skip;
continue;
}
if remaining.starts_with("\\let")
&& let Some(skip) = self.parse_let(remaining)
{
i += skip;
continue;
}
let ch = remaining.chars().next().unwrap_or('\0');
result.push(ch);
i += ch.len_utf8();
}
result
}
pub fn expand_all(&self, text: &str) -> String {
let mut result = text.to_string();
for _ in 0..10 {
let next = self.expand_once(&result);
if next == result {
break;
}
result = next;
}
result
}
fn parse_newcommand(&mut self, text: &str) -> Option<usize> {
let (start, only_if_absent) = if text.starts_with("\\providecommand") {
("\\providecommand".len(), true)
} else if text.starts_with("\\renewcommand") {
("\\renewcommand".len(), false)
} else {
("\\newcommand".len(), false)
};
let rest = text.get(start..)?;
let mut pos = 0;
while pos < rest.len() && rest[pos..].starts_with(|c: char| c.is_whitespace()) {
pos += rest[pos..].chars().next()?.len_utf8();
}
let (name, consumed) = if rest.get(pos..).is_some_and(|s| s.starts_with('{')) {
let (inner, end) = extract_braced(rest, pos)?;
let trimmed = inner.trim();
let name = trimmed.strip_prefix('\\').unwrap_or(trimmed).to_string();
(name, end)
} else if rest.get(pos..).is_some_and(|s| s.starts_with('\\')) {
let name_end = rest[pos + 1..]
.find(|c: char| !c.is_alphabetic() && c != '*')
.map(|i| pos + 1 + i)
.unwrap_or(rest.len());
(rest[pos + 1..name_end].to_string(), name_end)
} else {
return None;
};
pos = consumed;
while pos < rest.len() && rest[pos..].starts_with(|c: char| c.is_whitespace()) {
pos += rest[pos..].chars().next()?.len_utf8();
}
let mut param_count = 0;
if rest[pos..].starts_with('[') {
let close = rest[pos..].find(']')?;
let num_str = &rest[pos + 1..pos + close];
param_count = num_str.parse().ok()?;
pos += close + 1;
}
while pos < rest.len() && rest[pos..].starts_with(|c: char| c.is_whitespace()) {
pos += rest[pos..].chars().next()?.len_utf8();
}
let (body, end) = extract_braced(rest, pos)?;
pos = end;
if !only_if_absent || !self.defs.contains_key(&name) {
self.defs.insert(
name.clone(),
MacroDef {
name,
param_count,
body,
},
);
}
Some(start + pos)
}
fn parse_def(&mut self, text: &str) -> Option<usize> {
let start = "\\def".len();
let rest = text.get(start..)?;
let mut pos = 0;
while pos < rest.len() && rest[pos..].starts_with(|c: char| c.is_whitespace()) {
pos += rest[pos..].chars().next()?.len_utf8();
}
if !rest[pos..].starts_with('\\') {
return None;
}
let name_end = rest[pos + 1..]
.find(|c: char| !c.is_alphabetic() && c != '*')
.map(|i| pos + 1 + i)
.unwrap_or(rest.len());
let name = rest[pos + 1..name_end].to_string();
pos = name_end;
let mut param_count = 0;
while let Some(digit) = rest
.get(pos + 1..)
.and_then(|s| s.chars().next())
.filter(|c| c.is_ascii_digit())
{
let n = digit.to_digit(10).unwrap() as usize;
param_count = param_count.max(n);
pos += 1 + digit.len_utf8();
}
let (body, end) = extract_braced(rest, pos)?;
pos = end;
self.defs.insert(
name.clone(),
MacroDef {
name,
param_count,
body,
},
);
Some(start + pos)
}
fn parse_let(&mut self, text: &str) -> Option<usize> {
let start = "\\let".len();
let rest = text.get(start..)?;
let mut pos = 0;
while pos < rest.len() && rest[pos..].starts_with(|c: char| c.is_whitespace()) {
pos += rest[pos..].chars().next()?.len_utf8();
}
if !rest[pos..].starts_with('\\') {
return None;
}
let new_end = rest[pos + 1..]
.find(|c: char| !c.is_alphabetic() && c != '*')
.map(|i| pos + 1 + i)
.unwrap_or(rest.len());
let new_name = rest[pos + 1..new_end].to_string();
pos = new_end;
while pos < rest.len() && rest[pos..].starts_with(|c: char| c.is_whitespace()) {
pos += rest[pos..].chars().next()?.len_utf8();
}
if rest[pos..].starts_with('=') {
pos += 1;
while pos < rest.len() && rest[pos..].starts_with(|c: char| c.is_whitespace()) {
pos += rest[pos..].chars().next()?.len_utf8();
}
}
if !rest[pos..].starts_with('\\') {
return None;
}
let old_end = rest[pos + 1..]
.find(|c: char| !c.is_alphabetic() && c != '*')
.map(|i| pos + 1 + i)
.unwrap_or(rest.len());
let old_name = rest[pos + 1..old_end].to_string();
pos = old_end;
self.aliases.insert(new_name, old_name);
Some(start + pos)
}
fn expand_once(&self, text: &str) -> String {
let mut result = String::with_capacity(text.len() * 2);
let mut i = 0;
while i < text.len() {
let remaining = &text[i..];
if remaining.starts_with("\\newcommand")
|| remaining.starts_with("\\renewcommand")
|| remaining.starts_with("\\providecommand")
|| remaining.starts_with("\\def")
|| remaining.starts_with("\\let")
{
let cmd = if remaining.starts_with("\\providecommand") {
"\\providecommand"
} else if remaining.starts_with("\\renewcommand") {
"\\renewcommand"
} else if remaining.starts_with("\\newcommand") {
"\\newcommand"
} else if remaining.starts_with("\\let") {
"\\let"
} else {
"\\def"
};
result.push_str(cmd);
i += cmd.len();
continue;
}
if let Some(after_backslash) = remaining.strip_prefix('\\') {
let name_end = if after_backslash.is_empty() {
0
} else {
after_backslash
.find(|c: char| !c.is_alphabetic() && c != '*')
.unwrap_or(after_backslash.len())
};
let name = &after_backslash[..name_end];
if let Some(def) = self.defs.get(name) {
let after = &after_backslash[name_end..];
let (args, consumed) = self.collect_args(after, def.param_count);
let expanded = self.substitute(&def.body, &args);
result.push_str(&expanded);
i += 1 + name_end + consumed;
continue;
}
if let Some(target) = self.aliases.get(name) {
result.push('\\');
result.push_str(target);
i += 1 + name_end;
continue;
}
}
let ch = remaining.chars().next().unwrap_or('\0');
result.push(ch);
i += ch.len_utf8();
}
result
}
fn collect_args(&self, text: &str, count: usize) -> (Vec<String>, usize) {
let mut args = Vec::with_capacity(count);
let mut pos = 0;
for _ in 0..count {
while pos < text.len() && text[pos..].starts_with(|c: char| c.is_whitespace()) {
pos += text[pos..].chars().next().unwrap().len_utf8();
}
if text.get(pos..).is_some_and(|s| s.starts_with('{'))
&& let Some((inner, end)) = extract_braced(text, pos)
{
args.push(inner);
pos = end;
continue;
}
break;
}
(args, pos)
}
fn substitute(&self, body: &str, args: &[String]) -> String {
let mut result = String::with_capacity(body.len() * 2);
let mut i = 0;
while i < body.len() {
if body.get(i..).is_some_and(|s| s.starts_with('#'))
&& let Some(ch) = body.get(i + 1..).and_then(|s| s.chars().next())
&& let Some(n) = ch.to_digit(10)
{
let idx = n as usize;
if idx > 0 && idx <= args.len() {
result.push_str(&args[idx - 1]);
}
i += 1 + ch.len_utf8();
continue;
}
let c = body[i..].chars().next().unwrap();
result.push(c);
i += c.len_utf8();
}
result
}
}
fn extract_braced(text: &str, start: usize) -> Option<(String, usize)> {
if start >= text.len() || !text[start..].starts_with('{') {
return None;
}
let mut depth = 0;
let mut content_start = None;
for (offset, ch) in text[start..].char_indices() {
let index = start + offset;
if ch == '{' {
depth += 1;
if depth == 1 {
content_start = Some(index + ch.len_utf8());
}
} else if ch == '}' {
depth -= 1;
if depth == 0 {
let inner_start = content_start?;
return Some((text[inner_start..index].to_string(), index + ch.len_utf8()));
}
}
}
None
}
pub fn expand_document(text: &str) -> String {
let mut store = MacroStore::new();
let stripped = store.extract_definitions(text);
store.expand_all(&stripped)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_newcommand_no_args() {
let mut store = MacroStore::new();
let cleaned = store.extract_definitions("\\newcommand{\\hello}{Hello World} begin");
assert_eq!(cleaned, " begin");
assert_eq!(store.defs["hello"].body, "Hello World");
assert_eq!(store.defs["hello"].param_count, 0);
}
#[test]
fn test_newcommand_with_args() {
let mut store = MacroStore::new();
let cleaned = store.extract_definitions("\\newcommand{\\greet}[1]{Hello, #1!} text");
assert_eq!(cleaned, " text");
assert_eq!(store.defs["greet"].body, "Hello, #1!");
assert_eq!(store.defs["greet"].param_count, 1);
}
#[test]
fn test_def_with_params() {
let mut store = MacroStore::new();
let cleaned = store.extract_definitions("\\def\\foo#1#2{#1 loves #2} end");
assert_eq!(cleaned, " end");
assert_eq!(store.defs["foo"].body, "#1 loves #2");
assert_eq!(store.defs["foo"].param_count, 2);
}
#[test]
fn test_expand_no_args() {
let mut store = MacroStore::new();
store.extract_definitions("\\newcommand{\\hi}{Hi}");
assert_eq!(store.expand_all("Say \\hi."), "Say Hi.");
}
#[test]
fn test_expand_with_args() {
let mut store = MacroStore::new();
store.extract_definitions("\\newcommand{\\greet}[1]{Hello, #1!}");
assert_eq!(store.expand_all("\\greet{World}"), "Hello, World!");
}
#[test]
fn test_expand_def() {
let mut store = MacroStore::new();
store.extract_definitions("\\def\\twice#1{#1 #1}");
assert_eq!(store.expand_all("\\twice{hello}"), "hello hello");
}
#[test]
fn test_multiple_macros() {
let mut store = MacroStore::new();
store.extract_definitions("\\newcommand{\\a}{A}\\newcommand{\\b}{B}");
assert_eq!(store.expand_all("\\a and \\b"), "A and B");
}
#[test]
fn test_unknown_command_preserved() {
let store = MacroStore::new();
assert_eq!(store.expand_all("\\unknown{test}"), "\\unknown{test}");
}
#[test]
fn test_renewcommand_overrides_definition() {
let mut store = MacroStore::new();
store.extract_definitions("\\newcommand{\\foo}{old}\\renewcommand{\\foo}{new}");
assert_eq!(store.defs["foo"].body, "new");
assert_eq!(store.expand_all("\\foo"), "new");
}
#[test]
fn test_providecommand_defines_when_absent() {
let mut store = MacroStore::new();
store.extract_definitions("\\providecommand{\\foo}{bar}");
assert_eq!(store.defs["foo"].body, "bar");
assert_eq!(store.expand_all("\\foo"), "bar");
}
#[test]
fn test_providecommand_does_not_override_existing() {
let mut store = MacroStore::new();
store.extract_definitions("\\newcommand{\\foo}{first}\\providecommand{\\foo}{second}");
assert_eq!(store.defs["foo"].body, "first", "providecommand must keep the existing definition");
assert_eq!(store.expand_all("\\foo"), "first");
}
#[test]
fn test_let_alias() {
let mut store = MacroStore::new();
store.extract_definitions("\\let\\oldsection\\section");
assert_eq!(store.expand_all("\\oldsection"), "\\section");
}
#[test]
fn test_let_alias_with_equals() {
let mut store = MacroStore::new();
store.extract_definitions("\\let\\foo=\\bar");
assert_eq!(store.expand_all("\\foo"), "\\bar");
}
#[test]
fn test_let_alias_to_macro() {
let mut store = MacroStore::new();
store.extract_definitions("\\newcommand{\\bar}{BAR}\\let\\foo\\bar");
assert_eq!(store.expand_all("\\foo"), "BAR");
}
#[test]
fn test_expand_multiple_args() {
let mut store = MacroStore::new();
store.extract_definitions("\\newcommand{\\add}[2]{#1 + #2}");
assert_eq!(store.expand_all("\\add{a}{b}"), "a + b");
}
#[test]
fn test_expand_document_helper() {
let input = "\\newcommand{\\hi}{Hello}\\hi there";
assert_eq!(expand_document(input), "Hello there");
}
#[test]
fn test_nested_macro_expansion() {
let mut store = MacroStore::new();
store.extract_definitions("\\newcommand{\\inner}{X}\\newcommand{\\outer}{\\inner Y}");
let result = store.expand_all("\\outer");
assert!(result.contains('X'), "nested expansion should produce X, got: {result}");
}
#[test]
fn test_macro_with_optional_arg_not_stripped() {
let mut store = MacroStore::new();
store.extract_definitions("\\newcommand{\\foo}[1][default]{value: #1}");
}
#[test]
fn test_def_no_args() {
let mut store = MacroStore::new();
store.extract_definitions("\\def\\bar{BAR}");
assert_eq!(store.expand_all("\\bar"), "BAR");
}
#[test]
fn test_expand_preserves_non_macro_text() {
let mut store = MacroStore::new();
store.extract_definitions("\\newcommand{\\x}{X}");
assert_eq!(store.expand_all("before \\x after"), "before X after");
}
}