sql-values 0.8.0

SQL values, with PostgreSQL's value rules beside readers of the text PostgreSQL, MySQL and SQLite emit
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
//! The subset of PostgreSQL 18's advanced regular expressions whose `textregexeq` matches without
//! flags are decided here.
//!
//! A pattern of the subset holds literal characters, `\` before an ASCII punctuation character,
//! `.`, bracket expressions of characters, ranges and character classes such as `[:space:]`, `^`,
//! `$`, capturing and `(?:` groups, alternation, and the quantifiers `*`, `+`, `?` and `{m}`,
//! `{m,}`, `{m,n}`, greedy or not. It holds no back reference, lookaround, escape letter,
//! collating element, equivalence class, director or embedded option, so PostgreSQL matches it
//! through the search DFA alone and runs no recursion that may outgrow the stack.

mod class;

use alloc::{boxed::Box, vec, vec::Vec};

use class::Class;

const DUPMAX: usize = 255;

const GROUP_DEPTH_LIMIT: usize = 64;

const EXPANDED_SIZE_LIMIT: usize = 10_000;

/// PostgreSQL's `MAX_SIMPLE_CHR`, past which a character takes its colour from a map whose rows
/// are the ranges the pattern mentions and whose columns are the combinations of the classes
/// asking the locale.
const LAST_SIMPLE: char = '\u{7ff}';

const COLOR_LIMIT: usize = 16_000;

const ARCS_PER_ELEMENT: usize = 32;

/// Why [`PgRegex::new`] refuses a pattern, naming its first construct outside the subset, which
/// PostgreSQL may take or refuse.
///
/// ```
/// use sql_values::postgres::{PgRegex, RegexError};
///
/// assert_eq!(PgRegex::new(r"\d+").unwrap_err(), RegexError::ClassEscape);
/// assert_eq!(PgRegex::new("(?=a)").unwrap_err(), RegexError::Lookaround);
/// assert_eq!(PgRegex::new("a{256}").unwrap_err(), RegexError::BoundPastDupmax);
/// assert_eq!(
///     PgRegex::new(r"(a)\1").unwrap_err().to_string(),
///     "the regular expression subset takes no back reference",
/// );
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
pub enum RegexError {
    /// `\d`, `\s`, `\w` or their uppercase negations, in or out of a bracket expression.
    #[error("the regular expression subset takes no class escape such as \\d")]
    ClassEscape,
    /// `\` and a nonzero digit outside a bracket expression.
    #[error("the regular expression subset takes no back reference")]
    BackReference,
    /// `\A`, `\Z`, `\m`, `\M`, `\y` or `\Y` outside a bracket expression.
    #[error("the regular expression subset takes no constraint escape such as \\y")]
    ConstraintEscape,
    /// Any other `\`, such as a character-entry escape like `\n` or `\x41`, an escape inside a
    /// bracket expression, an escape PostgreSQL refuses, or a `\` ending the pattern.
    #[error(
        "the regular expression subset takes no escape but \\ before ASCII punctuation outside a bracket expression"
    )]
    OtherEscape,
    /// `(?=`, `(?!`, `(?<=` or `(?<!`.
    #[error("the regular expression subset takes no lookahead or lookbehind constraint")]
    Lookaround,
    /// `(?` and a letter, such as `(?i)`.
    #[error("the regular expression subset takes no embedded option")]
    EmbeddedOption,
    /// `(?#`.
    #[error("the regular expression subset takes no comment")]
    Comment,
    /// `***` opening the pattern, such as `***=`.
    #[error("the regular expression subset takes no director such as ***=")]
    Director,
    /// A collating element such as `[.a.]` or an equivalence class such as `[=a=]` inside a
    /// bracket expression.
    #[error("the regular expression subset takes no collating element or equivalence class")]
    CollatingElement,
    /// A bracket expression opening with `]`, holding a `-` that is neither first, last nor
    /// between the ends of a range, holding a range whose end precedes its start or is a
    /// character class, or naming a character class PostgreSQL does not know.
    #[error("the regular expression subset takes no bracket expression of this form")]
    BracketForm,
    /// A count in a bound past 255, PostgreSQL's `DUPMAX`.
    #[error("the regular expression subset takes no repetition count past 255")]
    BoundPastDupmax,
    /// A `{` opening no `{m}`, `{m,}` or `{m,n}` closed by `}`, or a bound whose `n` is below its
    /// `m`.
    #[error("the regular expression subset takes no bound of this form")]
    BoundForm,
    /// A quantifier after nothing, after `(` or `|`, after an anchor, or after another
    /// quantifier and its optional non-greedy `?`.
    #[error("the regular expression subset takes no quantifier without an operand")]
    QuantifierOperand,
    /// A `(` without its `)`, a bracket expression without its `]`, or a `)`, `]` or `}` without
    /// its opener.
    #[error("the regular expression subset takes no unbalanced parenthesis, bracket or brace")]
    Unbalanced,
    /// Groups nested past 64 deep.
    #[error("the regular expression subset takes no groups nested past 64 deep")]
    TooDeep,
    /// A pattern past 10000 elements once its bounded repetitions are copied out, as
    /// PostgreSQL's compiler copies them, an element weighing more for every 32 arcs its
    /// colours may draw, or a pattern that may split the characters into more than 16000
    /// colours.
    #[error("the regular expression subset takes no pattern expanding past 10000 elements")]
    TooLarge,
}

