sscanf 0.5.0

A sscanf (inverse of format!()) macro with near unlimited parsing capabilities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
use crate::{FromScanf, advanced::FormatOptions};

use regex_automata::{Span, util::captures::Captures};

#[expect(unused_imports, reason = "for doc links")]
use crate::advanced::{MatchPart, Matcher};

mod alt;
mod context;
mod seq;
mod template;

pub use alt::*;
pub use seq::*;

pub(crate) use context::*;
pub(crate) use template::*;

/// A tree representation of regex capture group matches.
///
/// This type is the parameter to the [`FromScanf::from_match`] method.
///
/// Use [`text()`](Self::text) for the full matched string, and the `as_*` methods to access specific matcher views.
///
/// Convenience methods include [`parse()`](Self::parse) to parse this match tree into a value.
///
/// ## On Optional Capture Groups
///
/// This documentation refers to "optional capture groups" or "capture groups that did not match" (what the regex
/// crate calls "capture groups that did not participate in the match"). These refer to
/// capture groups that are not guaranteed to match text when the regex is applied to a string. This can happen
/// when the capture group is optional in the regex, like `(x)?`, or when it is part of an alternation, like
/// `(x)|y`. In both cases, it is possible for the overall regex to match a string without that capture group
/// actually capturing any text.
///
/// In this crate, these capture groups are referred to as "optional" and are represented by `Option<Match>` in the
/// return type of [`as_opt()`](Self::as_opt).  
/// Note that there is **no** automatic handling of `Option` types in either the `sscanf` macro or the `FromScanf`
/// derive!
///
/// #### Example of using optional capture groups to parse an enum:
/// ```
/// use sscanf::advanced::{Matcher, Match, FormatOptions};
/// # #[derive(Debug, PartialEq, Eq)]
/// enum MyType<'a> {
///     Digits(usize),
///     Letters(&'a str),
/// }
/// impl<'input> sscanf::FromScanf<'input> for MyType<'input> {
///     // matches either digits or letters, but not both
///     fn get_matcher(_: &FormatOptions) -> Matcher {
///         Matcher::Alt(vec![
///             Matcher::from_regex(r"\d+").unwrap(),
///             Matcher::from_regex(r"[a-zA-Z]+").unwrap(),
///         ])
///     }
///
///     fn from_match(matches: Match<'_, 'input>, _: &FormatOptions) -> Option<Self> {
///         let matches = matches.as_alt();
///         let text = matches.get().text();
///         if matches.matched_index() == 0 {
///             // The first alternative matched (\d+)
///             Some(Self::Digits(text.parse().ok()?))
///         } else {
///             // exactly one of the capture groups will match
///             assert_eq!(matches.matched_index(), 1);
///             // The second alternative matched ([a-zA-Z]+)
///             Some(Self::Letters(text))
///         }
///     }
/// }
///
/// let digits = sscanf::sscanf!("123", "{MyType}").unwrap();
/// assert_eq!(digits, MyType::Digits(123));
///
/// let letters = sscanf::sscanf!("abc", "{MyType}").unwrap();
/// assert_eq!(letters, MyType::Letters("abc"));
/// ```
///
/// Side note: The derive macro uses this mechanism for enums. If it doesn't work for your enum, implement this trait
/// explicitly using regex alternations for variants, each wrapped in a capture group to check which variant matched:
/// `(...)|(...)|(...)`.
///
/// Because of this, there are utility methods on [`Matcher`](crate::advanced::Matcher) for combining matchers:
/// ```
/// # use sscanf::advanced::Matcher;
/// # fn get_matcher() -> Matcher {
/// Matcher::Alt(vec![
///     Matcher::from_regex(r"\d+").unwrap(),
///     Matcher::from_regex(r"[a-zA-Z]+").unwrap(),
/// ])
/// # }
/// ```
///
/// ## Lifetime Parameters
/// The first lifetime parameter (`'t`) is the lifetime of the match tree itself. Match trees are only valid within
/// [`FromScanf::from_match`] and can't be stored. This can usually be set to `'_`.
///
/// The second lifetime parameter (`'input`) is the lifetime of the input string that was parsed to create this match
/// tree.  
/// If your type borrows parts of the input string, like `&str` does, you need to match the lifetime parameter on
/// your type to the `'input` parameter.
#[derive(Clone, Copy)]
pub struct Match<'t, 'input> {
    template: &'t MatchTreeTemplate,
    captures: &'t Captures,
    input: &'input str,
    full_text: &'input str,
    context: ContextChain<'t>,
}

