Skip to main content

aft_base/
pattern_compile.rs

1use regex::bytes::{Regex, RegexBuilder};
2
3const DEFAULT_SIZE_LIMIT_BYTES: usize = 10 * 1024 * 1024;
4
5#[derive(Clone, Debug)]
6pub enum CompiledPattern {
7    Literal(LiteralSearch),
8    Regex {
9        compiled: Regex,
10        raw_pattern: String,
11        case_insensitive: bool,
12    },
13}
14
15#[derive(Clone, Debug, PartialEq, Eq)]
16pub struct LiteralSearch {
17    pub needle: Vec<u8>,
18    pub case_insensitive_ascii: bool,
19}
20
21#[derive(Clone, Debug)]
22pub struct CompileOpts {
23    pub literal: bool,
24    pub case_insensitive: bool,
25    pub multi_line: bool,
26    pub size_limit_bytes: usize,
27}
28
29impl Default for CompileOpts {
30    fn default() -> Self {
31        Self {
32            literal: false,
33            case_insensitive: false,
34            multi_line: true,
35            size_limit_bytes: DEFAULT_SIZE_LIMIT_BYTES,
36        }
37    }
38}
39
40#[derive(Clone, Debug, PartialEq, Eq)]
41pub enum CompileResult {
42    Ok(CompiledPattern),
43    InvalidPattern { message: String, pattern: String },
44    UnsupportedSyntax { feature: String, pattern: String },
45}
46
47impl PartialEq for CompiledPattern {
48    fn eq(&self, other: &Self) -> bool {
49        match (self, other) {
50            (CompiledPattern::Literal(left), CompiledPattern::Literal(right)) => left == right,
51            (
52                CompiledPattern::Regex {
53                    raw_pattern: left_pattern,
54                    case_insensitive: left_case,
55                    ..
56                },
57                CompiledPattern::Regex {
58                    raw_pattern: right_pattern,
59                    case_insensitive: right_case,
60                    ..
61                },
62            ) => left_pattern == right_pattern && left_case == right_case,
63            _ => false,
64        }
65    }
66}
67
68impl Eq for CompiledPattern {}
69
70impl CompiledPattern {
71    pub fn is_literal(&self) -> bool {
72        matches!(self, CompiledPattern::Literal(_))
73    }
74
75    pub fn case_insensitive(&self) -> bool {
76        match self {
77            CompiledPattern::Literal(literal) => literal.case_insensitive_ascii,
78            CompiledPattern::Regex {
79                case_insensitive, ..
80            } => *case_insensitive,
81        }
82    }
83
84    pub fn raw_pattern_for_trigrams(&self) -> String {
85        match self {
86            CompiledPattern::Literal(literal) => {
87                regex::escape(&String::from_utf8_lossy(&literal.needle))
88            }
89            CompiledPattern::Regex { raw_pattern, .. } => raw_pattern.clone(),
90        }
91    }
92}
93
94/// Search the whole input normally, repairing only matches that consumed an
95/// LF. Re-searching the match's starting line recovers the line-local match
96/// that the cross-line match would otherwise hide, then scanning resumes at
97/// the next line start so that lines the cross-line match consumed are checked.
98pub fn for_each_line_match(
99    regex: &regex::bytes::Regex,
100    content: &[u8],
101    mut visit: impl FnMut(usize, usize) -> bool,
102) {
103    let replacement_for = |start: usize, search_from: usize| {
104        let line_start = content[search_from..start]
105            .iter()
106            .rposition(|byte| *byte == b'\n')
107            .map_or(search_from, |newline| search_from + newline + 1);
108        let line_end = content[line_start..]
109            .iter()
110            .position(|byte| *byte == b'\n')
111            .map_or(content.len(), |newline| line_start + newline);
112        let replacement = regex
113            .find(&content[line_start..line_end])
114            .map(|matched| (line_start + matched.start(), line_start + matched.end()));
115        (replacement, line_end + 1)
116    };
117
118    // Keep the common path on the regex crate's streaming iterator. It is
119    // faster than restarting a search for every ordinary match.
120    let mut resume_from = 0;
121    let mut line_search_from = 0;
122    let mut first_pass = true;
123    loop {
124        if first_pass {
125            first_pass = false;
126            let mut resume = None;
127            for matched in regex.find_iter(content) {
128                let start = matched.start();
129                let end = matched.end();
130                if content[start..end].contains(&b'\n') {
131                    let (replacement, next_line_start) = replacement_for(start, line_search_from);
132                    if let Some((replacement_start, replacement_end)) = replacement {
133                        if !visit(replacement_start, replacement_end) {
134                            return;
135                        }
136                    }
137                    resume = Some(next_line_start);
138                    break;
139                }
140                if !visit(start, end) {
141                    return;
142                }
143            }
144            let Some(next_line_start) = resume else {
145                return;
146            };
147            resume_from = next_line_start;
148            line_search_from = next_line_start;
149        } else {
150            if resume_from > content.len() {
151                return;
152            }
153            let Some(matched) = regex.find_at(content, resume_from) else {
154                return;
155            };
156            let start = matched.start();
157            let end = matched.end();
158            if content[start..end].contains(&b'\n') {
159                let (replacement, next_line_start) = replacement_for(start, line_search_from);
160                if let Some((replacement_start, replacement_end)) = replacement {
161                    if !visit(replacement_start, replacement_end) {
162                        return;
163                    }
164                }
165                resume_from = next_line_start;
166                line_search_from = next_line_start;
167            } else {
168                if !visit(start, end) {
169                    return;
170                }
171                resume_from = if start == end { start + 1 } else { end };
172            }
173        }
174    }
175}
176
177pub fn compile(pattern: &str, opts: CompileOpts) -> CompileResult {
178    if pattern.len() > opts.size_limit_bytes {
179        return CompileResult::InvalidPattern {
180            message: format!(
181                "invalid regex: pattern exceeds size limit of {} bytes",
182                opts.size_limit_bytes
183            ),
184            pattern: pattern.to_string(),
185        };
186    }
187
188    if !opts.literal {
189        if let Some(feature) = detect_unsupported_features(pattern) {
190            return CompileResult::UnsupportedSyntax {
191                feature,
192                pattern: pattern.to_string(),
193            };
194        }
195    }
196
197    let has_regex_meta = has_regex_metachar(pattern);
198    let ascii_safe_literal = opts.case_insensitive && pattern.is_ascii();
199    if opts.literal || (!has_regex_meta && (!opts.case_insensitive || ascii_safe_literal)) {
200        if !opts.case_insensitive || pattern.is_ascii() {
201            let needle = if opts.case_insensitive {
202                pattern
203                    .as_bytes()
204                    .iter()
205                    .map(|byte| byte.to_ascii_lowercase())
206                    .collect()
207            } else {
208                pattern.as_bytes().to_vec()
209            };
210            return CompileResult::Ok(CompiledPattern::Literal(LiteralSearch {
211                needle,
212                case_insensitive_ascii: opts.case_insensitive,
213            }));
214        }
215    }
216
217    let mut regex_pattern = if opts.literal || !has_regex_meta {
218        regex::escape(pattern)
219    } else {
220        pattern.to_string()
221    };
222    let mut builder_case_insensitive = opts.case_insensitive;
223    if opts.case_insensitive && !pattern.is_ascii() {
224        regex_pattern = format!("(?i){regex_pattern}");
225        builder_case_insensitive = false;
226    }
227
228    let mut builder = RegexBuilder::new(&regex_pattern);
229    builder.case_insensitive(builder_case_insensitive);
230    builder.multi_line(opts.multi_line);
231    builder.size_limit(opts.size_limit_bytes);
232
233    match builder.build() {
234        Ok(compiled) => CompileResult::Ok(CompiledPattern::Regex {
235            compiled,
236            raw_pattern: regex_pattern,
237            case_insensitive: opts.case_insensitive,
238        }),
239        Err(error) => CompileResult::InvalidPattern {
240            message: format!("invalid regex: {error}"),
241            pattern: pattern.to_string(),
242        },
243    }
244}
245
246pub fn detect_unsupported_features(pattern: &str) -> Option<String> {
247    if ["(?=", "(?!", "(?<=", "(?<!"]
248        .iter()
249        .any(|token| contains_syntax_token(pattern, token))
250    {
251        return Some("lookaround".to_string());
252    }
253    if contains_syntax_token(pattern, "(?P=") || contains_numeric_backreference(pattern) {
254        return Some("backreference".to_string());
255    }
256    if ["*+", "++", "?+"]
257        .iter()
258        .any(|token| contains_syntax_token(pattern, token))
259    {
260        return Some("possessive quantifier".to_string());
261    }
262    if contains_syntax_token(pattern, "(?>") {
263        return Some("atomic group".to_string());
264    }
265    None
266}
267
268fn contains_syntax_token(pattern: &str, token: &str) -> bool {
269    let bytes = pattern.as_bytes();
270    let token = token.as_bytes();
271    let mut index = 0;
272    let mut class_depth = 0usize;
273
274    while index < bytes.len() {
275        match bytes[index] {
276            b'\\' => index = index.saturating_add(2),
277            b'[' => {
278                class_depth = class_depth.saturating_add(1);
279                index += 1;
280            }
281            b']' if class_depth > 0 => {
282                class_depth -= 1;
283                index += 1;
284            }
285            _ if class_depth == 0 && bytes[index..].starts_with(token) => return true,
286            _ => index += 1,
287        }
288    }
289
290    false
291}
292
293fn has_regex_metachar(pattern: &str) -> bool {
294    pattern.chars().any(|c| {
295        matches!(
296            c,
297            '.' | '*' | '+' | '?' | '(' | ')' | '[' | ']' | '{' | '}' | '|' | '^' | '$' | '\\'
298        )
299    })
300}
301
302fn contains_numeric_backreference(pattern: &str) -> bool {
303    let mut escaped = false;
304    for ch in pattern.chars() {
305        if escaped {
306            if ('1'..='9').contains(&ch) {
307                return true;
308            }
309            escaped = false;
310            continue;
311        }
312        escaped = ch == '\\';
313    }
314    false
315}
316
317#[cfg(test)]
318mod tests {
319    use super::*;
320
321    fn assert_literal(pattern: &str, case_insensitive: bool, expected: &[u8]) {
322        let result = compile(
323            pattern,
324            CompileOpts {
325                case_insensitive,
326                ..CompileOpts::default()
327            },
328        );
329        match result {
330            CompileResult::Ok(CompiledPattern::Literal(literal)) => {
331                assert_eq!(literal.needle, expected);
332                assert_eq!(literal.case_insensitive_ascii, case_insensitive);
333            }
334            other => panic!("expected literal, got {other:?}"),
335        }
336    }
337
338    #[test]
339    fn literal_pattern_without_metachars_uses_fast_path() {
340        assert_literal("needle", false, b"needle");
341    }
342
343    #[test]
344    fn ascii_case_insensitive_literal_uses_lowercase_fast_path() {
345        assert_literal("Needle", true, b"needle");
346    }
347
348    #[test]
349    fn non_ascii_case_insensitive_literal_forces_regex_with_inline_flag() {
350        let result = compile(
351            "Äbc",
352            CompileOpts {
353                case_insensitive: true,
354                ..CompileOpts::default()
355            },
356        );
357        match result {
358            CompileResult::Ok(CompiledPattern::Regex {
359                raw_pattern,
360                case_insensitive,
361                ..
362            }) => {
363                assert!(raw_pattern.starts_with("(?i)"));
364                assert!(case_insensitive);
365            }
366            other => panic!("expected regex, got {other:?}"),
367        }
368    }
369
370    #[test]
371    fn regex_pattern_retains_raw_pattern_and_compiles_bytes_regex() {
372        let result = compile("foo.*bar", CompileOpts::default());
373        match result {
374            CompileResult::Ok(CompiledPattern::Regex {
375                compiled,
376                raw_pattern,
377                ..
378            }) => {
379                assert_eq!(raw_pattern, "foo.*bar");
380                assert!(compiled.is_match(b"foo middle bar"));
381            }
382            other => panic!("expected regex, got {other:?}"),
383        }
384    }
385
386    #[test]
387    fn invalid_pattern_surfaces_compile_error() {
388        let result = compile("[", CompileOpts::default());
389        assert!(matches!(result, CompileResult::InvalidPattern { .. }));
390    }
391
392    #[test]
393    fn pattern_exceeding_size_limit_is_invalid() {
394        let result = compile(
395            "abcd",
396            CompileOpts {
397                size_limit_bytes: 3,
398                ..CompileOpts::default()
399            },
400        );
401        assert!(matches!(result, CompileResult::InvalidPattern { .. }));
402    }
403
404    #[test]
405    fn unsupported_syntax_is_detected_before_compile() {
406        for pattern in [
407            "(?=foo)",
408            "(?!foo)",
409            "(?<=foo)",
410            "(?<!foo)",
411            "(?P=name)",
412            r"\1",
413            "foo*+",
414            "(?>foo)",
415        ] {
416            assert!(
417                matches!(
418                    compile(pattern, CompileOpts::default()),
419                    CompileResult::UnsupportedSyntax { .. }
420                ),
421                "{pattern}"
422            );
423        }
424    }
425
426    #[test]
427    fn valid_regex_tokens_are_not_misclassified_as_unsupported() {
428        for (pattern, haystack) in [
429            (r"\*+", b"***".as_slice()),
430            (r"\(?=", b"(=".as_slice()),
431            (r"\(?P=", b"(P=".as_slice()),
432            (r"\(?>", b"(>".as_slice()),
433            (r"[(?=]+", b"(?=".as_slice()),
434            (r"[*+]+", b"*+".as_slice()),
435            (r"[(?>]+", b"(?>".as_slice()),
436            (r"[(?P=]+", b"(?P=".as_slice()),
437        ] {
438            match compile(pattern, CompileOpts::default()) {
439                CompileResult::Ok(CompiledPattern::Regex { compiled, .. }) => {
440                    assert!(compiled.is_match(haystack), "{pattern}");
441                }
442                other => panic!("expected valid regex for {pattern}, got {other:?}"),
443            }
444        }
445    }
446
447    #[test]
448    fn forced_literal_honors_regex_characters() {
449        let result = compile(
450            "foo.*bar",
451            CompileOpts {
452                literal: true,
453                ..CompileOpts::default()
454            },
455        );
456        match result {
457            CompileResult::Ok(CompiledPattern::Literal(literal)) => {
458                assert_eq!(literal.needle, b"foo.*bar");
459            }
460            other => panic!("expected literal, got {other:?}"),
461        }
462    }
463}