impl RegexError {
    /// The error for the escape `\` and `escaped` outside a bracket expression, `escaped` being
    /// no ASCII punctuation.
    fn escape(escaped: Option<char>) -> Self {
        match escaped {
            Some('d' | 'D' | 's' | 'S' | 'w' | 'W') => Self::ClassEscape,
            Some('1'..='9') => Self::BackReference,
            Some('A' | 'Z' | 'm' | 'M' | 'y' | 'Y') => Self::ConstraintEscape,
            _ => Self::OtherEscape,
        }
    }

    /// The error for the escape `\` and `escaped` inside a bracket expression.
    fn bracket_escape(escaped: Option<char>) -> Self {
        match escaped {
            Some('d' | 'D' | 's' | 'S' | 'w' | 'W') => Self::ClassEscape,
            _ => Self::OtherEscape,
        }
    }
}

/// A parsed pattern of the subset.
#[derive(Debug)]
enum Node {
    Char(char),
    Any,
    /// The bracket expression at this index of the parser's sets.
    Set(usize),
    Start,
    End,
    Concat(Vec<Node>),
    Alternation(Vec<Node>),
    Repeat {
        node: Box<Node>,
        min: usize,
        max: Option<usize>,
    },
}

impl Node {
    /// The size of the pattern with its bounded repetitions copied out, as PostgreSQL's compiler
    /// copies them, each element weighing one more for every [`ARCS_PER_ELEMENT`] arcs its
    /// colours may draw.
    fn expanded_size(&self, sets: &[Set], colors: Colors) -> usize {
        match self {
            Self::Char(character) => 1 + colors.char_arcs(*character) / ARCS_PER_ELEMENT,
            Self::Any | Self::Start | Self::End => 1,
            Self::Set(index) => {
                let set = &sets[*index];
                1 + set.ranges.len() + set.classes.len() + set.arcs(colors) / ARCS_PER_ELEMENT
            }
            Self::Concat(nodes) | Self::Alternation(nodes) => nodes.iter().fold(1, |size, node| {
                size.saturating_add(node.expanded_size(sets, colors))
            }),
            Self::Repeat { node, min, max } => node
                .expanded_size(sets, colors)
                .saturating_mul(max.unwrap_or(*min) + 1),
        }
    }
}

/// Bounds on the colours PostgreSQL's compiler splits the characters into for a pattern, a
/// character or bracket expression drawing one arc of the automaton per colour it covers.
#[derive(Debug, Clone, Copy)]
struct Colors {
    total: usize,
    /// The columns of the colour map past [`LAST_SIMPLE`].
    high_columns: usize,
}

impl Colors {
    fn char_arcs(self, character: char) -> usize {
        if character <= LAST_SIMPLE {
            1
        } else {
            self.high_columns
        }
    }
}

/// A bracket expression.
#[derive(Debug, Clone)]
struct Set {
    negated: bool,
    ranges: Vec<(char, char)>,
    classes: Vec<Class>,
}

