use std::collections::BTreeSet;
use regex_syntax::hir::{Class, Hir, HirKind};
const EXACT_CAP: usize = 16;
const CLASS_CAP: u32 = 4;
pub(super) const DNF_CAP: usize = 64;
pub(super) fn rewrite(re: &str) -> String {
let chars: Vec<char> = re.chars().collect();
let mut out = String::with_capacity(re.len());
let (mut i, mut escaped, mut class) = (0, false, 0_isize);
while let Some(&c) = chars.get(i) {
i += 1;
if escaped {
escaped = false;
match c {
'd' => out.push_str("[0-9]"),
'D' => out.push_str("[^0-9]"),
'w' => out.push_str("[A-Za-z0-9_]"),
'W' => out.push_str("[^A-Za-z0-9_]"),
_ => {
out.push('\\');
out.push(c);
}
}
continue;
}
match c {
'\\' => {
escaped = true;
continue;
}
'[' => class += 1,
']' => class -= 1,
'{' if class == 0 && i > 1 => {
if let Some((star, len)) = wide_range(&chars[i..]) {
out.push_str(star);
i += len;
continue;
}
}
_ => {}
}
out.push(c);
}
if escaped {
out.push('\\');
}
out
}
fn wide_range(rest: &[char]) -> Option<(&'static str, usize)> {
let star = match rest.first()? {
'0' => "*",
'1' => "+",
_ => return None,
};
if rest.get(1) != Some(&',') {
return None;
}
let digits = rest[2..].iter().take_while(|c| c.is_ascii_digit()).count();
(digits >= 3 && rest.get(2 + digits) == Some(&'}')).then_some((star, digits + 3))
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Cond {
All,
Atom(Vec<u8>),
And(Vec<Self>),
Or(Vec<Self>),
}
struct Info {
exact: Option<BTreeSet<Vec<u8>>>,
cond: Cond,
}
impl Info {
fn exact(s: &[u8]) -> Self {
Self {
exact: Some(BTreeSet::from([s.to_vec()])),
cond: Cond::All,
}
}
const fn unknown() -> Self {
Self {
exact: None,
cond: Cond::All,
}
}
fn into_cond(self, min: usize) -> Cond {
match self.exact {
Some(set) => exact_cond(set, min),
None => self.cond,
}
}
}
fn and(parts: Vec<Cond>) -> Cond {
let mut out = BTreeSet::new();
for p in parts {
match p {
Cond::All => {}
Cond::And(inner) => out.extend(inner),
other => {
out.insert(other);
}
}
}
collapse(out, Cond::And)
}
fn or(parts: Vec<Cond>) -> Cond {
let mut out = BTreeSet::new();
for p in parts {
match p {
Cond::All => return Cond::All,
Cond::Or(inner) => out.extend(inner),
other => {
out.insert(other);
}
}
}
collapse(out, Cond::Or)
}
fn collapse(set: BTreeSet<Cond>, many: fn(Vec<Cond>) -> Cond) -> Cond {
if set.len() > 1 {
return many(set.into_iter().collect());
}
set.into_iter().next().unwrap_or(Cond::All)
}
fn exact_cond(set: BTreeSet<Vec<u8>>, min: usize) -> Cond {
if set.iter().any(|s| s.len() < min) {
return Cond::All;
}
or(set.into_iter().map(Cond::Atom).collect())
}
fn class_set(
ranges: impl Iterator<Item = (u32, u32)> + Clone,
to: fn(u32) -> Option<Vec<u8>>,
) -> Info {
let width: u32 = ranges.clone().map(|(a, b)| b - a + 1).sum();
if width > CLASS_CAP {
return Info::unknown();
}
let set = ranges.flat_map(|(a, b)| a..=b).filter_map(to).collect();
Info {
exact: Some(set),
cond: Cond::All,
}
}
fn info(h: &Hir, min: usize) -> Info {
match h.kind() {
HirKind::Empty | HirKind::Look(_) => Info::exact(b""),
HirKind::Literal(l) => Info::exact(&l.0),
HirKind::Class(Class::Unicode(c)) => class_set(
c.ranges()
.iter()
.map(|r| (u32::from(r.start()), u32::from(r.end()))),
|cp| char::from_u32(cp).map(|ch| ch.to_string().into_bytes()),
),
HirKind::Class(Class::Bytes(c)) => class_set(
c.ranges()
.iter()
.map(|r| (u32::from(r.start()), u32::from(r.end()))),
|b| u8::try_from(b).ok().map(|b| vec![b]),
),
HirKind::Repetition(r) => {
if r.min == 0 {
return Info::unknown();
}
let sub = info(&r.sub, min);
if r.min == 1 && r.max == Some(1) {
return sub;
}
Info {
exact: None,
cond: sub.into_cond(min),
}
}
HirKind::Capture(c) => info(&c.sub, min),
HirKind::Concat(parts) => concat(parts, min),
HirKind::Alternation(parts) => {
let infos: Vec<Info> = parts.iter().map(|p| info(p, min)).collect();
let total: Option<usize> = infos
.iter()
.map(|i| i.exact.as_ref().map(BTreeSet::len))
.sum();
if total.is_some_and(|n| n <= EXACT_CAP) {
return Info {
exact: Some(
infos
.into_iter()
.filter_map(|i| i.exact)
.flatten()
.collect(),
),
cond: Cond::All,
};
}
Info {
exact: None,
cond: or(infos.into_iter().map(|i| i.into_cond(min)).collect()),
}
}
}
}
fn concat(parts: &[Hir], min: usize) -> Info {
let mut conds = Vec::new();
let mut run: BTreeSet<Vec<u8>> = BTreeSet::from([Vec::new()]);
for p in parts {
let pi = info(p, min);
match pi.exact {
Some(e) if run.len() * e.len() <= EXACT_CAP => {
let mut next = BTreeSet::new();
for a in &run {
for b in &e {
let mut s = a.clone();
s.extend_from_slice(b);
next.insert(s);
}
}
run = next;
}
Some(e) => conds.push(exact_cond(std::mem::replace(&mut run, e), min)),
None => {
conds.push(exact_cond(
std::mem::replace(&mut run, BTreeSet::from([Vec::new()])),
min,
));
conds.push(pi.cond);
}
}
}
if conds.is_empty() {
return Info {
exact: Some(run),
cond: Cond::All,
};
}
conds.push(exact_cond(run, min));
Info {
exact: None,
cond: and(conds),
}
}
fn flat(c: &Cond) -> (BTreeSet<Vec<u8>>, Option<BTreeSet<Vec<u8>>>) {
match c {
Cond::All => (BTreeSet::new(), None),
Cond::Atom(a) => (BTreeSet::from([a.clone()]), None),
Cond::And(parts) => {
let mut all = BTreeSet::new();
let mut best: Option<BTreeSet<Vec<u8>>> = None;
let score = |s: &BTreeSet<Vec<u8>>| {
(
s.iter().map(Vec::len).min().unwrap_or(0),
usize::MAX - s.len(),
)
};
for p in parts {
let (a, any) = flat(p);
all.extend(a);
if let Some(any) = any
&& best.as_ref().is_none_or(|b| score(&any) > score(b))
{
best = Some(any);
}
}
(all, best)
}
Cond::Or(parts) => {
let mut any = BTreeSet::new();
for p in parts {
let (a, sub) = flat(p);
if let Some(longest) = a.iter().max_by_key(|l| l.len()) {
any.insert(longest.clone());
} else if let Some(sub) = sub {
any.extend(sub);
} else {
return (BTreeSet::new(), None);
}
}
(BTreeSet::new(), Some(any))
}
}
}
fn dnf(c: &Cond, cap: usize) -> Option<Vec<BTreeSet<Vec<u8>>>> {
match c {
Cond::All => Some(vec![BTreeSet::new()]),
Cond::Atom(a) => Some(vec![BTreeSet::from([a.clone()])]),
Cond::Or(parts) => {
let mut out = Vec::new();
for p in parts {
let d = dnf(p, cap)?;
if d.iter().any(BTreeSet::is_empty) {
return Some(vec![BTreeSet::new()]);
}
out.extend(d);
if out.len() > cap {
return None;
}
}
Some(out)
}
Cond::And(parts) => {
let mut out = vec![BTreeSet::new()];
for p in parts {
let Some(d) = dnf(p, cap) else { continue };
if d.len() * out.len() > cap {
continue;
}
let mut next = Vec::with_capacity(d.len() * out.len());
for a in &out {
for b in &d {
let mut s = a.clone();
s.extend(b.iter().cloned());
next.push(s);
}
}
out = next;
}
Some(out)
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub(super) enum Required {
Nothing,
Clauses(Vec<Vec<Vec<u8>>>),
Flat {
all_of: Vec<Vec<u8>>,
any_of: Vec<Vec<u8>>,
},
}
pub(super) fn required(hir: &Hir, min: usize) -> Required {
let cond = info(hir, min).into_cond(min);
if let Some(clauses) = dnf(&cond, DNF_CAP) {
if clauses.iter().any(BTreeSet::is_empty) {
return Required::Nothing;
}
return Required::Clauses(
clauses
.into_iter()
.map(|c| c.into_iter().collect())
.collect(),
);
}
let (all, any) = flat(&cond);
let (all_of, any_of): (Vec<Vec<u8>>, Vec<Vec<u8>>) = (
all.into_iter().collect(),
any.unwrap_or_default().into_iter().collect(),
);
if all_of.is_empty() && any_of.is_empty() {
return Required::Nothing;
}
Required::Flat { all_of, any_of }
}