impl<'t, 'input> Match<'t, 'input> {
    /// Internal constructor. `Match` can only be received as a parameter to `FromScanf::from_match` and from
    /// the methods on an existing `Match`.
    pub(crate) fn new(
        template: &'t MatchTreeTemplate,
        captures: &'t Captures,
        input: &'input str,
        current: Span,
        context: ContextChain<'t>,
    ) -> Self {
        Self {
            template,
            captures,
            input,
            full_text: &input[current],
            context,
        }
    }

    /// Returns the entire matched text for this match tree.
    pub fn text(&self) -> &'input str {
        self.full_text
    }

    /// Convenience method to call [`FromScanf::from_match`] with this match tree.
    ///
    /// The type `T` must implement the [`FromScanf`] trait, and this object must have been created from a match to
    /// [`T::get_matcher()`](FromScanf::get_matcher).
    pub fn parse<T: FromScanf<'input>>(&self, options: &FormatOptions) -> Option<T> {
        let context = self.context.and(Context::Parse(std::any::type_name::<T>()));
        T::from_match(Match { context, ..*self }, options)
    }

    /// Returns the match as a Vec of regex captures.
    ///
    /// Each entry in the Vec corresponds to a capture group in the regex. Note that they are each wrapped in an
    /// `Option`, because capture groups in optional sections and alternations might not have matched.
    ///
    /// ## Panics
    /// Panics if this `Match` was not created from a [`Matcher::Regex`].
    pub fn as_regex_matches(&'t self) -> Vec<Option<&'input str>> {
        let MatchTreeKind::Regex(range) = &self.template.kind else {
            panic!(
                "sscanf: Match::as_regex_matches called on a {}.\nContext: {}",
                self.template.kind_name(),
                self.context
            )
        };
        range
            .clone()
            .map(|i| self.captures.get_group(i).map(|span| &self.input[span]))
            .collect()
    }

    /// Returns the match as a [`SeqMatch`].
    ///
    /// ## Panics
    /// Panics if this `Match` was not created from a [`Matcher::Seq`].
    pub fn as_seq(&'t self) -> SeqMatch<'t, 'input> {
        let MatchTreeKind::Seq(children) = &self.template.kind else {
            panic!(
                "sscanf: Match::as_seq called on a {}.\nContext: {}",
                self.template.kind_name(),
                self.context,
            )
        };
        SeqMatch {
            children,
            captures: self.captures,
            input: self.input,
            full_text: self.full_text,
            context: self.context.and(Context::AsSeq),
        }
    }

    /// Returns the match as an [`AltMatch`].
    ///
    /// ## Panics
    /// Panics if this `Match` was not created from a [`Matcher::Alt`].
    pub fn as_alt(&'t self) -> AltMatch<'t, 'input> {
        let MatchTreeKind::Alt(children) = &self.template.kind else {
            panic!(
                "sscanf: Match::as_alt called on a {}.\nContext: {}",
                self.template.kind_name(),
                self.context,
            )
        };
        let Some((matched_index, child, span)) = children
            .iter()
            .enumerate()
            .find_map(|(i, child)| Some((i, child, self.captures.get_group(child.index)?)))
        else {
            panic!(
                "sscanf: AltMatch has no matching alternative!\nContext: {}",
                self.context,
            );
        };

        let child = Match::new(
            child,
            self.captures,
            self.input,
            span,
            self.context.and(Context::AsAlt(matched_index)),
        );
        AltMatch {
            matched_index,
            child,
            full_text: self.full_text,
        }
    }

    /// Returns the match as an [`AltMatch`], with enum variants as context.
    ///
    /// ## Panics
    /// Panics if this `Match` was not created from a [`Matcher::Alt`].
    pub fn as_alt_enum(&'t self, variants: &[&'static str]) -> AltMatch<'t, 'input> {
        let MatchTreeKind::Alt(children) = &self.template.kind else {
            panic!(
                "sscanf: Match::as_alt_enum called on a {}.\nContext: {}",
                self.template.kind_name(),
                self.context,
            )
        };

        assert_eq!(
            children.len(),
            variants.len(),
            "sscanf: Mismatch between number of alternatives and number of variant names provided to Match::as_alt_enum.\nContext: {}",
            self.context,
        );

        let Some((matched_index, child, span)) = children
            .iter()
            .enumerate()
            .find_map(|(i, child)| Some((i, child, self.captures.get_group(child.index)?)))
        else {
            panic!(
                "sscanf: AltMatch has no matching alternative!\nContext: {}",
                self.context,
            );
        };

        let child = Match::new(
            child,
            self.captures,
            self.input,
            span,
            self.context
                .and(Context::AsAltEnum(variants[matched_index])),
        );
        AltMatch {
            matched_index,
            child,
            full_text: self.full_text,
        }
    }

    /// Returns the match as an optional [`Match`]
    ///
    /// ## Panics
    /// Panics if this `Match` was not created from a [`Matcher::Optional`].
    pub fn as_opt(&'t self) -> Option<Match<'t, 'input>> {
        let MatchTreeKind::Optional(child) = &self.template.kind else {
            panic!(
                "sscanf: Match::as_opt called on a {}.\nContext: {}",
                self.template.kind_name(),
                self.context,
            )
        };
        let span = self.captures.get_group(child.index)?;
        Some(Match::new(
            child,
            self.captures,
            self.input,
            span,
            self.context.and(Context::AsOpt),
        ))
    }
}

