Skip to main content

brush_parser/
pattern.rs

1//! Implements parsing for shell glob and extglob patterns.
2
3use crate::error;
4
5/// Represents the kind of an extended glob.
6pub enum ExtendedGlobKind {
7    /// The `+` extended glob; matches one or more occurrences of the inner pattern.
8    Plus,
9    /// The `@` extended glob; allows matching an alternation of inner patterns.
10    At,
11    /// The `!` extended glob; matches the negation of the inner pattern.
12    Exclamation,
13    /// The `?` extended glob; matches zero or one occurrence of the inner pattern.
14    Question,
15    /// The `*` extended glob; matches zero or more occurrences of the inner pattern.
16    Star,
17}
18
19/// Converts a shell pattern to a regular expression string.
20///
21/// # Arguments
22///
23/// * `pattern` - The shell pattern to convert.
24/// * `enable_extended_globbing` - Whether to enable extended globbing (extglob).
25pub fn pattern_to_regex_str(
26    pattern: &str,
27    enable_extended_globbing: bool,
28) -> Result<String, error::WordParseError> {
29    let regex_str = pattern_to_regex_translator::pattern(pattern, enable_extended_globbing)
30        .map_err(|e| error::WordParseError::Pattern(e.into()))?;
31    Ok(regex_str)
32}
33
34/// Formats a range between two bracket expression members, returning `None` if the
35/// range is reversed (and therefore matches nothing).
36fn bracket_range(from: (String, char), to: (String, char)) -> Option<String> {
37    let (from_str, from_c) = from;
38    let (to_str, to_c) = to;
39
40    if from_c <= to_c {
41        Some(std::format!("{from_str}-{to_str}"))
42    } else {
43        None
44    }
45}
46
47peg::parser! {
48    grammar pattern_to_regex_translator(enable_extended_globbing: bool) for str {
49        pub(crate) rule pattern() -> String =
50            pieces:(pattern_piece()*) {
51                pieces.join("")
52            }
53
54        rule pattern_piece() -> String =
55            escape_sequence() /
56            bracket_expression() /
57            extglob_enabled() s:extended_glob_pattern() { s } /
58            wildcard() /
59            [c if regex_char_needs_escaping(c)] {
60                let mut s = '\\'.to_string();
61                s.push(c);
62                s
63            } /
64            [c] { c.to_string() }
65
66        rule escape_sequence() -> String =
67            sequence:$(['\\'] [c if regex_char_needs_escaping(c)]) { sequence.to_owned() } /
68            ['\\'] [c] { c.to_string() }
69
70        rule bracket_expression() -> String =
71            "[" invert:(invert_char()?) leading:(leading_bracket_member()?) members:bracket_member()* "]" {
72                let mut members = leading
73                    .into_iter()
74                    .chain(members)
75                    .flatten()
76                    .collect::<Vec<_>>();
77
78                // If we completed the parse but ended up with no valid members
79                // of the bracket expression, then return a regex that matches nothing.
80                // (Or in the inverted case, matches everything.)
81                if members.is_empty() {
82                    if invert.is_some() {
83                        String::from(".")
84                    } else {
85                        String::from("(?!)")
86                    }
87                } else {
88                    if invert.is_some() {
89                        members.insert(0, String::from("^"));
90                    }
91
92                    std::format!("[{}]", members.join(""))
93                }
94            }
95
96        // A ']' first in the expression (after any '!' or '^') is a member, not the end.
97        // It may also be the low end of a range, so it goes through the same range
98        // validation as any other member.
99        rule leading_bracket_member() -> Option<String> =
100            from:close_bracket_member() "-" to:single_char_bracket_member() {
101                bracket_range(from, to)
102            } /
103            from:close_bracket_member() { Some(from.0) }
104
105        rule close_bracket_member() -> (String, char) =
106            "]" { (String::from(r"\]"), ']') }
107
108        rule invert_char() -> bool =
109            ['!' | '^'] { true }
110
111        rule bracket_member() -> Option<String> =
112            e:char_class_expression() { Some(e) } /
113            r:char_range() { r } /
114            m:single_char_bracket_member() {
115                let (char_str, _) = m;
116                Some(char_str)
117            }
118
119        rule char_class_expression() -> String =
120            e:$("[:" char_class() ":]") { e.to_owned() }
121
122        rule char_class() =
123            "alnum" / "alpha" / "blank" / "cntrl" / "digit" / "graph" / "lower" / "print" / "punct" / "space" / "upper"/ "xdigit"
124
125        rule char_range() -> Option<String> =
126            from:single_char_bracket_member() "-" to:single_char_bracket_member() {
127                bracket_range(from, to)
128            }
129
130        rule single_char_bracket_member() -> (String, char) =
131            // Preserve escaped characters as-is.
132            ['\\'] [c] { (std::format!("\\{c}"), c) } /
133            // Escape the characters that are special inside a regex character class;
134            // left bare, a '^' first in the class would negate it and a '-' would be
135            // read as a range separator.
136            [c if matches!(c, '[' | '^' | '-')] { (std::format!("\\{c}"), c) } /
137            // Any other character except closing bracket gets added as-is.
138            [c if c != ']'] { (c.to_string(), c) }
139
140        rule wildcard() -> String =
141            "?" { String::from(".") } /
142            "*" { String::from(".*") }
143
144        rule extglob_enabled() -> () =
145            &[_] {? if enable_extended_globbing { Ok(()) } else { Err("extglob disabled") } }
146
147        pub(crate) rule extended_glob_pattern() -> String =
148            kind:extended_glob_prefix() "(" branches:extended_glob_body() ")" {
149                let mut s = String::new();
150
151                // fancy_regex uses ?! to indicate a negative lookahead.
152                if matches!(kind, ExtendedGlobKind::Exclamation) {
153                    if !branches.is_empty() {
154                        s.push_str("(?:(?!");
155                        s.push_str(&branches.join("|"));
156                        s.push_str(").*|(?>");
157                        s.push_str(&branches.join("|"));
158                        s.push_str(").+?|)");
159                    } else {
160                        s.push_str("(?:.+)");
161                    }
162                } else {
163                    s.push('(');
164                    s.push_str(&branches.join("|"));
165                    s.push(')');
166
167                    match kind {
168                        ExtendedGlobKind::Plus => s.push('+'),
169                        ExtendedGlobKind::Question => s.push('?'),
170                        ExtendedGlobKind::Star => s.push('*'),
171                        ExtendedGlobKind::At | ExtendedGlobKind::Exclamation => (),
172                    }
173                }
174
175                s
176            }
177
178        rule extended_glob_prefix() -> ExtendedGlobKind =
179            "+" { ExtendedGlobKind::Plus } /
180            "@" { ExtendedGlobKind::At } /
181            "!" { ExtendedGlobKind::Exclamation } /
182            "?" { ExtendedGlobKind::Question } /
183            "*" { ExtendedGlobKind::Star }
184
185        pub(crate) rule extended_glob_body() -> Vec<String> =
186            // Cover case with *no* branches.
187            &[')'] { vec![] } /
188            // Otherwise, look for branches separated by '|'.
189            extended_glob_branch() ** "|"
190
191        rule extended_glob_branch() -> String =
192            // Cover case of empty branch.
193            &['|' | ')'] { String::new() } /
194            pieces:(!['|' | ')'] piece:pattern_piece() { piece })+ {
195                pieces.join("")
196            }
197
198        // A glob metacharacter construct: wildcard, bracket expression, or extglob.
199        rule glob_piece() =
200            bracket_expression() /
201            extglob_enabled() extended_glob_pattern() /
202            wildcard()
203
204        // A non-glob piece: an escape sequence or any character not starting a glob.
205        rule non_glob_piece() =
206            escape_sequence() /
207            !glob_piece() [_]
208
209        // Succeeds (returning true) if the pattern contains at least one glob
210        // metacharacter. The same bracket_expression, wildcard, and
211        // extended_glob_pattern rules used for regex conversion are reused here
212        // via negative lookaheads, keeping a single source of truth.
213        pub(crate) rule has_glob_metacharacters() -> bool =
214            non_glob_piece()* glob_piece() [_]* { true }
215    }
216}
217
218/// Returns whether a pattern string contains any glob metacharacters.
219///
220/// Uses the same PEG grammar rules that `pattern_to_regex_str` uses, keeping
221/// a single source of truth for what constitutes a glob metacharacter.
222///
223/// # Arguments
224///
225/// * `pattern` - The shell pattern to check.
226/// * `enable_extended_globbing` - Whether to enable extended globbing (extglob).
227pub fn pattern_has_glob_metacharacters(pattern: &str, enable_extended_globbing: bool) -> bool {
228    pattern_to_regex_translator::has_glob_metacharacters(pattern, enable_extended_globbing)
229        .unwrap_or(false)
230}
231
232/// Returns whether or not a given character needs to be escaped in a regular expression.
233///
234/// # Arguments
235///
236/// * `c` - The character to check.
237pub const fn regex_char_needs_escaping(c: char) -> bool {
238    matches!(
239        c,
240        '[' | ']' | '(' | ')' | '{' | '}' | '*' | '?' | '.' | '+' | '^' | '$' | '|' | '\\' | '-'
241    )
242}
243
244#[cfg(test)]
245#[expect(clippy::panic_in_result_fn)]
246mod tests {
247    use super::*;
248    use anyhow::Result;
249
250    #[test]
251    fn test_bracket_exprs() -> Result<()> {
252        assert_eq!(pattern_to_regex_str("[a-z]", true)?, "[a-z]");
253        assert_eq!(pattern_to_regex_str("[z-a]", true)?, "(?!)");
254        assert_eq!(pattern_to_regex_str("[+-/]", true)?, "[+-/]");
255        assert_eq!(pattern_to_regex_str(r"[\*-/]", true)?, r"[\*-/]");
256        assert_eq!(pattern_to_regex_str("[abc]", true)?, "[abc]");
257        assert_eq!(pattern_to_regex_str(r"[\(]", true)?, r"[\(]");
258        assert_eq!(pattern_to_regex_str(r"[(]", true)?, "[(]");
259        assert_eq!(pattern_to_regex_str("[[:digit:]]", true)?, "[[:digit:]]");
260        assert_eq!(pattern_to_regex_str(r"[-(),!]*", true)?, r"[\-(),!].*");
261        assert_eq!(
262            pattern_to_regex_str(r"[-\(\),\!]*", true)?,
263            r"[\-\(\),\!].*"
264        );
265        assert_eq!(pattern_to_regex_str(r"[a\-b]", true)?, r"[a\-b]");
266        assert_eq!(pattern_to_regex_str(r"[a\-\*]", true)?, r"[a\-\*]");
267
268        // A ']' in the first member position (after any '!' or '^') is a member of the
269        // bracket expression, not its terminator.
270        assert_eq!(pattern_to_regex_str("[]]", true)?, r"[\]]");
271        assert_eq!(pattern_to_regex_str("[][]", true)?, r"[\]\[]");
272        assert_eq!(pattern_to_regex_str("[]abc[]", true)?, r"[\]abc\[]");
273        assert_eq!(pattern_to_regex_str("[]]]", true)?, r"[\]]\]");
274        assert_eq!(pattern_to_regex_str("[!]]", true)?, r"[^\]]");
275        assert_eq!(pattern_to_regex_str("[^][]", true)?, r"[^\]\[]");
276
277        // A range starting at that ']' is validated like any other range.
278        assert_eq!(pattern_to_regex_str("[]-a]", true)?, r"[\]-a]");
279        assert_eq!(pattern_to_regex_str("[]-a[]", true)?, r"[\]-a\[]");
280        assert_eq!(pattern_to_regex_str("[]-A]", true)?, "(?!)");
281        assert_eq!(pattern_to_regex_str("[!]-A]", true)?, ".");
282
283        // '^' and '-' are escaped as members, so a '^' left first by a dropped
284        // range can't negate the class and a '-' endpoint can't be read as a
285        // range separator.
286        assert_eq!(pattern_to_regex_str("[9-0^a]", true)?, r"[\^a]");
287        assert_eq!(pattern_to_regex_str("[z-a^]", true)?, r"[\^]");
288        assert_eq!(pattern_to_regex_str("[+--]", true)?, r"[+-\-]");
289        assert_eq!(pattern_to_regex_str("[--/]", true)?, r"[\--/]");
290
291        // An unterminated bracket expression is still just literal text.
292        assert_eq!(pattern_to_regex_str("[]", true)?, r"\[\]");
293        assert_eq!(pattern_to_regex_str("[!]", true)?, r"\[!\]");
294
295        Ok(())
296    }
297
298    #[test]
299    fn test_extended_glob() -> Result<()> {
300        assert_eq!(
301            pattern_to_regex_translator::extended_glob_pattern("@(a|b)", true)?,
302            "(a|b)"
303        );
304
305        assert_eq!(
306            pattern_to_regex_translator::extended_glob_pattern("@(|a)", true)?,
307            "(|a)"
308        );
309
310        assert_eq!(
311            pattern_to_regex_translator::extended_glob_pattern("@(|)", true)?,
312            "(|)"
313        );
314
315        assert_eq!(
316            pattern_to_regex_translator::extended_glob_body("ab|ac", true)?,
317            vec!["ab", "ac"],
318        );
319
320        assert_eq!(
321            pattern_to_regex_translator::extended_glob_pattern("*(ab|ac)", true)?,
322            "(ab|ac)*"
323        );
324
325        assert_eq!(
326            pattern_to_regex_translator::extended_glob_body("", true)?,
327            Vec::<String>::new(),
328        );
329
330        Ok(())
331    }
332
333    #[test]
334    fn test_has_glob_metacharacters() {
335        // Basic metacharacters.
336        assert!(pattern_has_glob_metacharacters("*", false));
337        assert!(pattern_has_glob_metacharacters("?", false));
338        assert!(pattern_has_glob_metacharacters("a*b", false));
339        assert!(pattern_has_glob_metacharacters("a?b", false));
340
341        // Valid bracket expressions.
342        assert!(pattern_has_glob_metacharacters("[abc]", false));
343        assert!(pattern_has_glob_metacharacters("[a-z]", false));
344        assert!(pattern_has_glob_metacharacters("[!a]", false));
345
346        // A leading ']' is a member, so these are bracket expressions too.
347        assert!(pattern_has_glob_metacharacters("[]]", false));
348        assert!(pattern_has_glob_metacharacters("[][]", false));
349        assert!(pattern_has_glob_metacharacters("[!]]", false));
350
351        // Lone `]` is NOT a glob metacharacter.
352        assert!(!pattern_has_glob_metacharacters("]", false));
353        assert!(!pattern_has_glob_metacharacters("foo]", false));
354        assert!(!pattern_has_glob_metacharacters("a]b", false));
355
356        // Lone `[` without matching `]` is NOT a glob metacharacter.
357        assert!(!pattern_has_glob_metacharacters("[", false));
358        assert!(!pattern_has_glob_metacharacters("[]", false));
359        assert!(!pattern_has_glob_metacharacters("[!]", false));
360        assert!(!pattern_has_glob_metacharacters("[abc", false));
361        assert!(!pattern_has_glob_metacharacters("a[b", false));
362
363        // Plain text — no glob chars.
364        assert!(!pattern_has_glob_metacharacters("hello", false));
365        assert!(!pattern_has_glob_metacharacters("", false));
366
367        // Backslash-escaped metacharacters are not globs.
368        assert!(!pattern_has_glob_metacharacters(r"\*", false));
369        assert!(!pattern_has_glob_metacharacters(r"\?", false));
370        assert!(!pattern_has_glob_metacharacters(r"\[abc]", false));
371
372        // Extglob patterns — not detected without extended globbing.
373        assert!(!pattern_has_glob_metacharacters("@(a)", false));
374        assert!(!pattern_has_glob_metacharacters("!(a)", false));
375        assert!(!pattern_has_glob_metacharacters("+(a)", false));
376
377        // Extglob patterns — detected with extended globbing.
378        assert!(pattern_has_glob_metacharacters("@(a)", true));
379        assert!(pattern_has_glob_metacharacters("!(a)", true));
380        assert!(pattern_has_glob_metacharacters("+(a)", true));
381
382        // *( and ?( are already caught by * and ? checks.
383        assert!(pattern_has_glob_metacharacters("*(a)", false));
384        assert!(pattern_has_glob_metacharacters("?(a)", false));
385    }
386}