Skip to main content

badness_parser/semantic/
xparse.rs

1//! Parser for the **xparse argument specification** mini-language — the string in
2//! the second group of `\NewDocumentCommand{\foo}{<spec>}{…}` (and the environment
3//! variants). It describes argument shapes; processing behavior is ignored.
4//!
5//! The full grammar is tokenized so the cursor never desyncs on a type's trailing
6//! material (delimiter tokens, `{default}` groups, embellishment sets). But our
7//! [`ArgSpec`] model only distinguishes a `{…}` [`ArgKind::Brace`] from a `[…]`
8//! [`ArgKind::Bracket`] slot, because that is all the CST produces and all a
9//! consumer (the formatter's arity glue) can act on. So an [`ArgSpec`] is emitted
10//! **only** for argument types that yield an actual `{…}`/`[…]` node:
11//!
12//! - `m` → required brace; `o`, `O{default}` → optional bracket.
13//! - `r⟨t1⟩⟨t2⟩` / `R⟨…⟩{default}` (required delimited) and `d⟨t1⟩⟨t2⟩` /
14//!   `D⟨…⟩{default}` (optional delimited) → an [`ArgSpec`] **only** when the
15//!   delimiters are literally `[`/`]` (bracket) or `{`/`}` (brace); other delimiters
16//!   (`(`/`)`, `<`/`>`, …) produce no CST node, so no slot.
17//! - `s` (star), `t⟨token⟩` (optional token), `v` (verbatim), and `e`/`E`
18//!   (embellishments) produce no `{…}`/`[…]` node, so no slot — but their trailing
19//!   material is still consumed.
20//!
21//! This keeps the emitted slot count equal to the `GROUP`/`OPTIONAL` nodes the
22//! greedy parser actually attaches, which is what the formatter counts. Modifiers
23//! (`+`, `!`) and argument processors (`>{…}`) are skipped. Unknown type letters
24//! stop the scan (conservative: never panic, never invent slots).
25
26use super::signature::{ArgKind, ArgSpec, ContentKind};
27
28/// Parse an xparse argument-spec string into the `{…}`/`[…]` argument slots it
29/// declares, in order. See the module docs for the type-by-type mapping.
30pub fn parse_spec(spec: &str) -> Vec<ArgSpec> {
31    let chars: Vec<char> = spec.chars().collect();
32    let mut cursor = Cursor {
33        chars: &chars,
34        i: 0,
35    };
36    let mut args = Vec::new();
37
38    loop {
39        cursor.skip_modifiers();
40        cursor.skip_ws();
41        let Some(c) = cursor.bump() else { break };
42        match c {
43            'm' => args.push(brace(true)),
44            'o' => args.push(bracket(false)),
45            'O' => {
46                cursor.skip_group();
47                args.push(bracket(false));
48            }
49            // Required (`r`/`R`) and optional (`d`/`D`) delimited args: a slot only
50            // when the delimiters are the bracket/brace pair the CST models.
51            'r' | 'R' | 'd' | 'D' => {
52                let required = matches!(c, 'r' | 'R');
53                let open = cursor.read_token();
54                let close = cursor.read_token();
55                if matches!(c, 'R' | 'D') {
56                    cursor.skip_group(); // the {default}
57                }
58                if let Some(kind) = delimiter_kind(open.as_deref(), close.as_deref()) {
59                    args.push(ArgSpec {
60                        required,
61                        kind,
62                        content: ContentKind::Opaque,
63                    });
64                }
65            }
66            't' => {
67                cursor.read_token(); // the test token; yields no node
68            }
69            'e' => {
70                cursor.skip_group(); // {<tokens>}
71            }
72            'E' => {
73                cursor.skip_group(); // {<tokens>}
74                cursor.skip_group(); // {<defaults>}
75            }
76            // `s` (star), `v` (verbatim): consumed, no `{…}`/`[…]` node.
77            's' | 'v' => {}
78            // Unknown letter: stop rather than guess and miscount.
79            _ => break,
80        }
81    }
82
83    args
84}
85
86fn brace(required: bool) -> ArgSpec {
87    ArgSpec {
88        required,
89        kind: ArgKind::Brace,
90        content: ContentKind::Opaque,
91    }
92}
93
94fn bracket(required: bool) -> ArgSpec {
95    ArgSpec {
96        required,
97        kind: ArgKind::Bracket,
98        content: ContentKind::Opaque,
99    }
100}
101
102/// The `ArgKind` for a delimited arg whose delimiters are `open`/`close`, or `None`
103/// when the pair is not one the CST produces a node for.
104fn delimiter_kind(open: Option<&str>, close: Option<&str>) -> Option<ArgKind> {
105    match (open, close) {
106        (Some("["), Some("]")) => Some(ArgKind::Bracket),
107        (Some("{"), Some("}")) => Some(ArgKind::Brace),
108        _ => None,
109    }
110}
111
112/// A char cursor over the spec string with the small consumption primitives the
113/// xparse types need.
114struct Cursor<'a> {
115    chars: &'a [char],
116    i: usize,
117}
118
119impl Cursor<'_> {
120    fn peek(&self) -> Option<char> {
121        self.chars.get(self.i).copied()
122    }
123
124    fn bump(&mut self) -> Option<char> {
125        let c = self.peek()?;
126        self.i += 1;
127        Some(c)
128    }
129
130    fn skip_ws(&mut self) {
131        while self.peek().is_some_and(char::is_whitespace) {
132            self.i += 1;
133        }
134    }
135
136    /// Skip the type-prefix modifiers that may precede any argument type: `+`
137    /// (long), `!` (no-leading-space), and `>{processor}` argument processors.
138    fn skip_modifiers(&mut self) {
139        loop {
140            self.skip_ws();
141            match self.peek() {
142                Some('+') | Some('!') => self.i += 1,
143                Some('>') => {
144                    self.i += 1;
145                    self.skip_group();
146                }
147                _ => break,
148            }
149        }
150    }
151
152    /// Read a single spec token after optional whitespace: a control sequence
153    /// (`\` + a letter run, or `\` + one symbol) or a single character. Used for the
154    /// delimiter tokens of `r`/`R`/`d`/`D` and the test token of `t`.
155    fn read_token(&mut self) -> Option<String> {
156        self.skip_ws();
157        let first = self.bump()?;
158        if first != '\\' {
159            return Some(first.to_string());
160        }
161        let mut token = String::from('\\');
162        match self.peek() {
163            Some(c) if c.is_ascii_alphabetic() => {
164                while self.peek().is_some_and(|c| c.is_ascii_alphabetic()) {
165                    token.push(self.bump().expect("peeked"));
166                }
167            }
168            Some(_) => token.push(self.bump().expect("peeked")),
169            None => {}
170        }
171        Some(token)
172    }
173
174    /// If the next non-whitespace char opens a `{…}` group, skip the whole balanced
175    /// group (nested braces included). A no-op otherwise — tolerant of a malformed
176    /// spec missing the group a type would normally carry.
177    fn skip_group(&mut self) {
178        self.skip_ws();
179        if self.peek() != Some('{') {
180            return;
181        }
182        let mut depth = 0;
183        while let Some(c) = self.bump() {
184            match c {
185                '{' => depth += 1,
186                '}' => {
187                    depth -= 1;
188                    if depth == 0 {
189                        return;
190                    }
191                }
192                _ => {}
193            }
194        }
195    }
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201
202    fn kinds(spec: &str) -> Vec<(bool, ArgKind)> {
203        parse_spec(spec)
204            .into_iter()
205            .map(|a| (a.required, a.kind))
206            .collect()
207    }
208
209    #[test]
210    fn mandatory_and_optional_basics() {
211        assert_eq!(
212            kinds("m o m"),
213            vec![
214                (true, ArgKind::Brace),
215                (false, ArgKind::Bracket),
216                (true, ArgKind::Brace),
217            ]
218        );
219    }
220
221    #[test]
222    fn optional_with_default_consumes_group() {
223        // The `{0}` default must not be read as another argument.
224        assert_eq!(
225            kinds("O{0} m"),
226            vec![(false, ArgKind::Bracket), (true, ArgKind::Brace)]
227        );
228    }
229
230    #[test]
231    fn star_and_token_yield_no_slot() {
232        assert_eq!(kinds("s m"), vec![(true, ArgKind::Brace)]);
233        // `t` consumes its test token (`*`), leaving just the `m`.
234        assert_eq!(kinds("t* m"), vec![(true, ArgKind::Brace)]);
235    }
236
237    #[test]
238    fn verbatim_yields_no_slot() {
239        assert_eq!(kinds("v"), vec![]);
240    }
241
242    #[test]
243    fn bracket_delimited_maps_to_bracket() {
244        // `d[]` and `r[]` are `[…]`-delimited, so they yield a bracket slot.
245        assert_eq!(kinds("d[]"), vec![(false, ArgKind::Bracket)]);
246        assert_eq!(kinds("r[]"), vec![(true, ArgKind::Bracket)]);
247    }
248
249    #[test]
250    fn paren_delimited_yields_no_slot() {
251        // `()`-delimited args produce no CST node, so no slot — but the two
252        // delimiter tokens are still consumed, so a trailing `m` is found.
253        assert_eq!(kinds("d() m"), vec![(true, ArgKind::Brace)]);
254        assert_eq!(kinds("r<> m"), vec![(true, ArgKind::Brace)]);
255    }
256
257    #[test]
258    fn required_delimited_with_default_consumes_group() {
259        // `R(){default}`: two delimiter tokens then a default group, then `m`.
260        assert_eq!(kinds("R(){x} m"), vec![(true, ArgKind::Brace)]);
261        // `D[]{default}`: bracket-delimited optional with a default → one bracket
262        // slot, then `m`.
263        assert_eq!(
264            kinds("D[]{x} m"),
265            vec![(false, ArgKind::Bracket), (true, ArgKind::Brace)]
266        );
267    }
268
269    #[test]
270    fn embellishments_consume_their_groups() {
271        // `e{^_}` consumes one group; `E{^_}{\d\d}` consumes two. Neither yields a
272        // slot, so only the `m` remains.
273        assert_eq!(kinds("e{^_} m"), vec![(true, ArgKind::Brace)]);
274        assert_eq!(kinds("E{^_}{00} m"), vec![(true, ArgKind::Brace)]);
275    }
276
277    #[test]
278    fn modifiers_and_processors_skipped() {
279        assert_eq!(kinds("+m"), vec![(true, ArgKind::Brace)]);
280        assert_eq!(kinds("!o"), vec![(false, ArgKind::Bracket)]);
281        assert_eq!(kinds(">{\\TrimSpaces} m"), vec![(true, ArgKind::Brace)]);
282    }
283
284    #[test]
285    fn empty_and_whitespace_specs() {
286        assert_eq!(kinds(""), vec![]);
287        assert_eq!(kinds("   "), vec![]);
288        assert_eq!(
289            kinds("  m   o  "),
290            vec![(true, ArgKind::Brace), (false, ArgKind::Bracket)]
291        );
292    }
293
294    #[test]
295    fn unknown_letter_stops_scan() {
296        // A garbage letter halts parsing; the `m` before it is kept, the rest dropped.
297        assert_eq!(kinds("m z m"), vec![(true, ArgKind::Brace)]);
298    }
299
300    #[test]
301    fn control_sequence_delimiters_consumed() {
302        // `d\langle\rangle`: control-word delimiter tokens, non-bracket → no slot,
303        // but both are consumed so the `m` is reached.
304        assert_eq!(kinds("d\\langle\\rangle m"), vec![(true, ArgKind::Brace)]);
305    }
306}