impl std::fmt::Debug for Match<'_, '_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.template.kind {
            MatchTreeKind::Regex(_) => {
                let captures = self.as_regex_matches();
                f.debug_struct("RegexMatch")
                    .field("full_text", &self.text())
                    .field("captures", &captures)
                    .finish()
            }
            MatchTreeKind::Seq(_) => self.as_seq().fmt(f),
            MatchTreeKind::Alt(_) => self.as_alt().fmt(f),
            MatchTreeKind::Optional(_) => {
                let opt = self.as_opt();
                f.debug_struct("OptionalMatch")
                    .field("full_text", &self.text())
                    .field("child", &opt)
                    .finish()
            }
        }
    }
}

impl std::fmt::Display for Match<'_, '_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.text().fmt(f)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::assert_panic_message_eq;

    #[test]
    fn has_correct_panics() {
        let parsed = regex_automata::meta::Regex::new("(a)(b)(c)(d)").unwrap();
        let captures = parsed.create_captures();

        let input = "abcd";

        let current = Span { start: 0, end: 4 };

        let context: ContextChain = Context::Root.into();

        let template_seq = MatchTreeTemplate {
            index: 0,
            kind: MatchTreeKind::Seq(vec![]),
        };
        let template_regex = MatchTreeTemplate {
            index: 0,
            kind: MatchTreeKind::Regex(1..2),
        };
        let template_alt = MatchTreeTemplate {
            index: 0,
            kind: MatchTreeKind::Alt(vec![]),
        };
        let template_opt = MatchTreeTemplate {
            index: 0,
            kind: MatchTreeKind::Optional(Box::new(MatchTreeTemplate {
                index: 1,
                kind: MatchTreeKind::Regex(2..3),
            })),
        };

        let match_tree_seq = Match::new(&template_seq, &captures, input, current, context);
        assert_panic_message_eq!(
            match_tree_seq.as_regex_matches(),
            r#"sscanf: Match::as_regex_matches called on a Sequence Match.
Context: sscanf"#
        );

        let context = context.and(Context::AsSeq);
        let match_tree_regex = Match::new(&template_regex, &captures, input, current, context);
        assert_panic_message_eq!(
            match_tree_regex.as_seq(),
            r#"sscanf: Match::as_seq called on a Regex Match.
Context: sscanf -> as_seq()"#
        );

        let context = context.and(Context::AsAltEnum("hi"));
        let match_tree_alt = Match::new(&template_alt, &captures, input, current, context);
        assert_panic_message_eq!(
            match_tree_alt.as_opt(),
            r#"sscanf: Match::as_opt called on a Alt Match.
Context: sscanf -> as_seq() -> as_alt(hi matched)"#
        );

        let context = context.and(Context::Parse("MyType"));
        let match_tree_opt = Match::new(&template_opt, &captures, input, current, context);
        assert_panic_message_eq!(
            match_tree_opt.as_alt(),
            r#"sscanf: Match::as_alt called on a Optional Match.
Context: sscanf -> as_seq() -> as_alt(hi matched) -> parse as MyType"#
        );
    }

    #[test]
    fn test_match_tree_debug() {
        let parsed =
            regex_automata::meta::Regex::new("([a-b]{2})((cd)|(ef))gh((i)?)((j)?)").unwrap();
        let mut captures = parsed.create_captures();

        let input = "abcdghj";

        parsed.captures(input, &mut captures);

        let current = Span {
            start: 0,
            end: input.len(),
        };

        let context: ContextChain = Context::Root.into();

        let template_regex = MatchTreeTemplate {
            index: 0,
            kind: MatchTreeKind::Seq(vec![
                Some(MatchTreeTemplate {
                    index: 1,
                    kind: MatchTreeKind::Regex(1..2),
                }),
                Some(MatchTreeTemplate {
                    index: 2,
                    kind: MatchTreeKind::Alt(vec![
                        MatchTreeTemplate {
                            index: 3,
                            kind: MatchTreeKind::Regex(3..4),
                        },
                        MatchTreeTemplate {
                            index: 4,
                            kind: MatchTreeKind::Regex(5..6),
                        },
                    ]),
                }),
                Some(MatchTreeTemplate {
                    index: 5,
                    kind: MatchTreeKind::Optional(Box::new(MatchTreeTemplate {
                        index: 6,
                        kind: MatchTreeKind::Regex(7..7),
                    })),
                }),
                Some(MatchTreeTemplate {
                    index: 7,
                    kind: MatchTreeKind::Optional(Box::new(MatchTreeTemplate {
                        index: 8,
                        kind: MatchTreeKind::Regex(9..9),
                    })),
                }),
            ]),
        };

        let match_tree_regex = Match::new(&template_regex, &captures, input, current, context);
        assert_eq!(
            format!("{:#?}", match_tree_regex),
            r#"Match::Seq {
    full_text: "abcdghj",
    children: [
        Some(
            RegexMatch {
                full_text: "ab",
                captures: [
                    Some(
                        "ab",
                    ),
                ],
            },
        ),
        Some(
            AltMatch {
                full_text: "cd",
                matched_index: 0,
                child: RegexMatch {
                    full_text: "cd",
                    captures: [
                        Some(
                            "cd",
                        ),
                    ],
                },
            },
        ),
        Some(
            OptionalMatch {
                full_text: "",
                child: None,
            },
        ),
        Some(
            OptionalMatch {
                full_text: "j",
                child: Some(
                    RegexMatch {
                        full_text: "j",
                        captures: [],
                    },
                ),
            },
        ),
    ],
    ..
}"#
        );
    }
}