1use crate::error;
4
5pub enum ExtendedGlobKind {
7 Plus,
9 At,
11 Exclamation,
13 Question,
15 Star,
17}
18
19pub 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
34fn 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 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 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 ['\\'] [c] { (std::format!("\\{c}"), c) } /
133 [c if matches!(c, '[' | '^' | '-')] { (std::format!("\\{c}"), c) } /
137 [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 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 &[')'] { vec![] } /
188 extended_glob_branch() ** "|"
190
191 rule extended_glob_branch() -> String =
192 &['|' | ')'] { String::new() } /
194 pieces:(!['|' | ')'] piece:pattern_piece() { piece })+ {
195 pieces.join("")
196 }
197
198 rule glob_piece() =
200 bracket_expression() /
201 extglob_enabled() extended_glob_pattern() /
202 wildcard()
203
204 rule non_glob_piece() =
206 escape_sequence() /
207 !glob_piece() [_]
208
209 pub(crate) rule has_glob_metacharacters() -> bool =
214 non_glob_piece()* glob_piece() [_]* { true }
215 }
216}
217
218pub 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
232pub 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 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 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 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 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 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 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 assert!(pattern_has_glob_metacharacters("[]]", false));
348 assert!(pattern_has_glob_metacharacters("[][]", false));
349 assert!(pattern_has_glob_metacharacters("[!]]", false));
350
351 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 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 assert!(!pattern_has_glob_metacharacters("hello", false));
365 assert!(!pattern_has_glob_metacharacters("", false));
366
367 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 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 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 assert!(pattern_has_glob_metacharacters("*(a)", false));
384 assert!(pattern_has_glob_metacharacters("?(a)", false));
385 }
386}