Skip to main content

globset/
glob.rs

1use std::fmt::Write;
2use std::path::{Path, is_separator};
3
4use regex_automata::meta::Regex;
5
6use crate::{Candidate, Error, ErrorKind, new_regex};
7
8/// Describes a matching strategy for a particular pattern.
9///
10/// This provides a way to more quickly determine whether a pattern matches
11/// a particular file path in a way that scales with a large number of
12/// patterns. For example, if many patterns are of the form `*.ext`, then it's
13/// possible to test whether any of those patterns matches by looking up a
14/// file path's extension in a hash table.
15#[derive(Clone, Debug, Eq, PartialEq)]
16pub(crate) enum MatchStrategy {
17    /// A pattern matches if and only if the entire file path matches this
18    /// literal string.
19    Literal(String),
20    /// A pattern matches if and only if the file path's basename matches this
21    /// literal string.
22    BasenameLiteral(String),
23    /// A pattern matches if and only if the file path's extension matches this
24    /// literal string.
25    Extension(String),
26    /// A pattern matches if and only if this prefix literal is a prefix of the
27    /// candidate file path.
28    Prefix(String),
29    /// A pattern matches if and only if this prefix literal is a prefix of the
30    /// candidate file path.
31    ///
32    /// An exception: if `component` is true, then `suffix` must appear at the
33    /// beginning of a file path or immediately following a `/`.
34    Suffix {
35        /// The actual suffix.
36        suffix: String,
37        /// Whether this must start at the beginning of a path component.
38        component: bool,
39    },
40    /// A pattern matches only if the given extension matches the file path's
41    /// extension. Note that this is a necessary but NOT sufficient criterion.
42    /// Namely, if the extension matches, then a full regex search is still
43    /// required.
44    RequiredExtension(String),
45    /// A regex that only needs to inspect the final path component.
46    BasenameRegex(String),
47    /// A regex needs to be used for matching.
48    Regex,
49}
50
51impl MatchStrategy {
52    /// Returns a matching strategy for the given pattern.
53    pub(crate) fn new(pat: &Glob) -> MatchStrategy {
54        if let Some(lit) = pat.basename_literal() {
55            MatchStrategy::BasenameLiteral(lit)
56        } else if let Some(lit) = pat.literal() {
57            MatchStrategy::Literal(lit)
58        } else if let Some(ext) = pat.ext() {
59            MatchStrategy::Extension(ext)
60        } else if let Some(prefix) = pat.prefix() {
61            MatchStrategy::Prefix(prefix)
62        } else if let Some((suffix, component)) = pat.suffix() {
63            MatchStrategy::Suffix { suffix, component }
64        } else if let Some(ext) = pat.required_ext() {
65            MatchStrategy::RequiredExtension(ext)
66        } else if let Some(re) = pat.basename_regex() {
67            MatchStrategy::BasenameRegex(re)
68        } else {
69            MatchStrategy::Regex
70        }
71    }
72}
73
74/// Glob represents a successfully parsed shell glob pattern.
75///
76/// It cannot be used directly to match file paths, but it can be converted
77/// to a regular expression string or a matcher.
78#[derive(Clone, Eq)]
79#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
80pub struct Glob {
81    glob: String,
82    re: String,
83    opts: GlobOptions,
84    tokens: Tokens,
85}
86
87impl AsRef<Glob> for Glob {
88    fn as_ref(&self) -> &Glob {
89        self
90    }
91}
92
93impl PartialEq for Glob {
94    fn eq(&self, other: &Glob) -> bool {
95        self.glob == other.glob && self.opts == other.opts
96    }
97}
98
99impl std::hash::Hash for Glob {
100    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
101        self.glob.hash(state);
102        self.opts.hash(state);
103    }
104}
105
106impl std::fmt::Debug for Glob {
107    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108        if f.alternate() {
109            f.debug_struct("Glob")
110                .field("glob", &self.glob)
111                .field("re", &self.re)
112                .field("opts", &self.opts)
113                .field("tokens", &self.tokens)
114                .finish()
115        } else {
116            f.debug_tuple("Glob").field(&self.glob).finish()
117        }
118    }
119}
120
121impl std::fmt::Display for Glob {
122    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123        self.glob.fmt(f)
124    }
125}
126
127impl std::str::FromStr for Glob {
128    type Err = Error;
129
130    fn from_str(glob: &str) -> Result<Self, Self::Err> {
131        Self::new(glob)
132    }
133}
134
135/// A matcher for a single pattern.
136#[derive(Clone, Debug)]
137pub struct GlobMatcher {
138    /// The underlying pattern.
139    pat: Glob,
140    /// The pattern, as a compiled regex.
141    re: Regex,
142}
143
144impl GlobMatcher {
145    /// Tests whether the given path matches this pattern or not.
146    pub fn is_match<P: AsRef<Path>>(&self, path: P) -> bool {
147        self.is_match_candidate(&Candidate::new(path.as_ref()))
148    }
149
150    /// Tests whether the given path matches this pattern or not.
151    pub fn is_match_candidate(&self, path: &Candidate<'_>) -> bool {
152        self.re.is_match(&path.path)
153    }
154
155    /// Returns the `Glob` used to compile this matcher.
156    pub fn glob(&self) -> &Glob {
157        &self.pat
158    }
159}
160
161/// A strategic matcher for a single pattern.
162#[cfg(test)]
163#[derive(Clone, Debug)]
164struct GlobStrategic {
165    /// The match strategy to use.
166    strategy: MatchStrategy,
167    /// The pattern, as a compiled regex.
168    re: Regex,
169}
170
171#[cfg(test)]
172impl GlobStrategic {
173    /// Tests whether the given path matches this pattern or not.
174    fn is_match<P: AsRef<Path>>(&self, path: P) -> bool {
175        self.is_match_candidate(&Candidate::new(path.as_ref()))
176    }
177
178    /// Tests whether the given path matches this pattern or not.
179    fn is_match_candidate(&self, candidate: &Candidate<'_>) -> bool {
180        let byte_path = &*candidate.path;
181
182        match self.strategy {
183            MatchStrategy::Literal(ref lit) => lit.as_bytes() == byte_path,
184            MatchStrategy::BasenameLiteral(ref lit) => {
185                lit.as_bytes() == &*candidate.basename
186            }
187            MatchStrategy::Extension(ref ext) => {
188                ext.as_bytes() == &*candidate.ext
189            }
190            MatchStrategy::Prefix(ref pre) => {
191                starts_with(pre.as_bytes(), byte_path)
192            }
193            MatchStrategy::Suffix { ref suffix, component } => {
194                if component && byte_path == &suffix.as_bytes()[1..] {
195                    return true;
196                }
197                ends_with(suffix.as_bytes(), byte_path)
198            }
199            MatchStrategy::RequiredExtension(ref ext) => {
200                let ext = ext.as_bytes();
201                &*candidate.ext == ext && self.re.is_match(byte_path)
202            }
203            MatchStrategy::BasenameRegex(_) => {
204                self.re.is_match(candidate.basename_for_regex())
205            }
206            MatchStrategy::Regex => self.re.is_match(byte_path),
207        }
208    }
209}
210
211/// A builder for a pattern.
212///
213/// This builder enables configuring the match semantics of a pattern. For
214/// example, one can make matching case insensitive.
215///
216/// The lifetime `'a` refers to the lifetime of the pattern string.
217#[derive(Clone, Debug)]
218pub struct GlobBuilder<'a> {
219    /// The glob pattern to compile.
220    glob: &'a str,
221    /// Options for the pattern.
222    opts: GlobOptions,
223}
224
225#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
226#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
227struct GlobOptions {
228    /// Whether to match case insensitively.
229    case_insensitive: bool,
230    /// Whether to require a literal separator to match a separator in a file
231    /// path. e.g., when enabled, `*` won't match `/`.
232    literal_separator: bool,
233    /// Whether or not to use `\` to escape special characters.
234    /// e.g., when enabled, `\*` will match a literal `*`.
235    backslash_escape: bool,
236    /// Whether or not an empty case in an alternate will be removed.
237    /// e.g., when enabled, `{,a}` will match "" and "a".
238    empty_alternates: bool,
239    /// Whether or not an unclosed character class is allowed. When an unclosed
240    /// character class is found, the opening `[` is treated as a literal `[`.
241    /// When this isn't enabled, an opening `[` without a corresponding `]` is
242    /// treated as an error.
243    allow_unclosed_class: bool,
244}
245
246impl GlobOptions {
247    fn default() -> GlobOptions {
248        GlobOptions {
249            case_insensitive: false,
250            literal_separator: false,
251            backslash_escape: !is_separator('\\'),
252            empty_alternates: false,
253            allow_unclosed_class: false,
254        }
255    }
256}
257
258#[derive(Clone, Debug, Default, Eq, PartialEq)]
259#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
260struct Tokens(Vec<Token>);
261
262impl std::ops::Deref for Tokens {
263    type Target = Vec<Token>;
264    fn deref(&self) -> &Vec<Token> {
265        &self.0
266    }
267}
268
269impl std::ops::DerefMut for Tokens {
270    fn deref_mut(&mut self) -> &mut Vec<Token> {
271        &mut self.0
272    }
273}
274
275#[derive(Clone, Debug, Eq, PartialEq)]
276#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
277enum Token {
278    Literal(char),
279    Any,
280    ZeroOrMore,
281    RecursivePrefix,
282    RecursiveSuffix,
283    RecursiveZeroOrMore,
284    Class { negated: bool, ranges: Vec<(char, char)> },
285    Alternates(Vec<Tokens>),
286}
287
288impl Glob {
289    /// Builds a new pattern with default options.
290    pub fn new(glob: &str) -> Result<Glob, Error> {
291        GlobBuilder::new(glob).build()
292    }
293
294    /// Returns a matcher for this pattern.
295    pub fn compile_matcher(&self) -> GlobMatcher {
296        let re =
297            new_regex(&self.re).expect("regex compilation shouldn't fail");
298        GlobMatcher { pat: self.clone(), re }
299    }
300
301    /// Returns a strategic matcher.
302    ///
303    /// This isn't exposed because it's not clear whether it's actually
304    /// faster than just running a regex for a *single* pattern. If it
305    /// is faster, then GlobMatcher should do it automatically.
306    #[cfg(test)]
307    fn compile_strategic_matcher(&self) -> GlobStrategic {
308        let strategy = MatchStrategy::new(self);
309        let pattern = match &strategy {
310            MatchStrategy::BasenameRegex(re) => re,
311            _ => &self.re,
312        };
313        let re = new_regex(pattern).expect("regex compilation shouldn't fail");
314        GlobStrategic { strategy, re }
315    }
316
317    /// Returns the original glob pattern used to build this pattern.
318    pub fn glob(&self) -> &str {
319        &self.glob
320    }
321
322    /// Returns the regular expression string for this glob.
323    ///
324    /// Note that regular expressions for globs are intended to be matched on
325    /// arbitrary bytes (`&[u8]`) instead of Unicode strings (`&str`). In
326    /// particular, globs are frequently used on file paths, where there is no
327    /// general guarantee that file paths are themselves valid UTF-8. As a
328    /// result, callers will need to ensure that they are using a regex API
329    /// that can match on arbitrary bytes. For example, the
330    /// [`regex`](https://crates.io/regex)
331    /// crate's
332    /// [`Regex`](https://docs.rs/regex/*/regex/struct.Regex.html)
333    /// API is not suitable for this since it matches on `&str`, but its
334    /// [`bytes::Regex`](https://docs.rs/regex/*/regex/bytes/struct.Regex.html)
335    /// API is suitable for this.
336    pub fn regex(&self) -> &str {
337        &self.re
338    }
339
340    /// Returns the pattern as a literal if and only if the pattern must match
341    /// an entire path exactly.
342    ///
343    /// The basic format of these patterns is `{literal}`.
344    fn literal(&self) -> Option<String> {
345        if self.opts.case_insensitive {
346            return None;
347        }
348        let mut lit = String::new();
349        for t in &*self.tokens {
350            let Token::Literal(c) = *t else { return None };
351            lit.push(c);
352        }
353        if lit.is_empty() { None } else { Some(lit) }
354    }
355
356    /// Returns an extension if this pattern matches a file path if and only
357    /// if the file path has the extension returned.
358    ///
359    /// Note that this extension returned differs from the extension that
360    /// std::path::Path::extension returns. Namely, this extension includes
361    /// the '.'. Also, paths like `.rs` are considered to have an extension
362    /// of `.rs`.
363    fn ext(&self) -> Option<String> {
364        if self.opts.case_insensitive {
365            return None;
366        }
367        let start = match *self.tokens.get(0)? {
368            Token::RecursivePrefix => 1,
369            _ => 0,
370        };
371        match *self.tokens.get(start)? {
372            Token::ZeroOrMore => {
373                // If there was no recursive prefix, then we only permit
374                // `*` if `*` can match a `/`. For example, if `*` can't
375                // match `/`, then `*.c` doesn't match `foo/bar.c`.
376                if start == 0 && self.opts.literal_separator {
377                    return None;
378                }
379            }
380            _ => return None,
381        }
382        match *self.tokens.get(start + 1)? {
383            Token::Literal('.') => {}
384            _ => return None,
385        }
386        let mut lit = ".".to_string();
387        for t in self.tokens[start + 2..].iter() {
388            match *t {
389                Token::Literal('.') | Token::Literal('/') => return None,
390                Token::Literal(c) => lit.push(c),
391                _ => return None,
392            }
393        }
394        if lit.is_empty() { None } else { Some(lit) }
395    }
396
397    /// This is like `ext`, but returns an extension even if it isn't sufficient
398    /// to imply a match. Namely, if an extension is returned, then it is
399    /// necessary but not sufficient for a match.
400    fn required_ext(&self) -> Option<String> {
401        if self.opts.case_insensitive {
402            return None;
403        }
404        // We don't care at all about the beginning of this pattern. All we
405        // need to check for is if it ends with a literal of the form `.ext`.
406        let mut ext: Vec<char> = vec![]; // built in reverse
407        for t in self.tokens.iter().rev() {
408            match *t {
409                Token::Literal('/') => return None,
410                Token::Literal(c) => {
411                    ext.push(c);
412                    if c == '.' {
413                        break;
414                    }
415                }
416                _ => return None,
417            }
418        }
419        if ext.last() != Some(&'.') {
420            None
421        } else {
422            ext.reverse();
423            Some(ext.into_iter().collect())
424        }
425    }
426
427    /// Returns a literal prefix of this pattern if the entire pattern matches
428    /// if the literal prefix matches.
429    fn prefix(&self) -> Option<String> {
430        if self.opts.case_insensitive {
431            return None;
432        }
433        let (end, need_sep) = match *self.tokens.last()? {
434            Token::ZeroOrMore => {
435                if self.opts.literal_separator {
436                    // If a trailing `*` can't match a `/`, then we can't
437                    // assume a match of the prefix corresponds to a match
438                    // of the overall pattern. e.g., `foo/*` with
439                    // `literal_separator` enabled matches `foo/bar` but not
440                    // `foo/bar/baz`, even though `foo/bar/baz` has a `foo/`
441                    // literal prefix.
442                    return None;
443                }
444                (self.tokens.len() - 1, false)
445            }
446            Token::RecursiveSuffix => (self.tokens.len() - 1, true),
447            _ => (self.tokens.len(), false),
448        };
449        let mut lit = String::new();
450        for t in &self.tokens[0..end] {
451            let Token::Literal(c) = *t else { return None };
452            lit.push(c);
453        }
454        if need_sep {
455            lit.push('/');
456        }
457        if lit.is_empty() { None } else { Some(lit) }
458    }
459
460    /// Returns a literal suffix of this pattern if the entire pattern matches
461    /// if the literal suffix matches.
462    ///
463    /// If a literal suffix is returned and it must match either the entire
464    /// file path or be preceded by a `/`, then also return true. This happens
465    /// with a pattern like `**/foo/bar`. Namely, this pattern matches
466    /// `foo/bar` and `baz/foo/bar`, but not `foofoo/bar`. In this case, the
467    /// suffix returned is `/foo/bar` (but should match the entire path
468    /// `foo/bar`).
469    ///
470    /// When this returns true, the suffix literal is guaranteed to start with
471    /// a `/`.
472    fn suffix(&self) -> Option<(String, bool)> {
473        if self.opts.case_insensitive {
474            return None;
475        }
476        let mut lit = String::new();
477        let (start, entire) = match *self.tokens.get(0)? {
478            Token::RecursivePrefix => {
479                // We only care if this follows a path component if the next
480                // token is a literal.
481                if let Some(&Token::Literal(_)) = self.tokens.get(1) {
482                    lit.push('/');
483                    (1, true)
484                } else {
485                    (1, false)
486                }
487            }
488            _ => (0, false),
489        };
490        let start = match *self.tokens.get(start)? {
491            Token::ZeroOrMore => {
492                // If literal_separator is enabled, then a `*` can't
493                // necessarily match everything, so reporting a suffix match
494                // as a match of the pattern would be a false positive.
495                if self.opts.literal_separator {
496                    return None;
497                }
498                start + 1
499            }
500            _ => start,
501        };
502        for t in &self.tokens[start..] {
503            let Token::Literal(c) = *t else { return None };
504            lit.push(c);
505        }
506        if lit.is_empty() || lit == "/" { None } else { Some((lit, entire)) }
507    }
508
509    /// If this pattern only needs to inspect the basename of a file path,
510    /// then the tokens corresponding to only the basename match are returned.
511    ///
512    /// For example, given a pattern of `**/*.foo`, only the tokens
513    /// corresponding to `*.foo` are returned.
514    ///
515    /// Note that this will return None if any match of the basename tokens
516    /// doesn't correspond to a match of the entire pattern. For example, the
517    /// glob `foo` only matches when a file path has a basename of `foo`, but
518    /// doesn't *always* match when a file path has a basename of `foo`. e.g.,
519    /// `foo` doesn't match `abc/foo`.
520    fn basename_tokens(&self) -> Option<&[Token]> {
521        let start = match *self.tokens.get(0)? {
522            Token::RecursivePrefix => 1,
523            _ => {
524                // With nothing to gobble up the parent portion of a path,
525                // we can't assume that matching on only the basename is
526                // correct.
527                return None;
528            }
529        };
530        if self.tokens[start..].is_empty() {
531            return None;
532        }
533        for t in self.tokens[start..].iter() {
534            match *t {
535                Token::Literal('/') => return None,
536                Token::Literal(_) => {} // OK
537                Token::Any | Token::ZeroOrMore => {
538                    if !self.opts.literal_separator {
539                        // In this case, `*` and `?` can match a path
540                        // separator, which means this could reach outside
541                        // the basename.
542                        return None;
543                    }
544                }
545                Token::RecursivePrefix
546                | Token::RecursiveSuffix
547                | Token::RecursiveZeroOrMore => {
548                    return None;
549                }
550                Token::Class { negated, ref ranges } => {
551                    let contains_slash = ranges
552                        .iter()
553                        .any(|&(start, end)| start <= '/' && '/' <= end);
554                    if contains_slash != negated {
555                        return None;
556                    }
557                }
558                Token::Alternates(..) => {
559                    return None;
560                }
561            }
562        }
563        Some(&self.tokens[start..])
564    }
565
566    /// Returns the pattern as a literal if and only if the pattern exclusively
567    /// matches the basename of a file path *and* is a literal.
568    ///
569    /// The basic format of these patterns is `**/{literal}`, where `{literal}`
570    /// does not contain a path separator.
571    fn basename_literal(&self) -> Option<String> {
572        if self.opts.case_insensitive {
573            return None;
574        }
575        let tokens = self.basename_tokens()?;
576        let mut lit = String::new();
577        for t in tokens {
578            let Token::Literal(c) = *t else { return None };
579            lit.push(c);
580        }
581        Some(lit)
582    }
583
584    /// Returns a regex for the basename when it determines the whole match.
585    fn basename_regex(&self) -> Option<String> {
586        let tokens = self.basename_tokens()?;
587        Some(Tokens::to_regex_with(&self.opts, tokens))
588    }
589}
590
591impl<'a> GlobBuilder<'a> {
592    /// Create a new builder for the pattern given.
593    ///
594    /// The pattern is not compiled until `build` is called.
595    pub fn new(glob: &'a str) -> GlobBuilder<'a> {
596        GlobBuilder { glob, opts: GlobOptions::default() }
597    }
598
599    /// Parses and builds the pattern.
600    pub fn build(&self) -> Result<Glob, Error> {
601        let mut p = Parser {
602            glob: &self.glob,
603            alternates_stack: Vec::new(),
604            branches: vec![Tokens::default()],
605            chars: self.glob.chars().peekable(),
606            prev: None,
607            cur: None,
608            found_unclosed_class: false,
609            opts: &self.opts,
610        };
611        p.parse()?;
612        if p.branches.is_empty() {
613            // OK because of how the branches/alternate_stack are managed.
614            // If we end up here, then there *must* be a bug in the parser
615            // somewhere.
616            unreachable!()
617        } else if p.branches.len() > 1 {
618            Err(Error {
619                glob: Some(self.glob.to_string()),
620                kind: ErrorKind::UnclosedAlternates,
621            })
622        } else {
623            let tokens = p.branches.pop().unwrap();
624            Ok(Glob {
625                glob: self.glob.to_string(),
626                re: Tokens::to_regex_with(&self.opts, &tokens),
627                opts: self.opts,
628                tokens,
629            })
630        }
631    }
632
633    /// Toggle whether the pattern matches case insensitively or not.
634    ///
635    /// This is disabled by default.
636    pub fn case_insensitive(&mut self, yes: bool) -> &mut GlobBuilder<'a> {
637        self.opts.case_insensitive = yes;
638        self
639    }
640
641    /// Toggle whether a literal `/` is required to match a path separator.
642    ///
643    /// By default this is false: `*` and `?` will match `/`.
644    pub fn literal_separator(&mut self, yes: bool) -> &mut GlobBuilder<'a> {
645        self.opts.literal_separator = yes;
646        self
647    }
648
649    /// When enabled, a back slash (`\`) may be used to escape
650    /// special characters in a glob pattern. Additionally, this will
651    /// prevent `\` from being interpreted as a path separator on all
652    /// platforms.
653    ///
654    /// This is enabled by default on platforms where `\` is not a
655    /// path separator and disabled by default on platforms where `\`
656    /// is a path separator.
657    pub fn backslash_escape(&mut self, yes: bool) -> &mut GlobBuilder<'a> {
658        self.opts.backslash_escape = yes;
659        self
660    }
661
662    /// Toggle whether an empty pattern in a list of alternates is accepted.
663    ///
664    /// For example, if this is set then the glob `foo{,.txt}` will match both
665    /// `foo` and `foo.txt`.
666    ///
667    /// By default this is false.
668    pub fn empty_alternates(&mut self, yes: bool) -> &mut GlobBuilder<'a> {
669        self.opts.empty_alternates = yes;
670        self
671    }
672
673    /// Toggle whether unclosed character classes are allowed. When allowed,
674    /// a `[` without a matching `]` is treated literally instead of resulting
675    /// in a parse error.
676    ///
677    /// For example, if this is set then the glob `[abc` will be treated as the
678    /// literal string `[abc` instead of returning an error.
679    ///
680    /// By default, this is false. Generally speaking, enabling this leads to
681    /// worse failure modes since the glob parser becomes more permissive. You
682    /// might want to enable this when compatibility (e.g., with POSIX glob
683    /// implementations) is more important than good error messages.
684    pub fn allow_unclosed_class(&mut self, yes: bool) -> &mut GlobBuilder<'a> {
685        self.opts.allow_unclosed_class = yes;
686        self
687    }
688}
689
690impl Tokens {
691    /// Convert this pattern to a string that is guaranteed to be a valid
692    /// regular expression and will represent the matching semantics of this
693    /// glob pattern and the options given.
694    fn to_regex_with(options: &GlobOptions, tokens: &[Token]) -> String {
695        let mut re = String::new();
696        re.push_str("(?-u)");
697        if options.case_insensitive {
698            re.push_str("(?i)");
699        }
700        re.push('^');
701        // Special case. If the entire glob is just `**`, then it should match
702        // everything.
703        if tokens.len() == 1 && tokens[0] == Token::RecursivePrefix {
704            re.push_str(".*");
705            re.push('$');
706            return re;
707        }
708        Self::tokens_to_regex(options, tokens, &mut re);
709        re.push('$');
710        re
711    }
712
713    fn tokens_to_regex(
714        options: &GlobOptions,
715        tokens: &[Token],
716        re: &mut String,
717    ) {
718        for tok in tokens.iter() {
719            match *tok {
720                Token::Literal(c) => {
721                    re.push_str(&char_to_escaped_literal(c));
722                }
723                Token::Any => {
724                    if options.literal_separator {
725                        re.push_str("[^/]");
726                    } else {
727                        re.push_str(".");
728                    }
729                }
730                Token::ZeroOrMore => {
731                    if options.literal_separator {
732                        re.push_str("[^/]*");
733                    } else {
734                        re.push_str(".*");
735                    }
736                }
737                Token::RecursivePrefix => {
738                    re.push_str("(?:/?|.*/)");
739                }
740                Token::RecursiveSuffix => {
741                    re.push_str("/.*");
742                }
743                Token::RecursiveZeroOrMore => {
744                    re.push_str("(?:/|/.*/)");
745                }
746                Token::Class { negated, ref ranges } => {
747                    let mut filtered_ranges = vec![];
748                    let ranges_to_use =
749                        if options.literal_separator && !negated {
750                            for &(start, end) in ranges {
751                                if start > '/' || end < '/' {
752                                    filtered_ranges.push((start, end));
753                                } else if start == '/' && end == '/' {
754                                    // Exclude '/'
755                                } else if start == '/' && end > '/' {
756                                    filtered_ranges.push(('0', end));
757                                } else if start < '/' && end == '/' {
758                                    filtered_ranges.push((start, '.'));
759                                } else if start < '/' && end > '/' {
760                                    filtered_ranges.push((start, '.'));
761                                    filtered_ranges.push(('0', end));
762                                }
763                            }
764                            &filtered_ranges
765                        } else {
766                            ranges
767                        };
768
769                    if ranges_to_use.is_empty() {
770                        // A non-negated class that only contained '/' cannot match anything
771                        // when literal_separator is enabled.
772                        re.push_str("[^\\s\\S]");
773                    } else {
774                        re.push('[');
775                        if negated {
776                            re.push('^');
777                            if options.literal_separator {
778                                re.push('/');
779                            }
780                        }
781                        for r in ranges_to_use {
782                            if r.0 == r.1 {
783                                // Not strictly necessary, but nicer to look at.
784                                re.push_str(&char_to_escaped_literal(r.0));
785                            } else {
786                                re.push_str(&char_to_escaped_literal(r.0));
787                                re.push('-');
788                                re.push_str(&char_to_escaped_literal(r.1));
789                            }
790                        }
791                        re.push(']');
792                    }
793                }
794                Token::Alternates(ref patterns) => {
795                    let mut parts = vec![];
796                    for pat in patterns {
797                        let mut altre = String::new();
798                        Self::tokens_to_regex(options, &pat, &mut altre);
799                        if !altre.is_empty() || options.empty_alternates {
800                            parts.push(altre);
801                        }
802                    }
803
804                    // It is possible to have an empty set in which case the
805                    // resulting alternation '()' would be an error.
806                    if !parts.is_empty() {
807                        re.push_str("(?:");
808                        re.push_str(&parts.join("|"));
809                        re.push(')');
810                    }
811                }
812            }
813        }
814    }
815}
816
817/// Convert a Unicode scalar value to an escaped string suitable for use as
818/// a literal in a non-Unicode regex.
819fn char_to_escaped_literal(c: char) -> String {
820    let mut buf = [0; 4];
821    let bytes = c.encode_utf8(&mut buf).as_bytes();
822    bytes_to_escaped_literal(bytes)
823}
824
825/// Converts an arbitrary sequence of bytes to a UTF-8 string. All non-ASCII
826/// code units are converted to their escaped form.
827fn bytes_to_escaped_literal(bs: &[u8]) -> String {
828    let mut s = String::with_capacity(bs.len());
829    for &b in bs {
830        if b <= 0x7F {
831            regex_syntax::escape_into(
832                char::from(b).encode_utf8(&mut [0; 4]),
833                &mut s,
834            );
835        } else {
836            write!(&mut s, "\\x{:02x}", b).unwrap();
837        }
838    }
839    s
840}
841
842struct Parser<'a> {
843    /// The glob to parse.
844    glob: &'a str,
845    /// Marks the index in `stack` where the alternation started.
846    alternates_stack: Vec<usize>,
847    /// The set of active alternation branches being parsed.
848    /// Tokens are added to the end of the last one.
849    branches: Vec<Tokens>,
850    /// A character iterator over the glob pattern to parse.
851    chars: std::iter::Peekable<std::str::Chars<'a>>,
852    /// The previous character seen.
853    prev: Option<char>,
854    /// The current character.
855    cur: Option<char>,
856    /// Whether we failed to find a closing `]` for a character
857    /// class. This can only be true when `GlobOptions::allow_unclosed_class`
858    /// is enabled. When enabled, it is impossible to ever parse another
859    /// character class with this glob. That's because classes cannot be
860    /// nested *and* the only way this happens is when there is never a `]`.
861    ///
862    /// We track this state so that we don't end up spending quadratic time
863    /// trying to parse something like `[[[[[[[[[[[[[[[[[[[[[[[...`.
864    found_unclosed_class: bool,
865    /// Glob options, which may influence parsing.
866    opts: &'a GlobOptions,
867}
868
869impl<'a> Parser<'a> {
870    fn error(&self, kind: ErrorKind) -> Error {
871        Error { glob: Some(self.glob.to_string()), kind }
872    }
873
874    fn parse(&mut self) -> Result<(), Error> {
875        while let Some(c) = self.bump() {
876            match c {
877                '?' => self.push_token(Token::Any)?,
878                '*' => self.parse_star()?,
879                '[' if !self.found_unclosed_class => self.parse_class()?,
880                '{' => self.push_alternate()?,
881                '}' => self.pop_alternate()?,
882                ',' => self.parse_comma()?,
883                '\\' => self.parse_backslash()?,
884                c => self.push_token(Token::Literal(c))?,
885            }
886        }
887        Ok(())
888    }
889
890    fn push_alternate(&mut self) -> Result<(), Error> {
891        // Bound alternate nesting so recursive token-to-regex compilation and
892        // token tree drop cannot overflow the stack, while staying well within
893        // regex-syntax's default group nesting limit (250).
894        const MAX_ALTERNATES_DEPTH: usize = 100;
895        if self.alternates_stack.len() >= MAX_ALTERNATES_DEPTH {
896            return Err(self.error(ErrorKind::TooManyNestedAlternates));
897        }
898        self.alternates_stack.push(self.branches.len());
899        self.branches.push(Tokens::default());
900        Ok(())
901    }
902
903    fn pop_alternate(&mut self) -> Result<(), Error> {
904        let Some(start) = self.alternates_stack.pop() else {
905            return Err(self.error(ErrorKind::UnopenedAlternates));
906        };
907        assert!(start <= self.branches.len());
908        let alts = Token::Alternates(self.branches.drain(start..).collect());
909        self.push_token(alts)?;
910        Ok(())
911    }
912
913    fn push_token(&mut self, tok: Token) -> Result<(), Error> {
914        if let Some(ref mut pat) = self.branches.last_mut() {
915            return Ok(pat.push(tok));
916        }
917        Err(self.error(ErrorKind::UnopenedAlternates))
918    }
919
920    fn pop_token(&mut self) -> Result<Token, Error> {
921        if let Some(ref mut pat) = self.branches.last_mut() {
922            return Ok(pat.pop().unwrap());
923        }
924        Err(self.error(ErrorKind::UnopenedAlternates))
925    }
926
927    fn have_tokens(&self) -> Result<bool, Error> {
928        match self.branches.last() {
929            None => Err(self.error(ErrorKind::UnopenedAlternates)),
930            Some(ref pat) => Ok(!pat.is_empty()),
931        }
932    }
933
934    fn parse_comma(&mut self) -> Result<(), Error> {
935        // If we aren't inside a group alternation, then don't
936        // treat commas specially. Otherwise, we need to start
937        // a new alternate branch.
938        if self.alternates_stack.is_empty() {
939            self.push_token(Token::Literal(','))
940        } else {
941            Ok(self.branches.push(Tokens::default()))
942        }
943    }
944
945    fn parse_backslash(&mut self) -> Result<(), Error> {
946        if self.opts.backslash_escape {
947            match self.bump() {
948                None => Err(self.error(ErrorKind::DanglingEscape)),
949                Some(c) => self.push_token(Token::Literal(c)),
950            }
951        } else if is_separator('\\') {
952            // Normalize all patterns to use / as a separator.
953            self.push_token(Token::Literal('/'))
954        } else {
955            self.push_token(Token::Literal('\\'))
956        }
957    }
958
959    fn parse_star(&mut self) -> Result<(), Error> {
960        let prev = self.prev;
961        if self.peek() != Some('*') {
962            self.push_token(Token::ZeroOrMore)?;
963            return Ok(());
964        }
965        assert!(self.bump() == Some('*'));
966        if !self.have_tokens()? {
967            if !self.peek().map_or(true, is_separator) {
968                self.push_token(Token::ZeroOrMore)?;
969                self.push_token(Token::ZeroOrMore)?;
970            } else {
971                self.push_token(Token::RecursivePrefix)?;
972                assert!(self.bump().map_or(true, is_separator));
973            }
974            return Ok(());
975        }
976
977        if !prev.map(is_separator).unwrap_or(false) {
978            if self.branches.len() <= 1
979                || (prev != Some(',') && prev != Some('{'))
980            {
981                self.push_token(Token::ZeroOrMore)?;
982                self.push_token(Token::ZeroOrMore)?;
983                return Ok(());
984            }
985        }
986        let is_suffix = match self.peek() {
987            None => {
988                assert!(self.bump().is_none());
989                true
990            }
991            Some(',') | Some('}') if self.branches.len() >= 2 => true,
992            Some(c) if is_separator(c) => {
993                assert!(self.bump().map(is_separator).unwrap_or(false));
994                false
995            }
996            _ => {
997                self.push_token(Token::ZeroOrMore)?;
998                self.push_token(Token::ZeroOrMore)?;
999                return Ok(());
1000            }
1001        };
1002        match self.pop_token()? {
1003            Token::RecursivePrefix => {
1004                self.push_token(Token::RecursivePrefix)?;
1005            }
1006            Token::RecursiveSuffix => {
1007                self.push_token(Token::RecursiveSuffix)?;
1008            }
1009            _ => {
1010                if is_suffix {
1011                    self.push_token(Token::RecursiveSuffix)?;
1012                } else {
1013                    self.push_token(Token::RecursiveZeroOrMore)?;
1014                }
1015            }
1016        }
1017        Ok(())
1018    }
1019
1020    fn parse_class(&mut self) -> Result<(), Error> {
1021        // Save parser state for potential rollback to literal '[' parsing.
1022        let saved_chars = self.chars.clone();
1023        let saved_prev = self.prev;
1024        let saved_cur = self.cur;
1025
1026        fn add_to_last_range(
1027            glob: &str,
1028            r: &mut (char, char),
1029            add: char,
1030        ) -> Result<(), Error> {
1031            r.1 = add;
1032            if r.1 < r.0 {
1033                Err(Error {
1034                    glob: Some(glob.to_string()),
1035                    kind: ErrorKind::InvalidRange(r.0, r.1),
1036                })
1037            } else {
1038                Ok(())
1039            }
1040        }
1041        let mut ranges = vec![];
1042        let negated = match self.chars.peek() {
1043            Some(&'!') | Some(&'^') => {
1044                let bump = self.bump();
1045                assert!(bump == Some('!') || bump == Some('^'));
1046                true
1047            }
1048            _ => false,
1049        };
1050        let mut first = true;
1051        let mut in_range = false;
1052        loop {
1053            let Some(c) = self.bump() else {
1054                return if self.opts.allow_unclosed_class == true {
1055                    self.chars = saved_chars;
1056                    self.cur = saved_cur;
1057                    self.prev = saved_prev;
1058                    self.found_unclosed_class = true;
1059
1060                    self.push_token(Token::Literal('['))
1061                } else {
1062                    Err(self.error(ErrorKind::UnclosedClass))
1063                };
1064            };
1065            match c {
1066                ']' => {
1067                    if first {
1068                        ranges.push((']', ']'));
1069                    } else {
1070                        break;
1071                    }
1072                }
1073                '-' => {
1074                    if first {
1075                        ranges.push(('-', '-'));
1076                    } else if in_range {
1077                        // invariant: in_range is only set when there is
1078                        // already at least one character seen.
1079                        let r = ranges.last_mut().unwrap();
1080                        add_to_last_range(&self.glob, r, '-')?;
1081                        in_range = false;
1082                    } else {
1083                        assert!(!ranges.is_empty());
1084                        in_range = true;
1085                    }
1086                }
1087                // Check for POSIX character class syntax: [[:name:]]
1088                // We expand these directly into char ranges at parse
1089                // time so that Token::Class remains unchanged.
1090                '[' if !in_range && self.peek() == Some(':') => {
1091                    if let Some(class_ranges) = self.try_parse_posix_class() {
1092                        ranges.extend(class_ranges);
1093                        in_range = false;
1094                    } else {
1095                        // Not a valid POSIX class, treat '[' as literal
1096                        ranges.push(('[', '['));
1097                        in_range = false;
1098                    }
1099                }
1100                c => {
1101                    if in_range {
1102                        // invariant: in_range is only set when there is
1103                        // already at least one character seen.
1104                        add_to_last_range(
1105                            &self.glob,
1106                            ranges.last_mut().unwrap(),
1107                            c,
1108                        )?;
1109                    } else {
1110                        ranges.push((c, c));
1111                    }
1112                    in_range = false;
1113                }
1114            }
1115            first = false;
1116        }
1117        if in_range {
1118            // Means that the last character in the class was a '-', so add
1119            // it as a literal.
1120            ranges.push(('-', '-'));
1121        }
1122        self.push_token(Token::Class { negated, ranges })
1123    }
1124
1125    /// Try to parse a POSIX character class like `[:space:]` inside a
1126    /// bracket expression. Called when we've just consumed `[` and peeked
1127    /// `:`. Returns the equivalent ASCII char ranges on success, or `None`
1128    /// if this isn't a valid POSIX class (in which case the parser state
1129    /// is restored).
1130    fn try_parse_posix_class(&mut self) -> Option<&'static [(char, char)]> {
1131        let saved_chars = self.chars.clone();
1132        let saved_prev = self.prev;
1133        let saved_cur = self.cur;
1134
1135        // Consume the ':'
1136        if self.bump() != Some(':') {
1137            self.chars = saved_chars;
1138            self.prev = saved_prev;
1139            self.cur = saved_cur;
1140            return None;
1141        }
1142
1143        // Collect the class name (only lowercase ascii)
1144        let mut name = String::new();
1145        loop {
1146            match self.bump() {
1147                Some(':') if self.peek() == Some(']') => {
1148                    self.bump(); // consume ']'
1149                    return posix_class_ranges(&name);
1150                }
1151                Some(c) if c.is_ascii_lowercase() && name.len() < 8 => {
1152                    name.push(c);
1153                }
1154                _ => {
1155                    // Not a valid POSIX class, restore state
1156                    self.chars = saved_chars;
1157                    self.prev = saved_prev;
1158                    self.cur = saved_cur;
1159                    return None;
1160                }
1161            }
1162        }
1163    }
1164
1165    fn bump(&mut self) -> Option<char> {
1166        self.prev = self.cur;
1167        self.cur = self.chars.next();
1168        self.cur
1169    }
1170
1171    fn peek(&mut self) -> Option<char> {
1172        self.chars.peek().copied()
1173    }
1174}
1175
1176/// Returns the ASCII char ranges for a POSIX character class name.
1177/// All definitions are ASCII-only to avoid locale-dependent behavior.
1178fn posix_class_ranges(name: &str) -> Option<&'static [(char, char)]> {
1179    Some(match name {
1180        "alnum" => &[('0', '9'), ('A', 'Z'), ('a', 'z')],
1181        "alpha" => &[('A', 'Z'), ('a', 'z')],
1182        "blank" => &[('\t', '\t'), (' ', ' ')],
1183        "cntrl" => &[('\x00', '\x1f'), ('\x7f', '\x7f')],
1184        "digit" => &[('0', '9')],
1185        "graph" => &[('!', '~')],
1186        "lower" => &[('a', 'z')],
1187        "print" => &[(' ', '~')],
1188        "punct" => &[('!', '/'), (':', '@'), ('[', '`'), ('{', '~')],
1189        "space" => &[('\t', '\r'), (' ', ' ')],
1190        "upper" => &[('A', 'Z')],
1191        "xdigit" => &[('0', '9'), ('A', 'F'), ('a', 'f')],
1192        _ => return None,
1193    })
1194}
1195
1196#[cfg(test)]
1197fn starts_with(needle: &[u8], haystack: &[u8]) -> bool {
1198    needle.len() <= haystack.len() && needle == &haystack[..needle.len()]
1199}
1200
1201#[cfg(test)]
1202fn ends_with(needle: &[u8], haystack: &[u8]) -> bool {
1203    if needle.len() > haystack.len() {
1204        return false;
1205    }
1206    needle == &haystack[haystack.len() - needle.len()..]
1207}
1208
1209#[cfg(test)]
1210mod tests {
1211    use super::Token::*;
1212    use super::{Glob, GlobBuilder, Token};
1213    use crate::{ErrorKind, GlobSetBuilder};
1214
1215    #[derive(Clone, Copy, Debug, Default)]
1216    struct Options {
1217        casei: Option<bool>,
1218        litsep: Option<bool>,
1219        bsesc: Option<bool>,
1220        ealtre: Option<bool>,
1221        unccls: Option<bool>,
1222    }
1223
1224    macro_rules! syntax {
1225        ($name:ident, $pat:expr, $tokens:expr) => {
1226            #[test]
1227            fn $name() {
1228                let pat = Glob::new($pat).unwrap();
1229                assert_eq!($tokens, pat.tokens.0);
1230            }
1231        };
1232    }
1233
1234    macro_rules! syntaxerr {
1235        ($name:ident, $pat:expr, $err:expr) => {
1236            #[test]
1237            fn $name() {
1238                let err = Glob::new($pat).unwrap_err();
1239                assert_eq!(&$err, err.kind());
1240            }
1241        };
1242    }
1243
1244    macro_rules! toregex {
1245        ($name:ident, $pat:expr, $re:expr) => {
1246            toregex!($name, $pat, $re, Options::default());
1247        };
1248        ($name:ident, $pat:expr, $re:expr, $options:expr) => {
1249            #[test]
1250            fn $name() {
1251                let mut builder = GlobBuilder::new($pat);
1252                if let Some(casei) = $options.casei {
1253                    builder.case_insensitive(casei);
1254                }
1255                if let Some(litsep) = $options.litsep {
1256                    builder.literal_separator(litsep);
1257                }
1258                if let Some(bsesc) = $options.bsesc {
1259                    builder.backslash_escape(bsesc);
1260                }
1261                if let Some(ealtre) = $options.ealtre {
1262                    builder.empty_alternates(ealtre);
1263                }
1264                if let Some(unccls) = $options.unccls {
1265                    builder.allow_unclosed_class(unccls);
1266                }
1267
1268                let pat = builder.build().unwrap();
1269                assert_eq!(format!("(?-u){}", $re), pat.regex());
1270            }
1271        };
1272    }
1273
1274    macro_rules! matches {
1275        ($name:ident, $pat:expr, $path:expr) => {
1276            matches!($name, $pat, $path, Options::default());
1277        };
1278        ($name:ident, $pat:expr, $path:expr, $options:expr) => {
1279            #[test]
1280            fn $name() {
1281                let mut builder = GlobBuilder::new($pat);
1282                if let Some(casei) = $options.casei {
1283                    builder.case_insensitive(casei);
1284                }
1285                if let Some(litsep) = $options.litsep {
1286                    builder.literal_separator(litsep);
1287                }
1288                if let Some(bsesc) = $options.bsesc {
1289                    builder.backslash_escape(bsesc);
1290                }
1291                if let Some(ealtre) = $options.ealtre {
1292                    builder.empty_alternates(ealtre);
1293                }
1294                let pat = builder.build().unwrap();
1295                let matcher = pat.compile_matcher();
1296                let strategic = pat.compile_strategic_matcher();
1297                let set = GlobSetBuilder::new().add(pat).build().unwrap();
1298                assert!(matcher.is_match($path));
1299                assert!(strategic.is_match($path));
1300                assert!(set.is_match($path));
1301            }
1302        };
1303    }
1304
1305    macro_rules! nmatches {
1306        ($name:ident, $pat:expr, $path:expr) => {
1307            nmatches!($name, $pat, $path, Options::default());
1308        };
1309        ($name:ident, $pat:expr, $path:expr, $options:expr) => {
1310            #[test]
1311            fn $name() {
1312                let mut builder = GlobBuilder::new($pat);
1313                if let Some(casei) = $options.casei {
1314                    builder.case_insensitive(casei);
1315                }
1316                if let Some(litsep) = $options.litsep {
1317                    builder.literal_separator(litsep);
1318                }
1319                if let Some(bsesc) = $options.bsesc {
1320                    builder.backslash_escape(bsesc);
1321                }
1322                if let Some(ealtre) = $options.ealtre {
1323                    builder.empty_alternates(ealtre);
1324                }
1325                let pat = builder.build().unwrap();
1326                let matcher = pat.compile_matcher();
1327                let strategic = pat.compile_strategic_matcher();
1328                let set = GlobSetBuilder::new().add(pat).build().unwrap();
1329                assert!(!matcher.is_match($path));
1330                assert!(!strategic.is_match($path));
1331                assert!(!set.is_match($path));
1332            }
1333        };
1334    }
1335
1336    fn s(string: &str) -> String {
1337        string.to_string()
1338    }
1339
1340    fn class(s: char, e: char) -> Token {
1341        Class { negated: false, ranges: vec![(s, e)] }
1342    }
1343
1344    fn classn(s: char, e: char) -> Token {
1345        Class { negated: true, ranges: vec![(s, e)] }
1346    }
1347
1348    fn rclass(ranges: &[(char, char)]) -> Token {
1349        Class { negated: false, ranges: ranges.to_vec() }
1350    }
1351
1352    fn rclassn(ranges: &[(char, char)]) -> Token {
1353        Class { negated: true, ranges: ranges.to_vec() }
1354    }
1355
1356    syntax!(literal1, "a", vec![Literal('a')]);
1357    syntax!(literal2, "ab", vec![Literal('a'), Literal('b')]);
1358    syntax!(any1, "?", vec![Any]);
1359    syntax!(any2, "a?b", vec![Literal('a'), Any, Literal('b')]);
1360    syntax!(seq1, "*", vec![ZeroOrMore]);
1361    syntax!(seq2, "a*b", vec![Literal('a'), ZeroOrMore, Literal('b')]);
1362    syntax!(
1363        seq3,
1364        "*a*b*",
1365        vec![ZeroOrMore, Literal('a'), ZeroOrMore, Literal('b'), ZeroOrMore,]
1366    );
1367    syntax!(rseq1, "**", vec![RecursivePrefix]);
1368    syntax!(rseq2, "**/", vec![RecursivePrefix]);
1369    syntax!(rseq3, "/**", vec![RecursiveSuffix]);
1370    syntax!(rseq4, "/**/", vec![RecursiveZeroOrMore]);
1371    syntax!(
1372        rseq5,
1373        "a/**/b",
1374        vec![Literal('a'), RecursiveZeroOrMore, Literal('b'),]
1375    );
1376    syntax!(cls1, "[a]", vec![class('a', 'a')]);
1377    syntax!(cls2, "[!a]", vec![classn('a', 'a')]);
1378    syntax!(cls3, "[a-z]", vec![class('a', 'z')]);
1379    syntax!(cls4, "[!a-z]", vec![classn('a', 'z')]);
1380    syntax!(cls5, "[-]", vec![class('-', '-')]);
1381    syntax!(cls6, "[]]", vec![class(']', ']')]);
1382    syntax!(cls7, "[*]", vec![class('*', '*')]);
1383    syntax!(cls8, "[!!]", vec![classn('!', '!')]);
1384    syntax!(cls9, "[a-]", vec![rclass(&[('a', 'a'), ('-', '-')])]);
1385    syntax!(cls10, "[-a-z]", vec![rclass(&[('-', '-'), ('a', 'z')])]);
1386    syntax!(cls11, "[a-z-]", vec![rclass(&[('a', 'z'), ('-', '-')])]);
1387    syntax!(
1388        cls12,
1389        "[-a-z-]",
1390        vec![rclass(&[('-', '-'), ('a', 'z'), ('-', '-')]),]
1391    );
1392    syntax!(cls13, "[]-z]", vec![class(']', 'z')]);
1393    syntax!(cls14, "[--z]", vec![class('-', 'z')]);
1394    syntax!(cls15, "[ --]", vec![class(' ', '-')]);
1395    syntax!(cls16, "[0-9a-z]", vec![rclass(&[('0', '9'), ('a', 'z')])]);
1396    syntax!(cls17, "[a-z0-9]", vec![rclass(&[('a', 'z'), ('0', '9')])]);
1397    syntax!(cls18, "[!0-9a-z]", vec![rclassn(&[('0', '9'), ('a', 'z')])]);
1398    syntax!(cls19, "[!a-z0-9]", vec![rclassn(&[('a', 'z'), ('0', '9')])]);
1399    syntax!(cls20, "[^a]", vec![classn('a', 'a')]);
1400    syntax!(cls21, "[^a-z]", vec![classn('a', 'z')]);
1401
1402    // POSIX character classes expand into ranges
1403    syntax!(posix1, "[[:digit:]]", vec![rclass(&[('0', '9')])]);
1404    syntax!(posix2, "[[:alpha:]]", vec![rclass(&[('A', 'Z'), ('a', 'z')])]);
1405    syntax!(posix3, "[[:space:]]", vec![rclass(&[('\t', '\r'), (' ', ' ')])]);
1406    // Negated POSIX class
1407    syntax!(posix4, "[^[:digit:]]", vec![rclassn(&[('0', '9')])]);
1408    // Mixed: range + POSIX class
1409    syntax!(posix5, "[a-f[:digit:]]", vec![rclass(&[('a', 'f'), ('0', '9')])]);
1410    // Multiple POSIX classes
1411    syntax!(
1412        posix6,
1413        "[[:digit:][:alpha:]]",
1414        vec![rclass(&[('0', '9'), ('A', 'Z'), ('a', 'z')])]
1415    );
1416    // Invalid POSIX class name: consumed up to ':]', '[' pushed as
1417    // literal in the bracket expression, the bracket closes at next ']'.
1418    syntax!(posix7, "[[:bogus:]]", vec![rclass(&[('[', '[')])]);
1419
1420    syntaxerr!(err_unclosed1, "[", ErrorKind::UnclosedClass);
1421    syntaxerr!(err_unclosed2, "[]", ErrorKind::UnclosedClass);
1422    syntaxerr!(err_unclosed3, "[!", ErrorKind::UnclosedClass);
1423    syntaxerr!(err_unclosed4, "[!]", ErrorKind::UnclosedClass);
1424    syntaxerr!(err_range1, "[z-a]", ErrorKind::InvalidRange('z', 'a'));
1425    syntaxerr!(err_range2, "[z--]", ErrorKind::InvalidRange('z', '-'));
1426    syntaxerr!(err_alt1, "{a,b", ErrorKind::UnclosedAlternates);
1427    syntaxerr!(err_alt2, "{a,{b,c}", ErrorKind::UnclosedAlternates);
1428    syntaxerr!(err_alt3, "a,b}", ErrorKind::UnopenedAlternates);
1429    syntaxerr!(err_alt4, "{a,b}}", ErrorKind::UnopenedAlternates);
1430
1431    #[test]
1432    fn nested_alternates_depth_limit() {
1433        let ok_pat = "{".repeat(100) + "a" + &"}".repeat(100);
1434        let matcher = Glob::new(&ok_pat).unwrap().compile_matcher();
1435        assert!(matcher.is_match("a"));
1436        assert!(!matcher.is_match("b"));
1437
1438        let over_pat = "{".repeat(101) + "a" + &"}".repeat(101);
1439        let err = Glob::new(&over_pat).unwrap_err();
1440        assert_eq!(&ErrorKind::TooManyNestedAlternates, err.kind());
1441
1442        let deep_pat = "{".repeat(14_000) + "a" + &"}".repeat(14_000);
1443        let err = Glob::new(&deep_pat).unwrap_err();
1444        assert_eq!(&ErrorKind::TooManyNestedAlternates, err.kind());
1445    }
1446
1447    const CASEI: Options = Options {
1448        casei: Some(true),
1449        litsep: None,
1450        bsesc: None,
1451        ealtre: None,
1452        unccls: None,
1453    };
1454    const SLASHLIT: Options = Options {
1455        casei: None,
1456        litsep: Some(true),
1457        bsesc: None,
1458        ealtre: None,
1459        unccls: None,
1460    };
1461    const NOBSESC: Options = Options {
1462        casei: None,
1463        litsep: None,
1464        bsesc: Some(false),
1465        ealtre: None,
1466        unccls: None,
1467    };
1468    const BSESC: Options = Options {
1469        casei: None,
1470        litsep: None,
1471        bsesc: Some(true),
1472        ealtre: None,
1473        unccls: None,
1474    };
1475    const EALTRE: Options = Options {
1476        casei: None,
1477        litsep: None,
1478        bsesc: Some(true),
1479        ealtre: Some(true),
1480        unccls: None,
1481    };
1482    const UNCCLS: Options = Options {
1483        casei: None,
1484        litsep: None,
1485        bsesc: None,
1486        ealtre: None,
1487        unccls: Some(true),
1488    };
1489
1490    toregex!(allow_unclosed_class_single, r"[", r"^\[$", &UNCCLS);
1491    toregex!(allow_unclosed_class_many, r"[abc", r"^\[abc$", &UNCCLS);
1492    toregex!(allow_unclosed_class_empty1, r"[]", r"^\[\]$", &UNCCLS);
1493    toregex!(allow_unclosed_class_empty2, r"[][", r"^\[\]\[$", &UNCCLS);
1494    toregex!(allow_unclosed_class_negated_unclosed, r"[!", r"^\[!$", &UNCCLS);
1495    toregex!(allow_unclosed_class_negated_empty, r"[!]", r"^\[!\]$", &UNCCLS);
1496    toregex!(
1497        allow_unclosed_class_brace1,
1498        r"{[abc,xyz}",
1499        r"^(?:\[abc|xyz)$",
1500        &UNCCLS
1501    );
1502    toregex!(
1503        allow_unclosed_class_brace2,
1504        r"{[abc,[xyz}",
1505        r"^(?:\[abc|\[xyz)$",
1506        &UNCCLS
1507    );
1508    toregex!(
1509        allow_unclosed_class_brace3,
1510        r"{[abc],[xyz}",
1511        r"^(?:[abc]|\[xyz)$",
1512        &UNCCLS
1513    );
1514
1515    toregex!(re_empty, "", "^$");
1516
1517    toregex!(re_casei, "a", "(?i)^a$", &CASEI);
1518
1519    toregex!(re_slash1, "?", r"^[^/]$", SLASHLIT);
1520    toregex!(re_slash2, "*", r"^[^/]*$", SLASHLIT);
1521
1522    toregex!(re1, "a", "^a$");
1523    toregex!(re2, "?", "^.$");
1524    toregex!(re3, "*", "^.*$");
1525    toregex!(re4, "a?", "^a.$");
1526    toregex!(re5, "?a", "^.a$");
1527    toregex!(re6, "a*", "^a.*$");
1528    toregex!(re7, "*a", "^.*a$");
1529    toregex!(re8, "[*]", r"^[\*]$");
1530    toregex!(re9, "[+]", r"^[\+]$");
1531    toregex!(re10, "+", r"^\+$");
1532    toregex!(re11, "☃", r"^\xe2\x98\x83$");
1533    toregex!(re12, "**", r"^.*$");
1534    toregex!(re13, "**/", r"^.*$");
1535    toregex!(re14, "**/*", r"^(?:/?|.*/).*$");
1536    toregex!(re15, "**/**", r"^.*$");
1537    toregex!(re16, "**/**/*", r"^(?:/?|.*/).*$");
1538    toregex!(re17, "**/**/**", r"^.*$");
1539    toregex!(re18, "**/**/**/*", r"^(?:/?|.*/).*$");
1540    toregex!(re19, "a/**", r"^a/.*$");
1541    toregex!(re20, "a/**/**", r"^a/.*$");
1542    toregex!(re21, "a/**/**/**", r"^a/.*$");
1543    toregex!(re22, "a/**/b", r"^a(?:/|/.*/)b$");
1544    toregex!(re23, "a/**/**/b", r"^a(?:/|/.*/)b$");
1545    toregex!(re24, "a/**/**/**/b", r"^a(?:/|/.*/)b$");
1546    toregex!(re25, "**/b", r"^(?:/?|.*/)b$");
1547    toregex!(re26, "**/**/b", r"^(?:/?|.*/)b$");
1548    toregex!(re27, "**/**/**/b", r"^(?:/?|.*/)b$");
1549    toregex!(re28, "a**", r"^a.*.*$");
1550    toregex!(re29, "**a", r"^.*.*a$");
1551    toregex!(re30, "a**b", r"^a.*.*b$");
1552    toregex!(re31, "***", r"^.*.*.*$");
1553    toregex!(re32, "/a**", r"^/a.*.*$");
1554    toregex!(re33, "/**a", r"^/.*.*a$");
1555    toregex!(re34, "/a**b", r"^/a.*.*b$");
1556    toregex!(re35, "{a,b}", r"^(?:a|b)$");
1557    toregex!(re36, "{a,{b,c}}", r"^(?:a|(?:b|c))$");
1558    toregex!(re37, "{{a,b},{c,d}}", r"^(?:(?:a|b)|(?:c|d))$");
1559
1560    matches!(match1, "a", "a");
1561    matches!(match2, "a*b", "a_b");
1562    matches!(match3, "a*b*c", "abc");
1563    matches!(match4, "a*b*c", "a_b_c");
1564    matches!(match5, "a*b*c", "a___b___c");
1565    matches!(match6, "abc*abc*abc", "abcabcabcabcabcabcabc");
1566    matches!(match7, "a*a*a*a*a*a*a*a*a", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
1567    matches!(match8, "a*b[xyz]c*d", "abxcdbxcddd");
1568    matches!(match9, "*.rs", ".rs");
1569    matches!(match10, "☃", "☃");
1570
1571    matches!(matchrec1, "some/**/needle.txt", "some/needle.txt");
1572    matches!(matchrec2, "some/**/needle.txt", "some/one/needle.txt");
1573    matches!(matchrec3, "some/**/needle.txt", "some/one/two/needle.txt");
1574    matches!(matchrec4, "some/**/needle.txt", "some/other/needle.txt");
1575    matches!(matchrec5, "**", "abcde");
1576    matches!(matchrec6, "**", "");
1577    matches!(matchrec7, "**", ".asdf");
1578    matches!(matchrec8, "**", "/x/.asdf");
1579    matches!(matchrec9, "some/**/**/needle.txt", "some/needle.txt");
1580    matches!(matchrec10, "some/**/**/needle.txt", "some/one/needle.txt");
1581    matches!(matchrec11, "some/**/**/needle.txt", "some/one/two/needle.txt");
1582    matches!(matchrec12, "some/**/**/needle.txt", "some/other/needle.txt");
1583    matches!(matchrec13, "**/test", "one/two/test");
1584    matches!(matchrec14, "**/test", "one/test");
1585    matches!(matchrec15, "**/test", "test");
1586    matches!(matchrec16, "/**/test", "/one/two/test");
1587    matches!(matchrec17, "/**/test", "/one/test");
1588    matches!(matchrec18, "/**/test", "/test");
1589    matches!(matchrec19, "**/.*", ".abc");
1590    matches!(matchrec20, "**/.*", "abc/.abc");
1591    matches!(matchrec21, "**/foo/bar", "foo/bar");
1592    matches!(matchrec22, ".*/**", ".abc/abc");
1593    matches!(matchrec23, "test/**", "test/");
1594    matches!(matchrec24, "test/**", "test/one");
1595    matches!(matchrec25, "test/**", "test/one/two");
1596    matches!(matchrec26, "some/*/needle.txt", "some/one/needle.txt");
1597
1598    matches!(basename_empty, "**/*", "", SLASHLIT);
1599    matches!(basename_trailing_separator, "**/*", "foo/", SLASHLIT);
1600    matches!(basename_parent_component, "**/.*", "foo/..", SLASHLIT);
1601    matches!(basename_class, "**/*.py[cod]", "src/module.pyc", SLASHLIT);
1602    matches!(basename_negated_class, "**/[!/]", "foo/a", SLASHLIT);
1603    matches!(class_includes_separator, "**/[!a]", "/");
1604    matches!(class_separator_range, "**/[.-0]", "/");
1605    nmatches!(class_excludes_separator, "**/[!a]", "/", SLASHLIT);
1606    nmatches!(class_excludes_separator_range, "**/[.-0]", "/", SLASHLIT);
1607    nmatches!(basename_class_miss, "**/*.py[cod]", "src/module.pyi", SLASHLIT);
1608
1609    matches!(matchrange1, "a[0-9]b", "a0b");
1610    matches!(matchrange2, "a[0-9]b", "a9b");
1611    matches!(matchrange3, "a[!0-9]b", "a_b");
1612    matches!(matchrange4, "[a-z123]", "1");
1613    matches!(matchrange5, "[1a-z23]", "1");
1614    matches!(matchrange6, "[123a-z]", "1");
1615    matches!(matchrange7, "[abc-]", "-");
1616    matches!(matchrange8, "[-abc]", "-");
1617    matches!(matchrange9, "[-a-c]", "b");
1618    matches!(matchrange10, "[a-c-]", "b");
1619    matches!(matchrange11, "[-]", "-");
1620    matches!(matchrange12, "a[^0-9]b", "a_b");
1621
1622    matches!(matchpat1, "*hello.txt", "hello.txt");
1623    matches!(matchpat2, "*hello.txt", "gareth_says_hello.txt");
1624    matches!(matchpat3, "*hello.txt", "some/path/to/hello.txt");
1625    matches!(matchpat4, "*hello.txt", "some\\path\\to\\hello.txt");
1626    matches!(matchpat5, "*hello.txt", "/an/absolute/path/to/hello.txt");
1627    matches!(matchpat6, "*some/path/to/hello.txt", "some/path/to/hello.txt");
1628    matches!(
1629        matchpat7,
1630        "*some/path/to/hello.txt",
1631        "a/bigger/some/path/to/hello.txt"
1632    );
1633
1634    matches!(matchescape, "_[[]_[]]_[?]_[*]_!_", "_[_]_?_*_!_");
1635
1636    matches!(matchcasei1, "aBcDeFg", "aBcDeFg", CASEI);
1637    matches!(matchcasei2, "aBcDeFg", "abcdefg", CASEI);
1638    matches!(matchcasei3, "aBcDeFg", "ABCDEFG", CASEI);
1639    matches!(matchcasei4, "aBcDeFg", "AbCdEfG", CASEI);
1640
1641    matches!(matchalt1, "a,b", "a,b");
1642    matches!(matchalt2, ",", ",");
1643    matches!(matchalt3, "{a,b}", "a");
1644    matches!(matchalt4, "{a,b}", "b");
1645    matches!(matchalt5, "{**/src/**,foo}", "abc/src/bar");
1646    matches!(matchalt6, "{**/src/**,foo}", "foo");
1647    matches!(matchalt7, "{[}],foo}", "}");
1648    matches!(matchalt8, "{foo}", "foo");
1649    matches!(matchalt9, "{}", "");
1650    matches!(matchalt10, "{,}", "");
1651    matches!(matchalt11, "{*.foo,*.bar,*.wat}", "test.foo");
1652    matches!(matchalt12, "{*.foo,*.bar,*.wat}", "test.bar");
1653    matches!(matchalt13, "{*.foo,*.bar,*.wat}", "test.wat");
1654    matches!(matchalt14, "foo{,.txt}", "foo.txt");
1655    nmatches!(matchalt15, "foo{,.txt}", "foo");
1656    matches!(matchalt16, "foo{,.txt}", "foo", EALTRE);
1657    matches!(matchalt17, "{a,b{c,d}}", "bc");
1658    matches!(matchalt18, "{a,b{c,d}}", "bd");
1659    matches!(matchalt19, "{a,b{c,d}}", "a");
1660
1661    matches!(matchslash1, "abc/def", "abc/def", SLASHLIT);
1662    #[cfg(unix)]
1663    nmatches!(matchslash2, "abc?def", "abc/def", SLASHLIT);
1664    #[cfg(not(unix))]
1665    nmatches!(matchslash2, "abc?def", "abc\\def", SLASHLIT);
1666    nmatches!(matchslash3, "abc*def", "abc/def", SLASHLIT);
1667    nmatches!(matchslash4, "abc[/]def", "abc/def", SLASHLIT);
1668    #[cfg(unix)]
1669    nmatches!(matchslash5, "abc\\def", "abc/def", SLASHLIT);
1670    #[cfg(not(unix))]
1671    matches!(matchslash5, "abc\\def", "abc/def", SLASHLIT);
1672
1673    matches!(matchbackslash1, "\\[", "[", BSESC);
1674    matches!(matchbackslash2, "\\?", "?", BSESC);
1675    matches!(matchbackslash3, "\\*", "*", BSESC);
1676    matches!(matchbackslash4, "\\[a-z]", "\\a", NOBSESC);
1677    matches!(matchbackslash5, "\\?", "\\a", NOBSESC);
1678    matches!(matchbackslash6, "\\*", "\\\\", NOBSESC);
1679    #[cfg(unix)]
1680    matches!(matchbackslash7, "\\a", "a");
1681    #[cfg(not(unix))]
1682    matches!(matchbackslash8, "\\a", "/a");
1683
1684    nmatches!(matchnot1, "a*b*c", "abcd");
1685    nmatches!(matchnot2, "abc*abc*abc", "abcabcabcabcabcabcabca");
1686    nmatches!(matchnot3, "some/**/needle.txt", "some/other/notthis.txt");
1687    nmatches!(matchnot4, "some/**/**/needle.txt", "some/other/notthis.txt");
1688    nmatches!(matchnot5, "/**/test", "test");
1689    nmatches!(matchnot6, "/**/test", "/one/notthis");
1690    nmatches!(matchnot7, "/**/test", "/notthis");
1691    nmatches!(matchnot8, "**/.*", "ab.c");
1692    nmatches!(matchnot9, "**/.*", "abc/ab.c");
1693    nmatches!(matchnot10, ".*/**", "a.bc");
1694    nmatches!(matchnot11, ".*/**", "abc/a.bc");
1695    nmatches!(matchnot12, "a[0-9]b", "a_b");
1696    nmatches!(matchnot13, "a[!0-9]b", "a0b");
1697    nmatches!(matchnot14, "a[!0-9]b", "a9b");
1698    nmatches!(matchnot15, "[!-]", "-");
1699    nmatches!(matchnot16, "*hello.txt", "hello.txt-and-then-some");
1700    nmatches!(matchnot17, "*hello.txt", "goodbye.txt");
1701    nmatches!(
1702        matchnot18,
1703        "*some/path/to/hello.txt",
1704        "some/path/to/hello.txt-and-then-some"
1705    );
1706    nmatches!(
1707        matchnot19,
1708        "*some/path/to/hello.txt",
1709        "some/other/path/to/hello.txt"
1710    );
1711    nmatches!(matchnot20, "a", "foo/a");
1712    nmatches!(matchnot21, "./foo", "foo");
1713    nmatches!(matchnot22, "**/foo", "foofoo");
1714    nmatches!(matchnot23, "**/foo/bar", "foofoo/bar");
1715    nmatches!(matchnot24, "/*.c", "mozilla-sha1/sha1.c");
1716    nmatches!(matchnot25, "*.c", "mozilla-sha1/sha1.c", SLASHLIT);
1717    nmatches!(
1718        matchnot26,
1719        "**/m4/ltoptions.m4",
1720        "csharp/src/packages/repositories.config",
1721        SLASHLIT
1722    );
1723    nmatches!(matchnot27, "a[^0-9]b", "a0b");
1724    nmatches!(matchnot28, "a[^0-9]b", "a9b");
1725    nmatches!(matchnot29, "[^-]", "-");
1726    nmatches!(matchnot30, "some/*/needle.txt", "some/needle.txt");
1727    nmatches!(
1728        matchrec31,
1729        "some/*/needle.txt",
1730        "some/one/two/needle.txt",
1731        SLASHLIT
1732    );
1733    nmatches!(
1734        matchrec32,
1735        "some/*/needle.txt",
1736        "some/one/two/three/needle.txt",
1737        SLASHLIT
1738    );
1739    nmatches!(matchrec33, ".*/**", ".abc");
1740    nmatches!(matchrec34, "foo/**", "foo");
1741
1742    // POSIX character class matching
1743    matches!(posix_match1, "[[:space:]]", " ");
1744    matches!(posix_match2, "[[:space:]]", "\t");
1745    matches!(posix_match3, "[[:digit:]]", "5");
1746    matches!(posix_match4, "[[:digit:]]", "0");
1747    matches!(posix_match5, "[[:alpha:]]", "a");
1748    matches!(posix_match6, "[[:alpha:]]", "Z");
1749    matches!(posix_match7, "[[:lower:]]", "a");
1750    matches!(posix_match8, "[[:upper:]]", "Z");
1751    matches!(posix_match9, "[[:alnum:]]", "a");
1752    matches!(posix_match10, "[[:alnum:]]", "3");
1753    matches!(posix_match11, "[[:xdigit:]]", "f");
1754    matches!(posix_match12, "[[:xdigit:]]", "A");
1755    nmatches!(posix_nomatch1, "[[:space:]]", "a");
1756    nmatches!(posix_nomatch2, "[[:digit:]]", "x");
1757    nmatches!(posix_nomatch3, "[[:lower:]]", "Z");
1758    nmatches!(posix_nomatch4, "[[:upper:]]", "a");
1759    // Negated
1760    matches!(posix_neg1, "[^[:digit:]]", "a");
1761    nmatches!(posix_neg2, "[^[:digit:]]", "5");
1762    matches!(posix_neg3, "[![:space:]]", "x");
1763    nmatches!(posix_neg4, "[![:space:]]", " ");
1764    // Mixed with ranges
1765    matches!(posix_mix1, "[[:digit:]a-f]", "c");
1766    matches!(posix_mix2, "[[:digit:]a-f]", "7");
1767    nmatches!(posix_mix3, "[[:digit:]a-f]", "g");
1768    matches!(posix_mix4, "[a[:space:]]", " ");
1769    matches!(posix_mix5, "[a[:space:]]", "a");
1770    // In filenames (the original issue's use case)
1771    matches!(posix_file1, "foo[[:space:]]bar.txt", "foo bar.txt");
1772    matches!(posix_file2, "foo[[:space:]]bar.txt", "foo\tbar.txt");
1773    nmatches!(posix_file3, "foo[[:space:]]bar.txt", "fooXbar.txt");
1774    matches!(posix_file4, "test[[:digit:]].txt", "test9.txt");
1775    nmatches!(posix_file5, "test[[:digit:]].txt", "testa.txt");
1776    // Multiple POSIX classes
1777    matches!(posix_multi1, "[[:digit:][:alpha:]]", "a");
1778    matches!(posix_multi2, "[[:digit:][:alpha:]]", "5");
1779    nmatches!(posix_multi3, "[[:digit:][:alpha:]]", " ");
1780    // Edge: dash with POSIX class
1781    matches!(posix_dash1, "[-[:digit:]]", "-");
1782    matches!(posix_dash2, "[-[:digit:]]", "3");
1783    matches!(posix_dash3, "[[:digit:]-]", "8");
1784    matches!(posix_dash4, "[[:digit:]-]", "-");
1785
1786    macro_rules! extract {
1787        ($which:ident, $name:ident, $pat:expr, $expect:expr) => {
1788            extract!($which, $name, $pat, $expect, Options::default());
1789        };
1790        ($which:ident, $name:ident, $pat:expr, $expect:expr, $options:expr) => {
1791            #[test]
1792            fn $name() {
1793                let mut builder = GlobBuilder::new($pat);
1794                if let Some(casei) = $options.casei {
1795                    builder.case_insensitive(casei);
1796                }
1797                if let Some(litsep) = $options.litsep {
1798                    builder.literal_separator(litsep);
1799                }
1800                if let Some(bsesc) = $options.bsesc {
1801                    builder.backslash_escape(bsesc);
1802                }
1803                if let Some(ealtre) = $options.ealtre {
1804                    builder.empty_alternates(ealtre);
1805                }
1806                let pat = builder.build().unwrap();
1807                assert_eq!($expect, pat.$which());
1808            }
1809        };
1810    }
1811
1812    macro_rules! literal {
1813        ($($tt:tt)*) => { extract!(literal, $($tt)*); }
1814    }
1815
1816    macro_rules! basetokens {
1817        ($($tt:tt)*) => { extract!(basename_tokens, $($tt)*); }
1818    }
1819
1820    macro_rules! ext {
1821        ($($tt:tt)*) => { extract!(ext, $($tt)*); }
1822    }
1823
1824    macro_rules! required_ext {
1825        ($($tt:tt)*) => { extract!(required_ext, $($tt)*); }
1826    }
1827
1828    macro_rules! prefix {
1829        ($($tt:tt)*) => { extract!(prefix, $($tt)*); }
1830    }
1831
1832    macro_rules! suffix {
1833        ($($tt:tt)*) => { extract!(suffix, $($tt)*); }
1834    }
1835
1836    macro_rules! baseliteral {
1837        ($($tt:tt)*) => { extract!(basename_literal, $($tt)*); }
1838    }
1839
1840    literal!(extract_lit1, "foo", Some(s("foo")));
1841    literal!(extract_lit2, "foo", None, CASEI);
1842    literal!(extract_lit3, "/foo", Some(s("/foo")));
1843    literal!(extract_lit4, "/foo/", Some(s("/foo/")));
1844    literal!(extract_lit5, "/foo/bar", Some(s("/foo/bar")));
1845    literal!(extract_lit6, "*.foo", None);
1846    literal!(extract_lit7, "foo/bar", Some(s("foo/bar")));
1847    literal!(extract_lit8, "**/foo/bar", None);
1848
1849    basetokens!(
1850        extract_basetoks1,
1851        "**/foo",
1852        Some(&*vec![Literal('f'), Literal('o'), Literal('o'),])
1853    );
1854    basetokens!(
1855        extract_basetoks2,
1856        "**/foo",
1857        Some(&*vec![Literal('f'), Literal('o'), Literal('o'),]),
1858        CASEI
1859    );
1860    basetokens!(
1861        extract_basetoks3,
1862        "**/foo",
1863        Some(&*vec![Literal('f'), Literal('o'), Literal('o'),]),
1864        SLASHLIT
1865    );
1866    basetokens!(extract_basetoks4, "*foo", None, SLASHLIT);
1867    basetokens!(extract_basetoks5, "*foo", None);
1868    basetokens!(extract_basetoks6, "**/fo*o", None);
1869    basetokens!(
1870        extract_basetoks7,
1871        "**/fo*o",
1872        Some(&*vec![Literal('f'), Literal('o'), ZeroOrMore, Literal('o'),]),
1873        SLASHLIT
1874    );
1875
1876    ext!(extract_ext1, "**/*.rs", Some(s(".rs")));
1877    ext!(extract_ext2, "**/*.rs.bak", None);
1878    ext!(extract_ext3, "*.rs", Some(s(".rs")));
1879    ext!(extract_ext4, "a*.rs", None);
1880    ext!(extract_ext5, "/*.c", None);
1881    ext!(extract_ext6, "*.c", None, SLASHLIT);
1882    ext!(extract_ext7, "*.c", Some(s(".c")));
1883
1884    required_ext!(extract_req_ext1, "*.rs", Some(s(".rs")));
1885    required_ext!(extract_req_ext2, "/foo/bar/*.rs", Some(s(".rs")));
1886    required_ext!(extract_req_ext3, "/foo/bar/*.rs", Some(s(".rs")));
1887    required_ext!(extract_req_ext4, "/foo/bar/.rs", Some(s(".rs")));
1888    required_ext!(extract_req_ext5, ".rs", Some(s(".rs")));
1889    required_ext!(extract_req_ext6, "./rs", None);
1890    required_ext!(extract_req_ext7, "foo", None);
1891    required_ext!(extract_req_ext8, ".foo/", None);
1892    required_ext!(extract_req_ext9, "foo/", None);
1893
1894    prefix!(extract_prefix1, "/foo", Some(s("/foo")));
1895    prefix!(extract_prefix2, "/foo/*", Some(s("/foo/")));
1896    prefix!(extract_prefix3, "**/foo", None);
1897    prefix!(extract_prefix4, "foo/**", Some(s("foo/")));
1898
1899    suffix!(extract_suffix1, "**/foo/bar", Some((s("/foo/bar"), true)));
1900    suffix!(extract_suffix2, "*/foo/bar", Some((s("/foo/bar"), false)));
1901    suffix!(extract_suffix3, "*/foo/bar", None, SLASHLIT);
1902    suffix!(extract_suffix4, "foo/bar", Some((s("foo/bar"), false)));
1903    suffix!(extract_suffix5, "*.foo", Some((s(".foo"), false)));
1904    suffix!(extract_suffix6, "*.foo", None, SLASHLIT);
1905    suffix!(extract_suffix7, "**/*_test", Some((s("_test"), false)));
1906
1907    baseliteral!(extract_baselit1, "**/foo", Some(s("foo")));
1908    baseliteral!(extract_baselit2, "foo", None);
1909    baseliteral!(extract_baselit3, "*foo", None);
1910    baseliteral!(extract_baselit4, "*/foo", None);
1911
1912    #[test]
1913    fn class_literal_separator() {
1914        let glob = GlobBuilder::new("*[/]*")
1915            .literal_separator(true)
1916            .build()
1917            .unwrap()
1918            .compile_matcher();
1919        assert!(!glob.is_match("a/b"));
1920
1921        let glob_neg = GlobBuilder::new("[^a]*")
1922            .literal_separator(true)
1923            .build()
1924            .unwrap()
1925            .compile_matcher();
1926        assert!(!glob_neg.is_match("/b"));
1927
1928        let glob_range = GlobBuilder::new("[ -~]")
1929            .literal_separator(true)
1930            .build()
1931            .unwrap()
1932            .compile_matcher();
1933        assert!(!glob_range.is_match("/"));
1934        assert!(glob_range.is_match("a"));
1935    }
1936}