impl Set {
    fn contains(&self, character: char) -> bool {
        (self
            .ranges
            .iter()
            .any(|(low, high)| (*low..=*high).contains(&character))
            || self.classes.iter().any(|class| class.contains(character)))
            != self.negated
    }

    /// A bound on the arcs the set draws, one per colour it covers.
    fn arcs(&self, colors: Colors) -> usize {
        if self.negated || !self.classes.is_empty() {
            return colors.total;
        }
        self.ranges
            .iter()
            .map(|(low, high)| {
                usize::try_from(u32::from(*high) - u32::from(*low))
                    .map_or(usize::MAX, |width| width.saturating_add(1))
            })
            .fold(0, usize::saturating_add)
            .min(colors.total)
    }
}

struct Parser<'pattern> {
    rest: &'pattern str,
    depth: usize,
    sets: Vec<Set>,
    /// A bound on the times the characters up to [`LAST_SIMPLE`] the pattern mentions start or
    /// stop a run of one colour.
    low_flips: usize,
    /// The characters and ranges past [`LAST_SIMPLE`] the pattern mentions.
    high_ranges: usize,
    /// The distinct classes the pattern mentions.
    classes: Vec<Class>,
}

impl Parser<'_> {
    fn new(pattern: &str) -> Parser<'_> {
        Parser {
            rest: pattern,
            depth: 0,
            sets: Vec::new(),
            low_flips: 0,
            high_ranges: 0,
            classes: Vec::new(),
        }
    }

    /// Count the characters `low` through `high` towards the pattern's colours.
    fn mention(&mut self, low: char, high: char) {
        if low <= LAST_SIMPLE {
            self.low_flips += 2;
        }
        if high > LAST_SIMPLE {
            self.high_ranges += 1;
        }
    }

    /// Count `class` towards the pattern's colours.
    fn mention_class(&mut self, class: Class) {
        if !self.classes.contains(&class) {
            self.low_flips += class.flips_through(LAST_SIMPLE);
            self.classes.push(class);
        }
    }

    fn colors(&self) -> Colors {
        let simple = usize::try_from(u32::from(LAST_SIMPLE)).map_or(usize::MAX, |last| last + 1);
        let asking = self
            .classes
            .iter()
            .filter(|class| class.asks_locale())
            .count();
        let high_columns = 1 << asking;
        let high_rows = self.high_ranges.saturating_mul(2).saturating_add(1);
        Colors {
            total: (self.low_flips + 1)
                .min(simple)
                .saturating_add(high_rows.saturating_mul(high_columns)),
            high_columns,
        }
    }

    /// The literal `character`, counted towards the pattern's colours.
    fn literal(&mut self, character: char) -> Node {
        self.mention(character, character);
        Node::Char(character)
    }

    fn peek(&self) -> Option<char> {
        self.rest.chars().next()
    }

    /// The character after the next one.
    fn peek_second(&self) -> Option<char> {
        let mut ahead = self.rest.chars();
        ahead.next();
        ahead.next()
    }

    fn next(&mut self) -> Option<char> {
        let next = self.peek()?;
        self.rest = &self.rest[next.len_utf8()..];
        Some(next)
    }

    fn eat(&mut self, expected: char) -> bool {
        let eaten = self.peek() == Some(expected);
        if eaten {
            self.next();
        }
        eaten
    }

    fn at_quantifier(&self) -> bool {
        matches!(self.peek(), Some('*' | '+' | '?' | '{'))
    }

    fn alternation(&mut self) -> Result<Node, RegexError> {
        let mut branches = vec![self.branch()?];
        while self.eat('|') {
            branches.push(self.branch()?);
        }
        Ok(if branches.len() == 1 {
            branches.swap_remove(0)
        } else {
            Node::Alternation(branches)
        })
    }

    fn branch(&mut self) -> Result<Node, RegexError> {
        let mut pieces = Vec::new();
        while let Some(first) = self.peek() {
            if first == '|' || first == ')' {
                break;
            }
            self.next();
            pieces.push(self.piece(first)?);
        }
        Ok(Node::Concat(pieces))
    }

    /// The atom opening with `first` and its quantifier.
    fn piece(&mut self, first: char) -> Result<Node, RegexError> {
        let atom = self.atom(first)?;
        if !self.at_quantifier() {
            return Ok(atom);
        }
        if matches!(atom, Node::Start | Node::End) {
            return Err(RegexError::QuantifierOperand);
        }
        let (min, max) = match self.next() {
            Some('*') => (0, None),
            Some('+') => (1, None),
            Some('?') => (0, Some(1)),
            _ => self.bound()?,
        };
        // Greediness decides which match is reported, never whether one is.
        self.eat('?');
        if self.at_quantifier() {
            return Err(RegexError::QuantifierOperand);
        }
        Ok(Node::Repeat {
            node: Box::new(atom),
            min,
            max,
        })
    }

    /// The atom opening with `first`.
    fn atom(&mut self, first: char) -> Result<Node, RegexError> {
        match first {
            '(' => self.group(),
            '.' => Ok(Node::Any),
            '^' => Ok(Node::Start),
            '$' => Ok(Node::End),
            '[' => self.set(),
            '\\' => match self.next() {
                Some(escaped) if escaped.is_ascii_punctuation() => Ok(self.literal(escaped)),
                escaped => Err(RegexError::escape(escaped)),
            },
            '*' | '+' | '?' | '{' => Err(RegexError::QuantifierOperand),
            ']' | '}' => Err(RegexError::Unbalanced),
            literal => Ok(self.literal(literal)),
        }
    }

    /// The group after its `(`.
    fn group(&mut self) -> Result<Node, RegexError> {
        if self.peek() == Some('?') {
            match self.peek_second() {
                Some(':') => {
                    self.next();
                    self.next();
                }
                Some('=' | '!') => return Err(RegexError::Lookaround),
                Some('<') => {
                    self.next();
                    self.next();
                    return Err(match self.peek() {
                        Some('=' | '!') => RegexError::Lookaround,
                        _ => RegexError::QuantifierOperand,
                    });
                }
                Some('#') => return Err(RegexError::Comment),
                Some(letter) if letter.is_ascii_alphabetic() => {
                    return Err(RegexError::EmbeddedOption);
                }
                _ => return Err(RegexError::QuantifierOperand),
            }
        }
        if self.depth == GROUP_DEPTH_LIMIT {
            return Err(RegexError::TooDeep);
        }
        self.depth += 1;
        let group = self.alternation()?;
        self.depth -= 1;
        if self.eat(')') {
            Ok(group)
        } else {
            Err(RegexError::Unbalanced)
        }
    }

    /// The bracket expression after its `[`.
    fn set(&mut self) -> Result<Node, RegexError> {
        let mut set = Set {
            negated: self.eat('^'),
            ranges: Vec::new(),
            classes: Vec::new(),
        };
        if self.eat('-') {
            self.mention('-', '-');
            set.ranges.push(('-', '-'));
        }
        loop {
            let low = match self.next() {
                None => return Err(RegexError::Unbalanced),
                Some(']') if !set.ranges.is_empty() || !set.classes.is_empty() => break,
                Some('-') if self.eat(']') => {
                    self.mention('-', '-');
                    set.ranges.push(('-', '-'));
                    break;
                }
                Some(']' | '-') => return Err(RegexError::BracketForm),
                Some('[') => match self.bracket_class()? {
                    Some(class) => {
                        self.mention_class(class);
                        set.classes.push(class);
                        continue;
                    }
                    None => '[',
                },
                Some('\\') => return Err(RegexError::bracket_escape(self.next())),
                Some(low) => low,
            };
            let high = match self.peek_second() {
                Some(high) if self.peek() == Some('-') && high != ']' => {
                    self.next();
                    self.next();
                    match high {
                        '[' => match self.bracket_class()? {
                            Some(_) => return Err(RegexError::BracketForm),
                            None => '[',
                        },
                        '\\' => return Err(RegexError::bracket_escape(self.next())),
                        '-' => return Err(RegexError::BracketForm),
                        high => high,
                    }
                }
                _ => low,
            };
            if high < low {
                return Err(RegexError::BracketForm);
            }
            self.mention(low, high);
            set.ranges.push((low, high));
        }
        self.sets.push(set);
        Ok(Node::Set(self.sets.len() - 1))
    }

    /// The class a `[` inside a bracket expression opens, or `None` when it stands for itself.
    fn bracket_class(&mut self) -> Result<Option<Class>, RegexError> {
        match self.peek() {
            Some(':') => {
                let (name, rest) = self.rest[1..]
                    .split_once(":]")
                    .ok_or(RegexError::Unbalanced)?;
                self.rest = rest;
                Class::named(name).map(Some).ok_or(RegexError::BracketForm)
            }
            Some('.' | '=') => Err(RegexError::CollatingElement),
            _ => Ok(None),
        }
    }

    /// The bounds of a `{m}`, `{m,}` or `{m,n}` quantifier after its `{`.
    fn bound(&mut self) -> Result<(usize, Option<usize>), RegexError> {
        let min = self.count()?;
        let max = if self.eat(',') {
            if self.peek() == Some('}') {
                None
            } else {
                Some(self.count()?)
            }
        } else {
            Some(min)
        };
        if !self.eat('}') || max.is_some_and(|max| max < min) {
            return Err(RegexError::BoundForm);
        }
        Ok((min, max))
    }

    fn count(&mut self) -> Result<usize, RegexError> {
        let mut count = None;
        while let Some(digit) = self.peek().and_then(|next| next.to_digit(10)) {
            self.next();
            // A digit fits any `usize`, and the count stops past `DUPMAX` before it can overflow.
            let value = count.unwrap_or(0) * 10 + usize::try_from(digit).unwrap_or(usize::MAX);
            if value > DUPMAX {
                return Err(RegexError::BoundPastDupmax);
            }
            count = Some(value);
        }
        count.ok_or(RegexError::BoundForm)
    }
}

