Skip to main content

base/
pattern.rs

1// pattern -- shell wildcards and a small engine for regular expressions (the shells of
2// JFNetworker's hosts: globs, find -name, grep)
3//
4//   glob(pat, s) -> bool          fnmatch(3) without flags: * any run of characters, ? one,
5//                                 [abc] [a-z] [!x] [^x] [[:digit:]] one of a set, \x the
6//                                 character x; '/' and a leading '.' are ordinary characters
7//                                 here (a caller matches path components one by one and hides
8//                                 dot files itself)
9//   has_glob(s) -> bool           s holds an unescaped *, ? or [ (a word to expand)
10//   Regex::new(pat, Syntax::Basic | Syntax::Extended, icase) -> Result<Regex, ReErr>
11//   Regex::is_match(s)            the expression matches somewhere in s
12//   Regex::find(s) / find_at(s, from) -> Option<(start, end)>   byte offsets of the leftmost
13//                                 match, the longest one starting there (POSIX)
14//   ReErr::text()                 the error in GNU grep's words ("Unmatched ( or \(")
15//
16// The expressions are POSIX's basic (BRE) and extended (ERE) syntax without back-references
17// and collating elements: characters, ".", bracket expressions with ranges, negation and the
18// classes [:alpha:] [:digit:] [:alnum:] [:upper:] [:lower:] [:space:] [:blank:] [:punct:]
19// [:xdigit:] [:print:] [:graph:] [:cntrl:]; the anchors ^ and $; the repetitions *, and in
20// ERE + ? {m} {m,} {m,n} (BRE: \+ \? \{m,n\} as GNU takes them); groups ( ) and alternatives |
21// (BRE: \( \) \|); GNU's \w \W \s \S and the word edges \< \> \b \B.  As GNU does, a
22// repetition with nothing before it is an ordinary character, an ERE "{" that starts no
23// interval too, and BRE takes ^ and $ as anchors only at the ends of the expression or of a
24// group.  Matching runs a Pike VM over the characters: time grows with the text times the
25// program, never exponentially; a repetition counts to 255 at most and a program has at most
26// 20000 steps (ReErr::TooBig beyond).  Case-insensitive matching compares simple lowercase
27// forms.
28
29use alloc::boxed::Box;
30use alloc::vec;
31use alloc::vec::Vec;
32
33// ---------------------------------------------------------------- wildcards
34
35/// a character class name of a bracket expression
36fn class_holds(name: &str, c: char) -> Option<bool> {
37    Some(match name {
38        "alpha" => c.is_alphabetic(),
39        "digit" => c.is_ascii_digit(),
40        "alnum" => c.is_alphanumeric(),
41        "upper" => c.is_uppercase(),
42        "lower" => c.is_lowercase(),
43        "space" => c.is_whitespace(),
44        "blank" => c == ' ' || c == '\t',
45        "punct" => c.is_ascii_punctuation(),
46        "xdigit" => c.is_ascii_hexdigit(),
47        "print" => !c.is_control(),
48        "graph" => !c.is_control() && !c.is_whitespace(),
49        "cntrl" => c.is_control(),
50        _ => return None,
51    })
52}
53
54/// a bracket expression from just after its '[': the set and the index after its ']' (None:
55/// not closed, or a class name that does not exist)
56fn bracket(p: &[char], mut i: usize, glob: bool) -> Option<(Set, usize)> {
57    let mut set = Set { neg: false, items: Vec::new() };
58    if i < p.len() && (p[i] == '^' || (glob && p[i] == '!')) {
59        set.neg = true;
60        i += 1;
61    }
62    let start = i;
63    loop {
64        let c = *p.get(i)?;
65        if c == ']' && i > start {
66            return Some((set, i + 1));
67        }
68        if c == '[' && p.get(i + 1) == Some(&':') {
69            let rest = &p[i + 2..];
70            let end = rest.windows(2).position(|w| w == [':', ']'])?;
71            let name: alloc::string::String = rest[..end].iter().collect();
72            class_holds(&name, 'a')?;
73            set.items.push(Item::Class(name));
74            i += 2 + end + 2;
75            continue;
76        }
77        if c == '[' && matches!(p.get(i + 1), Some('.') | Some('=')) {
78            return None;
79        }
80        let mut lo = c;
81        i += 1;
82        if glob && c == '\\' && i < p.len() {
83            lo = p[i];
84            i += 1;
85        }
86        if p.get(i) == Some(&'-') && p.get(i + 1).is_some_and(|&x| x != ']') {
87            let mut hi = p[i + 1];
88            i += 2;
89            if glob && hi == '\\' && i < p.len() {
90                hi = p[i];
91                i += 1;
92            }
93            if hi < lo {
94                return None;
95            }
96            set.items.push(Item::Range(lo, hi));
97        } else {
98            set.items.push(Item::Range(lo, lo));
99        }
100    }
101}
102
103/// the wildcard pattern matches all of s (fnmatch without flags)
104pub fn glob(pat: &str, s: &str) -> bool {
105    let p: Vec<char> = pat.chars().collect();
106    let t: Vec<char> = s.chars().collect();
107    let (mut pi, mut ti) = (0usize, 0usize);
108    // the last '*' and where its run ends now: a mismatch makes the run one longer
109    let mut star: Option<(usize, usize)> = None;
110    loop {
111        if pi < p.len() {
112            match p[pi] {
113                '*' => {
114                    star = Some((pi, ti));
115                    pi += 1;
116                    continue;
117                }
118                '?' if ti < t.len() => {
119                    pi += 1;
120                    ti += 1;
121                    continue;
122                }
123                '[' => {
124                    if let Some((set, next)) = bracket(&p, pi + 1, true) {
125                        if ti < t.len() && set.holds(t[ti], false) {
126                            pi = next;
127                            ti += 1;
128                            continue;
129                        }
130                    } else if ti < t.len() && t[ti] == '[' {
131                        // an open '[' stands for itself
132                        pi += 1;
133                        ti += 1;
134                        continue;
135                    }
136                }
137                '\\' if pi + 1 < p.len() => {
138                    if ti < t.len() && t[ti] == p[pi + 1] {
139                        pi += 2;
140                        ti += 1;
141                        continue;
142                    }
143                }
144                '?' => {}
145                c => {
146                    if ti < t.len() && t[ti] == c {
147                        pi += 1;
148                        ti += 1;
149                        continue;
150                    }
151                }
152            }
153        } else if ti == t.len() {
154            return true;
155        }
156        match star {
157            Some((sp, st)) if st < t.len() => {
158                star = Some((sp, st + 1));
159                pi = sp + 1;
160                ti = st + 1;
161            }
162            _ => return false,
163        }
164    }
165}
166
167/// the word holds an unescaped wildcard (*, ? or [)
168pub fn has_glob(s: &str) -> bool {
169    let mut esc = false;
170    for c in s.chars() {
171        if esc {
172            esc = false;
173            continue;
174        }
175        match c {
176            '\\' => esc = true,
177            '*' | '?' | '[' => return true,
178            _ => {}
179        }
180    }
181    false
182}
183
184// ---------------------------------------------------------------- regular expressions
185
186/// which syntax an expression is written in
187#[derive(Clone, Copy, Debug, PartialEq, Eq)]
188#[non_exhaustive]
189pub enum Syntax {
190    /// POSIX basic (grep): \( \) \{ \} \| \+ \? are the operators
191    Basic,
192    /// POSIX extended (grep -E, egrep)
193    Extended,
194}
195
196/// why an expression does not compile
197#[derive(Clone, Copy, Debug, PartialEq, Eq)]
198#[non_exhaustive]
199pub enum ReErr {
200    /// an open group without its end
201    Paren,
202    /// a group's end without its start
203    CloseParen,
204    /// a bracket expression without its ']'
205    Bracket,
206    /// a range whose end comes before its start
207    Range,
208    /// [:name:] with a name that is no class
209    Class,
210    /// a '\' at the end
211    Backslash,
212    /// \{ without \}
213    Brace,
214    /// what is between { and } is no interval
215    BraceContent,
216    /// a repetition of something that cannot repeat
217    Repeat,
218    /// the program would be too long
219    TooBig,
220}
221
222impl ReErr {
223    /// GNU grep's message
224    pub fn text(self) -> &'static str {
225        match self {
226            ReErr::Paren => "Unmatched ( or \\(",
227            ReErr::CloseParen => "Unmatched ) or \\)",
228            ReErr::Bracket => "Unmatched [, [^, [:, [., or [=",
229            ReErr::Range => "Invalid range end",
230            ReErr::Class => "Invalid character class name",
231            ReErr::Backslash => "Trailing backslash",
232            ReErr::Brace => "Unmatched \\{",
233            ReErr::BraceContent => "Invalid content of \\{\\}",
234            ReErr::Repeat => "Invalid preceding regular expression",
235            ReErr::TooBig => "Regular expression too big",
236        }
237    }
238}
239
240#[derive(Clone, Debug, PartialEq, Eq)]
241enum Item {
242    Range(char, char),
243    Class(alloc::string::String),
244}
245
246/// a set of characters of a bracket expression or of \w \s
247#[derive(Clone, Debug, PartialEq, Eq)]
248struct Set {
249    neg: bool,
250    items: Vec<Item>,
251}
252
253fn lower(c: char) -> char {
254    c.to_lowercase().next().unwrap_or(c)
255}
256
257fn upper(c: char) -> char {
258    c.to_uppercase().next().unwrap_or(c)
259}
260
261impl Set {
262    fn holds(&self, c: char, icase: bool) -> bool {
263        let one = |c: char| {
264            self.items.iter().any(|it| match it {
265                Item::Range(a, b) => *a <= c && c <= *b,
266                Item::Class(n) => class_holds(n, c).unwrap_or(false),
267            })
268        };
269        let hit = one(c) || (icase && (one(lower(c)) || one(upper(c))));
270        hit != self.neg
271    }
272    fn word(neg: bool) -> Set {
273        Set { neg, items: vec![Item::Class(alloc::string::String::from("alnum")), Item::Range('_', '_')] }
274    }
275    fn space(neg: bool) -> Set {
276        Set { neg, items: vec![Item::Class(alloc::string::String::from("space"))] }
277    }
278}
279
280/// a zero-width test at a position
281#[derive(Clone, Copy, Debug, PartialEq, Eq)]
282enum Edge {
283    Bol,
284    Eol,
285    /// \< and \>: a word starts / ends here
286    WordStart,
287    WordEnd,
288    /// \b and \B
289    Word,
290    NotWord,
291}
292
293#[derive(Clone, Debug, PartialEq, Eq)]
294enum Node {
295    Empty,
296    Char(char),
297    Any,
298    Set(Set),
299    Edge(Edge),
300    Cat(Vec<Node>),
301    Alt(Vec<Node>),
302    Rep(Box<Node>, u32, Option<u32>),
303}
304
305const REP_MAX: u32 = 255;
306const PROG_MAX: usize = 20_000;
307// groups inside groups, repetitions of one atom ("a{2}{2}"), compile steps (a part that emits
308// nothing still costs a step each time a repetition copies it)
309const DEPTH_MAX: u32 = 32;
310const REPS_MAX: u32 = 8;
311const WORK_MAX: usize = 16 * PROG_MAX;
312
313struct Parser<'a> {
314    p: &'a [char],
315    i: usize,
316    ere: bool,
317    depth: u32,
318}
319
320impl Parser<'_> {
321    fn peek(&self) -> Option<char> {
322        self.p.get(self.i).copied()
323    }
324    fn peek2(&self) -> Option<char> {
325        self.p.get(self.i + 1).copied()
326    }
327    /// at "|" (ERE) or "\|" (BRE)
328    fn at_alt(&self) -> bool {
329        if self.ere { self.peek() == Some('|') } else { self.peek() == Some('\\') && self.peek2() == Some('|') }
330    }
331    /// at ")" (ERE) or "\)" (BRE)
332    fn at_close(&self) -> bool {
333        if self.ere { self.peek() == Some(')') } else { self.peek() == Some('\\') && self.peek2() == Some(')') }
334    }
335    fn alt(&mut self) -> Result<Node, ReErr> {
336        let mut alts = vec![self.cat()?];
337        while self.at_alt() {
338            self.i += if self.ere { 1 } else { 2 };
339            alts.push(self.cat()?);
340        }
341        Ok(if alts.len() == 1 { alts.pop().unwrap_or(Node::Empty) } else { Node::Alt(alts) })
342    }
343    fn cat(&mut self) -> Result<Node, ReErr> {
344        let mut v: Vec<Node> = Vec::new();
345        let begin = self.i;
346        while self.i < self.p.len() && !self.at_alt() && !(self.depth > 0 && self.at_close()) {
347            if self.at_close() {
348                // ")" without a group: ERE takes it as a character only in GNU's lax way
349                return Err(ReErr::CloseParen);
350            }
351            let first = self.i == begin;
352            let atom = self.atom(first)?;
353            let atom = self.reps(atom)?;
354            v.push(atom);
355        }
356        Ok(match v.len() {
357            0 => Node::Empty,
358            1 => v.pop().unwrap_or(Node::Empty),
359            _ => Node::Cat(v),
360        })
361    }
362    /// an interval's numbers from just after its "{" up to and with its "}" ("\}" in BRE);
363    /// None when it is none (ERE: then "{" is a character)
364    fn interval(&mut self) -> Result<Option<(u32, Option<u32>)>, ReErr> {
365        let save = self.i;
366        let num = |s: &mut Parser| -> Option<u32> {
367            let st = s.i;
368            while s.peek().is_some_and(|c| c.is_ascii_digit()) {
369                s.i += 1;
370            }
371            if s.i == st {
372                return None;
373            }
374            let t: alloc::string::String = s.p[st..s.i].iter().collect();
375            Some(t.parse::<u32>().unwrap_or(u32::MAX))
376        };
377        let lo = num(self);
378        let comma = self.peek() == Some(',');
379        if comma {
380            self.i += 1;
381        }
382        let hi = if comma { num(self) } else { lo };
383        let closed = if self.ere {
384            if self.peek() == Some('}') {
385                self.i += 1;
386                true
387            } else {
388                false
389            }
390        } else if self.peek() == Some('\\') && self.peek2() == Some('}') {
391            self.i += 2;
392            true
393        } else {
394            false
395        };
396        if !closed || (lo.is_none() && !comma) {
397            if self.ere {
398                self.i = save;
399                return Ok(None);
400            }
401            return Err(if closed { ReErr::BraceContent } else { ReErr::Brace });
402        }
403        // "{,n}" is "{0,n}" (GNU)
404        let lo = lo.unwrap_or(0);
405        if lo > REP_MAX || hi.is_some_and(|h| h > REP_MAX || h < lo) {
406            return Err(if hi.is_some_and(|h| h < lo) { ReErr::BraceContent } else { ReErr::TooBig });
407        }
408        Ok(Some((lo, hi)))
409    }
410    /// the repetitions after an atom
411    fn reps(&mut self, mut atom: Node) -> Result<Node, ReErr> {
412        let mut reps = 0;
413        loop {
414            // an anchor does not repeat: the "*" after it is a character (GNU)
415            if matches!(atom, Node::Edge(_)) {
416                return Ok(atom);
417            }
418            let (lo, hi) = match (self.peek(), self.peek2()) {
419                (Some('*'), _) => {
420                    self.i += 1;
421                    (0, None)
422                }
423                (Some('+'), _) if self.ere => {
424                    self.i += 1;
425                    (1, None)
426                }
427                (Some('?'), _) if self.ere => {
428                    self.i += 1;
429                    (0, Some(1))
430                }
431                (Some('\\'), Some('+')) if !self.ere => {
432                    self.i += 2;
433                    (1, None)
434                }
435                (Some('\\'), Some('?')) if !self.ere => {
436                    self.i += 2;
437                    (0, Some(1))
438                }
439                (Some('{'), _) if self.ere => {
440                    self.i += 1;
441                    match self.interval()? {
442                        Some(x) => x,
443                        None => {
444                            // "{" that starts no interval is a character
445                            self.i -= 1;
446                            return Ok(atom);
447                        }
448                    }
449                }
450                (Some('\\'), Some('{')) if !self.ere => {
451                    self.i += 2;
452                    match self.interval()? {
453                        Some(x) => x,
454                        None => return Err(ReErr::Brace),
455                    }
456                }
457                _ => return Ok(atom),
458            };
459            // x{0} and any repetition of nothing match the empty string alone: "(a*){0}" is no
460            // "a*", and "(){255}{255}..." builds nothing (it took 255^n compile steps)
461            if hi == Some(0) || atom == Node::Empty {
462                atom = Node::Empty;
463                continue;
464            }
465            // a repetition of a repetition that may be empty makes no new strings: x** is x*
466            if let Node::Rep(_, 0, None) = atom
467                && lo <= 1
468            {
469                continue;
470            }
471            // x{1} is x; a longer chain of repetitions is refused (its tree would be as deep)
472            if (lo, hi) == (1, Some(1)) {
473                continue;
474            }
475            reps += 1;
476            if reps > REPS_MAX {
477                return Err(ReErr::TooBig);
478            }
479            atom = Node::Rep(Box::new(atom), lo, hi);
480        }
481    }
482    fn atom(&mut self, first: bool) -> Result<Node, ReErr> {
483        let Some(c) = self.peek() else { return Ok(Node::Empty) };
484        self.i += 1;
485        match c {
486            '.' => Ok(Node::Any),
487            '[' => {
488                let (set, next) = match bracket(self.p, self.i, false) {
489                    Some(x) => x,
490                    None => return Err(self.bracket_err()),
491                };
492                self.i = next;
493                Ok(Node::Set(set))
494            }
495            '^' if self.ere || first => Ok(Node::Edge(Edge::Bol)),
496            '$' if self.ere || self.i == self.p.len() || self.at_close() || self.at_alt() => Ok(Node::Edge(Edge::Eol)),
497            // a repetition with nothing before it stands for itself
498            '*' => Ok(Node::Char('*')),
499            '+' | '?' if self.ere && first => Ok(Node::Char(c)),
500            '{' if self.ere && first => Ok(Node::Char('{')),
501            '(' if self.ere => self.group(),
502            '\\' => {
503                let Some(e) = self.peek() else { return Err(ReErr::Backslash) };
504                self.i += 1;
505                match e {
506                    '(' if !self.ere => self.group(),
507                    '{' if !self.ere && first => Ok(Node::Char('{')),
508                    'w' => Ok(Node::Set(Set::word(false))),
509                    'W' => Ok(Node::Set(Set::word(true))),
510                    's' => Ok(Node::Set(Set::space(false))),
511                    'S' => Ok(Node::Set(Set::space(true))),
512                    '<' => Ok(Node::Edge(Edge::WordStart)),
513                    '>' => Ok(Node::Edge(Edge::WordEnd)),
514                    'b' => Ok(Node::Edge(Edge::Word)),
515                    'B' => Ok(Node::Edge(Edge::NotWord)),
516                    'n' => Ok(Node::Char('\n')),
517                    't' => Ok(Node::Char('\t')),
518                    x => Ok(Node::Char(x)),
519                }
520            }
521            x => Ok(Node::Char(x)),
522        }
523    }
524    fn bracket_err(&self) -> ReErr {
525        // a range backwards or a class that does not exist, else the bracket is open
526        let rest = &self.p[self.i..];
527        let end = rest.iter().skip(1).position(|&c| c == ']').map(|x| x + 1);
528        match end {
529            Some(e) => {
530                let body = &rest[..e];
531                if body.windows(2).any(|w| w == ['[', ':']) {
532                    ReErr::Class
533                } else if body.windows(3).any(|w| w[1] == '-' && w[2] < w[0]) {
534                    ReErr::Range
535                } else {
536                    ReErr::Bracket
537                }
538            }
539            None => ReErr::Bracket,
540        }
541    }
542    fn group(&mut self) -> Result<Node, ReErr> {
543        // groups in groups: the parser and the compiler go down one call per level
544        if self.depth >= DEPTH_MAX {
545            return Err(ReErr::TooBig);
546        }
547        self.depth += 1;
548        let inner = self.alt()?;
549        self.depth -= 1;
550        if !self.at_close() {
551            return Err(ReErr::Paren);
552        }
553        self.i += if self.ere { 1 } else { 2 };
554        Ok(inner)
555    }
556}
557
558#[derive(Clone, Debug, PartialEq, Eq)]
559enum Inst {
560    Char(char),
561    Any,
562    Set(usize),
563    Edge(Edge),
564    Split(usize, usize),
565    Jmp(usize),
566    Match,
567}
568
569/// a compiled regular expression
570#[derive(Clone, Debug, PartialEq, Eq)]
571pub struct Regex {
572    prog: Vec<Inst>,
573    sets: Vec<Set>,
574    icase: bool,
575}
576
577struct Comp {
578    prog: Vec<Inst>,
579    sets: Vec<Set>,
580    work: usize,
581}
582
583impl Comp {
584    fn emit(&mut self, i: Inst) -> Result<usize, ReErr> {
585        if self.prog.len() >= PROG_MAX {
586            return Err(ReErr::TooBig);
587        }
588        self.prog.push(i);
589        Ok(self.prog.len() - 1)
590    }
591    fn node(&mut self, n: &Node) -> Result<(), ReErr> {
592        self.work += 1;
593        if self.work > WORK_MAX {
594            return Err(ReErr::TooBig);
595        }
596        match n {
597            Node::Empty => {}
598            Node::Char(c) => {
599                self.emit(Inst::Char(*c))?;
600            }
601            Node::Any => {
602                self.emit(Inst::Any)?;
603            }
604            Node::Set(s) => {
605                self.sets.push(s.clone());
606                let k = self.sets.len() - 1;
607                self.emit(Inst::Set(k))?;
608            }
609            Node::Edge(e) => {
610                self.emit(Inst::Edge(*e))?;
611            }
612            Node::Cat(v) => {
613                for x in v {
614                    self.node(x)?;
615                }
616            }
617            Node::Alt(v) => {
618                let mut jumps = Vec::new();
619                for (k, x) in v.iter().enumerate() {
620                    if k + 1 < v.len() {
621                        let split = self.emit(Inst::Split(0, 0))?;
622                        self.node(x)?;
623                        jumps.push(self.emit(Inst::Jmp(0))?);
624                        let next = self.prog.len();
625                        self.prog[split] = Inst::Split(split + 1, next);
626                    } else {
627                        self.node(x)?;
628                    }
629                }
630                let end = self.prog.len();
631                for j in jumps {
632                    self.prog[j] = Inst::Jmp(end);
633                }
634            }
635            Node::Rep(x, lo, hi) => {
636                for _ in 0..*lo {
637                    self.node(x)?;
638                }
639                match hi {
640                    None => {
641                        // x*
642                        let split = self.emit(Inst::Split(0, 0))?;
643                        self.node(x)?;
644                        self.emit(Inst::Jmp(split))?;
645                        let end = self.prog.len();
646                        self.prog[split] = Inst::Split(split + 1, end);
647                    }
648                    Some(h) => {
649                        // (x(x(x)?)?)? for the optional ones
650                        let mut splits = Vec::new();
651                        for _ in *lo..*h {
652                            splits.push(self.emit(Inst::Split(0, 0))?);
653                            self.node(x)?;
654                        }
655                        let end = self.prog.len();
656                        for s in splits {
657                            self.prog[s] = Inst::Split(s + 1, end);
658                        }
659                    }
660                }
661            }
662        }
663        Ok(())
664    }
665}
666
667fn is_word(c: Option<char>) -> bool {
668    c.is_some_and(|c| c.is_alphanumeric() || c == '_')
669}
670
671impl Regex {
672    /// compiles an expression; `icase`: upper and lower case are the same
673    pub fn new(pat: &str, syntax: Syntax, icase: bool) -> Result<Regex, ReErr> {
674        let p: Vec<char> = pat.chars().collect();
675        let mut ps = Parser { p: &p, i: 0, ere: syntax == Syntax::Extended, depth: 0 };
676        let node = ps.alt()?;
677        if ps.i < p.len() {
678            return Err(if ps.at_close() { ReErr::CloseParen } else { ReErr::Paren });
679        }
680        let mut c = Comp { prog: Vec::new(), sets: Vec::new(), work: 0 };
681        c.node(&node)?;
682        c.emit(Inst::Match)?;
683        Ok(Regex { prog: c.prog, sets: c.sets, icase })
684    }
685
686    /// the expression matches somewhere in s
687    pub fn is_match(&self, s: &str) -> bool {
688        self.find(s).is_some()
689    }
690
691    /// the leftmost match (the longest of those starting there): byte offsets
692    pub fn find(&self, s: &str) -> Option<(usize, usize)> {
693        self.find_at(s, 0)
694    }
695
696    /// as find, starting the search at byte `from` (the edges still see the text before it)
697    pub fn find_at(&self, s: &str, from: usize) -> Option<(usize, usize)> {
698        let chars: Vec<(usize, char)> = s.char_indices().collect();
699        let start_k = chars.iter().position(|&(b, _)| b >= from).unwrap_or(chars.len());
700        // threads: (pc, start byte) in priority order (their starts never decrease along the
701        // list); `seen` holds the position each pc was last added at
702        let mut cur: Vec<(usize, usize)> = Vec::new();
703        let mut next: Vec<(usize, usize)> = Vec::new();
704        let mut seen = vec![usize::MAX; self.prog.len()];
705        let mut stack: Vec<usize> = Vec::new();
706        let mut best: Option<(usize, usize)> = None;
707        let byte_at = |k: usize| chars.get(k).map_or(s.len(), |x| x.0);
708        let ch = |k: usize| chars.get(k).map(|x| x.1);
709        let mut k = start_k;
710        loop {
711            let prev = if k == 0 { None } else { ch(k - 1) };
712            let here = ch(k);
713            // a new thread at this position while nothing matched yet
714            if best.is_none() {
715                self.add(&mut cur, &mut seen, &mut stack, k, 0, byte_at(k), prev, here);
716            }
717            next.clear();
718            for &(pc, st) in cur.iter() {
719                let step = match &self.prog[pc] {
720                    Inst::Match => {
721                        let end = byte_at(k);
722                        if best.is_none_or(|(bs, be)| st < bs || (st == bs && end > be)) {
723                            best = Some((st, end));
724                        }
725                        false
726                    }
727                    Inst::Char(c) => here.is_some_and(|h| h == *c || (self.icase && lower(h) == lower(*c))),
728                    Inst::Any => here.is_some_and(|h| h != '\n'),
729                    Inst::Set(i) => here.is_some_and(|h| self.sets[*i].holds(h, self.icase)),
730                    _ => false,
731                };
732                if step {
733                    self.add(&mut next, &mut seen, &mut stack, k + 1, pc + 1, st, here, ch(k + 1));
734                }
735            }
736            // a thread that started after the best match's start cannot win any more
737            if let Some((bs, _)) = best {
738                next.retain(|t| t.1 <= bs);
739            }
740            if k >= chars.len() || (next.is_empty() && best.is_some()) {
741                break;
742            }
743            core::mem::swap(&mut cur, &mut next);
744            k += 1;
745        }
746        best
747    }
748
749    /// adds a thread at character `k` (prev / here: the characters around the position),
750    /// following jumps, splits and edges.  `stack` (scratch): the steps still to follow, in the
751    /// order a recursion takes them (a split's first branch with all it leads to first) -- a
752    /// recursion went one level deeper per alternative and per optional repetition
753    #[allow(clippy::too_many_arguments)]
754    fn add(&self, list: &mut Vec<(usize, usize)>, seen: &mut [usize], stack: &mut Vec<usize>, k: usize, pc: usize, st: usize, prev: Option<char>, here: Option<char>) {
755        stack.clear();
756        stack.push(pc);
757        while let Some(pc) = stack.pop() {
758            if seen[pc] == k {
759                continue;
760            }
761            seen[pc] = k;
762            match &self.prog[pc] {
763                Inst::Jmp(t) => stack.push(*t),
764                Inst::Split(a, b) => {
765                    stack.push(*b);
766                    stack.push(*a);
767                }
768                Inst::Edge(e) => {
769                    let ok = match e {
770                        Edge::Bol => prev.is_none() || prev == Some('\n'),
771                        Edge::Eol => here.is_none() || here == Some('\n'),
772                        Edge::WordStart => !is_word(prev) && is_word(here),
773                        Edge::WordEnd => is_word(prev) && !is_word(here),
774                        Edge::Word => is_word(prev) != is_word(here),
775                        Edge::NotWord => is_word(prev) == is_word(here),
776                    };
777                    if ok {
778                        stack.push(pc + 1);
779                    }
780                }
781                _ => list.push((pc, st)),
782            }
783        }
784    }
785}