use std::borrow::Cow;
use aho_corasick::{AhoCorasick, MatchKind};
use regex_automata::meta;
use regex_automata::util::captures::GroupInfo;
use regex_automata::util::primitives::PatternID;
use regex_syntax::hir::literal::{ExtractKind, Extractor};
use regex_syntax::hir::{Class, Hir, HirKind, Literal, Look};
use super::dialect::{self, EndRefusal, JavaEnds, Reading, Terminators};
#[cfg(feature = "strmatch-backtracking")]
use super::plan::Backtrack;
use super::plan::{Anchor, JavaEnd, LineEnd, Plan, ShapeOp, SmallByteSet};
use super::{BuildError, MatcherTier};
const CLASS_BYTE_CAP: usize = 16;
const LITERAL_SET_CAP: usize = 2048;
pub struct Classified {
pub plan: Plan,
pub descriptor: Descriptor,
pub groups: Groups,
pub java_empty: bool,
pub non_empty: bool,
pub boundary_safe: bool,
}
pub struct Groups {
pub info: GroupInfo,
pub anchored: Option<Box<meta::Regex>>,
}
#[derive(Debug, Clone, Copy, Default)]
#[allow(
clippy::struct_excessive_bools,
reason = "independent switches, one per builder option"
)]
pub struct Options {
pub case_insensitive: bool,
#[cfg(feature = "strmatch-backtracking")]
pub ascii_fold_only: bool,
pub ascii_classes: bool,
pub java_line_end: bool,
pub java_dot: bool,
pub java_empty_matches: bool,
pub terminators: Terminators,
pub char_boundaries: bool,
pub crlf: bool,
#[cfg(feature = "strmatch-backtracking")]
pub backtracking: bool,
#[cfg(feature = "strmatch-backtracking")]
pub require_backtracking: bool,
}
#[derive(Debug, Clone)]
pub struct Descriptor {
pub tier: MatcherTier,
pub reason: &'static str,
pub hint: &'static str,
}
pub fn classify(pattern: &str, text: &str, opts: Options) -> Result<Classified, BuildError> {
if text.is_empty() {
return Err(BuildError::Empty);
}
let text: Cow<'_, str> = if opts.ascii_classes {
dialect::ascii_classes(text).map_err(|hint| BuildError::Dialect {
pattern: pattern.to_string(),
hint,
})?
} else {
Cow::Borrowed(text)
};
#[cfg(feature = "strmatch-backtracking")]
if opts.require_backtracking {
return backtrack(pattern, &text, opts)?
.ok_or_else(|| dialect_error(pattern, BACKTRACK_REFUSED));
}
let base = Reading {
fold: false,
java_dot: opts.java_dot,
terminators: opts.terminators,
crlf: opts.crlf,
};
let hir = match dialect::parse(&text, base) {
Ok(hir) => hir,
Err(e) => return refused(pattern, &text, *e, opts),
};
let reading = Reading {
fold: opts.case_insensitive,
..base
};
let engine: Cow<'_, Hir> = if opts.case_insensitive {
match dialect::parse(&text, reading) {
Ok(folded) => Cow::Owned(folded),
Err(e) => return refused(pattern, &text, *e, opts),
}
} else {
Cow::Borrowed(&hir)
};
let ends = if opts.java_line_end {
match dialect::java_line_ends(&text, reading) {
Ok(ends) => ends,
Err(EndRefusal::Syntax(e)) => return refused(pattern, &text, *e, opts),
Err(EndRefusal::Multiline) => {
return Err(dialect_error(pattern, dialect::MULTILINE_END_REFUSED));
}
Err(EndRefusal::NotLast) => return not_last(pattern, &text, opts),
}
} else {
None
};
let chars = opts.char_boundaries;
let (plan, descriptor) = choose(pattern, &hir, &engine, opts.case_insensitive, chars)?;
let groups = groups(pattern, &plan, &hir, &engine, chars)?;
let plan = match ends {
Some(ends) => line_end(pattern, plan, &groups, &ends, chars)?,
None => plan,
};
let non_empty = hir.properties().minimum_len().is_some_and(|len| len > 0);
Ok(Classified {
plan,
descriptor,
groups,
java_empty: opts.java_empty_matches
&& hir.properties().minimum_len().is_none_or(|n| n == 0),
non_empty,
boundary_safe: non_empty && hir.properties().is_utf8(),
})
}
fn line_end(
pattern: &str,
plan: Plan,
groups: &Groups,
ends: &JavaEnds,
chars: bool,
) -> Result<Plan, BuildError> {
let java = match plan.end_literals() {
Some((literals, case_insensitive, exact)) if ends.count == 1 => JavaEnd::Literals {
literals,
case_insensitive,
exact,
},
_ => {
let group_len = groups.info.group_len(PatternID::ZERO);
let marker = u32::try_from(group_len)
.map_err(|_| dialect_error(pattern, "use fewer capture groups"))?;
let find = build_meta(pattern, &ends.rewrite(1, false), chars)?;
let (kept, layout) = if group_len == 1 {
(None, group_info(pattern, [None, None])?)
} else {
let names = groups.info.pattern_names(PatternID::ZERO).chain([None]);
let layout = group_info(pattern, names)?;
(
Some(build_meta(pattern, &ends.rewrite(marker, true), chars)?),
layout,
)
};
JavaEnd::Regex {
find,
groups: kept,
layout,
}
}
};
Ok(Plan::LineEnd(Box::new(LineEnd {
inner: plan,
java,
terminators: ends.terminators,
})))
}
fn dialect_error(pattern: &str, hint: &'static str) -> BuildError {
BuildError::Dialect {
pattern: pattern.to_string(),
hint,
}
}
#[cfg_attr(
not(feature = "strmatch-backtracking"),
expect(
unused_variables,
reason = "text and opts feed only the backtracking tier"
)
)]
fn not_last(pattern: &str, text: &str, opts: Options) -> Result<Classified, BuildError> {
#[cfg(feature = "strmatch-backtracking")]
if opts.backtracking
&& let Some(classified) = backtrack(pattern, text, opts)?
{
return Ok(classified);
}
Err(dialect_error(pattern, dialect::NOT_LAST_END_REFUSED))
}
fn choose(
pattern: &str,
hir: &Hir,
engine: &Hir,
case_insensitive: bool,
chars: bool,
) -> Result<(Plan, Descriptor), BuildError> {
if let Some((reason, hint)) = hard_reject(hir) {
return meta_plan(pattern, engine, chars, reason, hint);
}
if !case_insensitive && let Some(shape) = try_simple_shape(hir) {
let descriptor = Descriptor {
tier: tier_for_shape(&shape),
reason: shape_reason(&shape),
hint: "",
};
return Ok((Plan::Shape(shape), descriptor));
}
if let Some((ac, anchor, literals)) = try_literal_alternation(hir, case_insensitive) {
return Ok(literal_plan(
ac,
anchor,
literals,
case_insensitive,
"literal-only:alternation",
));
}
if case_insensitive
&& let Some((ac, anchor, literals)) = try_single_literal_for_case_insensitive(hir)
{
return Ok(literal_plan(
ac,
anchor,
literals,
case_insensitive,
"literal-only:case-insensitive",
));
}
if let Some((ac, anchor, literals)) = try_extractor_fallback(hir, case_insensitive) {
return Ok(literal_plan(
ac,
anchor,
literals,
case_insensitive,
"literal-only:extracted",
));
}
meta_plan(
pattern,
engine,
chars,
"complex-shape",
"the pattern combines anchors, classes, and quantifiers in a way that \
prevents safe literal reduction; consider splitting into smaller \
patterns or accepting the Regex tier",
)
}
fn literal_plan(
ac: AhoCorasick,
anchor: Anchor,
literals: Vec<Vec<u8>>,
case_insensitive: bool,
reason: &'static str,
) -> (Plan, Descriptor) {
let plan = Plan::LiteralOnly {
ac: Box::new(ac),
anchor,
literals: literals_to_boxed(literals),
case_insensitive,
};
let descriptor = Descriptor {
tier: MatcherTier::LiteralSet,
reason,
hint: "",
};
(plan, descriptor)
}
fn groups(
pattern: &str,
plan: &Plan,
hir: &Hir,
engine: &Hir,
chars: bool,
) -> Result<Groups, BuildError> {
if let Plan::Meta(r) = plan {
return Ok(Groups {
info: r.group_info().clone(),
anchored: None,
});
}
if hir.properties().explicit_captures_len() == 0 {
return Ok(Groups {
info: group_info(pattern, [None])?,
anchored: None,
});
}
let r = build_meta(pattern, engine, chars)?;
Ok(Groups {
info: r.group_info().clone(),
anchored: Some(Box::new(r)),
})
}
fn group_info<'a>(
pattern: &str,
names: impl IntoIterator<Item = Option<&'a str>>,
) -> Result<GroupInfo, BuildError> {
let given: Vec<Option<&str>> = names.into_iter().collect();
let names: Vec<Option<&str>> = given
.iter()
.enumerate()
.map(|(i, name)| name.filter(|n| !given[i + 1..].contains(&Some(*n))))
.collect();
GroupInfo::new([names]).map_err(|e| BuildError::Groups {
pattern: pattern.to_string(),
source: Box::new(e),
hint: "use fewer capture groups",
})
}
#[cfg_attr(
not(feature = "strmatch-backtracking"),
expect(
unused_variables,
reason = "text and opts feed only the backtracking tier"
)
)]
fn refused(
pattern: &str,
text: &str,
err: regex_syntax::Error,
opts: Options,
) -> Result<Classified, BuildError> {
#[cfg(feature = "strmatch-backtracking")]
if opts.backtracking
&& let Some(classified) = backtrack(pattern, text, opts)?
{
return Ok(classified);
}
let hint = if needs_backtracking(&err) {
BACKTRACK_HINT
} else {
SYNTAX_HINT
};
Err(BuildError::Syntax {
pattern: pattern.to_string(),
source: Box::new(err),
hint,
})
}
#[cfg(feature = "strmatch-backtracking")]
fn backtrack(pattern: &str, text: &str, opts: Options) -> Result<Option<Classified>, BuildError> {
if opts.case_insensitive && opts.ascii_fold_only {
return Err(dialect_error(pattern, FOLD_BACKTRACK_REFUSED));
}
let mut text: Cow<'_, str> = Cow::Borrowed(text);
if opts.java_dot {
let read = dialect::java_dots_text(&text).map_err(|hint| dialect_error(pattern, hint))?;
text = Cow::Owned(read.into_owned());
}
let java_end_text = if opts.java_line_end
&& let Cow::Owned(read) = dialect::java_line_ends_text(&text, opts.terminators)
.map_err(|hint| dialect_error(pattern, hint))?
{
Some(read)
} else {
None
};
let build = |text: &str| {
let text = if opts.crlf {
Cow::Owned(format!("(?R){text}"))
} else {
Cow::Borrowed(text)
};
let mut builder = fancy_regex::RegexBuilder::new(&text);
builder.case_insensitive(opts.case_insensitive);
builder.build().ok()
};
let Some(r) = build(java_end_text.as_deref().unwrap_or(&text)) else {
return Ok(None);
};
let info = group_info(pattern, r.capture_names())?;
let backtrack = match java_end_text.and_then(|_| build(&text)) {
Some(plain) => Backtrack {
plain,
java_end: Some(r),
terminators: opts.terminators,
},
None => Backtrack {
plain: r,
java_end: None,
terminators: opts.terminators,
},
};
Ok(Some(Classified {
plan: Plan::Backtrack(Box::new(backtrack)),
descriptor: Descriptor {
tier: MatcherTier::Backtracking,
reason: "backtracking",
hint: "rewrite the pattern without lookaround or backreferences \
to reach the Regex tier",
},
groups: Groups {
info,
anchored: None,
},
java_empty: opts.java_empty_matches,
non_empty: false,
boundary_safe: false,
}))
}
#[cfg(feature = "strmatch-backtracking")]
const FOLD_BACKTRACK_REFUSED: &str = "the backtracking tier folds case by Unicode, where Java's \
(?i) folds ASCII alone: drop the (?i), or the construct that needs backtracking";
#[cfg(feature = "strmatch-backtracking")]
const BACKTRACK_REFUSED: &str = "the backtracking engine doesn't read the pattern: check a \
backreference names a group that comes before it";
fn needs_backtracking(err: ®ex_syntax::Error) -> bool {
use regex_syntax::ast::ErrorKind as K;
matches!(
err,
regex_syntax::Error::Parse(e)
if matches!(e.kind(), K::UnsupportedLookAround | K::UnsupportedBackreference)
)
}
const SYNTAX_HINT: &str = "check the regex syntax and ensure it parses under \
the regex-syntax crate's default flags";
const BACKTRACK_HINT: &str = "lookaround and backreferences run only on the backtracking tier: \
enable the strmatch-backtracking feature and \
StrMatcherBuilder::backtracking(true), or rewrite the pattern \
without them";
fn hard_reject(hir: &Hir) -> Option<(&'static str, &'static str)> {
use HirKind as K;
match hir.kind() {
K::Look(l) => match l {
Look::Start | Look::End => None,
Look::WordAscii
| Look::WordAsciiNegate
| Look::WordUnicode
| Look::WordUnicodeNegate
| Look::WordStartAscii
| Look::WordEndAscii
| Look::WordStartUnicode
| Look::WordEndUnicode
| Look::WordStartHalfAscii
| Look::WordEndHalfAscii
| Look::WordStartHalfUnicode
| Look::WordEndHalfUnicode => Some((
"word-boundary",
"remove the word-boundary assertion if the surrounding context \
is known, or accept the Regex tier",
)),
Look::StartLF | Look::EndLF | Look::StartCRLF | Look::EndCRLF => Some((
"multiline-anchor",
"split the haystack by line and use a non-multiline pattern, \
or accept the Regex tier",
)),
},
K::Repetition(r) => {
if r.max.is_none_or(|max| max != r.min) {
Some((
"unbounded-quantifier",
"bound the quantifier (e.g. {1,64}) so literal extraction \
can yield finite exact prefixes, or accept the Regex tier",
))
} else {
hard_reject(&r.sub)
}
}
K::Capture(c) => {
hard_reject(&c.sub)
}
K::Class(cls) => {
if class_byte_count(cls).is_none() {
Some((
"unicode-class",
"if ASCII-only is acceptable, use (?-u) to disable unicode \
classes, or accept the Regex tier",
))
} else {
None
}
}
K::Concat(parts) | K::Alternation(parts) => parts.iter().find_map(hard_reject),
K::Empty | K::Literal(_) => None,
}
}
fn try_simple_shape(hir: &Hir) -> Option<ShapeOp> {
match hir.kind() {
HirKind::Literal(lit) => simple_literal(&lit.0),
HirKind::Class(cls) => simple_class(cls),
HirKind::Concat(parts) => anchored_literal(parts),
HirKind::Capture(c) => try_simple_shape(&c.sub),
_ => None,
}
}
fn simple_literal(bytes: &[u8]) -> Option<ShapeOp> {
match bytes.len() {
0 => None,
1 => Some(ShapeOp::ContainsByte(bytes[0])),
_ => Some(ShapeOp::Contains(Box::new(
memchr::memmem::Finder::new(bytes).into_owned(),
))),
}
}
fn simple_class(cls: &Class) -> Option<ShapeOp> {
let bytes = collect_class_bytes(cls)?;
match bytes.len() {
0 => None,
1 => Some(ShapeOp::ContainsByte(bytes[0])),
n if n <= 3 => SmallByteSet::new(&bytes).map(ShapeOp::ByteSet),
_ => None,
}
}
fn anchored_literal(parts: &[Hir]) -> Option<ShapeOp> {
let (anchor_start, body, anchor_end) = strip_anchors(parts)?;
let body_bytes = collect_literal_bytes(body)?;
if body_bytes.is_empty() {
return None;
}
match (anchor_start, anchor_end) {
(true, true) => Some(ShapeOp::ExactMatch(body_bytes.into_boxed_slice())),
(true, false) => Some(ShapeOp::StartsWith(body_bytes.into_boxed_slice())),
(false, true) => Some(ShapeOp::EndsWith(body_bytes.into_boxed_slice())),
(false, false) => simple_literal(&body_bytes),
}
}
fn strip_anchors(parts: &[Hir]) -> Option<(bool, &[Hir], bool)> {
let (mut lo, mut hi) = (0_usize, parts.len());
let start = parts
.first()
.is_some_and(|p| matches!(p.kind(), HirKind::Look(Look::Start)));
if start {
lo += 1;
}
let end = parts
.last()
.is_some_and(|p| matches!(p.kind(), HirKind::Look(Look::End)));
if end {
hi -= 1;
}
if hi <= lo {
return None;
}
Some((start, &parts[lo..hi], end))
}
fn collect_literal_bytes(parts: &[Hir]) -> Option<Vec<u8>> {
if parts.is_empty() {
return None;
}
let mut out: Vec<u8> = Vec::new();
for p in parts {
match p.kind() {
HirKind::Literal(Literal(bytes)) => out.extend_from_slice(bytes),
HirKind::Capture(c) => {
let inner = capture_literal_bytes(c)?;
out.extend_from_slice(&inner);
}
_ => return None,
}
}
Some(out)
}
fn capture_literal_bytes(c: ®ex_syntax::hir::Capture) -> Option<Vec<u8>> {
match c.sub.kind() {
HirKind::Literal(Literal(bytes)) => Some(bytes.to_vec()),
HirKind::Concat(parts) => collect_literal_bytes(parts),
_ => None,
}
}
fn class_byte_count(cls: &Class) -> Option<usize> {
let bytes = collect_class_bytes(cls)?;
Some(bytes.len())
}
fn collect_class_bytes(cls: &Class) -> Option<Vec<u8>> {
match cls {
Class::Bytes(b) => {
let mut out = Vec::new();
for r in b.iter() {
for byte in r.start()..=r.end() {
out.push(byte);
if out.len() > CLASS_BYTE_CAP {
return None;
}
}
}
Some(out)
}
Class::Unicode(u) => {
let mut out = Vec::new();
for r in u.iter() {
if !r.end().is_ascii() {
return None;
}
for cp in r.start()..=r.end() {
out.push(u8::try_from(cp).ok()?);
if out.len() > CLASS_BYTE_CAP {
return None;
}
}
}
Some(out)
}
}
}
fn try_literal_alternation(
hir: &Hir,
case_insensitive: bool,
) -> Option<(AhoCorasick, Anchor, Vec<Vec<u8>>)> {
let (outer_anchor, inner) = strip_outer_concat_anchors(hir)?;
let HirKind::Alternation(branches) = inner.kind() else {
return None;
};
if branches.is_empty() {
return None;
}
let mut literals: Vec<Vec<u8>> = Vec::with_capacity(branches.len());
for branch in branches {
let body_bytes = match branch.kind() {
HirKind::Literal(Literal(b)) => b.to_vec(),
HirKind::Concat(parts) => collect_literal_bytes(parts)?,
HirKind::Capture(c) => capture_literal_bytes(c)?,
_ => return None,
};
if body_bytes.is_empty() {
return None;
}
literals.push(body_bytes);
}
if literals.len() < 2 || literals.len() > LITERAL_SET_CAP {
return None;
}
let ac = AhoCorasick::builder()
.match_kind(MatchKind::LeftmostFirst)
.ascii_case_insensitive(case_insensitive)
.build(&literals)
.ok()?;
Some((ac, outer_anchor, literals))
}
fn strip_outer_concat_anchors(hir: &Hir) -> Option<(Anchor, &Hir)> {
let HirKind::Concat(parts) = hir.kind() else {
return Some((Anchor::Anywhere, hir));
};
let (start, body, end) = strip_anchors(parts)?;
let anchor = anchor_of(start, end);
if body.len() == 1 {
Some((anchor, &body[0]))
} else {
None
}
}
fn try_single_literal_for_case_insensitive(
hir: &Hir,
) -> Option<(AhoCorasick, Anchor, Vec<Vec<u8>>)> {
let (anchor, inner) = strip_outer_concat_anchors(hir)?;
let body_bytes = match inner.kind() {
HirKind::Literal(Literal(b)) => b.to_vec(),
HirKind::Concat(parts) => collect_literal_bytes(parts)?,
HirKind::Capture(c) => capture_literal_bytes(c)?,
_ => return None,
};
if body_bytes.is_empty() {
return None;
}
let ac = AhoCorasick::builder()
.match_kind(MatchKind::LeftmostFirst)
.ascii_case_insensitive(true)
.build([&body_bytes])
.ok()?;
Some((ac, anchor, vec![body_bytes]))
}
fn try_extractor_fallback(
hir: &Hir,
case_insensitive: bool,
) -> Option<(AhoCorasick, Anchor, Vec<Vec<u8>>)> {
let (anchor, body) = match hir.kind() {
HirKind::Concat(parts) => {
let (start, body, end) = strip_anchors(parts)?;
(anchor_of(start, end), Hir::concat(body.to_vec()))
}
_ => (Anchor::Anywhere, hir.clone()),
};
if !body.properties().look_set().is_empty() {
return None;
}
let mut ex = Extractor::new();
ex.kind(ExtractKind::Prefix);
ex.limit_class(CLASS_BYTE_CAP);
ex.limit_total(LITERAL_SET_CAP);
let seq = ex.extract(&body);
if !seq.is_exact() {
return None;
}
let literals = seq.literals()?;
if literals.len() < 2 || literals.len() > LITERAL_SET_CAP {
return None;
}
let owned: Vec<Vec<u8>> = literals.iter().map(|l| l.as_bytes().to_vec()).collect();
let bytes: Vec<&[u8]> = owned.iter().map(Vec::as_slice).collect();
let ac = AhoCorasick::builder()
.match_kind(MatchKind::LeftmostFirst)
.ascii_case_insensitive(case_insensitive)
.build(&bytes)
.ok()?;
Some((ac, anchor, owned))
}
const fn anchor_of(start: bool, end: bool) -> Anchor {
match (start, end) {
(true, true) => Anchor::Exact,
(true, false) => Anchor::AtStart,
(false, true) => Anchor::AtEnd,
(false, false) => Anchor::Anywhere,
}
}
fn meta_plan(
pattern: &str,
engine: &Hir,
chars: bool,
reason: &'static str,
hint: &'static str,
) -> Result<(Plan, Descriptor), BuildError> {
let meta = build_meta(pattern, engine, chars)?;
let descriptor = Descriptor {
tier: MatcherTier::Regex,
reason,
hint,
};
Ok((Plan::Meta(Box::new(meta)), descriptor))
}
fn build_meta(pattern: &str, hir: &Hir, chars: bool) -> Result<meta::Regex, BuildError> {
meta::Regex::builder()
.configure(meta::Config::new().utf8_empty(chars))
.build_from_hir(hir)
.map_err(|e| BuildError::Compile {
pattern: pattern.to_string(),
source: Box::new(e),
hint: "shorten the pattern, or replace a large bounded repetition such as \
`\\w{5000}` with `\\w+` or a length check",
})
}
const fn shape_reason(shape: &ShapeOp) -> &'static str {
match shape {
ShapeOp::ContainsByte(_) => "shape:contains-byte",
ShapeOp::ByteSet(_) => "shape:byte-set",
ShapeOp::Contains(_) => "shape:contains-literal",
ShapeOp::StartsWith(_) => "shape:starts-with",
ShapeOp::EndsWith(_) => "shape:ends-with",
ShapeOp::ExactMatch(_) => "shape:exact-match",
}
}
fn tier_for_shape(shape: &ShapeOp) -> MatcherTier {
match shape {
ShapeOp::ContainsByte(_) | ShapeOp::ByteSet(_) => MatcherTier::Byte,
ShapeOp::StartsWith(b) | ShapeOp::EndsWith(b) | ShapeOp::ExactMatch(b) if b.len() == 1 => {
MatcherTier::Byte
}
ShapeOp::Contains(_)
| ShapeOp::StartsWith(_)
| ShapeOp::EndsWith(_)
| ShapeOp::ExactMatch(_) => MatcherTier::Literal,
}
}
fn literals_to_boxed(lits: Vec<Vec<u8>>) -> Box<[Box<[u8]>]> {
lits.into_iter()
.map(Vec::into_boxed_slice)
.collect::<Vec<_>>()
.into_boxed_slice()
}