use memchr::memmem::Finder;
use super::{BuildError, StrMatcher};
use crate::tier::MatcherTier;
#[derive(Debug)]
enum Kind {
Any,
Exact(Box<[u8]>),
Prefix(Box<[u8]>),
Suffix(Box<[u8]>),
Contains(Box<Finder<'static>>),
Affix {
prefix: Box<[u8]>,
suffix: Box<[u8]>,
},
Engine(Box<StrMatcher>),
}
#[derive(Debug)]
pub struct GlobMatcher {
kind: Kind,
tier: MatcherTier,
pattern: String,
reason: &'static str,
}
#[derive(Debug, Clone, Copy, Default)]
#[allow(
clippy::struct_excessive_bools,
reason = "independent switches, as glob 0.3's MatchOptions holds them"
)]
pub struct GlobBuilder {
literal_separator: bool,
case_insensitive: bool,
literal_leading_dot: bool,
backslash_literal: bool,
either_separator: bool,
}
impl GlobBuilder {
#[must_use]
pub const fn literal_separator(mut self, on: bool) -> Self {
self.literal_separator = on;
self
}
#[must_use]
pub const fn case_insensitive(mut self, on: bool) -> Self {
self.case_insensitive = on;
self
}
#[must_use]
pub const fn literal_leading_dot(mut self, on: bool) -> Self {
self.literal_leading_dot = on;
self
}
#[must_use]
pub const fn backslash_literal(mut self, on: bool) -> Self {
self.backslash_literal = on;
self
}
#[must_use]
pub const fn either_separator(mut self, on: bool) -> Self {
self.either_separator = on;
self
}
pub fn build(self, glob: &str) -> Result<GlobMatcher, BuildError> {
if glob.is_empty() {
return Err(BuildError::Empty);
}
let own = self.literal_leading_dot || self.backslash_literal || self.either_separator;
let simple = !self.case_insensitive
&& !own
&& !glob.contains(['?', '[', ']', '{', '}', '\\'])
&& !glob.contains("**")
&& (!self.literal_separator || !glob.contains('*'));
if simple && let Some((kind, reason)) = lower(glob) {
let tier = shape_tier(&kind);
return Ok(GlobMatcher {
kind,
tier,
pattern: glob.to_owned(),
reason,
});
}
let regex = if own {
Translate::new(glob, self)
.run()
.map_err(|(at, hint)| BuildError::GlobSyntax {
pattern: glob.to_owned(),
at,
hint,
})?
} else {
globset::GlobBuilder::new(glob)
.literal_separator(self.literal_separator)
.build()
.map_err(|e| BuildError::Glob {
pattern: glob.to_owned(),
source: Box::new(e),
hint: "check the glob syntax: `*`, `?`, `[...]`, `{a,b}`",
})?
.regex()
.to_owned()
};
let m = StrMatcher::builder()
.ascii_case_insensitive(self.case_insensitive)
.build(&format!("(?s){regex}"))?;
Ok(GlobMatcher {
tier: m.tier(),
reason: m.reason(),
kind: Kind::Engine(Box::new(m)),
pattern: glob.to_owned(),
})
}
}
struct Translate {
chars: Vec<(usize, char)>,
i: usize,
out: String,
b: GlobBuilder,
sep: &'static str,
}
type Stop = (usize, &'static str);
impl Translate {
fn new(glob: &str, b: GlobBuilder) -> Self {
Self {
chars: glob.char_indices().collect(),
i: 0,
out: String::from("^"),
b,
sep: if b.either_separator { r"/\\" } else { "/" },
}
}
fn run(mut self) -> Result<String, Stop> {
if self.b.literal_leading_dot && !self.b.literal_separator {
return Err((0, "literal_leading_dot needs literal_separator"));
}
self.seq(0, true)?;
self.out.push('$');
Ok(self.out)
}
fn peek(&self) -> Option<char> {
self.chars.get(self.i).map(|&(_, c)| c)
}
fn at(&self) -> usize {
match self.chars.get(self.i) {
Some(&(at, _)) => at,
None => self.chars.last().map_or(0, |&(at, c)| at + c.len_utf8()),
}
}
const fn is_sep(&self, c: char) -> bool {
c == '/' || (self.b.either_separator && c == '\\')
}
fn excluded(&self, start: bool) -> String {
let mut excluded = String::new();
if self.b.literal_separator {
excluded.push_str(self.sep);
}
if self.b.literal_leading_dot && start {
excluded.push_str(r"\.");
}
excluded
}
fn one(&self, start: bool) -> String {
let excluded = self.excluded(start);
if excluded.is_empty() {
".".to_owned()
} else {
format!("[^{excluded}]")
}
}
fn run_in(&self, start: bool) -> String {
let any = self.one(false);
if start && self.b.literal_leading_dot {
format!("(?:{}{any}*)?", self.one(true))
} else {
format!("{any}*")
}
}
fn literal(&mut self, c: char) {
self.out
.push_str(®ex_syntax::escape(c.encode_utf8(&mut [0; 4])));
}
fn seq(&mut self, depth: usize, mut start: bool) -> Result<(), Stop> {
while let Some(c) = self.peek() {
match c {
',' | '}' if depth > 0 => return Ok(()),
'{' => self.alternatives(depth, start)?,
'?' => {
self.i += 1;
let one = self.one(start);
self.out.push_str(&one);
}
'*' => {
if self.stars(start)? {
continue;
}
}
'[' => self.class(start)?,
c if self.is_sep(c) => {
self.i += 1;
let sep = format!("[{}]", self.sep);
self.out.push_str(&sep);
start = true;
continue;
}
'\\' if !self.b.backslash_literal => {
self.i += 1;
let Some(escaped) = self.peek() else {
return Err((self.at(), "a character after `\\`"));
};
self.i += 1;
self.literal(escaped);
}
c => {
self.i += 1;
self.literal(c);
}
}
start = false;
}
if depth > 0 {
return Err((self.at(), "a `}` to close `{`"));
}
Ok(())
}
fn alternatives(&mut self, depth: usize, start: bool) -> Result<(), Stop> {
let open = self.at();
self.i += 1;
self.out.push_str("(?:");
loop {
self.seq(depth + 1, start)?;
match self.peek() {
Some(',') => self.out.push('|'),
Some('}') => break,
_ => return Err((open, "a `}` to close `{`")),
}
self.i += 1;
}
self.i += 1;
self.out.push(')');
Ok(())
}
fn stars(&mut self, start: bool) -> Result<bool, Stop> {
let count = self.chars[self.i..]
.iter()
.take_while(|&&(_, c)| c == '*')
.count();
self.i += count;
let next = self.peek();
let whole = count > 1 && start && next.is_none_or(|n| self.is_sep(n));
if !whole {
if start && self.b.literal_leading_dot && matches!(next, Some('?' | '[')) {
let (any, first) = if next == Some('?') {
self.i += 1;
(self.one(false), self.one(true))
} else {
let set = self.read_class()?;
(self.class_at(&set, false), self.class_at(&set, true))
};
let lead = self.one(true);
let inner = self.one(false);
self.out
.extend(["(?:", &lead, &inner, "*", &any, "|", &first, ")"]);
return Ok(false);
}
let run = self.run_in(start);
self.out.push_str(&run);
return Ok(false);
}
let part = self.run_in(true);
let sep = format!("[{}]", self.sep);
let middle = next.is_some() && self.chars.get(self.i + 1).is_some();
self.i += usize::from(next.is_some());
let pieces: &[&str] = if middle {
&["(?:", &part, &sep, ")*"]
} else {
&["(?:", &part, "(?:", &sep, &part, ")*)?"]
};
self.out.extend(pieces.iter().copied());
Ok(middle)
}
fn class(&mut self, start: bool) -> Result<(), Stop> {
let set = self.read_class()?;
let class = self.class_at(&set, start);
self.out.push_str(&class);
Ok(())
}
fn class_at(&self, set: &str, start: bool) -> String {
let excluded = self.excluded(start);
if excluded.is_empty() {
set.to_owned()
} else {
["[", set, "&&[^", excluded.as_str(), "]]"].concat()
}
}
fn read_class(&mut self) -> Result<String, Stop> {
let open = self.at();
self.i += 1;
let negated = self.peek() == Some('!');
self.i += usize::from(negated);
let mut items = String::new();
let mut first = true;
loop {
let Some(c) = self.peek() else {
return Err((open, "a `]` to close `[`"));
};
self.i += 1;
if c == ']' && !first {
break;
}
first = false;
class_char(&mut items, c);
let range_end = self.chars.get(self.i + 1).map(|&(_, n)| n);
if self.peek() == Some('-')
&& let Some(end) = range_end.filter(|&n| n != ']')
{
self.i += 2;
items.push('-');
class_char(&mut items, end);
}
}
Ok(if negated {
format!("[^{items}]")
} else {
format!("[{items}]")
})
}
}
fn class_char(items: &mut String, c: char) {
if c.is_ascii_punctuation() {
items.push('\\');
}
items.push(c);
}
fn lower(glob: &str) -> Option<(Kind, &'static str)> {
let pieces: Vec<&[u8]> = glob.as_bytes().split(|&b| b == b'*').collect();
let boxed = |b: &[u8]| -> Box<[u8]> { b.into() };
Some(match pieces.as_slice() {
[exact] => (Kind::Exact(boxed(exact)), "glob:exact"),
[[], []] => (Kind::Any, "glob:any"),
[[], suffix] => (Kind::Suffix(boxed(suffix)), "glob:suffix"),
[prefix, []] => (Kind::Prefix(boxed(prefix)), "glob:prefix"),
[prefix, suffix] => (
Kind::Affix {
prefix: boxed(prefix),
suffix: boxed(suffix),
},
"glob:affix",
),
[[], middle, []] if !middle.is_empty() => (
Kind::Contains(Box::new(Finder::new(middle).into_owned())),
"glob:contains",
),
_ => return None,
})
}
fn shape_tier(kind: &Kind) -> MatcherTier {
match kind {
Kind::Any => MatcherTier::Fixed,
Kind::Exact(b) | Kind::Prefix(b) | Kind::Suffix(b) if b.len() == 1 => MatcherTier::Byte,
Kind::Contains(f) if f.needle().len() == 1 => MatcherTier::Byte,
Kind::Engine(m) => m.tier(),
Kind::Exact(_)
| Kind::Prefix(_)
| Kind::Suffix(_)
| Kind::Contains(_)
| Kind::Affix { .. } => MatcherTier::Literal,
}
}
impl GlobMatcher {
pub fn new(glob: &str) -> Result<Self, BuildError> {
GlobBuilder::default().build(glob)
}
#[must_use]
pub fn builder() -> GlobBuilder {
GlobBuilder::default()
}
#[must_use]
pub fn is_match(&self, hay: &[u8]) -> bool {
match &self.kind {
Kind::Any => true,
Kind::Exact(b) => hay == &**b,
Kind::Prefix(b) => hay.starts_with(b),
Kind::Suffix(b) => hay.ends_with(b),
Kind::Contains(f) => f.find(hay).is_some(),
Kind::Affix { prefix, suffix } => {
hay.len() >= prefix.len() + suffix.len()
&& hay.starts_with(prefix)
&& hay.ends_with(suffix)
}
Kind::Engine(m) => m.is_match(hay),
}
}
#[must_use]
pub const fn tier(&self) -> MatcherTier {
self.tier
}
#[must_use]
pub fn pattern(&self) -> &str {
&self.pattern
}
#[must_use]
pub const fn reason(&self) -> &'static str {
self.reason
}
#[must_use]
pub fn hint(&self) -> &'static str {
match &self.kind {
Kind::Engine(m) => m.hint(),
_ => "",
}
}
}
#[cfg(test)]
mod tests {
use proptest::prelude::*;
use super::*;
fn oracle(glob: &str, literal_separator: bool) -> globset::GlobMatcher {
globset::GlobBuilder::new(glob)
.literal_separator(literal_separator)
.build()
.unwrap()
.compile_matcher()
}
#[test]
fn simple_globs_lower_to_byte_shapes() {
let rows: &[(&str, MatcherTier, &str)] = &[
("*", MatcherTier::Fixed, "glob:any"),
("a.log", MatcherTier::Literal, "glob:exact"),
("*.log", MatcherTier::Literal, "glob:suffix"),
("/var/*", MatcherTier::Literal, "glob:prefix"),
("*error*", MatcherTier::Literal, "glob:contains"),
("*x*", MatcherTier::Byte, "glob:contains"),
("app-*.log", MatcherTier::Literal, "glob:affix"),
];
for (glob, tier, reason) in rows {
let m = GlobMatcher::new(glob).unwrap();
assert_eq!((m.tier(), m.reason()), (*tier, *reason), "{glob}");
}
}
#[test]
fn other_globs_run_on_their_regex_translation() {
for glob in ["a?c", "[ab]*", "{x,y}.log", "a*b*c", "**/x"] {
let m = GlobMatcher::new(glob).unwrap();
assert!(
!m.reason().starts_with("glob:"),
"{glob} lowered: {}",
m.reason()
);
}
let sep = GlobMatcher::builder()
.literal_separator(true)
.build("*.log")
.unwrap();
assert!(!sep.reason().starts_with("glob:"));
assert!(!sep.is_match(b"a/b.log"));
assert!(sep.is_match(b"b.log"));
let ci = GlobMatcher::builder()
.case_insensitive(true)
.build("*.LOG")
.unwrap();
assert!(ci.is_match(b"a.log"));
}
#[test]
fn bad_globs_are_errors() {
assert!(matches!(GlobMatcher::new(""), Err(BuildError::Empty)));
assert!(matches!(
GlobMatcher::new("[a"),
Err(BuildError::Glob { .. })
));
}
#[test]
fn glob_03_options_read_as_glob_03_does() {
let sep = GlobMatcher::builder().literal_separator(true);
let dot = sep.literal_leading_dot(true);
let either = sep.either_separator(true);
let literal = GlobMatcher::builder().backslash_literal(true);
let rows: &[(GlobBuilder, &str, &str, bool)] = &[
(dot, "*", ".git", false),
(dot, "*", "git", true),
(dot, ".*", ".git", true),
(dot, "?git", ".git", false),
(dot, "[.g]git", ".git", false),
(dot, "a/*", "a/.b", false),
(dot, "a/x*", "a/x.b", true),
(dot, "**/b", ".a/b", false),
(dot, "**/b", "a/c/b", true),
(dot, "**", "a/.c", false),
(sep, "**/b", "b", true),
(sep, "a/**", "a/b/c", true),
(sep, "*.log", "a/b.log", false),
(sep, "**.log", "b.log", true),
(sep, "[!a]", "/", false),
(either, "a/b", r"a\b", true),
(either, r"a\b", "a/b", true),
(either, "*", r"a\b", false),
(either.backslash_literal(true), "*", r"a\", false),
(either.backslash_literal(true), r"a\b", "a/b", true),
(literal, r"a\*", r"a\bc", true),
(literal, r"a\*", "a*", false),
(literal, "{x,y}.log", "y.log", true),
(literal.case_insensitive(true), "[A-C]B", "bb", true),
(literal.case_insensitive(true), "\u{c9}", "\u{e9}", false),
];
for &(b, glob, hay, want) in rows {
let m = b.build(glob).unwrap();
assert_eq!(m.is_match(hay.as_bytes()), want, "{glob} on {hay}");
}
let bad: &[(GlobBuilder, &str)] = &[
(literal, "[a"),
(literal, "{a,b"),
(GlobMatcher::builder().literal_leading_dot(true), "*"),
(GlobMatcher::builder().either_separator(true), "a{"),
];
for &(b, glob) in bad {
assert!(
matches!(b.build(glob), Err(BuildError::GlobSyntax { .. })),
"{glob}"
);
}
}
fn glob_03_strategy() -> impl Strategy<Value = String> {
prop::collection::vec(
prop::sample::select(vec![
"a", "B", ".", "/", "*", "?", "**/", "/**", "[a-b]", "[!a]", "[.]", "\\",
]),
1..6,
)
.prop_map(|p| p.concat())
}
fn glob_03_hay_strategy() -> impl Strategy<Value = String> {
prop::collection::vec(
prop::sample::select(vec!["a", "b", "B", ".", "/", ".a", "\\", "\n"]),
0..7,
)
.prop_map(|p| p.concat())
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(4096))]
#[test]
fn glob_03_options_agree_with_glob_03(
glob in glob_03_strategy(),
hay in glob_03_hay_strategy(),
sep in any::<bool>(),
dot in any::<bool>(),
fold in any::<bool>(),
) {
let Ok(theirs) = glob03::Pattern::new(&glob) else {
return Ok(());
};
let options = glob03::MatchOptions {
case_sensitive: !fold,
require_literal_separator: sep,
require_literal_leading_dot: sep && dot,
};
let ours = GlobMatcher::builder()
.backslash_literal(true)
.either_separator(cfg!(windows))
.literal_separator(sep)
.literal_leading_dot(sep && dot)
.case_insensitive(fold)
.build(&glob)
.unwrap();
prop_assert_eq!(
ours.is_match(hay.as_bytes()),
theirs.matches_with(&hay, options),
"glob {:?} on {:?}, separator {} dot {} fold {}", glob, hay, sep, dot, fold
);
}
}
fn glob_strategy() -> impl Strategy<Value = String> {
prop::collection::vec(
prop::sample::select(vec!["a", "b", "/", ".", "*", "ab"]),
1..6,
)
.prop_map(|p| p.concat())
.prop_filter("non-empty", |g| !g.is_empty())
}
fn hay_strategy() -> impl Strategy<Value = String> {
prop::collection::vec(
prop::sample::select(vec!["a", "b", "/", ".", "ab", "\n"]),
0..8,
)
.prop_map(|p| p.concat())
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(2048))]
#[test]
fn every_glob_agrees_with_globset(glob in glob_strategy(), hay in hay_strategy(), sep in any::<bool>()) {
let ours = GlobMatcher::builder().literal_separator(sep).build(&glob).unwrap();
prop_assert_eq!(
ours.is_match(hay.as_bytes()),
oracle(&glob, sep).is_match(&hay),
"glob {:?} reason {}", glob, ours.reason()
);
}
}
}