/// A step of the matching automaton.
#[derive(Debug, Clone, Copy)]
enum Step {
    Char(char),
    Any,
    Set(usize),
    Start,
    End,
    Split(usize, usize),
    Jump(usize),
    Match,
}

/// A pattern of a subset of PostgreSQL 18's advanced regular expressions, compiled once to an
/// automaton that answers `text ~ pattern` without flags for any text.
///
/// The subset holds literal characters, `\` before an ASCII punctuation character, `.`, bracket
/// expressions of characters, ranges and character classes, `^`, `$`, capturing and `(?:`
/// groups, alternation, and `*`, `+`, `?`, `{m}`, `{m,}` and `{m,n}`, greedy or not. PostgreSQL
/// compiles every pattern of the subset, and a pattern holding anything else is refused with the
/// [`RegexError`] naming its first construct the subset does not take.
///
/// The classes `[:alnum:]`, `[:alpha:]`, `[:ascii:]`, `[:blank:]`, `[:cntrl:]`, `[:digit:]`,
/// `[:graph:]`, `[:lower:]`, `[:print:]`, `[:punct:]`, `[:space:]`, `[:upper:]`, `[:word:]` and
/// `[:xdigit:]` match as in a UTF-8 database whose `LC_CTYPE` is glibc 2.41's `en_US.utf8`, the
/// locale of the `postgres:18.6` Docker image, so `[:space:]` holds U+3000 and not U+00A0.
///
/// ```
/// use sql_values::postgres::{PgRegex, RegexError};
///
/// let list = PgRegex::new(
///     r"^[a-z_][a-z0-9_]*:(read|insert|update|delete)(,[a-z_][a-z0-9_]*:(read|insert|update|delete))*$",
/// )
/// .unwrap();
/// assert!(list.is_match("resources:read,notes:insert"));
/// assert!(!list.is_match("resources:read,"));
///
/// let url = PgRegex::new("^https://[^[:space:]/?#]+").unwrap();
/// assert!(url.is_match("https://example.com/notes"));
/// assert!(!url.is_match("https://\u{3000}example.com"));
/// assert!(url.is_match("https://\u{a0}example.com"));
///
/// assert_eq!(PgRegex::new(r"\d+").unwrap_err(), RegexError::ClassEscape);
/// assert_eq!(PgRegex::new("(?=a)").unwrap_err(), RegexError::Lookaround);
/// assert_eq!(PgRegex::new("***=a").unwrap_err(), RegexError::Director);
/// ```
#[derive(Debug, Clone)]
pub struct PgRegex {
    steps: Vec<Step>,
    sets: Vec<Set>,
}

