Debian Codegraph @

debian/rust-vendor/fancy-regex/README.md

raw
1 # fancy-regex
2
3 A Rust library for compiling and matching regular expressions. It uses a hybrid
4 regex implementation designed to support a relatively rich set of features.
5 In particular, it uses backtracking to implement "fancy" features such as
6 look-around and backtracking, which are not supported in purely
7 NFA-based implementations (exemplified by
8 [RE2](https://github.com/google/re2), and implemented in Rust in the
9 [regex](https://crates.io/crates/regex) crate).
10
11 Aims to be compatible with Oniguruma syntax when the relevant flag is set.
12
13 Try it online in the **[fancy-regex playground](https://fancy-regex.github.io/fancy-regex/)** - test and explore regular expressions with advanced features in your browser.
14
15 [![docs](https://docs.rs/fancy-regex/badge.svg)](https://docs.rs/fancy-regex)
16 [![crate](https://img.shields.io/crates/v/fancy-regex.svg)](https://crates.io/crates/fancy-regex)
17 [![ci](https://github.com/fancy-regex/fancy-regex/workflows/ci/badge.svg)](https://github.com/fancy-regex/fancy-regex/actions?query=workflow%3Aci)
18 [![codecov](https://codecov.io/gh/fancy-regex/fancy-regex/branch/main/graph/badge.svg)](https://codecov.io/gh/fancy-regex/fancy-regex)
19
20 A goal is to be as efficient as possible. For a given regex, the NFA
21 implementation has asymptotic running time linear in the length of the
22 input, while in the general case a backtracking implementation has
23 exponential blowup. An example given in [Static Analysis for Regular
24 Expression Exponential Runtime via Substructural
25 Logics](https://arxiv.org/pdf/1405.7058.pdf) is:
26
27 ```python
28 import re
29 re.compile('(a|b|ab)*bc').match('ab' * 28 + 'ac')
30 ```
31
32 In Python (tested on both 2.7 and 3.5), this match takes 91s, and
33 doubles for each additional repeat of 'ab'.
34
35 Thus, many proponents
36 [advocate](https://swtch.com/~rsc/regexp/regexp1.html) a purely NFA
37 (nondeterministic finite automaton) based approach. Even so,
38 backreferences and look-around do add richness to regexes, and they
39 are commonly used in applications such as syntax highlighting for text
40 editors. In particular, TextMate's [syntax
41 definitions](https://manual.macromates.com/en/language_grammars),
42 based on the [Oniguruma](https://github.com/kkos/oniguruma)
43 backtracking engine, are now used in a number of other popular
44 editors, including Sublime Text and Atom. These syntax definitions
45 routinely use backreferences and look-around. For example, the
46 following regex captures a single-line Rust raw string:
47
48 ```
49 r(#*)".*?"\1
50 ```
51
52 There is no NFA that can express this simple and useful pattern. Yet,
53 a backtracking implementation handles it efficiently.
54
55 This package is one of the first that handles both cases well. The
56 exponential blowup case above is run in 258ns. Thus, it should be a
57 very appealing alternative for applications that require both richness
58 and performance.
59
60 ## A warning about worst-case performance
61
62 NFA-based approaches give strong guarantees about worst-case
63 performance. For regexes that contain "fancy" features such as
64 backreferences and look-around, this module gives no corresponding
65 guarantee. If an attacker can control the regular expressions that
66 will be matched against, they will be able to successfully mount a
67 denial-of-service attack. Be warned.
68
69 See [PERFORMANCE.md](PERFORMANCE.md) for some examples.
70
71 ## A hybrid approach
72
73 One workable approach is to detect the presence of "fancy" features,
74 and choose either an NFA implementation or a backtracker depending on
75 whether they are used.
76
77 However, this module attempts to be more fine-grained. Instead, it
78 implements a true hybrid approach. In essence, it is a backtracking VM
79 (as well explained in [Regular Expression Matching: the Virtual
80 Machine Approach](https://swtch.com/~rsc/regexp/regexp2.html)) in
81 which one of the "instructions" in the VM delegates to an inner NFA
82 implementation (in Rust, the regex crate, though a similar approach
83 would certainly be possible using RE2 or the Go
84 [regexp](https://golang.org/pkg/regexp/) package). Then there's an
85 analysis which decides for each subexpression whether it is "hard", or
86 can be delegated to the NFA matcher. At the moment, it is eager, and
87 delegates as much as possible to the NFA engine.
88
89 ## Theory
90
91 The core concept behind this library is to implement a backtracking virtual machine (VM) for regular expression matching, similar to PCRE.
92 However, whenever possible, this VM delegates work to an underlying regular expression engine - the Rust regex crate - which does not otherwise support "fancy" features like lookarounds and backreferences, but has other desirable design goals - specifically, the regex crate has runtime linear to input length.
93
94 For regular expressions that do not use "fancy" features, the library acts primarily as a lightweight wrapper around the underlying engine.
95 When such features are present, the library performs an analysis to determine which parts of the expression must be handled by the backtracking engine and which can be safely delegated.
96
97 This analysis operates in two phases:
98
99 ### Phase 1 - Bottom-Up Analysis
100
101 Each subexpression is analyzed to determine three key properties:
102
103 - *hard*: Whether the subexpression requires backtracking features (backreferences, look-around, atomic groups, conditionals)
104 - *minimum size*: The minimum number of characters this subexpression will match
105 - *constant size*: Whether the subexpression always matches the same number of characters
106
107 ### Phase 2 - Top-Down Compilation
108
109 The compilation phase proceeds from the root of the expression, passing a "hard context" that flows from parent to child expressions. This context indicates whether match length variations will affect backtracking decisions.
110
111 *Delegation Strategy*: If both the subexpression and context are "easy", the compiler generates a `Delegate` instruction to offload work to the high-performance NFA engine. Otherwise, it generates explicit VM instructions.
112
113 *Concatenation Optimization*: For sequences of subexpressions, the compiler employs a sophisticated strategy:
114
115 1. Identify a prefix of constant-size, easy subexpressions that can be safely delegated (because they won't affect backtracking)
116 2. If the context is easy, identify a suffix of easy subexpressions for delegation
117 3. Compile the remaining "hard" middle section with explicit backtracking instructions
118 4. The hard context flows from right to left - only the rightmost hard subexpression gets an easy context
119
120 This ensures maximum delegation while preserving correct backtracking semantics.
121
122 ### Summary
123
124 In summary, the system efficiently combines backtracking and automaton-based matching by delegating as much work as possible to the underlying high-performance NFA engine, only resorting to backtracking where strictly necessary. This hybrid approach provides both expressive power and performance for advanced regular expression features.
125
126 ## Current status
127
128 Still in development, though the basic ideas are in place. Currently,
129 the following features are missing:
130
131 * Backreferences at recursion levels
132
133 ### Experimental optimizations
134 fancy-regex now has a **Seek** pre-filter optimization (currently disabled by default) for hard (backtracking) patterns. It derives a regular approximation of the pattern and uses it to skip directly to the earliest plausible match position in the haystack, so the backtracking VM only needs to run from that position.
135 This helps greatly when working with anchored matches or searching large haystacks for literals etc.
136 It is considered experimental because it hasn't been field tested much yet - it is expected that everything should be fine because it was designed to be conservative, but there is a chance that the seek will accidentally skip over possible match positions.
137
138 ## Acknowledgements
139
140 Many thanks to [Andrew Gallant](http://blog.burntsushi.net/about/) for
141 stimulating conversations that inspired this approach, as well as for
142 creating the excellent regex crate.
143
144 ## Authors
145
146 The main authors are Raph Levien, Robin Stocker and Keith Hall.
147
148 ## Contributions
149
150 We gladly accept contributions via GitHub pull requests. Please see
151 [CONTRIBUTING.md](CONTRIBUTING.md) for more details.
152
153 This project started out as a Google 20% project, but none of the authors currently
154 work at Google so it has been forked to be community-maintained.