globset: support nested alternates
Before adoption: this commit came in with the history the project adopted, so no landing records it.
For example, `**/{node_modules/**/*/{ts,js},crates/**/*.{rs,toml}`. I originally didn't add this I think for implementation simplicity, but it turns out that it really isn't much work to do. There might have also been some odd behavior in the regex engine for dealing with empty alternates, but that has all been long fixed. Closes #3048, Closes #3112
authored by Luke Sandberg · committed by Andrew Gallant · parent b0c6d4c · Browse files · 3 files·+51 added−29 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+51 added−29 removed
- other:+51 added−29 removed
Provenance
- Commit
5f5da48- Tree
fcc61df- Author
Luke Sandberg <lukeisandberg@gmail.com>- Committer
Andrew Gallant <jamslam@gmail.com>- Parent
b0c6d4c
3 files changed+51 added−29 removed
modified:crates/globset/src/glob.rs+44 added-27 removed
581 unmodified lines582 /// Parses and builds the pattern.583 pub fn build(&self) -> Result<Glob, Error> {584 let mut p = Parser {585 glob: &self.glob,586+ alternates_stack: Vec::new(),586- stack: vec![Tokens::default()],587+ branches: vec![Tokens::default()],588 chars: self.glob.chars().peekable(),589 prev: None,590 cur: None,591 opts: &self.opts,592 };593 p.parse()?;593- if p.stack.is_empty() {594+ if p.branches.is_empty() {595+ // OK because of how the the branches/alternate_stack are managed.596+ // If we end up here, then there *must* be a bug in the parser597+ // somewhere.598+ unreachable!()599+ } else if p.branches.len() > 1 {600 Err(Error {601 glob: Some(self.glob.to_string()),596- kind: ErrorKind::UnopenedAlternates,597- })598- } else if p.stack.len() > 1 {599- Err(Error {600- glob: Some(self.glob.to_string()),602 kind: ErrorKind::UnclosedAlternates,603 })604 } else {604- let tokens = p.stack.pop().unwrap();605+ let tokens = p.branches.pop().unwrap();606 Ok(Glob {607 glob: self.glob.to_string(),608 re: tokens.to_regex_with(&self.opts),609 opts: self.opts,166 unmodified lines776 }777 778 struct Parser<'a> {779 glob: &'a str,780+ // Marks the index in `stack` where the alternation started.781+ alternates_stack: Vec<usize>,782+ // The set of active alternation branches being parsed.783+ // Tokens are added to the end of the last one.779- stack: Vec<Tokens>,784+ branches: Vec<Tokens>,785 chars: std::iter::Peekable<std::str::Chars<'a>>,786 prev: Option<char>,787 cur: Option<char>,788 opts: &'a GlobOptions,20 unmodified lines809 Ok(())810 }811 812 fn push_alternate(&mut self) -> Result<(), Error> {808- if self.stack.len() > 1 {809- return Err(self.error(ErrorKind::NestedAlternates));810- }811- Ok(self.stack.push(Tokens::default()))813+ self.alternates_stack.push(self.branches.len());814+ self.branches.push(Tokens::default());815+ Ok(())816 }817 818 fn pop_alternate(&mut self) -> Result<(), Error> {815- let mut alts = vec![];816- while self.stack.len() >= 2 {817- alts.push(self.stack.pop().unwrap());818- }819- self.push_token(Token::Alternates(alts))819+ let Some(start) = self.alternates_stack.pop() else {820+ return Err(self.error(ErrorKind::UnopenedAlternates));821+ };822+ assert!(start <= self.branches.len());823+ let alts = Token::Alternates(self.branches.drain(start..).collect());824+ self.push_token(alts)?;825+ Ok(())826 }827 828 fn push_token(&mut self, tok: Token) -> Result<(), Error> {823- if let Some(ref mut pat) = self.stack.last_mut() {829+ if let Some(ref mut pat) = self.branches.last_mut() {830 return Ok(pat.push(tok));831 }832 Err(self.error(ErrorKind::UnopenedAlternates))833 }834 835 fn pop_token(&mut self) -> Result<Token, Error> {830- if let Some(ref mut pat) = self.stack.last_mut() {836+ if let Some(ref mut pat) = self.branches.last_mut() {837 return Ok(pat.pop().unwrap());838 }839 Err(self.error(ErrorKind::UnopenedAlternates))840 }841 842 fn have_tokens(&self) -> Result<bool, Error> {837- match self.stack.last() {843+ match self.branches.last() {844 None => Err(self.error(ErrorKind::UnopenedAlternates)),845 Some(ref pat) => Ok(!pat.is_empty()),846 }847 }848 849 fn parse_comma(&mut self) -> Result<(), Error> {850 // If we aren't inside a group alternation, then don't851 // treat commas specially. Otherwise, we need to start846- // a new alternate.847- if self.stack.len() <= 1 {852+ // a new alternate branch.853+ if self.alternates_stack.is_empty() {854 self.push_token(Token::Literal(','))855 } else {850- Ok(self.stack.push(Tokens::default()))856+ Ok(self.branches.push(Tokens::default()))857 }858 }859 860 fn parse_backslash(&mut self) -> Result<(), Error> {28 unmodified lines889 return Ok(());890 }891 892 if !prev.map(is_separator).unwrap_or(false) {887- if self.stack.len() <= 1893+ if self.branches.len() <= 1894 || (prev != Some(',') && prev != Some('{'))895 {896 self.push_token(Token::ZeroOrMore)?;897 self.push_token(Token::ZeroOrMore)?;4 unmodified lines902 None => {903 assert!(self.bump().is_none());904 true905 }900- Some(',') | Some('}') if self.stack.len() >= 2 => true,906+ Some(',') | Some('}') if self.branches.len() >= 2 => true,907 Some(c) if is_separator(c) => {908 assert!(self.bump().map(is_separator).unwrap_or(false));909 false910 }319 unmodified lines1230 syntaxerr!(err_unclosed3, "[!", ErrorKind::UnclosedClass);1231 syntaxerr!(err_unclosed4, "[!]", ErrorKind::UnclosedClass);1232 syntaxerr!(err_range1, "[z-a]", ErrorKind::InvalidRange('z', 'a'));1233 syntaxerr!(err_range2, "[z--]", ErrorKind::InvalidRange('z', '-'));1234+ syntaxerr!(err_alt1, "{a,b", ErrorKind::UnclosedAlternates);1235+ syntaxerr!(err_alt2, "{a,{b,c}", ErrorKind::UnclosedAlternates);1236+ syntaxerr!(err_alt3, "a,b}", ErrorKind::UnopenedAlternates);1237+ syntaxerr!(err_alt4, "{a,b}}", ErrorKind::UnopenedAlternates);1238 1239 const CASEI: Options =1240 Options { casei: Some(true), litsep: None, bsesc: None, ealtre: None };1241 const SLASHLIT: Options =12 unmodified lines1254 bsesc: Some(true),1255 ealtre: Some(true),1256 };1257 1258+ toregex!(re_empty, "", "^$");1259+1260 toregex!(re_casei, "a", "(?i)^a$", &CASEI);1261 1262 toregex!(re_slash1, "?", r"^[^/]$", SLASHLIT);1263 toregex!(re_slash2, "*", r"^[^/]*$", SLASHLIT);31 unmodified lines1295 toregex!(re31, "***", r"^.*.*.*$");1296 toregex!(re32, "/a**", r"^/a.*.*$");1297 toregex!(re33, "/**a", r"^/.*.*a$");1298 toregex!(re34, "/a**b", r"^/a.*.*b$");1287- toregex!(re35, "{a,b}", r"^(?:b|a)$");1299+ toregex!(re35, "{a,b}", r"^(?:a|b)$");1300+ toregex!(re36, "{a,{b,c}}", r"^(?:a|(?:b|c))$");1301+ toregex!(re37, "{{a,b},{c,d}}", r"^(?:(?:a|b)|(?:c|d))$");1302 1303 matches!(match1, "a", "a");1304 matches!(match2, "a*b", "a_b");1305 matches!(match3, "a*b*c", "abc");79 unmodified lines1385 matches!(matchalt13, "{*.foo,*.bar,*.wat}", "test.wat");1386 matches!(matchalt14, "foo{,.txt}", "foo.txt");1387 nmatches!(matchalt15, "foo{,.txt}", "foo");1388 matches!(matchalt16, "foo{,.txt}", "foo", EALTRE);1389+ matches!(matchalt17, "{a,b{c,d}}", "bc");1390+ matches!(matchalt18, "{a,b{c,d}}", "bd");1391+ matches!(matchalt19, "{a,b{c,d}}", "a");1392 1393 matches!(matchslash1, "abc/def", "abc/def", SLASHLIT);1394 #[cfg(unix)]1395 nmatches!(matchslash2, "abc?def", "abc/def", SLASHLIT);199 unmodified linesmodified:crates/globset/src/lib.rs+5 added-2 removed
180 unmodified lines181 /// Occurs when a `}` is found without a matching `{`.182 UnopenedAlternates,183 /// Occurs when a `{` is found without a matching `}`.184 UnclosedAlternates,185- /// Occurs when an alternating group is nested inside another alternating186- /// group, e.g., `{{a,b},{c,d}}`.185+ /// **DEPRECATED**.186+ ///187+ /// This error used to occur when an alternating group was nested inside188+ /// another alternating group, e.g., `{{a,b},{c,d}}`. However, this is now189+ /// supported and as such this error cannot occur.190 NestedAlternates,191 /// Occurs when an unescaped '\' is found at the end of a glob.192 DanglingEscape,193 /// An error associated with parsing or compiling a regex.925 unmodified linesmodified:CHANGELOG.md+2 added
35 unmodified lines36 * [FEATURE #2849](https://github.com/BurntSushi/ripgrep/pull/2849):37 When using multithreading, schedule files to search in order given on CLI.38 * [FEATURE #2943](https://github.com/BurntSushi/ripgrep/issues/2943):39 Add `aarch64` release artifacts for Windows.40+* [FEATURE #3048](https://github.com/BurntSushi/ripgrep/pull/3048):41+ Globs in ripgrep (and the `globset` crate) now support nested alternates.42 43 44 14.1.1 (2024-09-08)45 ===================1709 unmodified lines