impl PgRegex {
    /// Compile `pattern`.
    ///
    /// # Errors
    ///
    /// The [`RegexError`] naming the first construct of `pattern` outside the subset, or
    /// [`RegexError::TooLarge`] for a pattern past the subset's size limit.
    pub fn new(pattern: &str) -> Result<Self, RegexError> {
        if pattern.starts_with("***") {
            return Err(RegexError::Director);
        }
        let mut parser = Parser::new(pattern);
        let node = parser.alternation()?;
        if !parser.rest.is_empty() {
            return Err(RegexError::Unbalanced);
        }
        let colors = parser.colors();
        if colors.total > COLOR_LIMIT
            || node.expanded_size(&parser.sets, colors) > EXPANDED_SIZE_LIMIT
        {
            return Err(RegexError::TooLarge);
        }
        let mut regex = Self {
            steps: Vec::new(),
            sets: parser.sets,
        };
        regex.compile(&node);
        regex.steps.push(Step::Match);
        Ok(regex)
    }

    fn compile(&mut self, node: &Node) {
        match node {
            Node::Char(character) => self.steps.push(Step::Char(*character)),
            Node::Any => self.steps.push(Step::Any),
            Node::Set(index) => self.steps.push(Step::Set(*index)),
            Node::Start => self.steps.push(Step::Start),
            Node::End => self.steps.push(Step::End),
            Node::Concat(nodes) => {
                for node in nodes {
                    self.compile(node);
                }
            }
            Node::Alternation(branches) => {
                let mut exits = Vec::with_capacity(branches.len());
                for (position, branch) in branches.iter().enumerate() {
                    if position + 1 == branches.len() {
                        self.compile(branch);
                        break;
                    }
                    let split = self.steps.len();
                    self.steps.push(Step::Split(split + 1, 0));
                    self.compile(branch);
                    exits.push(self.steps.len());
                    self.steps.push(Step::Jump(0));
                    self.steps[split] = Step::Split(split + 1, self.steps.len());
                }
                let end = self.steps.len();
                for exit in exits {
                    self.steps[exit] = Step::Jump(end);
                }
            }
            Node::Repeat { node, min, max } => {
                for _ in 0..*min {
                    self.compile(node);
                }
                if let Some(max) = max {
                    let mut exits = Vec::with_capacity(max - min);
                    for _ in *min..*max {
                        exits.push(self.steps.len());
                        self.steps.push(Step::Split(self.steps.len() + 1, 0));
                        self.compile(node);
                    }
                    let end = self.steps.len();
                    for exit in exits {
                        self.steps[exit] = Step::Split(exit + 1, end);
                    }
                } else {
                    let split = self.steps.len();
                    self.steps.push(Step::Split(split + 1, 0));
                    self.compile(node);
                    self.steps.push(Step::Jump(split));
                    self.steps[split] = Step::Split(split + 1, self.steps.len());
                }
            }
        }
    }

