Debian Codegraph @

debian/rust-vendor/fancy-regex/src/vm.rs

raw
1 // Copyright 2016 The Fancy Regex Authors.
2 //
3 // Permission is hereby granted, free of charge, to any person obtaining a copy
4 // of this software and associated documentation files (the "Software"), to deal
5 // in the Software without restriction, including without limitation the rights
6 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 // copies of the Software, and to permit persons to whom the Software is
8 // furnished to do so, subject to the following conditions:
9 //
10 // The above copyright notice and this permission notice shall be included in
11 // all copies or substantial portions of the Software.
12 //
13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 // THE SOFTWARE.
20
21 //! Backtracking VM for implementing fancy regexes.
22 //!
23 //! Read <https://swtch.com/~rsc/regexp/regexp2.html> for a good introduction for how this works.
24 //!
25 //! The VM executes a sequence of instructions (a program) against an input string. It keeps track
26 //! of a program counter (PC) and an index into the string (IX). Execution can have one or more
27 //! threads.
28 //!
29 //! One of the basic instructions is `Lit`, which matches a string against the input. If it matches,
30 //! the PC advances to the next instruction and the IX to the position after the matched string.
31 //! If not, the current thread is stopped because it failed.
32 //!
33 //! If execution reaches an `End` instruction, the program is successful because a match was found.
34 //! If there are no more threads to execute, the program has failed to match.
35 //!
36 //! A very simple program for the regex `a`:
37 //!
38 //! ```text
39 //! 0: Lit("a")
40 //! 1: End
41 //! ```
42 //!
43 //! The `Split` instruction causes execution to split into two threads. The first thread is executed
44 //! with the current string index. If it fails, we reset the string index and resume execution with
45 //! the second thread. That is what "backtracking" refers to. In order to do that, we keep a stack
46 //! of threads (PC and IX) to try.
47 //!
48 //! Example program for the regex `ab|ac`:
49 //!
50 //! ```text
51 //! 0: Split(1, 4)
52 //! 1: Lit("a")
53 //! 2: Lit("b")
54 //! 3: Jmp(6)
55 //! 4: Lit("a")
56 //! 5: Lit("c")
57 //! 6: End
58 //! ```
59 //!
60 //! The `Jmp` instruction causes execution to jump to the specified instruction. In the example it
61 //! is needed to separate the two threads.
62 //!
63 //! Let's step through execution with that program for the input `ac`:
64 //!
65 //! 1. We're at PC 0 and IX 0
66 //! 2. `Split(1, 4)` means we save a thread with PC 4 and IX 0 for trying later
67 //! 3. Continue at `Lit("a")` which matches, so we advance IX to 1
68 //! 4. `Lit("b")` doesn't match at IX 1 (`"b" != "c"`), so the thread fails
69 //! 5. We continue with the previously saved thread at PC 4 and IX 0 (backtracking)
70 //! 6. Both `Lit("a")` and `Lit("c")` match and we reach `End` -> successful match (index 0 to 2)
71
72 use alloc::boxed::Box;
73 use alloc::string::String;
74 #[cfg(feature = "variable-lookbehinds")]
75 use alloc::sync::Arc;
76 use alloc::vec;
77 use alloc::vec::Vec;
78 use core::fmt;
79 use regex_automata::meta::Regex;
80 use regex_automata::util::look::LookMatcher;
81 use regex_automata::util::pool::Pool;
82 use regex_automata::util::primitives::NonMaxUsize;
83 use regex_automata::Anchored;
84 use regex_automata::Input;
85
86 #[cfg(feature = "variable-lookbehinds")]
87 pub(crate) type CachePoolFn = alloc::boxed::Box<
88 dyn Fn() -> regex_automata::hybrid::dfa::Cache
89 + Send
90 + Sync
91 + core::panic::UnwindSafe
92 + core::panic::RefUnwindSafe,
93 >;
94
95 use crate::error::RuntimeError;
96 use crate::input::{Input as HaystackInput, RegexInput};
97 use crate::Assertion;
98 use crate::BytesMode;
99 use crate::Error;
100 use crate::Formatter;
101 use crate::Result;
102 use crate::{codepoint_len, HardRegexRuntimeOptions};
103
104 /// Enable tracing of VM execution. Only for debugging/investigating.
105 const OPTION_TRACE: u32 = 1 << 0;
106 /// When iterating over all matches within a text (e.g. with `find_iter`), empty matches need to be
107 /// handled specially. If we kept matching at the same position, we'd never stop. So what we do
108 /// after we've had an empty match, is to advance the position where matching is attempted.
109 /// If `\G` is used in the pattern, that means it no longer matches. If we didn't tell the VM about
110 /// the fact that we skipped because of an empty match, it would still treat `\G` as matching. So
111 /// this option is for communicating that to the VM. Phew.
112 pub(crate) const OPTION_NOT_CONTINUED_FROM_PREVIOUS_MATCH: u32 = 1 << 1;
113 /// When this option is set, the VM will reject any match where the engine consumed no characters.
114 /// \K is ignored as part of this check - so empty matches can still be reported if the engine
115 /// consumed characters and then \K was used afterwards.
116 pub(crate) const OPTION_FIND_NOT_EMPTY: u32 = 1 << 2;
117 #[cfg(feature = "leftmost_longest")]
118 /// When set, the VM uses leftmost-longest match semantics instead of leftmost-first.
119 pub(crate) const OPTION_LEFTMOST_LONGEST: u32 = 1 << 3;
120
121 // TODO: make configurable
122 const MAX_STACK: usize = 1_000_000;
123
124 /// Represents a range of capture groups by storing the first and last group numbers.
125 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
126 pub struct CaptureGroupRange(pub usize, pub usize);
127
128 impl CaptureGroupRange {
129 /// Returns the start (first) group number.
130 pub fn start(&self) -> usize {
131 self.0
132 }
133
134 /// Returns the end (last) group number.
135 pub fn end(&self) -> usize {
136 self.1
137 }
138
139 /// Converts this range to an Option, returning None if start equals end (no capture groups).
140 pub fn to_option_if_non_empty(self) -> Option<Self> {
141 if self.start() == self.end() {
142 None
143 } else {
144 Some(self)
145 }
146 }
147 }
148
149 /// Matches a single character class (e.g. `\d`, `[a-z]`, `\w`) without building
150 /// a regex-automata engine.
151 ///
152 /// Most "fancy" patterns interleave plain character classes with the features
153 /// that force backtracking (look-around, back-references, ...). Each such class
154 /// would otherwise be compiled to a full delegated `meta::Regex` whose
155 /// construction (NFA + reverse NFA + lazy DFA) dominates both compile time and
156 /// memory — and which is then searched, anchored, once per character inside the
157 /// backtracking loop. Because a class matches exactly one codepoint/byte, we can
158 /// instead test membership directly here, which is cheaper to build *and* faster
159 /// to match than calling into the engine.
160 ///
161 /// The ranges are taken verbatim from the `regex-syntax` `Hir` for the class
162 /// (sorted, non-overlapping, and already case-folded / Unicode-expanded), so the
163 /// matched set is identical to what the delegated engine would accept.
164 #[derive(Clone, PartialEq, Eq)]
165 pub enum CharClassMatcher {
166 /// Match one Unicode scalar value against inclusive `char` ranges. Used in
167 /// Unicode bytes mode, where the haystack is valid UTF-8.
168 Codepoint {
169 ranges: Box<[(char, char)]>,
170 name: Option<String>,
171 },
172 /// Match one byte against inclusive byte ranges. Used in ASCII bytes mode
173 /// (and for ASCII-only `(?-u:...)` classes).
174 Byte {
175 ranges: Box<[(u8, u8)]>,
176 name: Option<String>,
177 },
178 }
179
180 impl fmt::Debug for CharClassMatcher {
181 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182 if let Some(ref name) = match self {
183 CharClassMatcher::Codepoint { name, .. } => name,
184 CharClassMatcher::Byte { name, .. } => name,
185 } {
186 match self {
187 CharClassMatcher::Codepoint { .. } => write!(f, "Codepoint {}", name),
188 CharClassMatcher::Byte { .. } => write!(f, "Byte {}", name),
189 }
190 } else {
191 match self {
192 CharClassMatcher::Codepoint { ranges, .. } => {
193 f.debug_tuple("Codepoint").field(ranges).finish()
194 }
195 CharClassMatcher::Byte { ranges, .. } => {
196 f.debug_tuple("Byte").field(ranges).finish()
197 }
198 }
199 }
200 }
201 }
202
203 impl CharClassMatcher {
204 /// If the character at `ix` is in the class, returns the number of bytes it
205 /// occupies (so the caller can advance). Returns `None` on no match or at the
206 /// end of input.
207 #[inline]
208 fn match_len<S: HaystackInput + ?Sized>(&self, s: &S, ix: usize) -> Option<usize> {
209 let bytes = s.as_bytes();
210 if ix >= bytes.len() {
211 return None;
212 }
213 match self {
214 CharClassMatcher::Byte { ranges, .. } => {
215 if range_contains(ranges, bytes[ix]) {
216 Some(1)
217 } else {
218 None
219 }
220 }
221 CharClassMatcher::Codepoint { ranges, .. } => {
222 let len = codepoint_len(bytes[ix]);
223 let end = ix + len;
224 if end > bytes.len() {
225 return None;
226 }
227 // The haystack is valid UTF-8 in Unicode mode, so this decodes the
228 // codepoint; the `?` is a safety net for an unexpected boundary.
229 let c = core::str::from_utf8(&bytes[ix..end]).ok()?.chars().next()?;
230 if range_contains(ranges, c) {
231 Some(len)
232 } else {
233 None
234 }
235 }
236 }
237 }
238 }
239
240 /// A case-insensitive literal, matched natively by the VM instead of being
241 /// delegated to a `meta::Regex` engine.
242 ///
243 /// A case-insensitive alternation branch such as `(?i)abort` is a run of
244 /// literal characters; delegating each branch to its own engine makes build
245 /// cost scale with the number of branches. Like [`CharClassMatcher`],
246 /// membership can be tested directly: one sorted range set per original
247 /// character, holding its Unicode simple case-fold class (a singleton for
248 /// case-sensitive characters). The fold classes come from `regex-syntax`, so
249 /// the matched set is identical to what the delegated `(?i)` engine would
250 /// accept — including width-changing variants such as `k` ↔ U+212A KELVIN
251 /// SIGN, which is why matching advances codepoint by codepoint instead of
252 /// assuming the literal's own byte length.
253 ///
254 /// Only built in Unicode bytes mode (the haystack is valid UTF-8).
255 #[derive(Clone, Debug, PartialEq, Eq)]
256 pub struct CaseiLiteral {
257 chars: Box<[FoldRanges]>,
258 }
259
260 /// The characters matching one literal character, as sorted inclusive ranges
261 /// (its simple case-fold class, or a singleton when case-sensitive).
262 pub(crate) type FoldRanges = Box<[(char, char)]>;
263
264 impl CaseiLiteral {
265 pub(crate) fn new(chars: Box<[FoldRanges]>) -> Self {
266 CaseiLiteral { chars }
267 }
268
269 /// If the literal matches at `ix`, returns the matched byte length (which
270 /// can differ from the literal's own length under folding). `None` on no
271 /// match or end of input.
272 fn match_len<S: HaystackInput + ?Sized>(&self, s: &S, ix: usize) -> Option<usize> {
273 let bytes = s.as_bytes();
274 let mut pos = ix;
275 for ranges in self.chars.iter() {
276 if pos >= bytes.len() {
277 return None;
278 }
279 let len = codepoint_len(bytes[pos]);
280 let end = pos + len;
281 if end > bytes.len() {
282 return None;
283 }
284 // The haystack is valid UTF-8 in Unicode mode, so this decodes the
285 // codepoint; the `?` is a safety net for an unexpected boundary.
286 let c = core::str::from_utf8(&bytes[pos..end])
287 .ok()?
288 .chars()
289 .next()?;
290 if !range_contains(ranges.as_ref(), c) {
291 return None;
292 }
293 pos = end;
294 }
295 Some(pos - ix)
296 }
297 }
298
299 /// Binary-searches `ranges` (sorted, non-overlapping, inclusive) for `needle`.
300 #[inline]
301 fn range_contains<T: Ord + Copy>(ranges: &[(T, T)], needle: T) -> bool {
302 ranges
303 .binary_search_by(|&(lo, hi)| {
304 if needle < lo {
305 core::cmp::Ordering::Greater
306 } else if needle > hi {
307 core::cmp::Ordering::Less
308 } else {
309 core::cmp::Ordering::Equal
310 }
311 })
312 .is_ok()
313 }
314
315 #[derive(Clone)]
316 /// Delegate matching to the regex crate
317 pub struct Delegate {
318 /// The regex
319 pub inner: Regex,
320 /// The regex pattern as a string
321 pub pattern: String,
322 /// The range of capture groups. None if there are no capture groups.
323 pub capture_groups: Option<CaptureGroupRange>,
324 }
325
326 impl core::fmt::Debug for Delegate {
327 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
328 // Ensures it fails to compile if the struct changes
329 let Self {
330 inner: _,
331 pattern,
332 capture_groups,
333 } = self;
334
335 f.debug_struct("Delegate")
336 .field("pattern", pattern)
337 .field("capture_groups", capture_groups)
338 .finish()
339 }
340 }
341
342 /// Seek pre-filter: find the next plausible match position using a simplified approximation of the
343 /// pattern, then hand off to the backtracking VM at that position.
344 pub struct Seek {
345 /// The compiled seek pre-filter regex (un-anchored, finds leftmost match).
346 pub inner: Regex,
347 /// The seek-pattern string (for debug display).
348 pub pattern: String,
349 }
350
351 impl core::fmt::Debug for Seek {
352 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
353 // Ensures it fails to compile if the struct changes
354 let Self { inner: _, pattern } = self;
355
356 f.debug_struct("Seek").field("pattern", pattern).finish()
357 }
358 }
359
360 #[cfg(feature = "variable-lookbehinds")]
361 /// Delegate matching in reverse to regex-automata
362 pub struct ReverseBackwardsDelegate {
363 /// The regex pattern as a string which will be matched in reverse, in a backwards direction
364 pub pattern: String,
365 /// The delegate regex to match backwards (wrapped in Arc for efficient cloning)
366 pub(crate) dfa: Arc<regex_automata::hybrid::dfa::DFA>,
367 /// Cache pool for DFA searches
368 pub(crate) cache_pool: Pool<regex_automata::hybrid::dfa::Cache, CachePoolFn>,
369 /// The forward regex for capture group extraction
370 pub(crate) capture_group_extraction_inner: Option<Regex>,
371 /// The range of capture groups. None if there are no capture groups.
372 pub capture_groups: Option<CaptureGroupRange>,
373 }
374
375 #[cfg(feature = "variable-lookbehinds")]
376 impl Clone for ReverseBackwardsDelegate {
377 fn clone(&self) -> Self {
378 let dfa_for_closure = Arc::clone(&self.dfa);
379 let create: CachePoolFn = alloc::boxed::Box::new(move || dfa_for_closure.create_cache());
380 Self {
381 pattern: self.pattern.clone(),
382 cache_pool: Pool::new(create),
383 dfa: Arc::clone(&self.dfa),
384 capture_group_extraction_inner: self.capture_group_extraction_inner.clone(),
385 capture_groups: self.capture_groups,
386 }
387 }
388 }
389
390 #[cfg(feature = "variable-lookbehinds")]
391 impl core::fmt::Debug for ReverseBackwardsDelegate {
392 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
393 // Ensures it fails to compile if the struct changes
394 let Self {
395 pattern,
396 dfa: _,
397 cache_pool: _,
398 capture_group_extraction_inner: _,
399 capture_groups,
400 } = self;
401
402 f.debug_struct("ReverseBackwardsDelegate")
403 .field("pattern", pattern)
404 .field("capture_groups", capture_groups)
405 .finish()
406 }
407 }
408
409 /// Instruction of the VM.
410 #[derive(Debug)]
411 pub enum Insn {
412 /// Successful end of program
413 End,
414 /// Match any character (including newline)
415 Any,
416 /// Match any character except for the line feed character (`\n`)
417 AnyNoNL,
418 /// Match any character except for a carriage return or line feed character (`\r` or `\n`)
419 AnyNoCRLF,
420 /// Assertions
421 Assertion(Assertion),
422 /// Match the literal string at the current index
423 Lit(String),
424 /// Match a case-insensitive literal at the current index, without
425 /// delegating to a regex-automata engine.
426 LitCasei(CaseiLiteral),
427 /// Match a single character class (e.g. `\d`, `[a-z]`) at the current index,
428 /// without delegating to a regex-automata engine.
429 CharClass(CharClassMatcher),
430 /// Split execution into two threads. The two fields are positions of instructions. Execution
431 /// first tries the first thread. If that fails, the second position is tried.
432 Split(usize, usize),
433 /// Like `Split`, but also updates `match_attempt_start` for `OPTION_FIND_NOT_EMPTY` tracking.
434 /// Used exclusively for the unanchored search preamble.
435 SplitUnanchored(usize, usize),
436 /// Jump to instruction at position
437 Jmp(usize),
438 /// Save the current string index into the specified slot
439 Save(usize),
440 /// Save `0` into the specified slot
441 Save0(usize),
442 /// Save the current string index into the specified capture group start slot if the capture group is empty
443 /// or has already completed.
444 SaveCaptureGroupStart(usize),
445 /// Set the string index to the value that was saved in the specified slot
446 Restore(usize),
447 /// Repeat greedily (match as much as possible)
448 RepeatGr {
449 /// Minimum number of matches
450 lo: usize,
451 /// Maximum number of matches
452 hi: usize,
453 /// The instruction after the repeat
454 next: usize,
455 /// The slot for keeping track of the number of repetitions
456 repeat: usize,
457 },
458 /// Repeat non-greedily (prefer matching as little as possible)
459 RepeatNg {
460 /// Minimum number of matches
461 lo: usize,
462 /// Maximum number of matches
463 hi: usize,
464 /// The instruction after the repeat
465 next: usize,
466 /// The slot for keeping track of the number of repetitions
467 repeat: usize,
468 },
469 /// Repeat greedily and prevent infinite loops from empty matches
470 RepeatEpsilonGr {
471 /// Minimum number of matches
472 lo: usize,
473 /// The instruction after the repeat
474 next: usize,
475 /// The slot for keeping track of the number of repetitions
476 repeat: usize,
477 /// The slot for saving the previous IX to check if we had an empty match
478 check: usize,
479 },
480 /// Repeat non-greedily and prevent infinite loops from empty matches
481 RepeatEpsilonNg {
482 /// Minimum number of matches
483 lo: usize,
484 /// The instruction after the repeat
485 next: usize,
486 /// The slot for keeping track of the number of repetitions
487 repeat: usize,
488 /// The slot for saving the previous IX to check if we had an empty match
489 check: usize,
490 },
491 /// Negative look-around failed
492 FailNegativeLookAround,
493 /// Set IX back by the specified number of characters
494 GoBack(usize),
495 /// Back reference to a group number to check
496 Backref {
497 /// The save slot representing the start of the capture group
498 slot: usize,
499 /// Whether the backref should be matched case insensitively
500 casei: bool,
501 /// Whether Unicode mode is enabled (affects case folding behavior)
502 unicode: bool,
503 },
504 /// Begin of atomic group
505 BeginAtomic,
506 /// End of atomic group
507 EndAtomic,
508 /// Delegate matching to the regex crate
509 Delegate(Delegate),
510 /// Anchor to match at the position where the previous match ended
511 ContinueFromPreviousMatchEnd {
512 /// Whether this is at the start of the pattern (allowing early exit on failure)
513 at_start: bool,
514 },
515 /// Continue only if the specified capture group has already been populated as part of the match
516 BackrefExistsCondition(usize),
517 /// Immediately fail the current match attempt and trigger backtracking.
518 /// This is used for backtracking control verbs like `(*FAIL)`.
519 Fail,
520 #[cfg(feature = "variable-lookbehinds")]
521 /// Reverse lookbehind using regex-automata for variable-sized patterns
522 BackwardsDelegate(ReverseBackwardsDelegate),
523 /// Absent repeater operator - matches if delegate does not match from current position
524 AbsentRepeater(Delegate),
525 /// Seek pre-filter: advance `ix` to the next position where the pattern could plausibly match,
526 /// using an over-approximating regular expression. Replaces the `SplitUnanchored` / `Any` /
527 /// `Jmp` preamble for hard patterns when a useful seek approximation is available.
528 ///
529 /// Execution:
530 /// 1. Search `s[ix..]` un-anchored for the seek regex.
531 /// 2. If no match exists, return `None` immediately (the full pattern can never match).
532 /// 3. Otherwise push a backtrack branch `(pc, next_seek_start)` where `next_seek_start` is
533 /// one codepoint past the match start (or end for zero-width matches), set
534 /// `match_attempt_start = m.start()`, and continue from `pc+1` with `ix = m.start()`.
535 Seek(Seek),
536 /// For compatibility with Oniguruma, which ignores empty matches at the end of the input
537 /// if the previous character was a line break. So ^/$ and (?=) all fail to match, unless
538 /// \z was used and matched at this position.
539 RejectEmptyMatchAtEOFFollowingNewline,
540 }
541
542 /// Reusable per-run working memory: the backtracking [`State`] plus the slot
543 /// buffer used when calling delegated engines. Pooled on the [`Prog`] so that
544 /// repeated runs (every `find_iter` step, every `RegexSet` candidate
545 /// verification) don't re-allocate it; `run` resets it before use.
546 #[derive(Debug)]
547 struct Scratch {
548 state: State,
549 inner_slots: Vec<Option<NonMaxUsize>>,
550 }
551
552 fn new_scratch() -> Scratch {
553 Scratch {
554 state: State::new(0, MAX_STACK, 0),
555 inner_slots: Vec::new(),
556 }
557 }
558
559 /// Sequence of instructions for the VM to execute.
560 #[derive(Debug)]
561 pub struct Prog {
562 /// Instructions of the program
563 pub body: Vec<Insn>,
564 n_saves: usize,
565 /// How the VM advances positions: byte-level (Ascii) vs codepoint-level (Unicode/UnicodeBytes).
566 bytes_mode: BytesMode,
567 /// A pattern compatible with a DFA which can be used to seek to candidate positions where the real/full pattern might match
568 pub(crate) seek_pattern: String,
569 scratch_pool: Pool<Scratch, fn() -> Scratch>,
570 /// Maximum number of bytes this pattern can match. When `leftmost_longest` is enabled and a match
571 /// of this length is found, no longer match is possible, so backtracking can stop early.
572 pub max_size: usize,
573 }
574
575 impl Prog {
576 pub(crate) fn new(
577 body: Vec<Insn>,
578 n_saves: usize,
579 bytes_mode: BytesMode,
580 seek_pattern: String,
581 max_size: usize,
582 ) -> Prog {
583 Prog {
584 body,
585 n_saves,
586 bytes_mode,
587 seek_pattern,
588 scratch_pool: Pool::new(new_scratch),
589 max_size,
590 }
591 }
592
593 #[doc(hidden)]
594 pub(crate) fn debug_print(&self, writer: &mut Formatter<'_>) -> core::fmt::Result {
595 for (i, insn) in self.body.iter().enumerate() {
596 writeln!(writer, "{:3}: {:?}", i, insn)?;
597 }
598 Ok(())
599 }
600 }
601
602 #[derive(Debug)]
603 struct Branch {
604 pc: usize,
605 ix: usize,
606 nsave: usize,
607 }
608
609 #[derive(Debug)]
610 struct Save {
611 slot: usize,
612 value: usize,
613 }
614
615 #[derive(Debug)]
616 struct State {
617 /// Saved values indexed by slot. Mostly indices to s, but can be repeat values etc.
618 /// Always contains the saves of the current state.
619 saves: Vec<usize>,
620 /// Stack of backtrack branches.
621 stack: Vec<Branch>,
622 /// Old saves (slot, value)
623 oldsave: Vec<Save>,
624 /// Number of saves at the end of `oldsave` that need to be restored to `saves` on pop
625 nsave: usize,
626 explicit_sp: usize,
627 /// Maximum size of the stack. If the size would be exceeded during execution, a `StackOverflow`
628 /// error is raised.
629 max_stack: usize,
630 #[allow(dead_code)]
631 options: u32,
632 /// Reusable buffer for `backtrack_cut`'s slot dedup, kept to avoid
633 /// allocating on every atomic-group exit.
634 cut_scratch: Vec<usize>,
635 }
636
637 // Each element in the stack conceptually represents the entire state
638 // of the machine: the pc (index into prog), the index into the
639 // string, and the entire vector of saves. However, copying the save
640 // vector on every push/pop would be inefficient, so instead we use a
641 // copy-on-write approach for each slot within the save vector. The
642 // top `nsave` elements in `oldsave` represent the delta from the
643 // current machine state to the top of stack.
644
645 impl State {
646 fn new(n_saves: usize, max_stack: usize, options: u32) -> State {
647 State {
648 saves: vec![usize::MAX; n_saves],
649 stack: Vec::new(),
650 oldsave: Vec::new(),
651 nsave: 0,
652 explicit_sp: n_saves,
653 max_stack,
654 options,
655 cut_scratch: Vec::new(),
656 }
657 }
658
659 /// Reset for a fresh run, keeping the allocated buffers.
660 fn reset(&mut self, n_saves: usize, options: u32) {
661 self.saves.clear();
662 self.saves.resize(n_saves, usize::MAX);
663 self.stack.clear();
664 self.oldsave.clear();
665 self.nsave = 0;
666 self.explicit_sp = n_saves;
667 self.options = options;
668 }
669
670 // push a backtrack branch
671 fn push(&mut self, pc: usize, ix: usize) -> Result<()> {
672 if self.stack.len() < self.max_stack {
673 let nsave = self.nsave;
674 self.stack.push(Branch { pc, ix, nsave });
675 self.nsave = 0;
676 self.trace_stack("push");
677 Ok(())
678 } else {
679 Err(Error::RuntimeError(RuntimeError::StackOverflow))
680 }
681 }
682
683 // pop a backtrack branch
684 fn pop(&mut self) -> (usize, usize) {
685 for _ in 0..self.nsave {
686 let Save { slot, value } = self.oldsave.pop().unwrap();
687 self.saves[slot] = value;
688 }
689 let Branch { pc, ix, nsave } = self.stack.pop().unwrap();
690 self.nsave = nsave;
691 self.trace_stack("pop");
692 (pc, ix)
693 }
694
695 fn save(&mut self, slot: usize, val: usize) {
696 for i in 0..self.nsave {
697 // could avoid this iteration with some overhead; worth it?
698 if self.oldsave[self.oldsave.len() - i - 1].slot == slot {
699 // already saved, just update
700 self.saves[slot] = val;
701 return;
702 }
703 }
704 self.oldsave.push(Save {
705 slot,
706 value: self.saves[slot],
707 });
708 self.nsave += 1;
709 self.saves[slot] = val;
710
711 #[cfg(feature = "std")]
712 if self.options & OPTION_TRACE != 0 {
713 println!("saves: {:?}", self.saves);
714 }
715 }
716
717 fn get(&self, slot: usize) -> usize {
718 self.saves[slot]
719 }
720
721 // push a value onto the explicit stack; note: the entire contents of
722 // the explicit stack is saved and restored on backtrack.
723 fn stack_push(&mut self, val: usize) {
724 if self.saves.len() == self.explicit_sp {
725 self.saves.push(self.explicit_sp + 1);
726 }
727 let explicit_sp = self.explicit_sp;
728 let sp = self.get(explicit_sp);
729 if self.saves.len() == sp {
730 self.saves.push(val);
731 } else {
732 self.save(sp, val);
733 }
734 self.save(explicit_sp, sp + 1);
735 }
736
737 // pop a value from the explicit stack
738 fn stack_pop(&mut self) -> usize {
739 let explicit_sp = self.explicit_sp;
740 let sp = self.get(explicit_sp) - 1;
741 let result = self.get(sp);
742 self.save(explicit_sp, sp);
743 result
744 }
745
746 /// Get the current number of backtrack branches
747 fn backtrack_count(&self) -> usize {
748 self.stack.len()
749 }
750
751 /// Discard backtrack branches that were pushed since the call to `backtrack_count`.
752 ///
753 /// What we want:
754 /// * Keep the current `saves` as they are
755 /// * Only keep `count` backtrack branches on `stack`, discard the rest
756 /// * Keep the first `oldsave` for each slot, discard the rest (multiple pushes might have
757 /// happened with saves to the same slot)
758 fn backtrack_cut(&mut self, count: usize) {
759 if self.stack.len() == count {
760 // no backtrack branches to discard, all good
761 return;
762 }
763 // start and end indexes of old saves for the branch we're cutting to
764 let (oldsave_start, oldsave_end) = {
765 let mut end = self.oldsave.len() - self.nsave;
766 for &Branch { nsave, .. } in &self.stack[count + 1..] {
767 end -= nsave;
768 }
769 let start = end - self.stack[count].nsave;
770 (start, end)
771 };
772 // The seen-slot set is a plain Vec with linear lookup: per-branch save
773 // counts are small, and this avoids allocating on every atomic-group
774 // exit (the buffer is reused across calls).
775 let mut saved = core::mem::take(&mut self.cut_scratch);
776 saved.clear();
777 // keep all the old saves of our branch (they're all for different slots)
778 for &Save { slot, .. } in &self.oldsave[oldsave_start..oldsave_end] {
779 saved.push(slot);
780 }
781 let mut oldsave_ix = oldsave_end;
782 // for other old saves, keep them only if they're for a slot that we haven't saved yet
783 for ix in oldsave_end..self.oldsave.len() {
784 let Save { slot, .. } = self.oldsave[ix];
785 let new_slot = !saved.contains(&slot);
786 if new_slot {
787 saved.push(slot);
788 // put the save we want to keep (ix) after the ones we already have (oldsave_ix)
789 // note that it's fine if the indexes are the same (then swapping is a no-op)
790 self.oldsave.swap(oldsave_ix, ix);
791 oldsave_ix += 1;
792 }
793 }
794 self.stack.truncate(count);
795 self.oldsave.truncate(oldsave_ix);
796 self.nsave = oldsave_ix - oldsave_start;
797 self.cut_scratch = saved;
798 }
799
800 #[inline]
801 #[allow(unused_variables)]
802 fn trace_stack(&self, operation: &str) {
803 #[cfg(feature = "std")]
804 if self.options & OPTION_TRACE != 0 {
805 println!("stack after {}: {:?}", operation, self.stack);
806 }
807 }
808 }
809
810 fn codepoint_len_at<S: HaystackInput + ?Sized>(s: &S, ix: usize) -> usize {
811 codepoint_len(s.as_bytes()[ix])
812 }
813
814 /// Returns the number of bytes to advance forward from `ix`, respecting the bytes mode.
815 /// In `Ascii` mode, always advances 1 byte. In `Unicode`/`UnicodeBytes` mode, advances
816 /// by the full codepoint length at `ix`.
817 #[inline]
818 fn advance_one<S: HaystackInput + ?Sized>(s: &S, ix: usize, bytes_mode: BytesMode) -> usize {
819 match bytes_mode {
820 BytesMode::Ascii => 1,
821 _ => codepoint_len_at(s, ix),
822 }
823 }
824
825 /// Returns the previous position before `ix`, respecting the bytes mode.
826 /// In `Ascii` mode, simply returns `ix - 1`. In `Unicode`/`UnicodeBytes` mode,
827 /// skips backward over UTF-8 continuation bytes.
828 #[inline]
829 fn prev_ix<S: HaystackInput + ?Sized>(s: &S, ix: usize, bytes_mode: BytesMode) -> usize {
830 match bytes_mode {
831 BytesMode::Ascii => ix - 1,
832 _ => s.prev_codepoint_ix(ix),
833 }
834 }
835
836 #[inline]
837 fn matches_literal<S: HaystackInput + ?Sized>(
838 s: &S,
839 ix: usize,
840 end: usize,
841 literal: &[u8],
842 ) -> bool {
843 // Compare as bytes because the literal might be a single byte char whereas ix
844 // points to a multibyte char. Comparing with str would result in an error like
845 // "byte index N is not a char boundary".
846 end <= s.len() && &s.as_bytes()[ix..end] == literal
847 }
848
849 fn matches_literal_casei_unicode(text: &str, literal: &str) -> bool {
850 let mut text_chars = text.chars();
851 let mut literal_chars = literal.chars();
852 loop {
853 match (text_chars.next(), literal_chars.next()) {
854 (None, None) => return true,
855 (Some(t), Some(l)) => {
856 if t == l {
857 continue;
858 }
859 if t.is_ascii() && l.is_ascii() {
860 if t.eq_ignore_ascii_case(&l) {
861 continue;
862 }
863 return false;
864 }
865 if !chars_fold_equal(t, l) {
866 return false;
867 }
868 }
869 // One string ended before the other: not equal under folding.
870 _ => return false,
871 }
872 }
873 }
874
875 /// Whether two codepoints are equal under Unicode simple case folding — the
876 /// same equivalence a case-insensitive engine literal uses.
877 fn chars_fold_equal(a: char, b: char) -> bool {
878 use regex_syntax::hir::{ClassUnicode, ClassUnicodeRange};
879 let mut class = ClassUnicode::new([ClassUnicodeRange::new(a, a)]);
880 match class.try_case_fold_simple() {
881 Ok(()) => class
882 .ranges()
883 .iter()
884 .any(|r| r.start() <= b && b <= r.end()),
885 // Case-folding tables unavailable (regex-syntax built without
886 // unicode-case): exact comparison already failed, so no match.
887 Err(_) => false,
888 }
889 }
890
891 fn matches_literal_casei<S: HaystackInput + ?Sized>(
892 s: &S,
893 ix: usize,
894 end: usize,
895 literal: &[u8],
896 unicode: bool,
897 ) -> bool {
898 if end > s.len() {
899 return false;
900 }
901 if matches_literal(s, ix, end, literal) {
902 return true;
903 }
904 if !s.is_char_boundary(ix) || !s.is_char_boundary(end) {
905 return false;
906 }
907 let text_bytes = &s.as_bytes()[ix..end];
908 if text_bytes.is_ascii() && literal.is_ascii() {
909 return text_bytes.eq_ignore_ascii_case(literal);
910 }
911 if !unicode {
912 // ASCII-only case folding: if content is not ASCII, no match
913 return false;
914 }
915 // text captured and being backreferenced is not ascii, so we utilize regex-automata's case insensitive matching
916 if let (Ok(text_str), Ok(lit_str)) = (
917 core::str::from_utf8(text_bytes),
918 core::str::from_utf8(literal),
919 ) {
920 return matches_literal_casei_unicode(text_str, lit_str);
921 }
922 false
923 }
924
925 /// Helper function to store capture group positions from inner_slots into state.
926 /// This is used by both Delegate and BackwardsDelegate instructions.
927 #[inline]
928 fn store_capture_groups(
929 state: &mut State,
930 inner_slots: &[Option<NonMaxUsize>],
931 range: CaptureGroupRange,
932 skip_earlier_captures: bool,
933 ) {
934 let start_group = range.start();
935 let end_group = range.end();
936 for i in 0..(end_group - start_group) {
937 let slot = (start_group + i) * 2;
938 if let Some(start) = inner_slots[(i + 1) * 2] {
939 let end = inner_slots[(i + 1) * 2 + 1].unwrap();
940
941 let mut save = !skip_earlier_captures;
942 if skip_earlier_captures {
943 let existing_start = state.get(slot);
944 let existing_end = state.get(slot + 1);
945 save = (start.get() >= existing_start || existing_start == usize::MAX)
946 && (end.get() >= existing_end || existing_end == usize::MAX);
947 }
948 if save {
949 state.save(slot, start.get());
950 state.save(slot + 1, end.get());
951 }
952 }
953 }
954 }
955
956 #[cfg(feature = "leftmost_longest")]
957 #[inline]
958 fn apply_best_saves(state: &mut State, best_saves: &Option<Vec<usize>>) -> bool {
959 if let Some(saves) = best_saves {
960 state.saves.copy_from_slice(saves);
961 true
962 } else {
963 false
964 }
965 }
966
967 /// Run the program with trace printing for debugging.
968 pub fn run_trace(prog: &Prog, s: &str, pos: usize) -> Result<Option<Vec<usize>>> {
969 run(
970 prog,
971 &RegexInput::new(s).from_pos(pos),
972 OPTION_TRACE,
973 &HardRegexRuntimeOptions::default(),
974 )
975 }
976
977 /// Run the program with default options.
978 pub fn run_default(prog: &Prog, s: &str, pos: usize) -> Result<Option<Vec<usize>>> {
979 run(
980 prog,
981 &RegexInput::new(s).from_pos(pos),
982 0,
983 &HardRegexRuntimeOptions::default(),
984 )
985 }
986
987 /// Run the program with options, returning the full saves vector on a match.
988 pub(crate) fn run<S: HaystackInput + ?Sized>(
989 prog: &Prog,
990 input: &RegexInput<'_, S>,
991 option_flags: u32,
992 options: &HardRegexRuntimeOptions,
993 ) -> Result<Option<Vec<usize>>> {
994 // The clone is the one allocation the caller keeps (it owns the captures).
995 run_with(prog, input, option_flags, options, |state| {
996 state.saves.clone()
997 })
998 }
999
1000 /// Run the program with options, returning only the overall match span.
1001 ///
1002 /// Unlike [`run`], nothing is moved out of the pooled scratch, so `is_match`,
1003 /// `find`, `find_iter`, and RegexSet verification are allocation-free per call
1004 /// (after buffers have grown to steady state).
1005 pub(crate) fn run_spans<S: HaystackInput + ?Sized>(
1006 prog: &Prog,
1007 input: &RegexInput<'_, S>,
1008 option_flags: u32,
1009 options: &HardRegexRuntimeOptions,
1010 ) -> Result<Option<(usize, usize)>> {
1011 run_with(prog, input, option_flags, options, |state| {
1012 (state.get(0), state.get(1))
1013 })
1014 }
1015
1016 /// Run the program with options; `extract` pulls the result out of the final
1017 /// state before the scratch returns to the pool.
1018 #[allow(clippy::cognitive_complexity)]
1019 fn run_with<S: HaystackInput + ?Sized, T>(
1020 prog: &Prog,
1021 input: &RegexInput<'_, S>,
1022 option_flags: u32,
1023 options: &HardRegexRuntimeOptions,
1024 extract: impl FnOnce(&State) -> T,
1025 ) -> Result<Option<T>> {
1026 if input.is_done() {
1027 return Ok(None);
1028 }
1029 let haystack = input.haystack();
1030 let pos = input.effective_start();
1031 let match_range = input.get_range();
1032 let mut scratch_guard = prog.scratch_pool.get();
1033 let Scratch { state, inner_slots } = &mut *scratch_guard;
1034 state.reset(prog.n_saves, option_flags);
1035 inner_slots.clear();
1036 let look_matcher = LookMatcher::new();
1037 #[cfg(feature = "std")]
1038 if option_flags & OPTION_TRACE != 0 {
1039 println!("pos\tinstruction");
1040 }
1041 let mut backtrack_count = 0;
1042 let mut pc = 0;
1043 let mut ix = pos;
1044 let mut slash_z_matched = false;
1045 let mut match_attempt_start = pos;
1046 #[cfg(feature = "leftmost_longest")]
1047 let leftmost_longest = option_flags & OPTION_LEFTMOST_LONGEST != 0;
1048 #[cfg(feature = "leftmost_longest")]
1049 let mut best_saves: Option<Vec<usize>> = None;
1050 #[cfg(feature = "leftmost_longest")]
1051 let mut best_match_len = 0;
1052 loop {
1053 // break from this loop to fail, causes stack to pop
1054 'fail: loop {
1055 #[cfg(feature = "std")]
1056 if option_flags & OPTION_TRACE != 0 {
1057 println!("{}\t{} {:?}", ix, pc, prog.body[pc]);
1058 }
1059 match prog.body[pc] {
1060 Insn::End => {
1061 // save of end position into slot 1 is now done
1062 // with an explicit group; we might want to
1063 // optimize that.
1064 //state.saves[1] = ix;
1065 #[cfg(feature = "std")]
1066 if option_flags & OPTION_TRACE != 0 {
1067 println!("saves: {:?}", state.saves);
1068 }
1069 // Reject the match if it is empty and the flag to do so is enabled.
1070 // `match_attempt_start` is set by `SplitUnanchored` each time the unanchored
1071 // preamble begins a new match attempt at a fresh position, so this correctly
1072 // rejects empty matches regardless of where in the haystack the attempt starts.
1073 if option_flags & OPTION_FIND_NOT_EMPTY != 0 && ix == match_attempt_start {
1074 break 'fail;
1075 }
1076 if let Some(&slot1) = state.saves.get(1) {
1077 // With some features like keep out (\K), the match start can be after
1078 // the match end. Cap the start to <= end.
1079 if state.get(0) > slot1 {
1080 state.save(0, slot1);
1081 }
1082 }
1083 if state.get(0) < match_range.start || state.get(1) > match_range.end {
1084 break 'fail;
1085 }
1086 #[cfg(feature = "leftmost_longest")]
1087 if leftmost_longest {
1088 let match_len = state.get(1) - state.get(0);
1089 if best_saves.is_none() || match_len > best_match_len {
1090 best_saves = Some(state.saves.clone());
1091 best_match_len = match_len;
1092 }
1093 if best_match_len == prog.max_size {
1094 return Ok(Some(extract(state)));
1095 }
1096 break 'fail;
1097 }
1098 return Ok(Some(extract(state)));
1099 }
1100 Insn::Any => {
1101 if ix < haystack.len() {
1102 ix += advance_one(haystack, ix, prog.bytes_mode);
1103 } else {
1104 break 'fail;
1105 }
1106 }
1107 Insn::AnyNoNL => {
1108 if ix < haystack.len() && haystack.as_bytes()[ix] != b'\n' {
1109 ix += advance_one(haystack, ix, prog.bytes_mode);
1110 } else {
1111 break 'fail;
1112 }
1113 }
1114 Insn::AnyNoCRLF => {
1115 if ix < haystack.len()
1116 && haystack.as_bytes()[ix] != b'\r'
1117 && haystack.as_bytes()[ix] != b'\n'
1118 {
1119 ix += advance_one(haystack, ix, prog.bytes_mode);
1120 } else {
1121 break 'fail;
1122 }
1123 }
1124 Insn::Lit(ref val) => {
1125 let ix_end = ix + val.len();
1126 if !matches_literal(haystack, ix, ix_end, val.as_bytes()) {
1127 break 'fail;
1128 }
1129 ix = ix_end
1130 }
1131 Insn::LitCasei(ref lit) => match lit.match_len(haystack, ix) {
1132 Some(len) => ix += len,
1133 None => break 'fail,
1134 },
1135 Insn::CharClass(ref matcher) => match matcher.match_len(haystack, ix) {
1136 Some(len) => ix += len,
1137 None => break 'fail,
1138 },
1139 Insn::Assertion(assertion) => {
1140 if !match assertion {
1141 Assertion::StartText => input
1142 .start_text_override()
1143 .and_then(|value| {
1144 options.allow_input_assertion_overrides.then_some(value)
1145 })
1146 .unwrap_or_else(|| look_matcher.is_start(haystack.as_bytes(), ix)),
1147 Assertion::EndText => {
1148 let matched = input
1149 .end_text_override()
1150 .and_then(|value| {
1151 options.allow_input_assertion_overrides.then_some(value)
1152 })
1153 .unwrap_or_else(|| look_matcher.is_end(haystack.as_bytes(), ix));
1154 slash_z_matched |= matched;
1155 matched
1156 }
1157 Assertion::EndTextIgnoreTrailingNewlines { crlf } => {
1158 let bytes = haystack.as_bytes();
1159 let matched = if ix == bytes.len() {
1160 // At the end of string
1161 true
1162 } else if crlf {
1163 // In CRLF mode, trailing \r\n pairs and bare \n are ignored
1164 bytes[ix..].iter().all(|&b| b == b'\n' || b == b'\r')
1165 } else {
1166 // Check if all remaining bytes are newlines
1167 bytes[ix..].iter().all(|&b| b == b'\n')
1168 };
1169 slash_z_matched |= matched;
1170 matched
1171 }
1172 Assertion::StartLine { crlf: false } => {
1173 look_matcher.is_start_lf(haystack.as_bytes(), ix)
1174 }
1175 Assertion::StartLine { crlf: true } => {
1176 look_matcher.is_start_crlf(haystack.as_bytes(), ix)
1177 }
1178 Assertion::StartLineOniguruma { crlf: false } => {
1179 look_matcher.is_start_lf(haystack.as_bytes(), ix)
1180 && !(ix > 0 && ix == haystack.len())
1181 }
1182 Assertion::StartLineOniguruma { crlf: true } => {
1183 look_matcher.is_start_crlf(haystack.as_bytes(), ix)
1184 && !(ix > 0 && ix == haystack.len())
1185 }
1186 Assertion::EndLine { crlf: false } => {
1187 look_matcher.is_end_lf(haystack.as_bytes(), ix)
1188 }
1189 Assertion::EndLine { crlf: true } => {
1190 look_matcher.is_end_crlf(haystack.as_bytes(), ix)
1191 }
1192 Assertion::LeftWordBoundary => look_matcher
1193 .is_word_start_unicode(haystack.as_bytes(), ix)
1194 .unwrap(),
1195 Assertion::RightWordBoundary => look_matcher
1196 .is_word_end_unicode(haystack.as_bytes(), ix)
1197 .unwrap(),
1198 Assertion::LeftWordHalfBoundary => look_matcher
1199 .is_word_start_half_unicode(haystack.as_bytes(), ix)
1200 .unwrap(),
1201 Assertion::RightWordHalfBoundary => look_matcher
1202 .is_word_end_half_unicode(haystack.as_bytes(), ix)
1203 .unwrap(),
1204 Assertion::WordBoundary => look_matcher
1205 .is_word_unicode(haystack.as_bytes(), ix)
1206 .unwrap(),
1207 Assertion::NotWordBoundary => look_matcher
1208 .is_word_unicode_negate(haystack.as_bytes(), ix)
1209 .unwrap(),
1210 } {
1211 break 'fail;
1212 }
1213 }
1214 Insn::Split(x, y) => {
1215 state.push(y, ix)?;
1216 pc = x;
1217 continue;
1218 }
1219 Insn::SplitUnanchored(x, y) => {
1220 #[cfg(feature = "leftmost_longest")]
1221 if leftmost_longest && apply_best_saves(state, &best_saves) {
1222 return Ok(Some(extract(state)));
1223 }
1224 if ix > match_range.end {
1225 return Ok(None);
1226 }
1227 match_attempt_start = ix;
1228 slash_z_matched = false;
1229
1230 if input.is_anchored() {
1231 // Anchored mode: only try at the current position; do not push a
1232 // backtrack branch for advancing to the next position.
1233 } else {
1234 state.push(y, ix)?;
1235 }
1236 pc = x;
1237 continue;
1238 }
1239 Insn::Jmp(target) => {
1240 pc = target;
1241 continue;
1242 }
1243 Insn::Save(slot) => state.save(slot, ix),
1244 Insn::Save0(slot) => state.save(slot, 0),
1245 Insn::SaveCaptureGroupStart(group) => {
1246 let start_slot = group * 2;
1247 // if the capture group's start slot is empty
1248 // i.e. execution is not currently inside this capture group
1249 // or the end slot for that capture group is complete
1250 // then we save the current position in the capture group start slot
1251 if state.get(start_slot) == usize::MAX || state.get(start_slot + 1) <= ix {
1252 state.save(start_slot, ix);
1253 }
1254 }
1255 Insn::Restore(slot) => ix = state.get(slot),
1256 Insn::RepeatGr {
1257 lo,
1258 hi,
1259 next,
1260 repeat,
1261 } => {
1262 let repcount = state.get(repeat);
1263 if repcount == hi {
1264 pc = next;
1265 continue;
1266 }
1267 state.save(repeat, repcount + 1);
1268 if repcount >= lo {
1269 state.push(next, ix)?;
1270 }
1271 }
1272 Insn::RepeatNg {
1273 lo,
1274 hi,
1275 next,
1276 repeat,
1277 } => {
1278 let repcount = state.get(repeat);
1279 if repcount == hi {
1280 pc = next;
1281 continue;
1282 }
1283 state.save(repeat, repcount + 1);
1284 if repcount >= lo {
1285 state.push(pc + 1, ix)?;
1286 pc = next;
1287 continue;
1288 }
1289 }
1290 Insn::RepeatEpsilonGr {
1291 lo,
1292 next,
1293 repeat,
1294 check,
1295 } => {
1296 let repcount = state.get(repeat);
1297 if repcount > 0 && state.get(check) == ix {
1298 // zero-length match on repeat, then move to next instruction
1299 pc = next;
1300 continue;
1301 }
1302 state.save(repeat, repcount + 1);
1303 if repcount >= lo {
1304 state.save(check, ix);
1305 state.push(next, ix)?;
1306 }
1307 }
1308 Insn::RepeatEpsilonNg {
1309 lo,
1310 next,
1311 repeat,
1312 check,
1313 } => {
1314 let repcount = state.get(repeat);
1315 if repcount > 0 && state.get(check) == ix {
1316 // zero-length match on repeat, then move to next instruction
1317 pc = next;
1318 continue;
1319 }
1320 state.save(repeat, repcount + 1);
1321 if repcount >= lo {
1322 state.save(check, ix);
1323 state.push(pc + 1, ix)?;
1324 pc = next;
1325 continue;
1326 }
1327 }
1328 Insn::GoBack(count) => {
1329 for _ in 0..count {
1330 if ix == 0 {
1331 break 'fail;
1332 }
1333 ix = prev_ix(haystack, ix, prog.bytes_mode);
1334 }
1335 }
1336 Insn::FailNegativeLookAround => {
1337 // Reaching this instruction means that the body of the
1338 // look-around matched. Because it's a *negative* look-around,
1339 // that means the look-around itself should fail (not match).
1340 // But before, we need to discard all the states that have
1341 // been pushed with the look-around, because we don't want to
1342 // explore them.
1343 loop {
1344 let (popped_pc, _) = state.pop();
1345 if popped_pc == pc + 1 {
1346 // We've reached the state that would jump us to
1347 // after the look-around (in case the look-around
1348 // succeeded). That means we popped enough states.
1349 break;
1350 }
1351 }
1352 break 'fail;
1353 }
1354 Insn::Backref {
1355 slot,
1356 casei,
1357 unicode,
1358 } => {
1359 let lo = state.get(slot);
1360 if lo == usize::MAX {
1361 // Referenced group hasn't matched, so the backref doesn't match either
1362 break 'fail;
1363 }
1364 let hi = state.get(slot + 1);
1365 if hi == usize::MAX {
1366 // Referenced group hasn't matched, so the backref doesn't match either
1367 break 'fail;
1368 }
1369 let ref_text = &haystack.as_bytes()[lo..hi];
1370 let ix_end = ix + ref_text.len();
1371 if casei {
1372 if !matches_literal_casei(haystack, ix, ix_end, ref_text, unicode) {
1373 break 'fail;
1374 }
1375 } else if !matches_literal(haystack, ix, ix_end, ref_text) {
1376 break 'fail;
1377 }
1378 ix = ix_end;
1379 }
1380 Insn::BackrefExistsCondition(group) => {
1381 let lo = state.get(group * 2);
1382 if lo == usize::MAX {
1383 // Referenced group hasn't matched, so the backref doesn't match either
1384 break 'fail;
1385 }
1386 }
1387 Insn::Fail => {
1388 // Immediately fail and trigger backtracking
1389 break 'fail;
1390 }
1391 #[cfg(feature = "variable-lookbehinds")]
1392 Insn::BackwardsDelegate(ReverseBackwardsDelegate {
1393 ref dfa,
1394 ref cache_pool,
1395 pattern: _,
1396 ref capture_group_extraction_inner,
1397 capture_groups,
1398 }) => {
1399 // Use regex-automata to search backwards from current position
1400 let mut cache_guard = cache_pool.get();
1401 let input = Input::new(haystack.as_bytes())
1402 .anchored(Anchored::Yes)
1403 .range(0..ix);
1404
1405 match dfa.try_search_rev(&mut cache_guard, &input) {
1406 Ok(Some(match_result)) => {
1407 // Update ix to the start position of the match
1408 let match_start = match_result.offset();
1409
1410 if let Some(inner) = capture_group_extraction_inner {
1411 if let Some(range) = capture_groups {
1412 // There are capture groups, need to search forward to populate them
1413 let forward_input = Input::new(haystack.as_bytes())
1414 .span(match_start..ix)
1415 .anchored(Anchored::Yes);
1416 inner_slots.resize((range.end() - range.start() + 1) * 2, None);
1417
1418 if inner.search_slots(&forward_input, inner_slots).is_some() {
1419 // Store capture group positions, ignoring any whose range is earlier than what has been stored already
1420 store_capture_groups(state, inner_slots, range, true);
1421 } else {
1422 break 'fail;
1423 }
1424 } else {
1425 // No groups, just update ix to the match start
1426 ix = match_start;
1427 }
1428 } else {
1429 // No groups, just update ix to the match start
1430 ix = match_start;
1431 }
1432 }
1433 _ => break 'fail,
1434 }
1435 }
1436 Insn::BeginAtomic => {
1437 let count = state.backtrack_count();
1438 state.stack_push(count);
1439 }
1440 Insn::EndAtomic => {
1441 let count = state.stack_pop();
1442 state.backtrack_cut(count);
1443 }
1444 Insn::Delegate(Delegate {
1445 ref inner,
1446 pattern: _,
1447 capture_groups,
1448 }) => {
1449 let input = Input::new(haystack.as_bytes())
1450 .span(ix..haystack.len())
1451 .anchored(Anchored::Yes);
1452 if let Some(range) = capture_groups {
1453 // Has capture groups, need to extract them
1454 inner_slots.resize((range.end() - range.start() + 1) * 2, None);
1455 if inner.search_slots(&input, inner_slots).is_some() {
1456 // store the capture groups, no need to check current state to see if new values are further to the right
1457 store_capture_groups(state, inner_slots, range, false);
1458 ix = inner_slots[1].unwrap().get();
1459 } else {
1460 break 'fail;
1461 }
1462 } else {
1463 // No groups, so we can use faster methods
1464 match inner.search_half(&input) {
1465 Some(m) => ix = m.offset(),
1466 _ => break 'fail,
1467 }
1468 }
1469 }
1470 Insn::AbsentRepeater(ref delegate) => {
1471 // The absent operator matches the shortest string not containing the delegate pattern
1472 // We advance one character at a time, checking if delegate matches at each position
1473 // If delegate matches, we've found the boundary and continue to next instruction
1474 // If we reach end of string without delegate matching, we also continue
1475
1476 // Check if delegate matches at current position
1477 let input = Input::new(haystack.as_bytes())
1478 .span(ix..haystack.len())
1479 .anchored(Anchored::Yes);
1480 // capture groups in the delegate are always ignored, so we can use the quicker search_half method
1481 let delegate_matches_here = delegate.inner.search_half(&input).is_some();
1482
1483 if delegate_matches_here {
1484 // Delegate matches at current position - we've reached the boundary
1485 // Continue to next instruction without consuming any characters
1486 // Fall through via pc += 1 below
1487 } else if ix < haystack.len() {
1488 // Try advancing one character and checking again
1489 state.push(pc + 1, ix)?;
1490 ix += advance_one(haystack, ix, prog.bytes_mode);
1491 // Stay at same pc to check delegate match at new position
1492 continue;
1493 } else {
1494 // Reached end of string - delegate never matched, so we succeed
1495 // Fall through via pc += 1 below
1496 }
1497 }
1498 Insn::ContinueFromPreviousMatchEnd { at_start } => {
1499 let at_previous_match_end = input
1500 .continue_from_previous_match_end_override()
1501 .and_then(|value| options.allow_input_assertion_overrides.then_some(value))
1502 .unwrap_or(
1503 ix == pos
1504 && option_flags & OPTION_NOT_CONTINUED_FROM_PREVIOUS_MATCH == 0,
1505 );
1506 if !at_previous_match_end {
1507 // If \G is at the start of the pattern, and we are performing a non-anchored
1508 // search, then we can fail early instead of checking at each position in the
1509 // haystack because \G will never match at any other position
1510 if at_start && state.stack.len() == 1 && !input.is_anchored() {
1511 // The only item on the stack is from the SplitUnanchored (or Seek)
1512 // instruction for non-anchored search.
1513 // We can safely return None immediately.
1514 return Ok(None);
1515 }
1516 break 'fail;
1517 }
1518 }
1519 Insn::Seek(Seek { ref inner, .. }) => {
1520 #[cfg(feature = "leftmost_longest")]
1521 if leftmost_longest && apply_best_saves(state, &best_saves) {
1522 return Ok(Some(extract(state)));
1523 }
1524 // A sentinel value greater than haystack.len() is pushed onto the backtrack stack
1525 // when the seek found a zero-width match at end-of-string. On re-entry with
1526 // that sentinel, there are no more positions to try.
1527 if ix > match_range.end {
1528 return Ok(None);
1529 }
1530
1531 if input.is_anchored() {
1532 // Anchored mode: the idea is that since the many-DFA from the regex-set has
1533 // already confirmed a candidate match starting at this position, there is no
1534 // need to verify the seek pattern matches here. We also don't push any backtracking
1535 // states and just continue on like a no-op.
1536 } else {
1537 // TODO: ideally we would be able to use .earliest(true) as an extra optimization
1538 // as we only care about the start of the match, but unfortunately this doesn't
1539 // always return the correct start position, perhaps a bug in regex-automata
1540 let seek_input = Input::new(haystack.as_bytes()).span(ix..match_range.end);
1541 match inner.search(&seek_input) {
1542 None => return Ok(None),
1543 Some(m) => {
1544 // Compute the next position to retry the seek from on backtrack:
1545 // one codepoint past the start of this match (or past the end for
1546 // zero-width matches) so we make progress.
1547 let next_seek_start = if m.start() == m.end() {
1548 if m.end() < haystack.len() {
1549 m.end() + advance_one(haystack, m.end(), prog.bytes_mode)
1550 } else {
1551 // Zero-width match at end-of-string. Push a sentinel value
1552 // (haystack.len() + 1) so that if the main pattern fails and we
1553 // backtrack here, the `ix > haystack.len()` guard above returns None
1554 // immediately instead of looping.
1555 haystack.len() + 1
1556 }
1557 } else {
1558 m.start() + advance_one(haystack, m.start(), prog.bytes_mode)
1559 };
1560 state.push(pc, next_seek_start)?;
1561 ix = m.start();
1562 }
1563 }
1564 }
1565 match_attempt_start = ix;
1566 slash_z_matched = false;
1567 pc += 1;
1568 continue;
1569 }
1570 Insn::RejectEmptyMatchAtEOFFollowingNewline => {
1571 if ix == haystack.len()
1572 && ix > 0
1573 && matches_literal(haystack, ix - 1, ix, b"\n")
1574 && !slash_z_matched
1575 && match_attempt_start == ix
1576 {
1577 break 'fail;
1578 }
1579 }
1580 }
1581 pc += 1;
1582 }
1583 #[cfg(feature = "std")]
1584 if option_flags & OPTION_TRACE != 0 {
1585 println!("fail");
1586 }
1587 // "break 'fail" goes here
1588 if state.stack.is_empty() {
1589 #[cfg(feature = "leftmost_longest")]
1590 if leftmost_longest && apply_best_saves(state, &best_saves) {
1591 return Ok(Some(extract(state)));
1592 }
1593 return Ok(None);
1594 }
1595
1596 #[cfg(feature = "leftmost_longest")]
1597 if leftmost_longest
1598 && best_match_len == prog.max_size
1599 && apply_best_saves(state, &best_saves)
1600 {
1601 return Ok(Some(extract(state)));
1602 }
1603
1604 backtrack_count += 1;
1605 if backtrack_count > options.backtrack_limit {
1606 return Err(Error::RuntimeError(RuntimeError::BacktrackLimitExceeded));
1607 }
1608
1609 let (newpc, newix) = state.pop();
1610 pc = newpc;
1611 ix = newix;
1612 }
1613 }
1614
1615 #[cfg(test)]
1616 mod tests {
1617 use super::*;
1618 use quickcheck::{quickcheck, Arbitrary, Gen};
1619
1620 #[test]
1621 fn casei_unicode_fold_equality() {
1622 // Same-case and simple-fold pairs match.
1623 assert!(matches_literal_casei_unicode("ΑΛΦΑ", "αλφα"));
1624 assert!(matches_literal_casei_unicode("σ", "ς"));
1625 // Fold orbits that cross scripts/blocks: ſ (U+017F) folds to s,
1626 // K (U+212A, Kelvin sign) folds to k, Å (U+212B, Angstrom sign)
1627 // folds to å.
1628 assert!(matches_literal_casei_unicode("ſ", "s"));
1629 assert!(matches_literal_casei_unicode("S", "ſ"));
1630 assert!(matches_literal_casei_unicode("\u{212A}", "k"));
1631 assert!(matches_literal_casei_unicode("\u{212B}", "å"));
1632 // Mixed ASCII/non-ASCII content.
1633 assert!(matches_literal_casei_unicode("aΛb", "AλB"));
1634 // Simple folding does not include full case folding (ß ≠ ss).
1635 assert!(!matches_literal_casei_unicode("straße", "STRASSE"));
1636 // Both strings must end together: a folded prefix is not a match.
1637 assert!(!matches_literal_casei_unicode("sab", "ſa"));
1638 assert!(!matches_literal_casei_unicode("ſa", "ſab"));
1639 assert!(!matches_literal_casei_unicode("αα", "α"));
1640 }
1641
1642 #[test]
1643 fn state_push_pop() {
1644 let mut state = State::new(1, MAX_STACK, 0);
1645
1646 state.push(0, 0).unwrap();
1647 state.push(1, 1).unwrap();
1648 assert_eq!(state.pop(), (1, 1));
1649 assert_eq!(state.pop(), (0, 0));
1650 assert!(state.stack.is_empty());
1651
1652 state.push(2, 2).unwrap();
1653 assert_eq!(state.pop(), (2, 2));
1654 assert!(state.stack.is_empty());
1655 }
1656
1657 #[test]
1658 fn state_save_override() {
1659 let mut state = State::new(1, MAX_STACK, 0);
1660 state.save(0, 10);
1661 state.push(0, 0).unwrap();
1662 state.save(0, 20);
1663 assert_eq!(state.pop(), (0, 0));
1664 assert_eq!(state.get(0), 10);
1665 }
1666
1667 #[test]
1668 fn state_save_override_twice() {
1669 let mut state = State::new(1, MAX_STACK, 0);
1670 state.save(0, 10);
1671 state.push(0, 0).unwrap();
1672 state.save(0, 20);
1673 state.push(1, 1).unwrap();
1674 state.save(0, 30);
1675
1676 assert_eq!(state.get(0), 30);
1677 assert_eq!(state.pop(), (1, 1));
1678 assert_eq!(state.get(0), 20);
1679 assert_eq!(state.pop(), (0, 0));
1680 assert_eq!(state.get(0), 10);
1681 }
1682
1683 #[test]
1684 fn state_explicit_stack() {
1685 let mut state = State::new(1, MAX_STACK, 0);
1686 state.stack_push(11);
1687 state.stack_push(12);
1688
1689 state.push(100, 101).unwrap();
1690 state.stack_push(13);
1691 assert_eq!(state.stack_pop(), 13);
1692 state.stack_push(14);
1693 assert_eq!(state.pop(), (100, 101));
1694
1695 // Note: 14 is not there because it was pushed as part of the backtrack branch
1696 assert_eq!(state.stack_pop(), 12);
1697 assert_eq!(state.stack_pop(), 11);
1698 }
1699
1700 #[test]
1701 fn state_backtrack_cut_simple() {
1702 let mut state = State::new(2, MAX_STACK, 0);
1703 state.save(0, 1);
1704 state.save(1, 2);
1705
1706 let count = state.backtrack_count();
1707
1708 state.push(0, 0).unwrap();
1709 state.save(0, 3);
1710 assert_eq!(state.backtrack_count(), 1);
1711
1712 state.backtrack_cut(count);
1713 assert_eq!(state.backtrack_count(), 0);
1714 assert_eq!(state.get(0), 3);
1715 assert_eq!(state.get(1), 2);
1716 }
1717
1718 #[test]
1719 fn state_backtrack_cut_complex() {
1720 let mut state = State::new(2, MAX_STACK, 0);
1721 state.save(0, 1);
1722 state.save(1, 2);
1723
1724 state.push(0, 0).unwrap();
1725 state.save(0, 3);
1726
1727 let count = state.backtrack_count();
1728
1729 state.push(1, 1).unwrap();
1730 state.save(0, 4);
1731 state.push(2, 2).unwrap();
1732 state.save(1, 5);
1733 assert_eq!(state.backtrack_count(), 3);
1734
1735 state.backtrack_cut(count);
1736 assert_eq!(state.backtrack_count(), 1);
1737 assert_eq!(state.get(0), 4);
1738 assert_eq!(state.get(1), 5);
1739
1740 state.pop();
1741 assert_eq!(state.backtrack_count(), 0);
1742 // Check that oldsave were set correctly
1743 assert_eq!(state.get(0), 1);
1744 assert_eq!(state.get(1), 2);
1745 }
1746
1747 #[derive(Clone, Debug)]
1748 enum Operation {
1749 Push,
1750 Pop,
1751 Save(usize, usize),
1752 }
1753
1754 impl Arbitrary for Operation {
1755 fn arbitrary(g: &mut Gen) -> Self {
1756 match g.choose(&[0, 1, 2]) {
1757 Some(0) => Operation::Push,
1758 Some(1) => Operation::Pop,
1759 _ => Operation::Save(
1760 *g.choose(&[0usize, 1, 2, 3, 4]).unwrap(),
1761 usize::arbitrary(g),
1762 ),
1763 }
1764 }
1765 }
1766
1767 fn check_saves_for_operations(operations: Vec<Operation>) -> bool {
1768 let slots = operations
1769 .iter()
1770 .map(|o| match o {
1771 &Operation::Save(slot, _) => slot + 1,
1772 _ => 0,
1773 })
1774 .max()
1775 .unwrap_or(0);
1776 if slots == 0 {
1777 // No point checking if there's no save instructions
1778 return true;
1779 }
1780
1781 // Stack with the complete VM state (including saves)
1782 let mut stack = Vec::new();
1783 let mut saves = vec![usize::MAX; slots];
1784
1785 let mut state = State::new(slots, MAX_STACK, 0);
1786
1787 let mut expected = Vec::new();
1788 let mut actual = Vec::new();
1789
1790 for operation in operations {
1791 match operation {
1792 Operation::Push => {
1793 // We're not checking pc and ix later, so don't bother
1794 // putting in random values.
1795 stack.push((0, 0, saves.clone()));
1796 state.push(0, 0).unwrap();
1797 }
1798 Operation::Pop => {
1799 // Note that because we generate the operations randomly
1800 // there might be more pops than pushes. So ignore a pop
1801 // if the stack was empty.
1802 if let Some((_, _, previous_saves)) = stack.pop() {
1803 saves = previous_saves;
1804 state.pop();
1805 }
1806 }
1807 Operation::Save(slot, value) => {
1808 saves[slot] = value;
1809 state.save(slot, value);
1810 }
1811 }
1812
1813 // Remember state of saves for checking later
1814 expected.push(saves.clone());
1815 let mut actual_saves = vec![usize::MAX; slots];
1816 for (i, item) in actual_saves.iter_mut().enumerate().take(slots) {
1817 *item = state.get(i);
1818 }
1819 actual.push(actual_saves);
1820 }
1821
1822 expected == actual
1823 }
1824
1825 quickcheck! {
1826 fn state_save_quickcheck(operations: Vec<Operation>) -> bool {
1827 check_saves_for_operations(operations)
1828 }
1829 }
1830 }