Skip to main content

passgen/
parser.rs

1//! Parser for Passgen patterns.
2//!
3//! This is a hand-written recursive-descent parser, which accepts the same patterns as the C
4//! implementation of Passgen. Parsing happens in two layers: a lexer turns the input into tokens
5//! (resolving escape sequences such as `\n` or `\u{fc}`), and the parser turns the tokens into a
6//! [Pattern](crate::pattern::Pattern).
7//!
8//! ## Grammar
9//!
10//! ```text
11//! pattern  = segments
12//! segments = segment ( "|" segment )*
13//! segment  = weight* ( item modifier* )*
14//! weight   = "{" number "}"
15//! item     = group | set | special | literal
16//! modifier = "?" | "{" number "}" | "{" number? "," number? "}"
17//! group    = "(" segments ")"
18//! set      = "[" ( char ( "-" char )? )+ "]"
19//! special  = ( "\w" | "\p" ) "{" name "}" | "\m" "{" name ( ":" number )? "}"
20//! ```
21//!
22//! Characters with a meaning can be escaped with a backslash to get the character itself.
23//! In the name of a special, this goes for the colon and the closing brace.
24//!
25//! A segment with a weight of zero is never chosen, and is not part of the parsed pattern.
26//! A group in which this goes for all segments is an error.
27
28use super::pattern::*;
29use crate::markov::DEPTH_MAX;
30use std::ops::Range;
31
32type Pattern = crate::pattern::Pattern<Parsed>;
33type Group = crate::pattern::Group<Parsed>;
34type Segment = crate::pattern::Segment<Parsed>;
35type Item = crate::pattern::Item<Parsed>;
36
37/// How deeply groups can be nested in a pattern.
38///
39/// The parser (as well as everything that works with the parsed pattern) is recursive, so this
40/// keeps a pattern like `((((…` from overflowing the stack.
41pub const DEPTH_LIMIT: usize = 256;
42
43/// What is wrong with a pattern.
44#[derive(thiserror::Error, Debug, Clone, Copy, PartialEq, Eq)]
45#[non_exhaustive]
46pub enum ErrorKind {
47    /// A backslash before a character that it has no meaning with, as in `\q`.
48    #[error("unknown escape sequence")]
49    Escape,
50    /// A backslash at the end of the pattern.
51    #[error("unfinished escape sequence")]
52    EscapeUnfinished,
53    /// A unicode escape that is not `\u{…}` with one to six hex digits.
54    #[error("malformed unicode escape")]
55    UnicodeEscape,
56    /// A unicode escape with a number that is not a character.
57    #[error("unicode escape is not a valid codepoint")]
58    UnicodeRange,
59    /// A `)` that does not close a group.
60    #[error("closing parenthesis without an opening one")]
61    GroupUnopened,
62    /// A `(` without a `)` for it.
63    #[error("group is not closed")]
64    GroupUnclosed,
65    /// All segments of a group have a weight of zero.
66    #[error("nothing to choose from")]
67    GroupNothing,
68    /// A `[` without a `]` for it.
69    #[error("set is not closed")]
70    SetUnclosed,
71    /// A set without characters, as in `[]`.
72    #[error("set is empty")]
73    SetEmpty,
74    /// A range in a set that is not from a character to one that is not before it.
75    #[error("invalid range in set")]
76    SetRange,
77    /// Braces that are not a number or a range of numbers, a range that is the wrong way
78    /// around, or weights of segments that are too large.
79    #[error("invalid repetition")]
80    Repeat,
81    /// A `?` without something before it.
82    #[error("nothing to make optional")]
83    Optional,
84    /// No name in braces after `\w`, `\m` or `\p`.
85    #[error("expected a name in braces")]
86    Special,
87    /// Something after a colon in the braces, for something that does not take it.
88    #[error("only a Markov chain takes a parameter")]
89    SpecialParameter,
90    /// The length in `\m{name:length}` is not a number that is allowed.
91    #[error(
92        "length of a Markov chain must be a number from 0 to {}",
93        crate::markov::DEPTH_MAX
94    )]
95    MarkovLength,
96    /// Groups are nested more deeply than [DEPTH_LIMIT].
97    #[error("nested too deeply")]
98    DepthLimit,
99}
100
101/// Error parsing a pattern.
102#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
103#[error("{kind}")]
104pub struct Error {
105    /// What is wrong.
106    pub kind: ErrorKind,
107    /// Where in the pattern it is wrong, as a range of bytes.
108    pub span: Range<usize>,
109}
110
111impl Error {
112    fn new(kind: ErrorKind, span: Range<usize>) -> Self {
113        Self { kind, span }
114    }
115}
116
117type Result<T, E = Error> = std::result::Result<T, E>;
118
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
120enum Token {
121    /// Character that is not escaped. Has a meaning if it is part of the syntax.
122    Char(char),
123    /// Character escaped with a backslash, as in `\(` or `\w`. Depending on where it is, it
124    /// stands for the character itself, starts a special, or is not valid.
125    Escaped(char),
126    /// Result of an escape sequence, as in `\n` or `\u{fc}`. Always stands for itself.
127    Literal(char),
128}
129
130/// Turns a pattern into tokens.
131struct Lexer<'a> {
132    input: &'a str,
133    position: usize,
134}
135
136impl Lexer<'_> {
137    /// Returns the next character.
138    fn bump(&mut self) -> Option<char> {
139        let c = self.input[self.position..].chars().next()?;
140        self.position += c.len_utf8();
141        Some(c)
142    }
143
144    /// Returns the next token, along with where it is in the input.
145    fn token(&mut self) -> Result<Option<(Token, Range<usize>)>> {
146        let start = self.position;
147        let token = match self.bump() {
148            None => return Ok(None),
149            Some('\\') => self.escape(start)?,
150            Some(c) => Token::Char(c),
151        };
152        Ok(Some((token, start..self.position)))
153    }
154
155    /// Parses what follows a backslash.
156    fn escape(&mut self, start: usize) -> Result<Token> {
157        let token = match self.bump() {
158            None => {
159                return Err(Error::new(
160                    ErrorKind::EscapeUnfinished,
161                    start..self.position,
162                ));
163            }
164            Some('a') => Token::Literal('\x07'),
165            Some('b') => Token::Literal('\x08'),
166            Some('e') => Token::Literal('\x1b'),
167            Some('f') => Token::Literal('\x0c'),
168            Some('n') => Token::Literal('\n'),
169            Some('r') => Token::Literal('\r'),
170            Some('t') => Token::Literal('\t'),
171            Some('v') => Token::Literal('\x0b'),
172            Some('\\') => Token::Literal('\\'),
173            Some('u') => Token::Literal(self.unicode(start)?),
174            Some(c) => Token::Escaped(c),
175        };
176        Ok(token)
177    }
178
179    /// Parses the payload of a unicode escape: one to six hexadecimal digits in braces.
180    fn unicode(&mut self, start: usize) -> Result<char> {
181        let error = |lexer: &Self, kind| Err(Error::new(kind, start..lexer.position));
182
183        match self.bump() {
184            None => return error(self, ErrorKind::EscapeUnfinished),
185            Some('{') => {}
186            Some(_) => return error(self, ErrorKind::UnicodeEscape),
187        }
188
189        let mut codepoint = 0;
190        let mut digits = 0;
191        loop {
192            let digit = match self.bump() {
193                None => return error(self, ErrorKind::EscapeUnfinished),
194                Some('}') if digits > 0 => break,
195                Some(c) => c.to_digit(16),
196            };
197            match digit {
198                Some(digit) if digits < 6 => codepoint = codepoint * 16 + digit,
199                _ => return error(self, ErrorKind::UnicodeEscape),
200            }
201            digits += 1;
202        }
203
204        match char::from_u32(codepoint) {
205            Some(c) => Ok(c),
206            None => error(self, ErrorKind::UnicodeRange),
207        }
208    }
209}
210
211struct Parser<'a> {
212    lexer: Lexer<'a>,
213    /// Token that was looked at, but not consumed yet.
214    peeked: Option<Option<(Token, Range<usize>)>>,
215    /// How many groups we are in right now.
216    depth: usize,
217}
218
219impl<'a> Parser<'a> {
220    fn new(input: &'a str) -> Self {
221        Self {
222            lexer: Lexer { input, position: 0 },
223            peeked: None,
224            depth: 0,
225        }
226    }
227
228    /// Returns the next token, and consumes it.
229    fn next(&mut self) -> Result<Option<(Token, Range<usize>)>> {
230        match self.peeked.take() {
231            Some(token) => Ok(token),
232            None => self.lexer.token(),
233        }
234    }
235
236    /// Returns the next token, without consuming it.
237    fn peek(&mut self) -> Result<Option<(Token, Range<usize>)>> {
238        if self.peeked.is_none() {
239            self.peeked = Some(self.lexer.token()?);
240        }
241        Ok(self.peeked.clone().flatten())
242    }
243
244    /// Returns the next token, or the given error at the given position when there is none.
245    fn expect(&mut self, kind: ErrorKind, start: usize) -> Result<(Token, Range<usize>)> {
246        let end = self.lexer.input.len();
247        self.next()?.ok_or(Error::new(kind, start..end))
248    }
249
250    /// Parses segments separated by `|`, up to the end of the group. Gets the position of the
251    /// opening parenthesis, or `None` for the pattern itself (which ends with the input).
252    fn group(&mut self, open: Option<Range<usize>>) -> Result<Group> {
253        let mut group = Group::default();
254        let mut weights = 0;
255        let group_start = open.as_ref().map_or(0, |open| open.start);
256
257        loop {
258            let start = self.lexer.position;
259            let segment = self.segment(weights)?;
260
261            // the sum of the weights must not overflow.
262            weights = match weights.checked_add(segment.weight) {
263                Some(weights) => weights,
264                None => {
265                    let end = self
266                        .peek()?
267                        .map_or(self.lexer.position, |(_, span)| span.start);
268                    return Err(Error::new(ErrorKind::Repeat, start..end));
269                }
270            };
271
272            // a segment with a weight of zero is never chosen, so it is not an option. it is
273            // left out, so that a group with one other segment has nothing to choose (which
274            // uses no randomness).
275            if segment.weight > 0 {
276                group.segments.push(segment);
277            }
278
279            match (self.next()?, &open) {
280                (Some((Token::Char('|'), _)), _) => {}
281                (Some((Token::Char(')'), _)), Some(_)) => break,
282                (None, None) => break,
283                (Some((_, span)), _) => return Err(Error::new(ErrorKind::GroupUnopened, span)),
284                (None, Some(open)) => {
285                    return Err(Error::new(ErrorKind::GroupUnclosed, open.clone()));
286                }
287            }
288        }
289
290        // with only weights of zero, no segment can be chosen.
291        if weights == 0 {
292            let span = group_start..self.lexer.position;
293            return Err(Error::new(ErrorKind::GroupNothing, span));
294        }
295
296        Ok(group)
297    }
298
299    /// Parses items up to (and not including) the next `|` or `)`. Gets the sum of the weights
300    /// of the previous segments in this group.
301    fn segment(&mut self, weights: usize) -> Result<Segment> {
302        let mut segment = Segment::default();
303
304        while let Some((token, span)) = self.peek()? {
305            if matches!(token, Token::Char('|' | ')')) {
306                break;
307            }
308            self.next()?;
309
310            let pattern: Pattern = match token {
311                Token::Char('(') => self.nested(span)?.into(),
312                Token::Char('[') => self.set(span)?.into(),
313                Token::Char('{') => {
314                    // braces repeat the item before them. without one, they are the weight
315                    // of the segment.
316                    match segment.items.last_mut() {
317                        Some(item) => item.repeat = self.repeat(span)?,
318                        None => segment.weight = self.weight(span, weights)?,
319                    }
320                    continue;
321                }
322                Token::Char('?') => {
323                    match segment.items.last_mut() {
324                        Some(item) => item.optional = true,
325                        None => return Err(Error::new(ErrorKind::Optional, span)),
326                    }
327                    continue;
328                }
329                Token::Escaped('w') => Special::Wordlist(self.name(span)?).into(),
330                Token::Escaped('m') => Special::Markov(self.markov(span)?).into(),
331                Token::Escaped('p') => Special::Preset(self.name(span)?).into(),
332                Token::Escaped(c @ ('|' | '(' | ')' | '{' | '}' | '[' | ']' | '?')) => {
333                    Literal::new(c).into()
334                }
335                Token::Escaped(_) => return Err(Error::new(ErrorKind::Escape, span)),
336                Token::Char(c) | Token::Literal(c) => Literal::new(c).into(),
337            };
338
339            segment.items.push(Item::new(pattern));
340        }
341
342        Ok(segment)
343    }
344
345    /// Parses a group, after the opening parenthesis.
346    fn nested(&mut self, open: Range<usize>) -> Result<Group> {
347        if self.depth >= DEPTH_LIMIT {
348            return Err(Error::new(ErrorKind::DepthLimit, open));
349        }
350
351        self.depth += 1;
352        let group = self.group(Some(open))?;
353        self.depth -= 1;
354
355        Ok(group)
356    }
357
358    /// Parses a decimal number, if there is one.
359    fn number(&mut self) -> Result<Option<usize>> {
360        let mut number = None;
361        while let Some((Token::Char(c), span)) = self.peek()? {
362            let Some(digit) = c.to_digit(10) else { break };
363            self.next()?;
364            number = number
365                .unwrap_or(0usize)
366                .checked_mul(10)
367                .and_then(|number| number.checked_add(digit as usize));
368            if number.is_none() {
369                return Err(Error::new(ErrorKind::Repeat, span));
370            }
371        }
372        Ok(number)
373    }
374
375    /// Parses a repetition, after the opening brace: `{n}`, `{min,max}` or `{,max}`.
376    fn repeat(&mut self, open: Range<usize>) -> Result<std::ops::RangeInclusive<usize>> {
377        let min = self.number()?;
378
379        let (token, span) = self.expect(ErrorKind::Repeat, open.start)?;
380        let (range, close) = match (token, min) {
381            (Token::Char('}'), Some(min)) => return Ok(min..=min),
382            (Token::Char(','), _) => {
383                let max = self.number()?;
384                let (token, close) = self.expect(ErrorKind::Repeat, open.start)?;
385                if token != Token::Char('}') {
386                    return Err(Error::new(ErrorKind::Repeat, close));
387                }
388                // either number can be left out, but not both. a missing number is zero.
389                let range =
390                    (min.is_some() || max.is_some()).then(|| min.unwrap_or(0)..=max.unwrap_or(0));
391                (range, close)
392            }
393            (Token::Char('}'), None) => (None, span),
394            _ => return Err(Error::new(ErrorKind::Repeat, span)),
395        };
396
397        match range {
398            Some(range) if range.start() <= range.end() => Ok(range),
399            _ => Err(Error::new(ErrorKind::Repeat, open.start..close.end)),
400        }
401    }
402
403    /// Parses the weight of a segment, after the opening brace: `{n}`. Gets the sum of the
404    /// weights of the previous segments in the group, which must not overflow.
405    fn weight(&mut self, open: Range<usize>, weights: usize) -> Result<usize> {
406        let weight = self.number()?;
407        let (token, span) = self.expect(ErrorKind::Repeat, open.start)?;
408        if token != Token::Char('}') {
409            return Err(Error::new(ErrorKind::Repeat, span));
410        }
411
412        match weight {
413            Some(weight) if weights.checked_add(weight).is_some() => Ok(weight),
414            _ => Err(Error::new(ErrorKind::Repeat, open.start..span.end)),
415        }
416    }
417
418    /// Parses a set, after the opening bracket.
419    fn set(&mut self, open: Range<usize>) -> Result<Set> {
420        let mut set = Set::default();
421        let mut empty = true;
422        // character which is not in the set yet, because it might be the start of a range.
423        let mut pending: Option<char> = None;
424
425        loop {
426            let (token, span) = self.expect(ErrorKind::SetUnclosed, open.start)?;
427            let range = match token {
428                Token::Char(']') => break,
429                Token::Char('-') => {
430                    // a dash is only ever part of a range (a literal dash has to be escaped),
431                    // so it needs a character before it which is not already the end of one.
432                    let Some(start) = pending.take() else {
433                        return Err(Error::new(ErrorKind::SetRange, span));
434                    };
435                    let (token, end) = self.expect(ErrorKind::SetUnclosed, open.start)?;
436                    let range = span.start..end.end;
437                    if token == Token::Char(']') {
438                        return Err(Error::new(ErrorKind::SetRange, range));
439                    }
440                    let end = set_char(token, end)?;
441                    if end < start {
442                        return Err(Error::new(ErrorKind::SetRange, range));
443                    }
444                    Some(start..=end)
445                }
446                _ => pending.replace(set_char(token, span)?).map(|c| c..=c),
447            };
448
449            if let Some(range) = range {
450                set.insert(range, 1);
451                empty = false;
452            }
453        }
454
455        if let Some(c) = pending {
456            set.insert(c..=c, 1);
457            empty = false;
458        }
459
460        // a set stands for one of its characters, so it needs at least one.
461        if empty {
462            let end = self.lexer.position;
463            return Err(Error::new(ErrorKind::SetEmpty, open.start..end));
464        }
465
466        Ok(set)
467    }
468
469    /// Parses a name in braces, after an escape that takes one. A colon has to be escaped to
470    /// be part of the name.
471    fn name(&mut self, special: Range<usize>) -> Result<String> {
472        match self.name_parameter(special)? {
473            (name, None) => Ok(name),
474            (_, Some((_, span))) => Err(Error::new(ErrorKind::SpecialParameter, span)),
475        }
476    }
477
478    /// Parses the name of a wordlist in braces, which can have the length of the chain after
479    /// a colon, as in `{english:3}`.
480    fn markov(&mut self, special: Range<usize>) -> Result<MarkovRef> {
481        let (name, parameter) = self.name_parameter(special)?;
482        let mut markov = MarkovRef::new(name);
483        if let Some((parameter, span)) = parameter {
484            // only digits, so that there is one way to write a length.
485            let digits = !parameter.is_empty() && parameter.bytes().all(|b| b.is_ascii_digit());
486            markov.depth = match parameter.parse() {
487                Ok(depth) if digits && depth <= DEPTH_MAX => depth,
488                _ => return Err(Error::new(ErrorKind::MarkovLength, span)),
489            };
490        }
491        Ok(markov)
492    }
493
494    /// Parses a name in braces, with what is after a colon in them (and where that is), if
495    /// there is one.
496    fn name_parameter(&mut self, special: Range<usize>) -> Result<(String, Option<Parameter>)> {
497        let (token, span) = self.expect(ErrorKind::Special, special.start)?;
498        if token != Token::Char('{') {
499            return Err(Error::new(ErrorKind::Special, span));
500        }
501
502        let mut name = String::new();
503        let mut parameter: Option<Parameter> = None;
504        loop {
505            let (token, span) = self.expect(ErrorKind::Special, special.start)?;
506            match token {
507                Token::Char('}') if name.is_empty() => {
508                    return Err(Error::new(ErrorKind::Special, special.start..span.end));
509                }
510                Token::Char('}') => break,
511                Token::Char(':') if parameter.is_none() => {
512                    parameter = Some((String::new(), span.end..span.end));
513                }
514                Token::Char(c) | Token::Escaped(c) | Token::Literal(c) => match &mut parameter {
515                    Some((parameter, parameter_span)) => {
516                        parameter.push(c);
517                        parameter_span.end = span.end;
518                    }
519                    None => name.push(c),
520                },
521            }
522        }
523
524        Ok((name, parameter))
525    }
526}
527
528/// What is after a colon in the braces of a special, and where it is in the pattern.
529type Parameter = (String, Range<usize>);
530
531/// Gets the character that a token stands for inside of a set. The characters which have a
532/// meaning in a set can be escaped to get the character itself, and the opening bracket can be
533/// for symmetry.
534fn set_char(token: Token, span: Range<usize>) -> Result<char> {
535    match token {
536        Token::Char(c) | Token::Literal(c) | Token::Escaped(c @ ('-' | ']' | '[')) => Ok(c),
537        Token::Escaped(_) => Err(Error::new(ErrorKind::Escape, span)),
538    }
539}
540
541impl Pattern {
542    /// Parses a pattern.
543    pub fn parse(input: &str) -> Result<Self> {
544        Ok(Self::Group(Parser::new(input).group(None)?))
545    }
546}
547
548#[cfg(test)]
549mod tests {
550    use super::*;
551    use test_strategy::*;
552
553    macro_rules! group {
554        ($($segments:tt)*) => {
555            Pattern::Group(Group {
556                segments: vec![$($segments)*],
557            })
558        };
559    }
560
561    macro_rules! segment {
562        ($($items:tt)*) => {
563            Segment {
564                items: vec![$($items)*],
565                weight: 1,
566            }
567        };
568    }
569
570    macro_rules! set {
571        ($($range:expr),*) => {
572            {
573                let mut set = Set::default();
574                $(set.insert($range, 1);)*
575                set
576            }
577        };
578    }
579
580    #[test]
581    fn parse_literal() {
582        assert_eq!(
583            Pattern::parse("a").unwrap(),
584            group![segment![Item::new(Literal::new('a'))]]
585        );
586    }
587
588    #[test]
589    fn parse_literal_optional() {
590        assert_eq!(
591            Pattern::parse("a?").unwrap(),
592            group![segment![Item::new(Literal::new('a')).optional(true)]]
593        );
594    }
595
596    #[test]
597    fn parse_literal_repeat() {
598        assert_eq!(
599            Pattern::parse("a{1,3}").unwrap(),
600            group![segment![Item::new(Literal::new('a')).repeat(1..=3)]]
601        );
602    }
603
604    #[test]
605    fn parse_group() {
606        assert_eq!(
607            Pattern::parse("()").unwrap(),
608            group![segment![Item::new(group![segment![]])]],
609        );
610    }
611
612    #[test]
613    fn parse_group_segments() {
614        assert_eq!(
615            Pattern::parse("(a|b|c)").unwrap(),
616            group![segment![Item::new(group![
617                segment![Item::new(Literal::new('a'))],
618                segment![Item::new(Literal::new('b'))],
619                segment![Item::new(Literal::new('c'))],
620            ])]],
621        );
622    }
623
624    #[test]
625    fn parse_group_optional() {
626        assert_eq!(
627            Pattern::parse("()?").unwrap(),
628            group![segment![Item::new(group![segment![]]).optional(true)]],
629        );
630    }
631
632    #[test]
633    fn parse_group_repeat() {
634        assert_eq!(
635            Pattern::parse("(){1,3}").unwrap(),
636            group![segment![Item::new(group![segment![]]).repeat(1..=3)]],
637        );
638    }
639
640    #[test]
641    fn parse_set() {
642        assert_eq!(
643            Pattern::parse("[abc]").unwrap(),
644            group![segment![Item::new(set!['a'..='c'])]],
645        );
646    }
647
648    #[test]
649    fn parse_set_optional() {
650        assert_eq!(
651            Pattern::parse("[abc]?").unwrap(),
652            group![segment![Item::new(set!['a'..='c']).optional(true)]],
653        );
654    }
655
656    #[test]
657    fn parse_set_repeat() {
658        assert_eq!(
659            Pattern::parse("[abc]{1,3}").unwrap(),
660            group![segment![Item::new(set!['a'..='c']).repeat(1..=3)]],
661        );
662    }
663
664    #[proptest]
665    fn parse_repeat_exact(amount: usize) {
666        assert_eq!(
667            Pattern::parse(&format!("x{{{amount}}}")).unwrap(),
668            group![segment![
669                Item::new(Literal::new('x')).repeat(amount..=amount)
670            ]],
671        );
672    }
673
674    #[proptest]
675    fn parse_repeat_minmax(min: usize, max: usize) {
676        let result = Pattern::parse(&format!("x{{{min},{max}}}"));
677        if min <= max {
678            assert_eq!(
679                result.unwrap(),
680                group![segment![Item::new(Literal::new('x')).repeat(min..=max)]],
681            );
682        } else {
683            assert_eq!(result.unwrap_err().kind, ErrorKind::Repeat);
684        }
685    }
686
687    #[proptest]
688    fn parse_optional(optional: bool) {
689        let optional_str = match optional {
690            true => "?",
691            false => "",
692        };
693        assert_eq!(
694            Pattern::parse(&format!("x{optional_str}")).unwrap(),
695            group![segment![Item::new(Literal::new('x')).optional(optional)]],
696        );
697    }
698
699    #[proptest]
700    fn parse_arbitrary(input: String) {
701        let result = Pattern::parse(&input);
702        let _ = std::hint::black_box(result);
703    }
704
705    /// Arbitrary strings rarely look like patterns, so this one is made out of syntax.
706    #[proptest]
707    fn parse_arbitrary_syntax(#[strategy(r"([(){}\[\]|?,\\-]|[a-c0-9umpw]){0,32}")] input: String) {
708        if let Err(error) = Pattern::parse(&input) {
709            // errors point at something in the input.
710            assert!(error.span.start <= error.span.end);
711            assert!(input.get(error.span.clone()).is_some());
712        }
713    }
714
715    /// Parses a pattern consisting of literals into the string that it stands for.
716    fn literals(input: &str) -> String {
717        let Pattern::Group(group) = Pattern::parse(input).unwrap() else {
718            unreachable!()
719        };
720        assert_eq!(group.segments.len(), 1);
721        group.segments[0]
722            .items
723            .iter()
724            .map(|item| match &item.pattern {
725                Pattern::Literal(literal) => literal.value,
726                other => panic!("not a literal: {other:?}"),
727            })
728            .collect()
729    }
730
731    fn error(input: &str) -> (ErrorKind, Range<usize>) {
732        let error = Pattern::parse(input).unwrap_err();
733        (error.kind, error.span)
734    }
735
736    #[test]
737    fn parse_escapes() {
738        assert_eq!(
739            literals(r"\a\b\e\f\n\r\t\v\\"),
740            "\x07\x08\x1b\x0c\n\r\t\x0b\\"
741        );
742        assert_eq!(literals(r"\|\(\)\{\}\[\]\?"), "|(){}[]?");
743        assert_eq!(literals(r"a\|b"), "a|b");
744        // closing characters without an opening one, and characters which only have a meaning
745        // elsewhere, are literals.
746        assert_eq!(literals("a}]-,"), "a}]-,");
747    }
748
749    #[test]
750    fn parse_escapes_unknown() {
751        assert_eq!(error(r"ab\x"), (ErrorKind::Escape, 2..4));
752        assert_eq!(error(r"\-"), (ErrorKind::Escape, 0..2));
753        assert_eq!(error(r"[\a\x]"), (ErrorKind::Escape, 3..5));
754        assert_eq!(error(r"[a-\x]"), (ErrorKind::Escape, 3..5));
755        assert_eq!(error(r"ab\"), (ErrorKind::EscapeUnfinished, 2..3));
756    }
757
758    #[test]
759    fn parse_unicode_escapes() {
760        assert_eq!(literals(r"\u{41}"), "A");
761        assert_eq!(literals(r"\u{fc}\u{DC}"), "üÜ");
762        assert_eq!(literals(r"\u{00000a}\u{10ffff}"), "\n\u{10ffff}");
763        // unicode escapes are never syntax.
764        assert_eq!(literals(r"\u{28}a\u{7c}b\u{29}\u{3f}"), "(a|b)?");
765    }
766
767    #[test]
768    fn parse_unicode_escapes_invalid() {
769        assert_eq!(error(r"a\u41"), (ErrorKind::UnicodeEscape, 1..4));
770        assert_eq!(error(r"\u{}"), (ErrorKind::UnicodeEscape, 0..4));
771        assert_eq!(error(r"\u{4g}"), (ErrorKind::UnicodeEscape, 0..5));
772        assert_eq!(error(r"\u{0000041}"), (ErrorKind::UnicodeEscape, 0..10));
773        assert_eq!(error(r"\u{110000}"), (ErrorKind::UnicodeRange, 0..10));
774        assert_eq!(error(r"\u{d800}"), (ErrorKind::UnicodeRange, 0..8));
775        assert_eq!(error(r"\u"), (ErrorKind::EscapeUnfinished, 0..2));
776        assert_eq!(error(r"\u{41"), (ErrorKind::EscapeUnfinished, 0..5));
777    }
778
779    #[test]
780    fn parse_modifiers() {
781        // modifiers apply to the single character before them.
782        assert_eq!(
783            Pattern::parse("ab{2}").unwrap(),
784            group![segment![
785                Item::new(Literal::new('a')),
786                Item::new(Literal::new('b')).repeat(2..=2)
787            ]]
788        );
789        assert_eq!(
790            Pattern::parse("a?{3}").unwrap(),
791            group![segment![
792                Item::new(Literal::new('a')).optional(true).repeat(3..=3)
793            ]]
794        );
795        // the last repetition counts.
796        assert_eq!(
797            Pattern::parse("a{2}{3}").unwrap(),
798            group![segment![Item::new(Literal::new('a')).repeat(3..=3)]]
799        );
800        assert_eq!(
801            Pattern::parse("a{,3}").unwrap(),
802            group![segment![Item::new(Literal::new('a')).repeat(0..=3)]]
803        );
804    }
805
806    #[test]
807    fn parse_modifiers_invalid() {
808        assert_eq!(error("a{}"), (ErrorKind::Repeat, 1..3));
809        assert_eq!(error("a{,}"), (ErrorKind::Repeat, 1..4));
810        assert_eq!(error("a{3,}"), (ErrorKind::Repeat, 1..5));
811        assert_eq!(error("a{5,2}"), (ErrorKind::Repeat, 1..6));
812        assert_eq!(error("a{2"), (ErrorKind::Repeat, 1..3));
813        assert_eq!(error("a{2,3"), (ErrorKind::Repeat, 1..5));
814        assert_eq!(error("a{x}"), (ErrorKind::Repeat, 2..3));
815        assert_eq!(error("a{1,2,3}"), (ErrorKind::Repeat, 5..6));
816        assert_eq!(error(r"a{\u{32}}"), (ErrorKind::Repeat, 2..8));
817        assert_eq!(
818            error("a{99999999999999999999}"),
819            (ErrorKind::Repeat, 21..22)
820        );
821        assert_eq!(error("?"), (ErrorKind::Optional, 0..1));
822        assert_eq!(error("(a|?)"), (ErrorKind::Optional, 3..4));
823    }
824
825    #[test]
826    fn parse_weights() {
827        let segment = |c, weight| Segment {
828            items: vec![Item::new(Literal::new(c))],
829            weight,
830        };
831        assert_eq!(
832            Pattern::parse("({3}a|b)").unwrap(),
833            group![segment![Item::new(group![
834                segment('a', 3),
835                segment('b', 1)
836            ])]],
837        );
838        assert_eq!(
839            Pattern::parse("{2}a|{5}b").unwrap(),
840            group![segment('a', 2), segment('b', 5)],
841        );
842        // the last weight counts.
843        assert_eq!(Pattern::parse("{2}{3}a").unwrap(), group![segment('a', 3)]);
844    }
845
846    #[test]
847    fn parse_weights_zero() {
848        let segment = |c, weight| Segment {
849            items: vec![Item::new(Literal::new(c))],
850            weight,
851        };
852
853        // segments with a weight of zero are never chosen, so they are left out.
854        assert_eq!(Pattern::parse("{0}a|b").unwrap(), group![segment('b', 1)]);
855        assert_eq!(Pattern::parse("b|{0}a").unwrap(), group![segment('b', 1)]);
856        assert_eq!(
857            Pattern::parse("b|{0}a|{2}c").unwrap(),
858            group![segment('b', 1), segment('c', 2)],
859        );
860
861        // when no segment can be chosen, there is nothing to generate.
862        assert_eq!(error("{0}a"), (ErrorKind::GroupNothing, 0..4));
863        assert_eq!(error("{0}"), (ErrorKind::GroupNothing, 0..3));
864        assert_eq!(error("{0}a|{0}b"), (ErrorKind::GroupNothing, 0..9));
865        assert_eq!(error("x({0}a){2}"), (ErrorKind::GroupNothing, 1..7));
866        assert_eq!(error("x(a|({0}|{0}b))"), (ErrorKind::GroupNothing, 4..14));
867    }
868
869    #[test]
870    fn parse_weights_invalid() {
871        assert_eq!(error("({}a)"), (ErrorKind::Repeat, 1..3));
872        assert_eq!(error("({1,2}a)"), (ErrorKind::Repeat, 3..4));
873        assert_eq!(error("{2"), (ErrorKind::Repeat, 0..2));
874        assert_eq!(
875            error(&format!("{{{}}}a|{{1}}b", usize::MAX)),
876            (ErrorKind::Repeat, 24..27)
877        );
878        assert_eq!(
879            error(&format!("{{{}}}a|bc|d", usize::MAX)),
880            (ErrorKind::Repeat, 24..26)
881        );
882    }
883
884    #[test]
885    fn parse_groups_invalid() {
886        assert_eq!(error("(abc"), (ErrorKind::GroupUnclosed, 0..1));
887        assert_eq!(error("a(b(c)"), (ErrorKind::GroupUnclosed, 1..2));
888        assert_eq!(error("abc)"), (ErrorKind::GroupUnopened, 3..4));
889        assert_eq!(error("(a))"), (ErrorKind::GroupUnopened, 3..4));
890    }
891
892    #[test]
893    fn parse_groups_depth() {
894        let nested = |depth| format!("{}a{}", "(".repeat(depth), ")".repeat(depth));
895        assert!(Pattern::parse(&nested(DEPTH_LIMIT)).is_ok());
896        assert_eq!(
897            error(&nested(DEPTH_LIMIT + 1)),
898            (ErrorKind::DepthLimit, DEPTH_LIMIT..DEPTH_LIMIT + 1)
899        );
900        // only nesting counts.
901        assert!(Pattern::parse(&"(a)".repeat(DEPTH_LIMIT + 1)).is_ok());
902    }
903
904    #[test]
905    fn parse_sets() {
906        let set = |input: &str| {
907            let Pattern::Group(mut group) = Pattern::parse(input).unwrap() else {
908                unreachable!()
909            };
910            match group.segments.remove(0).items.remove(0).pattern {
911                Pattern::Set(set) => set,
912                other => panic!("not a set: {other:?}"),
913            }
914        };
915        assert_eq!(set("[a-cx]"), set!['a'..='c', 'x'..='x']);
916        assert_eq!(set("[a-a]"), set!['a'..='a']);
917        assert_eq!(set(r"[\]\[\-]"), set![']'..=']', '['..='[', '-'..='-']);
918        assert_eq!(set(r"[a\-z]"), set!['a'..='a', '-'..='-', 'z'..='z']);
919        assert_eq!(set(r"[\n-\u{41}]"), set!['\n'..='A']);
920        assert_eq!(set(r"[+-\-]"), set!['+'..='-']);
921        // nothing but the dash and the closing bracket has a meaning in a set.
922        assert_eq!(
923            set("[([{|?]"),
924            set!['('..='(', '['..='[', '{'..='{', '|'..='|', '?'..='?']
925        );
926    }
927
928    #[test]
929    fn parse_sets_invalid() {
930        assert_eq!(error("[]"), (ErrorKind::SetEmpty, 0..2));
931        assert_eq!(error("a[bc"), (ErrorKind::SetUnclosed, 1..4));
932        assert_eq!(error("[a-"), (ErrorKind::SetUnclosed, 0..3));
933        assert_eq!(error("[a-]"), (ErrorKind::SetRange, 2..4));
934        assert_eq!(error("[-a]"), (ErrorKind::SetRange, 1..2));
935        assert_eq!(error("[z-a]"), (ErrorKind::SetRange, 2..4));
936        assert_eq!(error("[a-c-e]"), (ErrorKind::SetRange, 4..5));
937    }
938
939    #[test]
940    fn parse_specials() {
941        let special = |special: Special| group![segment![Item::new(special)]];
942        assert_eq!(
943            Pattern::parse(r"\w{english}").unwrap(),
944            special(Special::Wordlist("english".into()))
945        );
946        assert_eq!(
947            Pattern::parse(r"\m{english}").unwrap(),
948            special(Special::Markov(MarkovRef::new("english")))
949        );
950        assert_eq!(
951            Pattern::parse(r"\p{apple}").unwrap(),
952            special(Special::Preset("apple".into()))
953        );
954        assert_eq!(
955            Pattern::parse(r"\w{a\}b\\{(}").unwrap(),
956            special(Special::Wordlist(r"a}b\{(".into()))
957        );
958        assert_eq!(
959            Pattern::parse(r"\w{a}{2}?").unwrap(),
960            group![segment![
961                Item::new(Special::Wordlist("a".into()))
962                    .repeat(2..=2)
963                    .optional(true)
964            ]]
965        );
966    }
967
968    #[test]
969    fn parse_specials_invalid() {
970        assert_eq!(error(r"\w"), (ErrorKind::Special, 0..2));
971        assert_eq!(error(r"\wx"), (ErrorKind::Special, 2..3));
972        assert_eq!(error(r"\w{}"), (ErrorKind::Special, 0..4));
973        assert_eq!(error(r"a\m{abc"), (ErrorKind::Special, 1..7));
974    }
975
976    #[test]
977    fn parse_error_span_multibyte() {
978        assert_eq!(error("üü("), (ErrorKind::GroupUnclosed, 4..5));
979        assert_eq!(error(r"ü\ü"), (ErrorKind::Escape, 2..5));
980    }
981
982    #[test]
983    fn parse_markov_length() {
984        let markov = |input: &str| match Pattern::parse(input).unwrap() {
985            Pattern::Group(group) => match &group.segments[0].items[0].pattern {
986                Pattern::Special(Special::Markov(markov)) => markov.clone(),
987                other => panic!("{other:?}"),
988            },
989            other => panic!("{other:?}"),
990        };
991
992        // the default is what it was when it could not be chosen.
993        assert_eq!(crate::markov::DEPTH_DEFAULT, 3);
994        assert_eq!(markov(r"\m{english}"), MarkovRef::new("english"));
995        assert_eq!(markov(r"\m{english}").depth, 3);
996        assert_eq!(markov(r"\m{english:3}"), MarkovRef::new("english"));
997        assert_eq!(markov(r"\m{english:1}"), MarkovRef::new("english").depth(1));
998        assert_eq!(markov(r"\m{english:8}").depth, DEPTH_MAX);
999        assert_eq!(markov(r"\m{english:02}").depth, 2);
1000
1001        // without a prefix: only how often the characters are in the words.
1002        assert_eq!(markov(r"\m{english:0}").depth, 0);
1003
1004        // an escaped colon is part of the name.
1005        assert_eq!(markov(r"\m{a\:b:2}"), MarkovRef::new("a:b").depth(2));
1006        assert_eq!(markov(r"\m{a\:2}"), MarkovRef::new("a:2"));
1007
1008        // modifiers come after the braces as before.
1009        assert!(Pattern::parse(r"\m{english:2}{3}?").is_ok());
1010    }
1011
1012    #[test]
1013    fn parse_markov_length_errors() {
1014        // the error is where the length is.
1015        assert_eq!(error(r"\m{english:9}"), (ErrorKind::MarkovLength, 11..12));
1016        assert_eq!(error(r"\m{english:}"), (ErrorKind::MarkovLength, 11..11));
1017        assert_eq!(error(r"\m{english:abc}"), (ErrorKind::MarkovLength, 11..14));
1018        assert_eq!(error(r"\m{english:+2}"), (ErrorKind::MarkovLength, 11..13));
1019        assert_eq!(error(r"\m{english:-1}"), (ErrorKind::MarkovLength, 11..13));
1020        assert_eq!(error(r"\m{english:2:3}"), (ErrorKind::MarkovLength, 11..14));
1021        assert_eq!(
1022            error(r"\m{english:99999999999999999999999}"),
1023            (ErrorKind::MarkovLength, 11..34)
1024        );
1025        assert_eq!(error(r"\m{:2}"), (ErrorKind::Special, 0..6));
1026        assert_eq!(error(r"\m{english:2"), (ErrorKind::Special, 0..12));
1027
1028        // only for markov chains.
1029        assert_eq!(
1030            error(r"\w{english:2}"),
1031            (ErrorKind::SpecialParameter, 11..12)
1032        );
1033        assert_eq!(error(r"\p{apple:2}"), (ErrorKind::SpecialParameter, 9..10));
1034        assert_eq!(
1035            error(r"\w{english:}"),
1036            (ErrorKind::SpecialParameter, 11..11)
1037        );
1038        assert!(Pattern::parse(r"\w{a\:b}").is_ok());
1039    }
1040}