    /// Whether `text ~ pattern` holds, as `textregexeq` without flags answers, a match anywhere
    /// in `text`, `^` and `$` anchoring at its ends alone, and `.` and a negated bracket
    /// expression matching a newline.
    #[must_use]
    pub fn is_match(&self, text: &str) -> bool {
        // The position each step was last reached at, to visit it once per position.
        let mut reached = vec![usize::MAX; self.steps.len()];
        let mut consuming = Vec::new();
        let mut seeds = Vec::new();
        let mut pending = Vec::new();
        let mut characters = text.chars();
        let mut position = 0;
        loop {
            let character = characters.next();
            consuming.clear();
            pending.append(&mut seeds);
            // A match may start at every position.
            pending.push(0);
            while let Some(index) = pending.pop() {
                if reached[index] == position {
                    continue;
                }
                reached[index] = position;
                match self.steps[index] {
                    Step::Match => return true,
                    Step::Split(first, second) => pending.extend([second, first]),
                    Step::Jump(target) => pending.push(target),
                    Step::Start if position == 0 => pending.push(index + 1),
                    Step::End if character.is_none() => pending.push(index + 1),
                    Step::Start | Step::End => {}
                    Step::Char(_) | Step::Any | Step::Set(_) => consuming.push(index),
                }
            }
            let Some(character) = character else {
                return false;
            };
            for &index in &consuming {
                let consumed = match self.steps[index] {
                    Step::Char(expected) => expected == character,
                    Step::Set(set) => self.sets[set].contains(character),
                    _ => true,
                };
                if consumed {
                    seeds.push(index + 1);
                }
            }
            position += 1;
        }
    }
}

