Skip to main content

latexml_core/common/
def_parser.rs

1use std::sync::LazyLock;
2
3use regex::Regex;
4
5use crate::{
6  common::{
7    arena::{self},
8    error::*,
9  },
10  mouth,
11  parameter::{Parameter, Parameters},
12  pin,
13  token::*,
14  tokens::{TeXString, Tokens},
15};
16
17static CSNAME_MACRO_RE: LazyLock<Regex> =
18  LazyLock::new(|| Regex::new(r"^\\csname\s+(.*)\\endcsname").unwrap());
19// Includes `_` (expl3 private/word-internal) and an optional `:<letters>`
20// suffix (expl3 parameter-type sigil) so prototype strings like
21// "\\draw_path_arc:nnn{}{}{}" parse with the entire `\draw_path_arc:nnn`
22// as the control-sequence name. Under normal LaTeX catcodes `_` is SUB
23// and `:` is OTHER, so these names only round-trip through the
24// tokenizer under expl3 catcode regime — but compile-time prototype
25// strings bypass the tokenizer, so this is purely a string-parsing
26// concern. Witness: l3draw_sty stubs would previously fail with
27// "Unrecognized parameter type with name '_begin', spec '_begin:'".
28static CS_RE: LazyLock<Regex> =
29  LazyLock::new(|| Regex::new(r"^(\\[a-zA-Z@_]+(?::[a-zA-Z]*)?)").unwrap());
30static SINGLE_CHAR_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\\.)").unwrap());
31static ACTIVE_CHAR_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(.)").unwrap());
32
33/// If calling at compile-time, pass `None` for state, to avoid initialization.
34pub fn parse_prototype(proto: &str, init_flag: bool) -> Result<(Token, Option<Parameters>)> {
35  let cs;
36  let normalized_proto = if let Some(captures) = CSNAME_MACRO_RE.captures(proto) {
37    let csname_content = captures.get(1).map_or("", |m| m.as_str());
38    // At compile time, reject \csname patterns with braces — these produce CS names
39    // like \begin{env} that can cause infinite loops in the proc macro expansion.
40    // Starred environments (\csname eqnarray*\endcsname) are fine.
41    if !init_flag && (csname_content.contains('{') || csname_content.contains('}')) {
42      panic!(
43        "\\csname...\\endcsname with braces in definition prototype is not supported at compile time: \"{}\". \
44         Use RawTeX!() or runtime DefMacroI() for CS names containing {{}} characters.",
45        proto
46      );
47    }
48    cs = T_CS!(s!("\\{}", csname_content));
49    // also replace in proto
50    CSNAME_MACRO_RE.replace(proto, "")
51  } else if let Some(captures) = CS_RE.captures(proto) {
52    // Match a cs
53    let csname = captures.get(1).map_or("", |m| m.as_str()).to_string();
54    cs = T_CS!(csname);
55    // also replace in proto
56    CS_RE.replace(proto, "")
57  } else if let Some(captures) = SINGLE_CHAR_RE.captures(proto) {
58    // Match a single char cs, env name,...
59    cs = T_CS!(captures.get(1).map_or("", |m| m.as_str()));
60    // also replace in proto
61    SINGLE_CHAR_RE.replace(proto, "")
62  } else if let Some(captures) = ACTIVE_CHAR_RE.captures(proto) {
63    // Match an active char
64    cs = mouth::tokenize_internal(TeXString::assembled(
65      captures.get(1).map_or("", |m| m.as_str()).to_string(),
66    ))
67    .unlist()
68    .remove(0);
69    // also replace in proto
70    ACTIVE_CHAR_RE.replace(proto, "")
71  } else {
72    let message = s!(
73      "Definition prototype doesn't have proper control sequence: \"{}\"",
74      proto
75    );
76    fatal!(Prototype, Misdefined, message);
77  };
78  let final_proto = normalized_proto.trim();
79  let paramlist = parse_parameters(final_proto, &cs, init_flag)?;
80  Ok((cs, paramlist))
81}
82
83/// If calling at compile-time, pass `None` for state, to avoid initialization.
84pub fn parse_parameters(
85  outer_prototype: &str,
86  cs: &Token,
87  init_flag: bool,
88) -> Result<Option<Parameters>> {
89  // The prototype grammar, as a winnow parse (#171 family; the golden corpus
90  // in `golden_tests` pins byte-equivalence with the prior regex munch loop):
91  //   item := "{" inner "}" \s*          (Plain, recursive inner)
92  //         | "[" inner "]" \s*          (Optional; inner may be Default:…)
93  //         | word (":" extra)? \s*      (named type, extra |-split)   [nonempty]
94  //         | any-single-char            (literal Token; spaces too — each
95  //                                       space is its own Token, faithfully)
96  use winnow::{
97    combinator::{delimited, opt, preceded},
98    prelude::*,
99    token::{any, take_while},
100  };
101
102  fn ws0(input: &mut &str) -> ModalResult<()> {
103    take_while(0.., |c: char| c.is_whitespace())
104      .void()
105      .parse_next(input)
106  }
107  /// `{inner}` / `[inner]` group: returns the inner slice; trailing \s* eaten.
108  fn group<'a>(open: char, close: char) -> impl FnMut(&mut &'a str) -> ModalResult<&'a str> {
109    move |input: &mut &'a str| {
110      let inner = delimited(open, take_while(0.., move |c| c != close), close).parse_next(input)?;
111      ws0(input)?;
112      Ok(inner)
113    }
114  }
115  /// `word(:extra)?` with word ∈ \w+ or a bare nonempty `:extra`; \s* eaten.
116  fn paramspec<'a>(input: &mut &'a str) -> ModalResult<(&'a str, Option<&'a str>)> {
117    let word = take_while(0.., |c: char| c.is_alphanumeric() || c == '_').parse_next(input)?;
118    let extra = opt(preceded(
119      ':',
120      take_while(0.., |c: char| !c.is_whitespace() && c != '{' && c != '['),
121    ))
122    .parse_next(input)?;
123    if word.is_empty() && extra.is_none() {
124      return Err(winnow::error::ErrMode::Backtrack(
125        winnow::error::ContextError::new(),
126      ));
127    }
128    ws0(input)?;
129    Ok((word, extra))
130  }
131
132  let mut parameters = Vec::with_capacity(4);
133  let mut rest: &str = outer_prototype;
134  let input = &mut rest;
135  while !input.is_empty() {
136    // Probe-and-commit on a copy per branch: a failing branch must not consume
137    // (`delimited` advances past its opening token before failing otherwise —
138    // e.g. a lone "{" from the non-nesting inner of "{{}}").
139    let mut probe;
140    let res = {
141      probe = *input;
142      group('{', '}')
143        .parse_next(&mut probe)
144        .inspect(|_| *input = probe)
145    };
146    let mut p: Parameter = match res {
147      Ok(inner_spec) => {
148        // Plain (possibly typed-inner) braced group, spec keeps its braces.
149        let inner: Option<Parameters> = if inner_spec.is_empty() {
150          None
151        } else {
152          parse_parameters(inner_spec, cs, init_flag)?
153        };
154        Parameter {
155          name: pin!("Plain"),
156          spec: arena::pin(format!("{{{inner_spec}}}")),
157          inner: inner.map(|ps| ps.into()).unwrap_or_default(),
158          ..Parameter::default()
159        }
160      },
161      _ => {
162        let res = {
163          probe = *input;
164          group('[', ']')
165            .parse_next(&mut probe)
166            .inspect(|_| *input = probe)
167        };
168        match res {
169          Ok(inner_spec) => {
170            let spec = arena::pin(format!("[{inner_spec}]"));
171            if let Some(default_str) = inner_spec.strip_prefix("Default:") {
172              let extra = if default_str.is_empty() {
173                vec![]
174              } else {
175                vec![mouth::tokenize_internal(TeXString::assembled(
176                  default_str.to_string(),
177                ))]
178              };
179              Parameter {
180                name: pin!("Optional"),
181                spec,
182                extra,
183                ..Parameter::default()
184              }
185            } else if !inner_spec.is_empty() {
186              Parameter {
187                name: pin!("Optional"),
188                spec,
189                inner: parse_parameters(inner_spec, cs, init_flag)?
190                  .map(|ps| ps.into())
191                  .unwrap_or_default(),
192                ..Parameter::default()
193              }
194            } else {
195              Parameter {
196                name: pin!("Optional"),
197                spec,
198                ..Parameter::default()
199              }
200            }
201          },
202          _ => {
203            let res = {
204              probe = *input;
205              paramspec.parse_next(&mut probe).inspect(|_| *input = probe)
206            };
207            match res {
208              Ok((word, extra_opt)) => {
209                let spec_str = match extra_opt {
210                  Some(extra) => format!("{word}:{extra}"),
211                  None => word.to_string(),
212                };
213                let extra: Vec<Tokens> = match extra_opt {
214                  None | Some("") => Vec::new(),
215                  Some(extra_str) => extra_str
216                    .split('|')
217                    .map(|t| {
218                      Tokens::new(
219                        mouth::tokenize_internal(TeXString::assembled(t.to_string())).unlist(),
220                      )
221                    })
222                    .collect(),
223                };
224                Parameter {
225                  name: arena::pin(word),
226                  spec: arena::pin(&spec_str),
227                  extra,
228                  ..Parameter::default()
229                }
230              },
231              _ => {
232                // Literal single char (incl. each whitespace char) as a Token parameter.
233                let ch = any.parse_next(input).map_err(
234                  |_: winnow::error::ErrMode<winnow::error::ContextError>| {
235                    Error::from(s!(
236                      "parse_parameters: unreadable prototype tail for {:?}",
237                      cs
238                    ))
239                  },
240                )?;
241                let ch_token = CharToken!(ch, Catcode::OTHER);
242                // "Match", not "Token": the Match reader consumes the literal
243                // from `extra` (or yields None), while the Token reader
244                // IGNORES extra and swallows one ARBITRARY token — a
245                // prototype like `\mode<>{}` then silently ate `<`+`p`+`r`
246                // of `\mode<presentation>` (beamerswitch witness; Perl's
247                // parseParameters has no such fallback at all, so no Perl
248                // binding can express these prototypes).
249                Parameter {
250                  name: pin!("Match"),
251                  spec: pin!("Match"),
252                  extra: vec![Tokens::new(vec![ch_token])],
253                  ..Parameter::default()
254                }
255              },
256            }
257          },
258        }
259      },
260    };
261    if init_flag {
262      p = p.init()?;
263    }
264    parameters.push(p);
265  }
266  if parameters.is_empty() {
267    Ok(None)
268  } else {
269    Ok(Some(Parameters::new(parameters)))
270  }
271}
272
273#[cfg(test)]
274mod golden_tests {
275  /// Render a parse result in a stable, comparison-friendly form.
276  fn describe(proto: &str) -> String {
277    match super::parse_parameters(proto, &crate::T_CS!("\\x"), false) {
278      Ok(None) => "None".to_string(),
279      Ok(Some(ps)) => ps
280        .get_parameters()
281        .iter()
282        .map(|p| {
283          format!(
284            "{}:{}/x{}/i{}",
285            crate::common::arena::with(p.name, |s| s.to_string()),
286            crate::common::arena::with(p.spec, |s| s.to_string()),
287            p.extra.len(),
288            p.inner
289              .as_ref()
290              .map(|ps| ps.get_parameters().len())
291              .unwrap_or(0)
292          )
293        })
294        .collect::<Vec<_>>()
295        .join(" | "),
296      Err(e) => format!("ERR:{e}"),
297    }
298  }
299
300  /// Golden corpus pinning the prototype grammar's behavior (captured from
301  /// the regex implementation 2026-06-10) — the gate for the winnow rewrite:
302  /// any divergence here is a semantics change, not a refactor.
303  ///
304  /// DELIBERATE semantics change 2026-08-31: literal-char fallbacks are
305  /// `Match` parameters (consume that literal, or None) instead of `Token`
306  /// (consume one ARBITRARY token, ignoring the literal) — identical on
307  /// well-formed input, no longer silently eats unrelated tokens on
308  /// mismatch (`\mode<>{}` ate `<pr` of `<presentation>`; beamerswitch).
309  #[test]
310  fn golden_prototype_corpus() {
311    crate::state::set_state(crate::state::State::new(
312      crate::state::StateOptions::default(),
313    ));
314    let golden: &[(&str, &str)] = &[
315      ("{}", "Plain:{}/x0/i0"),
316      ("{}{}", "Plain:{}/x0/i0 | Plain:{}/x0/i0"),
317      ("[]", "Optional:[]/x0/i0"),
318      ("[]{}", "Optional:[]/x0/i0 | Plain:{}/x0/i0"),
319      ("{Number}", "Plain:{Number}/x0/i1"),
320      (
321        "{Float}{Float} {}",
322        "Plain:{Float}/x0/i1 | Plain:{Float}/x0/i1 | Plain:{}/x0/i0",
323      ),
324      (
325        "OptionalMatch:* [][] Semiverbatim",
326        "OptionalMatch:OptionalMatch:*/x1/i0 | Optional:[]/x0/i0 | Optional:[]/x0/i0 | \
327         Semiverbatim:Semiverbatim/x0/i0",
328      ),
329      (
330        "OptionalKeyVals:LST",
331        "OptionalKeyVals:OptionalKeyVals:LST/x1/i0",
332      ),
333      (
334        "RequiredKeyVals:RH {}",
335        "RequiredKeyVals:RequiredKeyVals:RH/x1/i0 | Plain:{}/x0/i0",
336      ),
337      ("Until:\\end", "Until:Until:\\end/x1/i0"),
338      (
339        "XUntil:\\fi {}",
340        "XUntil:XUntil:\\fi/x1/i0 | Plain:{}/x0/i0",
341      ),
342      (
343        "[Default:0]{}",
344        "Optional:[Default:0]/x1/i0 | Plain:{}/x0/i0",
345      ),
346      ("Semiverbatim", "Semiverbatim:Semiverbatim/x0/i0"),
347      (
348        "SkipSpaces {}",
349        "SkipSpaces:SkipSpaces/x0/i0 | Plain:{}/x0/i0",
350      ),
351      ("Digested", "Digested:Digested/x0/i0"),
352      ("DigestedBody", "DigestedBody:DigestedBody/x0/i0"),
353      (
354        "(){}",
355        "Match:Match/x1/i0 | Match:Match/x1/i0 | Plain:{}/x0/i0",
356      ),
357      (
358        "( {Float} , {Float} )",
359        "Match:Match/x1/i0 | Match:Match/x1/i0 | Plain:{Float}/x0/i1 | Match:Match/x1/i0 | \
360         Match:Match/x1/i0 | Plain:{Float}/x0/i1 | Match:Match/x1/i0",
361      ),
362      ("Optional:=Default:9", "Optional:Optional:=Default:9/x1/i0"),
363      ("{Until:;}", "Plain:{Until:;}/x0/i1"),
364      ("+", "Match:Match/x1/i0"),
365      ("Match:- {}", "Match:Match:-/x1/i0 | Plain:{}/x0/i0"),
366      // pst_all_sty shapes: non-nesting braced inner ("{{}}" -> Plain with a
367      // lone "{" inner Token, then a dangling "}" Token) — regex-faithful.
368      (
369        "OptionalMatch:* {{}} [] {}",
370        "OptionalMatch:OptionalMatch:*/x1/i0 | Plain:{{}/x0/i1 | Match:Match/x1/i0 | Match:Match/x1/i0 | \
371         Optional:[]/x0/i0 | Plain:{}/x0/i0",
372      ),
373      ("{", "Match:Match/x1/i0"),
374    ];
375    for (proto, expected) in golden {
376      let expected = expected.split_whitespace().collect::<Vec<_>>().join(" ");
377      let actual = describe(proto)
378        .split_whitespace()
379        .collect::<Vec<_>>()
380        .join(" ");
381      assert_eq!(actual, expected, "prototype grammar diverged on {proto:?}");
382    }
383  }
384}