Debian Codegraph @

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

raw
1 // Copyright 2026 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 //! Translation of easy `Expr` subtrees directly into `regex_syntax::hir::Hir`.
22 //!
23 //! Delegating a subtree to regex-automata used to mean re-serializing it with
24 //! [`Expr::to_str`] and letting the engine parse the string all over again —
25 //! a full AST parse plus Hir translation per delegated engine. Building the
26 //! `Hir` directly from the `Expr` tree skips that second parse.
27 //!
28 //! The translation is defined to produce **exactly** the `Hir` that
29 //! `regex_syntax` would produce for the `to_str` output (there is an oracle
30 //! test asserting this equality). Node kinds outside the easy subset that
31 //! `to_str` handles — and any fragment whose semantics depend on parsing (a
32 //! `Delegate`'s inner string, a case-insensitive literal) that fails its
33 //! (fragment-sized) parse — return `None`, and the caller falls back to the
34 //! string path, preserving both behavior and error reporting.
35
36 use alloc::boxed::Box;
37 use alloc::string::String;
38 use alloc::vec::Vec;
39 use core::convert::TryFrom;
40
41 use regex_syntax::hir::{Capture, Dot, Hir, Look, Repetition};
42
43 use crate::{push_quoted, Assertion, Expr};
44
45 /// Context threaded through a translation: the syntax options the string path
46 /// would hand to the engine's parser, plus the capture-group counter (groups
47 /// are numbered in the order their `(` appears, starting at 1, exactly like
48 /// the parser numbers the `to_str` output).
49 pub(crate) struct HirCtx {
50 unicode: bool,
51 utf8: bool,
52 next_group: u32,
53 }
54
55 impl HirCtx {
56 pub(crate) fn new(unicode: bool, utf8: bool) -> Self {
57 HirCtx {
58 unicode,
59 utf8,
60 next_group: 1,
61 }
62 }
63 }
64
65 /// Translate an easy `Expr` subtree to an `Hir`, or `None` when it isn't
66 /// covered. `None` is always safe: the caller falls back to the string path.
67 pub(crate) fn expr_to_hir(expr: &Expr, ctx: &mut HirCtx) -> Option<Hir> {
68 Some(match *expr {
69 Expr::Empty | Expr::DefineGroup { .. } => Hir::empty(),
70 Expr::Any { newline, crlf } => {
71 let dot = match (newline, crlf, ctx.unicode, ctx.utf8) {
72 (true, _, true, _) => Dot::AnyChar,
73 (true, _, false, false) => Dot::AnyByte,
74 (false, false, true, _) => Dot::AnyCharExceptLF,
75 (false, false, false, false) => Dot::AnyByteExceptLF,
76 (false, true, true, _) => Dot::AnyCharExceptCRLF,
77 (false, true, false, false) => Dot::AnyByteExceptCRLF,
78 // A byte dot under a UTF-8-only haystack is rejected by the
79 // parser; let the string path produce that error.
80 (_, _, false, true) => return None,
81 };
82 Hir::dot(dot)
83 }
84 Expr::Literal { ref val, casei } => {
85 if !casei {
86 Hir::literal(val.as_bytes())
87 } else {
88 // Case-insensitive literals expand to case-folded classes with
89 // semantics owned by regex-syntax (Unicode simple folding vs
90 // ASCII folding, error cases in non-Unicode modes). Parse just
91 // this literal instead of replicating those rules.
92 let mut cooked = String::with_capacity(val.len() + 5);
93 cooked.push_str("(?i:");
94 push_quoted(&mut cooked, val);
95 cooked.push(')');
96 parse_fragment(&cooked, ctx)?
97 }
98 }
99 Expr::Assertion(assertion) => Hir::look(match assertion {
100 Assertion::StartText => Look::Start,
101 Assertion::EndText => Look::End,
102 Assertion::StartLine { crlf: false }
103 | Assertion::StartLineOniguruma { crlf: false } => Look::StartLF,
104 Assertion::EndLine { crlf: false } => Look::EndLF,
105 Assertion::StartLine { crlf: true } | Assertion::StartLineOniguruma { crlf: true } => {
106 Look::StartCRLF
107 }
108 Assertion::EndLine { crlf: true } => Look::EndCRLF,
109 // Word boundaries and \Z are hard and never reach a delegated
110 // subtree; be conservative if they somehow do.
111 _ => return None,
112 }),
113 Expr::Concat(ref children) => {
114 let subs = children
115 .iter()
116 .map(|child| expr_to_hir(child, ctx))
117 .collect::<Option<Vec<_>>>()?;
118 Hir::concat(subs)
119 }
120 Expr::Alt(ref children) => {
121 let subs = children
122 .iter()
123 .map(|child| expr_to_hir(child, ctx))
124 .collect::<Option<Vec<_>>>()?;
125 Hir::alternation(subs)
126 }
127 Expr::Group(ref child) => {
128 let index = ctx.next_group;
129 ctx.next_group += 1;
130 let sub = expr_to_hir(child, ctx)?;
131 Hir::capture(Capture {
132 index,
133 name: None,
134 sub: Box::new(sub),
135 })
136 }
137 Expr::Repeat {
138 ref child,
139 lo,
140 hi,
141 greedy,
142 } => {
143 let min = u32::try_from(lo).ok()?;
144 let max = if hi == usize::MAX {
145 None
146 } else {
147 Some(u32::try_from(hi).ok()?)
148 };
149 let sub = expr_to_hir(child, ctx)?;
150 Hir::repetition(Repetition {
151 min,
152 max,
153 greedy,
154 sub: Box::new(sub),
155 })
156 }
157 Expr::Delegate { ref inner, casei } => {
158 // Delegate nodes carry raw pattern fragments (character classes
159 // and the like); their meaning is defined by the parser.
160 if casei {
161 let mut cooked = String::with_capacity(inner.len() + 5);
162 cooked.push_str("(?i:");
163 cooked.push_str(inner);
164 cooked.push(')');
165 parse_fragment(&cooked, ctx)?
166 } else {
167 parse_fragment(inner, ctx)?
168 }
169 }
170 _ => return None,
171 })
172 }
173
174 fn parse_fragment(fragment: &str, ctx: &HirCtx) -> Option<Hir> {
175 regex_syntax::ParserBuilder::new()
176 .utf8(ctx.utf8)
177 .unicode(ctx.unicode)
178 .build()
179 .parse(fragment)
180 .ok()
181 }
182
183 #[cfg(test)]
184 mod tests {
185 use super::*;
186 use crate::analyze::{analyze, AnalyzeContext};
187 use crate::{BytesMode, RegexOptions};
188 use alloc::string::ToString;
189
190 /// Patterns covering the easy subset: literals (plain, quoted, casei,
191 /// non-ASCII), dots in all newline/CRLF modes, anchors in all line modes,
192 /// concat/alt/group nesting, all quantifier shapes, classes and other
193 /// delegated fragments, and mixed inline flags.
194 const PATTERNS: &[&str] = &[
195 "a",
196 "abc",
197 "a.c",
198 ".",
199 "(?s).",
200 "(?s:.)x",
201 "^abc$",
202 "(?m)^abc$",
203 "(?m:^)foo",
204 "(?Rm)^x$",
205 "(?i)abc",
206 "(?i)aBc(?-i)d",
207 "(?i)δΔ",
208 "αβγ",
209 "a+b*c?",
210 "a{2,5}",
211 "a{3}",
212 "a{2,}?",
213 "a+?b??",
214 "(a)(b(c))",
215 "(?:ab|cd)e",
216 "a|b|",
217 "(a|)",
218 "()",
219 "[a-z]+",
220 r"\d\w\s",
221 "[^a-c]{2,3}",
222 r"\p{L}+",
223 "(?i)[a-k]x",
224 r"\x61\n\t",
225 "(a+)(?:b|c)*",
226 r"\.\*\+#",
227 r"(?i)ſ",
228 // Hard patterns must be skipped by the harness (info.hard).
229 r"\bword\b",
230 r"(a)\1",
231 ];
232
233 /// The translator must produce exactly the Hir the parser produces for
234 /// the `to_str` serialization — or `None` where the parser errors, so the
235 /// string path can report the error.
236 fn check_oracle(bytes_mode: BytesMode) {
237 for pattern in PATTERNS {
238 let options = RegexOptions {
239 bytes_mode,
240 ..RegexOptions::default()
241 };
242 let Ok(tree) = crate::Expr::parse_tree_with_flags(pattern, options.compute_flags())
243 else {
244 continue;
245 };
246 let Ok(info) = analyze(&tree, AnalyzeContext::default()) else {
247 continue;
248 };
249 if info.hard {
250 continue;
251 }
252 let mut cooked = String::new();
253 tree.expr.to_str(&mut cooked, 0);
254 let unicode =
255 options.syntaxc.get_unicode() && !matches!(options.bytes_mode, BytesMode::Ascii);
256 let utf8 = matches!(options.bytes_mode, BytesMode::Unicode);
257 let expected = regex_syntax::ParserBuilder::new()
258 .utf8(utf8)
259 .unicode(unicode)
260 .build()
261 .parse(&cooked);
262 let got = expr_to_hir(&tree.expr, &mut HirCtx::new(unicode, utf8));
263 match expected {
264 Ok(hir) => assert_eq!(
265 Some(hir),
266 got,
267 "Hir mismatch for {:?} (cooked {:?}) in {:?} mode",
268 pattern,
269 cooked,
270 bytes_mode
271 ),
272 Err(_) => assert_eq!(
273 None, got,
274 "expected fallback for {:?} (cooked {:?}) in {:?} mode: the parser \
275 rejects it, so the translator must not accept it",
276 pattern, cooked, bytes_mode
277 ),
278 }
279 }
280 }
281
282 #[test]
283 fn oracle_unicode_mode() {
284 check_oracle(BytesMode::Unicode);
285 }
286
287 #[test]
288 fn oracle_unicode_bytes_mode() {
289 check_oracle(BytesMode::UnicodeBytes);
290 }
291
292 #[test]
293 fn oracle_ascii_mode() {
294 check_oracle(BytesMode::Ascii);
295 }
296
297 #[test]
298 fn group_numbering_matches_textual_order() {
299 let tree = crate::Expr::parse_tree("(a)((b)(c))").unwrap();
300 let hir = expr_to_hir(&tree.expr, &mut HirCtx::new(true, true)).unwrap();
301 let cooked = {
302 let mut s = String::new();
303 tree.expr.to_str(&mut s, 0);
304 s
305 };
306 let expected = regex_syntax::ParserBuilder::new().build().parse(&cooked);
307 assert_eq!(expected.unwrap().to_string(), hir.to_string());
308 }
309 }