#[cfg(test)]
mod tests {
    use alloc::{format, string::String};

    use super::{PgRegex, RegexError};

    /// Patterns PostgreSQL 18 compiles, with texts and whether each matches, as
    /// `SELECT text ~ pattern` answers.
    #[test]
    fn matches_as_postgresql_does() {
        let list = "^[a-z_][a-z0-9_]*:(read|insert|update|delete)(,[a-z_][a-z0-9_]*:(read|insert|update|delete))*$";
        for (pattern, text, expected) in [
            ("", "x", true),
            ("()", "x", true),
            ("a|", "x", true),
            ("|a", "x", true),
            ("[a^]", "^", true),
            ("a$", "a\n", false),
            ("^.$", "\n", true),
            ("^[^a]$", "\n", true),
            ("a^b", "ab", false),
            ("^a{0}b$", "b", true),
            ("^ab?c$", "ac", true),
            ("^ab?c$", "abbc", false),
            ("^a{1,2}?a$", "aaa", true),
            ("[-a]", "-", true),
            ("[a-]", "-", true),
            ("a\\.", "a.", true),
            ("a\\.", "ab", false),
            ("^[a-z]$", "é", false),
            ("^[à-ÿ]$", "é", true),
            ("a{255}", "a", false),
            ("^(ab|cd)*$", "abcdab", true),
            ("^(ab|cd)*$", "abc", false),
            ("^(a*)*$", "aaa", true),
            ("^(?:a|b)+c$", "abbac", true),
            ("b{2,}", "abbbc", true),
            ("b{2,}", "abc", false),
            ("^x{2,3}$", "xxxx", false),
            (list, "resources:read,team_members:delete", true),
            (list, "resources:read,", false),
            ("^https://[^[:space:]/?#]+$", "https://example.com", true),
            ("^https://[^[:space:]/?#]+$", "https://exa mple.com", false),
            (
                "^https://[^[:space:]/?#]+$",
                "https://exa\u{2000}mple.com",
                false,
            ),
            (
                "^https://[^[:space:]/?#]+$",
                "https://exa\u{a0}mple.com",
                true,
            ),
            ("^[^[:space:]]$", "\n", false),
            ("^[[:alpha:]]+$", "Ωmega", true),
            ("^[[:alpha:]]+$", "a1", false),
            ("^[[:alnum:]_]+$", "a1_", true),
            ("^[[:upper:]][[:lower:]]+$", "Élan", true),
            ("^[[:digit:]]$", "٣", false),
            ("^[[:punct:]]$", "¿", true),
            ("^[[:word:]-]+$", "a-b_c", true),
            ("^[-[:xdigit:]]+$", "-fF0", true),
            ("^[[:blank:][:cntrl:]]+$", "\t \u{7f}\u{85}", true),
            ("^[[:ascii:]]+$", "é", false),
            ("^[[:graph:]]$", " ", false),
            ("^[[:print:]]$", " ", true),
            ("[[]", "[", true),
            ("[a[]", "[", true),
            ("^[A-[]$", "Z", true),
            ("^[[-a]$", "_", true),
            ("^[[[:digit:]]+$", "[1", true),
            ("^[[:digit:][]+$", "1[", true),
            ("^[[:alpha:]:]$", ":", true),
        ] {
            let regex = PgRegex::new(pattern).unwrap_or_else(|error| panic!("{pattern}: {error}"));
            assert_eq!(regex.is_match(text), expected, "{text:?} ~ {pattern:?}");
        }
    }

