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());
19static 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
33pub 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 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 CSNAME_MACRO_RE.replace(proto, "")
51 } else if let Some(captures) = CS_RE.captures(proto) {
52 let csname = captures.get(1).map_or("", |m| m.as_str()).to_string();
54 cs = T_CS!(csname);
55 CS_RE.replace(proto, "")
57 } else if let Some(captures) = SINGLE_CHAR_RE.captures(proto) {
58 cs = T_CS!(captures.get(1).map_or("", |m| m.as_str()));
60 SINGLE_CHAR_RE.replace(proto, "")
62 } else if let Some(captures) = ACTIVE_CHAR_RE.captures(proto) {
63 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 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
83pub fn parse_parameters(
85 outer_prototype: &str,
86 cs: &Token,
87 init_flag: bool,
88) -> Result<Option<Parameters>> {
89 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 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 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 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 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 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 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 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 #[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 (
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}