mod charset;
mod classify;
mod dialect;
#[cfg(feature = "glob")]
mod glob;
mod js;
mod ops;
mod pcre;
mod plan;
mod py;
mod python_tables;
mod replace;
mod signature;
use std::collections::HashSet;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{LazyLock, Mutex};
use thiserror::Error;
use classify::{Classified, Groups, Options};
#[cfg(feature = "parse-grok")]
pub(crate) use dialect::ascii_set;
use plan::Plan;
pub use crate::Dialect;
pub use crate::tier::MatcherTier;
#[cfg(feature = "glob")]
pub use glob::{GlobBuilder, GlobMatcher};
pub use ops::{Captures, ReplaceError, ReplaceSyntax, Replacement};
pub use signature::{
MAX_ALL_OF, MAX_VERIFY, Signature, SignatureBuilder, SignatureError, SignatureMatch,
SignatureScratch, SignatureSet, Specificity, Verify,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Match {
pub start: usize,
pub end: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct SetMatch {
pub start: usize,
pub end: usize,
pub pattern_idx: usize,
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum BuildError {
#[error(
"strmatch: empty pattern\n \
hint: an empty pattern matches every position; pass a non-empty \
literal or wrap the matcher in Option for an absent-matcher slot"
)]
Empty,
#[error(
"strmatch: regex syntax error in pattern {pattern:?}\n \
reason: {source}\n \
hint: {hint}"
)]
Syntax {
pattern: String,
#[source]
source: Box<regex_syntax::Error>,
hint: &'static str,
},
#[error(
"strmatch: pattern {pattern:?} does not compile\n \
reason: {source}\n \
hint: {hint}"
)]
Compile {
pattern: String,
#[source]
source: Box<regex_automata::meta::BuildError>,
hint: &'static str,
},
#[error(
"strmatch: pattern {pattern:?} can't be read in the dialect the builder asked for\n \
hint: {hint}"
)]
Dialect {
pattern: String,
hint: &'static str,
},
#[error(
"strmatch: the capture groups of {pattern:?} don't build\n \
reason: {source}\n \
hint: {hint}"
)]
Groups {
pattern: String,
#[source]
source: Box<regex_automata::util::captures::GroupInfoError>,
hint: &'static str,
},
#[error(
"strmatch: the literal automaton does not build\n \
reason: {source}\n \
hint: {hint}"
)]
Automaton {
#[source]
source: Box<aho_corasick::BuildError>,
hint: &'static str,
},
#[cfg(feature = "glob")]
#[error(
"strmatch: glob {pattern:?} does not parse\n \
reason: {source}\n \
hint: {hint}"
)]
Glob {
pattern: String,
#[source]
source: Box<globset::Error>,
hint: &'static str,
},
#[cfg(feature = "glob")]
#[error("strmatch: glob {pattern:?} does not parse at byte {at}\n hint: {hint}")]
GlobSyntax {
pattern: String,
at: usize,
hint: &'static str,
},
#[error(
"strmatch: pattern {pattern:?} compiles to tier {got}, but builder \
requires at least {wanted}\n \
reason: {reason}\n \
hint: {hint}"
)]
TierTooLow {
pattern: String,
wanted: MatcherTier,
got: MatcherTier,
reason: &'static str,
hint: &'static str,
},
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OnBelowMin {
#[default]
Allow,
Warn,
Reject,
}
pub struct StrMatcher {
plan: Plan,
groups: Groups,
tier: MatcherTier,
pattern: String,
reason: &'static str,
hint: &'static str,
java_empty: bool,
dialect: Dialect,
non_empty: bool,
boundary_safe: bool,
group_count: usize,
slot_count: usize,
}
const fn on_boundaries(hay: &str, m: Match) -> bool {
hay.is_char_boundary(m.start) && hay.is_char_boundary(m.end)
}
impl std::fmt::Debug for StrMatcher {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("StrMatcher")
.field("tier", &self.tier)
.field("pattern", &self.pattern)
.field("reason", &self.reason)
.finish_non_exhaustive()
}
}
impl StrMatcher {
pub fn new(pattern: &str) -> Result<Self, BuildError> {
Self::builder().build(pattern)
}
#[must_use]
pub fn builder() -> StrMatcherBuilder {
StrMatcherBuilder::new()
}
#[inline]
#[must_use]
pub fn is_match(&self, hay: &[u8]) -> bool {
self.plan.is_match(hay)
}
#[inline]
#[must_use]
pub fn find(&self, hay: &[u8]) -> Option<Match> {
self.plan.find(hay)
}
#[must_use]
pub fn find_iter(&self, hay: &[u8]) -> std::vec::IntoIter<Match> {
let mut out: Vec<Match> = Vec::new();
if !self.each_match(hay, |m| {
out.push(m);
true
}) {
out.clear();
}
out.into_iter()
}
#[must_use]
pub fn is_match_str(&self, hay: &str) -> bool {
self.is_match(hay.as_bytes())
&& (self.boundary_safe || hay.is_ascii() || self.find_str(hay).is_some())
}
#[must_use]
pub fn find_str(&self, hay: &str) -> Option<Match> {
match self.plan.find(hay.as_bytes()) {
Some(m) if !on_boundaries(hay, m) => {
let mut first = None;
self.each_match_str(hay, |m| {
first = Some(m);
false
});
first
}
found => found,
}
}
#[must_use]
pub fn find_iter_str(&self, hay: &str) -> std::vec::IntoIter<Match> {
let mut out: Vec<Match> = Vec::new();
if !self.each_match_str(hay, |m| {
out.push(m);
true
}) {
out.clear();
}
out.into_iter()
}
fn each_match_str(&self, hay: &str, mut f: impl FnMut(Match) -> bool) -> bool {
self.each_match(hay.as_bytes(), |m| !on_boundaries(hay, m) || f(m))
}
fn each_match(&self, hay: &[u8], f: impl FnMut(Match) -> bool) -> bool {
if self.java_empty {
self.plan.for_each_match_java(hay, f)
} else if self.non_empty {
self.plan.for_each_match_non_empty(hay, f)
} else {
self.plan.for_each_match(hay, f)
}
}
#[must_use]
pub const fn tier(&self) -> MatcherTier {
self.tier
}
#[must_use]
pub fn cost(&self) -> Option<crate::cost::Cost> {
let engine = match self.tier {
MatcherTier::Byte => "memchr",
MatcherTier::Literal => "memmem",
MatcherTier::LiteralSet => "aho_corasick",
MatcherTier::Regex => "lazy_dfa_find",
_ => return None,
};
crate::cost::of(engine)
}
#[must_use]
pub fn pattern(&self) -> &str {
&self.pattern
}
#[must_use]
pub const fn reason(&self) -> &'static str {
self.reason
}
#[must_use]
pub const fn hint(&self) -> &'static str {
self.hint
}
#[must_use]
pub const fn dialect(&self) -> Dialect {
self.dialect
}
}
#[derive(Debug, Clone, Default)]
#[allow(
clippy::struct_excessive_bools,
reason = "independent switches, each set by its own method"
)]
pub struct StrMatcherBuilder {
min_tier: Option<MatcherTier>,
on_below_min: OnBelowMin,
ascii_case_insensitive: bool,
ascii_classes: bool,
java_line_end: bool,
java_dot: bool,
java_empty_matches: bool,
dialect: Dialect,
crlf: bool,
#[cfg(feature = "strmatch-backtracking")]
backtracking: bool,
}
impl StrMatcherBuilder {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub const fn min_tier(mut self, tier: MatcherTier) -> Self {
self.min_tier = Some(tier);
self
}
#[must_use]
pub const fn on_below_min(mut self, policy: OnBelowMin) -> Self {
self.on_below_min = policy;
self
}
#[must_use]
pub const fn ascii_case_insensitive(mut self, enabled: bool) -> Self {
self.ascii_case_insensitive = enabled;
self
}
#[must_use]
pub const fn ascii_classes(mut self, enabled: bool) -> Self {
self.ascii_classes = enabled;
self
}
#[must_use]
pub const fn java_line_end(mut self, enabled: bool) -> Self {
self.java_line_end = enabled;
self
}
#[must_use]
pub const fn java_dot(mut self, enabled: bool) -> Self {
self.java_dot = enabled;
self
}
#[must_use]
pub const fn java_empty_matches(mut self, enabled: bool) -> Self {
self.java_empty_matches = enabled;
self
}
#[must_use]
pub const fn crlf(mut self, enabled: bool) -> Self {
self.crlf = enabled;
self
}
#[cfg(feature = "strmatch-backtracking")]
#[must_use]
pub const fn backtracking(mut self, enabled: bool) -> Self {
self.backtracking = enabled;
self
}
#[must_use]
pub const fn dialect(mut self, dialect: Dialect) -> Self {
self.dialect = dialect;
match dialect {
Dialect::Java => {
self.ascii_classes = true;
self.java_line_end = true;
self.java_dot = true;
self.java_empty_matches = true;
}
Dialect::Pcre | Dialect::Python => {
self.java_line_end = true;
self.java_empty_matches = true;
}
Dialect::JavaScript => self.java_empty_matches = true,
_ => {}
}
self
}
pub fn build(&self, pattern: &str) -> Result<StrMatcher, BuildError> {
let refuse = |hint| BuildError::Dialect {
pattern: pattern.to_owned(),
hint,
};
let java;
let read;
let (text, fold, backtrack) = match self.dialect {
Dialect::Rust => (pattern, false, None),
Dialect::Java => {
java = dialect::java_syntax(pattern).map_err(refuse)?;
(java.text.as_str(), java.fold, java.backtrack)
}
Dialect::Pcre => {
read = pcre::syntax(pattern).map_err(refuse)?;
(read.text.as_str(), false, read.backtrack)
}
Dialect::JavaScript => {
read = js::syntax(pattern).map_err(refuse)?;
(read.text.as_str(), false, read.backtrack)
}
Dialect::Python => {
read = py::syntax(pattern).map_err(refuse)?;
(read.text.as_str(), false, read.backtrack)
}
_ => {
return Err(refuse(
"strmatch reads the Rust, Java, PCRE2, JavaScript and Python dialects",
));
}
};
#[cfg(feature = "strmatch-backtracking")]
let require_backtracking = match backtrack {
Some(why) if !self.backtracking => return Err(refuse(why)),
found => found.is_some(),
};
#[cfg(not(feature = "strmatch-backtracking"))]
if let Some(why) = backtrack {
return Err(refuse(why));
}
let opts = Options {
case_insensitive: self.ascii_case_insensitive || fold,
#[cfg(feature = "strmatch-backtracking")]
ascii_fold_only: self.dialect == Dialect::Java,
ascii_classes: self.ascii_classes,
java_line_end: self.java_line_end,
java_dot: self.java_dot,
java_empty_matches: self.java_empty_matches,
terminators: match self.dialect {
Dialect::Pcre | Dialect::Python => dialect::Terminators::Lf,
_ => dialect::Terminators::Java,
},
char_boundaries: self.dialect != Dialect::Rust,
crlf: self.crlf,
#[cfg(feature = "strmatch-backtracking")]
backtracking: self.backtracking,
#[cfg(feature = "strmatch-backtracking")]
require_backtracking,
};
let classified = classify::classify(pattern, text, opts)?;
let tier = classified.descriptor.tier;
if let Some(min) = self.min_tier
&& tier.rank() < min.rank()
{
return self.apply_below_min(pattern, min, classified);
}
if is_fallback(tier) {
warn::on_regex_fallback(
pattern,
classified.descriptor.reason,
classified.descriptor.hint,
false,
);
metrics_inc_fallback();
}
Ok(StrMatcher::from_classified(
pattern,
self.dialect,
classified,
))
}
fn apply_below_min(
&self,
pattern: &str,
wanted: MatcherTier,
classified: Classified,
) -> Result<StrMatcher, BuildError> {
let got = classified.descriptor.tier;
let reason = classified.descriptor.reason;
let hint = classified.descriptor.hint;
match self.on_below_min {
OnBelowMin::Reject => Err(BuildError::TierTooLow {
pattern: pattern.to_string(),
wanted,
got,
reason,
hint,
}),
OnBelowMin::Warn => {
warn::on_regex_fallback(pattern, reason, hint, true);
metrics_inc_fallback();
Ok(StrMatcher::from_classified(
pattern,
self.dialect,
classified,
))
}
OnBelowMin::Allow => {
if is_fallback(got) {
warn::on_regex_fallback(pattern, reason, hint, false);
metrics_inc_fallback();
}
Ok(StrMatcher::from_classified(
pattern,
self.dialect,
classified,
))
}
}
}
}
const fn is_fallback(tier: MatcherTier) -> bool {
matches!(tier, MatcherTier::Regex | MatcherTier::Backtracking)
}
impl StrMatcher {
fn from_classified(pattern: &str, dialect: Dialect, classified: Classified) -> Self {
let group_count = classified
.groups
.info
.group_len(regex_automata::util::primitives::PatternID::ZERO);
let slot_count = classified
.plan
.layout()
.unwrap_or(&classified.groups.info)
.slot_len();
Self {
dialect,
plan: classified.plan,
groups: classified.groups,
tier: classified.descriptor.tier,
pattern: pattern.to_string(),
reason: classified.descriptor.reason,
hint: classified.descriptor.hint,
java_empty: classified.java_empty,
non_empty: classified.non_empty,
boundary_safe: classified.boundary_safe,
group_count,
slot_count,
}
}
}
pub struct StrMatcherSet {
merged: Option<MergedAc>,
individual: Vec<(usize, StrMatcher)>,
tiers: Vec<MatcherTier>,
}
struct MergedAc {
ac: aho_corasick::AhoCorasick,
pattern_indices: Vec<usize>,
}
impl StrMatcherSet {
pub fn new<I, S>(patterns: I) -> Result<Self, BuildError>
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
Self::builder().build_set(patterns)
}
#[must_use]
pub fn builder() -> StrMatcherBuilder {
StrMatcherBuilder::new()
}
#[must_use]
pub fn is_match(&self, hay: &[u8]) -> bool {
if let Some(m) = &self.merged
&& m.ac.find(hay).is_some()
{
return true;
}
self.individual.iter().any(|(_, m)| m.is_match(hay))
}
#[must_use]
pub fn earliest_match(&self, hay: &[u8]) -> Option<SetMatch> {
let mut best: Option<SetMatch> = self.merged.as_ref().and_then(|m| {
m.ac.find(hay).map(|hit| SetMatch {
start: hit.start(),
end: hit.end(),
pattern_idx: m.pattern_indices[hit.pattern().as_usize()],
})
});
for (idx, matcher) in &self.individual {
if let Some(found) = matcher.find(hay) {
let cand = SetMatch {
start: found.start,
end: found.end,
pattern_idx: *idx,
};
best = match best {
None => Some(cand),
Some(b) if cand.start < b.start => Some(cand),
Some(b) if cand.start == b.start && cand.pattern_idx < b.pattern_idx => {
Some(cand)
}
Some(b) => Some(b),
};
}
}
best
}
#[must_use]
pub fn find_iter(&self, hay: &[u8]) -> std::vec::IntoIter<SetMatch> {
let mut all: Vec<SetMatch> = Vec::new();
if let Some(m) = &self.merged {
for hit in m.ac.find_iter(hay) {
all.push(SetMatch {
start: hit.start(),
end: hit.end(),
pattern_idx: m.pattern_indices[hit.pattern().as_usize()],
});
}
}
for (idx, matcher) in &self.individual {
for hit in matcher.find_iter(hay) {
all.push(SetMatch {
start: hit.start,
end: hit.end,
pattern_idx: *idx,
});
}
}
all.sort_by_key(|m| (m.start, m.pattern_idx));
all.into_iter()
}
#[must_use]
pub fn tier_counts(&self) -> [usize; MatcherTier::ALL.len()] {
let mut counts = [0_usize; MatcherTier::ALL.len()];
for t in &self.tiers {
counts[t.index()] += 1;
}
counts
}
#[must_use]
pub const fn len(&self) -> usize {
self.tiers.len()
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.tiers.is_empty()
}
}
impl StrMatcherBuilder {
pub fn build_set<I, S>(&self, patterns: I) -> Result<StrMatcherSet, BuildError>
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
let mut individual: Vec<(usize, StrMatcher)> = Vec::new();
let mut merge_lits: Vec<Vec<u8>> = Vec::new();
let mut pattern_indices: Vec<usize> = Vec::new();
let mut tiers: Vec<MatcherTier> = Vec::new();
for (idx, pat) in patterns.into_iter().enumerate() {
let m = self.build(pat.as_ref())?;
tiers.push(m.tier);
match m.plan.merge_literals() {
Some((lits, ci)) if ci == self.ascii_case_insensitive && !m.java_empty => {
for lit in lits {
pattern_indices.push(idx);
merge_lits.push(lit);
}
}
_ => individual.push((idx, m)),
}
}
let merged = if merge_lits.is_empty() {
None
} else {
let ac = aho_corasick::AhoCorasickBuilder::new()
.ascii_case_insensitive(self.ascii_case_insensitive)
.match_kind(aho_corasick::MatchKind::LeftmostLongest)
.build(&merge_lits)
.map_err(|e| BuildError::Automaton {
source: Box::new(e),
hint: "split the set into smaller sets",
})?;
Some(MergedAc {
ac,
pattern_indices,
})
};
Ok(StrMatcherSet {
merged,
individual,
tiers,
})
}
}
mod warn {
use super::{AtomicBool, AtomicUsize, HashSet, LazyLock, Mutex, Ordering};
pub(super) const WARN_CAP: usize = 10;
static WARNED_HASHES: LazyLock<Mutex<HashSet<u64>>> =
LazyLock::new(|| Mutex::new(HashSet::new()));
static DISTINCT: AtomicUsize = AtomicUsize::new(0);
static SUMMARY_EMITTED: AtomicBool = AtomicBool::new(false);
fn hash_pattern(pattern: &str) -> u64 {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut h = DefaultHasher::new();
pattern.hash(&mut h);
h.finish()
}
pub(super) fn on_regex_fallback(
pattern: &str,
reason: &'static str,
hint: &'static str,
force: bool,
) {
let h = hash_pattern(pattern);
let already_warned = {
let mut set = WARNED_HASHES
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
!set.insert(h)
};
if already_warned && !force {
return;
}
let n = if force {
DISTINCT.load(Ordering::Relaxed)
} else {
DISTINCT.fetch_add(1, Ordering::Relaxed) + 1
};
let summary = !force && n == WARN_CAP + 1 && !SUMMARY_EMITTED.swap(true, Ordering::Relaxed);
emit(pattern, reason, hint, force || n <= WARN_CAP, summary);
}
#[cfg(feature = "tracing")]
fn emit(pattern: &str, reason: &'static str, hint: &'static str, warn: bool, summary: bool) {
if warn {
tracing::warn!(
target: "grippo::strmatch",
pattern,
reason,
hint,
"pattern falls through to regex engine on hot path"
);
} else {
tracing::debug!(
target: "grippo::strmatch",
pattern,
reason,
hint,
"regex fallback (WARN suppressed past cap)"
);
}
if summary {
tracing::info!(
target: "grippo::strmatch",
cap = WARN_CAP,
"{}+ distinct patterns have fallen through to the regex engine; \
further fall-throughs log at DEBUG. Inspect StrMatcher::tier() / \
StrMatcherSet::tier_counts() at runtime, or scrape the \
strmatch_regex_fallback_total metric.",
WARN_CAP,
);
}
}
#[cfg(not(feature = "tracing"))]
const fn emit(_: &str, _: &'static str, _: &'static str, _: bool, _: bool) {}
#[cfg(test)]
pub(super) fn reset_for_tests() {
WARNED_HASHES
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clear();
DISTINCT.store(0, Ordering::Relaxed);
SUMMARY_EMITTED.store(false, Ordering::Relaxed);
}
#[cfg(test)]
pub(super) fn distinct_for_tests() -> usize {
DISTINCT.load(Ordering::Relaxed)
}
}
#[cfg(feature = "metrics")]
fn metrics_inc_fallback() {
metrics::counter!("strmatch_regex_fallback_total").increment(1);
}
#[cfg(not(feature = "metrics"))]
const fn metrics_inc_fallback() {}
#[cfg(test)]
pub(crate) fn reset_warn_state_for_tests() {
warn::reset_for_tests();
}
#[cfg(test)]
mod tests;