    /// Patterns PostgreSQL refuses, and patterns it compiles holding what the subset leaves out,
    /// each refused with its first construct outside the subset.
    #[test]
    fn names_the_first_construct_outside_the_subset() {
        let deep = format!("{}a{}", "(".repeat(65), ")".repeat(65));
        let nested = format!("{}a{}", "(".repeat(64), ")".repeat(64));
        let complement: String = ('\u{100}'..='\u{2f3}').collect();
        let complement = format!("{complement}([^a]{{255}}){{17}}");
        let high: String = ('\u{4e00}'..'\u{4ec8}').collect();
        let high = format!(
            "{high}[[:alpha:]][[:punct:]][[:space:]][[:upper:]][[:lower:]][[:print:]][[:graph:]][[:word:]][[:alnum:]]"
        );
        assert!(PgRegex::new(&nested).is_ok());
        for (pattern, expected) in [
            (r"\d", RegexError::ClassEscape),
            (r"a\W", RegexError::ClassEscape),
            (r"[\d]", RegexError::ClassEscape),
            (r"(a)\1", RegexError::BackReference),
            (r"\y", RegexError::ConstraintEscape),
            (r"\A", RegexError::ConstraintEscape),
            (r"\n", RegexError::OtherEscape),
            (r"\x41", RegexError::OtherEscape),
            (r"\é", RegexError::OtherEscape),
            ("a\\", RegexError::OtherEscape),
            (r"[\.]", RegexError::OtherEscape),
            (r"[a-\]]", RegexError::OtherEscape),
            ("(?=a)", RegexError::Lookaround),
            ("(?!a)", RegexError::Lookaround),
            ("(?<=a)", RegexError::Lookaround),
            ("(?<!a)", RegexError::Lookaround),
            ("(?<a)", RegexError::QuantifierOperand),
            ("(?)", RegexError::QuantifierOperand),
            ("(?i)a", RegexError::EmbeddedOption),
            ("(?#x)a", RegexError::Comment),
            ("***=a", RegexError::Director),
            ("***:a", RegexError::Director),
            ("[[.a.]]", RegexError::CollatingElement),
            ("[[=a=]]", RegexError::CollatingElement),
            ("[a-[.z.]]", RegexError::CollatingElement),
            ("[[:foo:]]", RegexError::BracketForm),
            ("[[:ALPHA:]]", RegexError::BracketForm),
            ("[[::]]", RegexError::BracketForm),
            ("[[:a]b:]]", RegexError::BracketForm),
            ("[[:alpha:]-z]", RegexError::BracketForm),
            ("[a-[:alpha:]]", RegexError::BracketForm),
            ("[[:digit:]--]", RegexError::BracketForm),
            ("[a-[]", RegexError::BracketForm),
            ("[[:alpha]]", RegexError::Unbalanced),
            ("[[:]]", RegexError::Unbalanced),
            ("[[:alpha:]", RegexError::Unbalanced),
            ("[[", RegexError::Unbalanced),
            ("[[:space:]\\s]", RegexError::ClassEscape),
            ("[]a]", RegexError::BracketForm),
            ("[^]a]", RegexError::BracketForm),
            ("[a-c-e]", RegexError::BracketForm),
            ("[a--]", RegexError::BracketForm),
            ("[z-a]", RegexError::BracketForm),
            ("a{256}", RegexError::BoundPastDupmax),
            ("a{1,300}", RegexError::BoundPastDupmax),
            ("a{3,2}", RegexError::BoundForm),
            ("a{", RegexError::BoundForm),
            ("a{,2}", RegexError::BoundForm),
            ("a{2", RegexError::BoundForm),
            ("a**", RegexError::QuantifierOperand),
            ("a*?+", RegexError::QuantifierOperand),
            ("*a", RegexError::QuantifierOperand),
            ("^*a", RegexError::QuantifierOperand),
            ("a$+", RegexError::QuantifierOperand),
            ("a|*", RegexError::QuantifierOperand),
            ("(+a)", RegexError::QuantifierOperand),
            ("(a", RegexError::Unbalanced),
            ("a)", RegexError::Unbalanced),
            ("[a", RegexError::Unbalanced),
            ("]", RegexError::Unbalanced),
            ("a}", RegexError::Unbalanced),
            (deep.as_str(), RegexError::TooDeep),
            ("((a{100}){100}){100}", RegexError::TooLarge),
            (complement.as_str(), RegexError::TooLarge),
            (high.as_str(), RegexError::TooLarge),
        ] {
            assert_eq!(PgRegex::new(pattern).err(), Some(expected), "{pattern}");
        }
    }
}