use std::borrow::Cow;
use std::cell::Cell;
use regex_automata::util::captures::{Captures as Slots, GroupInfo};
use regex_automata::util::interpolate;
use regex_automata::util::iter::Searcher;
use regex_automata::util::primitives::{NonMaxUsize, PatternID};
use regex_automata::{Anchored, Input, meta};
use super::dialect::{self, final_terminator};
use super::plan::{JavaEnd, Plan, resume};
use super::{Match, StrMatcher};
#[derive(Debug, Clone)]
pub struct Captures {
slots: Slots,
len: usize,
}
impl Captures {
#[must_use]
pub fn is_match(&self) -> bool {
self.slots.is_match()
}
#[must_use]
pub fn get(&self, index: usize) -> Option<Match> {
if index >= self.len {
return None;
}
self.slots.get_group(index).map(|s| Match {
start: s.start,
end: s.end,
})
}
#[must_use]
pub fn name(&self, name: &str) -> Option<Match> {
self.slots.get_group_by_name(name).map(|s| Match {
start: s.start,
end: s.end,
})
}
#[must_use]
pub const fn group_len(&self) -> usize {
self.len
}
pub fn expand(&self, hay: &[u8], rep: &Replacement, dst: &mut Vec<u8>) {
rep.write(hay, |i| self.get(i), self.slots.group_info(), dst);
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ReplaceSyntax {
Literal,
#[default]
Rust,
Java,
}
#[derive(Debug, Clone)]
pub struct Replacement {
text: Box<[u8]>,
expand: Expand,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Expand {
None,
WholeMatch,
Groups,
}
impl Replacement {
fn bind(text: Vec<u8>) -> Self {
if memchr::memchr(b'$', &text).is_none() {
return Self {
text: text.into_boxed_slice(),
expand: Expand::None,
};
}
let (whole, groups) = (Cell::new(false), Cell::new(false));
let mut plain: Vec<u8> = Vec::with_capacity(text.len());
interpolate::bytes(
&text,
|index, _| {
if index == 0 {
whole.set(true);
} else {
groups.set(true);
}
},
|_| {
groups.set(true);
None
},
&mut plain,
);
let (text, expand) = match (whole.get(), groups.get()) {
(_, true) => (text, Expand::Groups),
(true, false) => (text, Expand::WholeMatch),
(false, false) => (plain, Expand::None),
};
Self {
text: text.into_boxed_slice(),
expand,
}
}
fn write(
&self,
hay: &[u8],
group: impl Fn(usize) -> Option<Match>,
info: &GroupInfo,
dst: &mut Vec<u8>,
) {
if self.expand == Expand::None {
dst.extend_from_slice(&self.text);
return;
}
interpolate::bytes(
&self.text,
|index, dst| {
if let Some(text) = group(index).and_then(|m| hay.get(m.start..m.end)) {
dst.extend_from_slice(text);
}
},
|name| info.to_index(PatternID::ZERO, name),
dst,
);
}
}
impl StrMatcher {
#[must_use]
pub fn group_len(&self) -> usize {
self.groups.info.group_len(PatternID::ZERO)
}
pub fn group_names(&self) -> impl Iterator<Item = Option<&str>> + '_ {
self.groups.info.pattern_names(PatternID::ZERO)
}
#[must_use]
pub fn group_index(&self, name: &str) -> Option<usize> {
self.groups.info.to_index(PatternID::ZERO, name)
}
#[must_use]
pub fn create_captures(&self) -> Captures {
let layout = self.plan.layout().unwrap_or(&self.groups.info);
Captures {
slots: Slots::all(layout.clone()),
len: self.group_len(),
}
}
#[must_use]
pub fn captures(&self, hay: &[u8]) -> Option<Captures> {
let mut caps = self.create_captures();
self.captures_into(hay, &mut caps).then_some(caps)
}
pub fn captures_into(&self, hay: &[u8], caps: &mut Captures) -> bool {
self.fit(caps);
if !self.captures_from(&self.plan, hay, 0, caps) {
caps.slots.set_pattern(None);
}
caps.slots.is_match()
}
fn captures_from(&self, plan: &Plan, hay: &[u8], from: usize, caps: &mut Captures) -> bool {
let input = Input::new(hay).span(from.min(hay.len())..hay.len());
match plan {
Plan::Meta(r) => r.search_captures(&input, &mut caps.slots),
#[cfg(feature = "strmatch-backtracking")]
Plan::Backtrack(r) => match r.on(hay).captures_from_pos(hay, from) {
Ok(Some(found)) => fill_backtrack(&found, &self.groups.info, caps),
Ok(None) => caps.slots.set_pattern(None),
Err(_) => return false,
},
Plan::LineEnd(le) => match (final_terminator(hay), &le.java) {
(None, _) => return self.captures_from(&le.inner, hay, from, caps),
(Some(_), JavaEnd::Regex { find, groups, .. }) => {
java_captures(groups.as_ref().unwrap_or(find), &input, caps);
}
(Some(t), JavaEnd::Literals { .. }) => match le.find_at(hay, t, from) {
Some(m) => self.read_groups(&hay[..m.end], m, caps),
None => caps.slots.set_pattern(None),
},
},
plan => match plan.find_from(hay, from) {
Ok(Some(m)) => self.read_groups(hay, m, caps),
Ok(None) => caps.slots.set_pattern(None),
Err(_) => return false,
},
}
true
}
#[must_use]
pub fn captures_iter(&self, hay: &[u8]) -> std::vec::IntoIter<Captures> {
let mut out: Vec<Captures> = Vec::new();
let mut caps = self.create_captures();
if !self.each_captures(hay, 0, &mut caps, |c| {
out.push(c.clone());
true
}) {
out.clear();
}
out.into_iter()
}
#[must_use]
pub fn replacement(&self, text: impl AsRef<[u8]>, syntax: ReplaceSyntax) -> Replacement {
let text = text.as_ref();
match syntax {
ReplaceSyntax::Literal => Replacement {
text: text.into(),
expand: Expand::None,
},
ReplaceSyntax::Rust => Replacement::bind(text.to_vec()),
ReplaceSyntax::Java => {
Replacement::bind(dialect::java_replacement(text, self.group_len()))
}
}
}
#[must_use]
pub fn replace<'h>(&self, hay: &'h [u8], rep: &Replacement) -> Cow<'h, [u8]> {
self.replacen(hay, 1, rep)
}
#[must_use]
pub fn replace_all<'h>(&self, hay: &'h [u8], rep: &Replacement) -> Cow<'h, [u8]> {
self.replacen(hay, 0, rep)
}
#[must_use]
pub fn replacen<'h>(&self, hay: &'h [u8], limit: usize, rep: &Replacement) -> Cow<'h, [u8]> {
let mut out: Option<Vec<u8>> = None;
let mut last = 0;
let mut done = 0;
let info = &self.groups.info;
let mut put = |m: Match, write: &dyn Fn(&mut Vec<u8>)| {
let dst = out.get_or_insert_with(|| Vec::with_capacity(hay.len()));
dst.extend_from_slice(&hay[last..m.start]);
write(dst);
last = m.end;
done += 1;
limit == 0 || done < limit
};
let complete = if rep.expand == Expand::Groups {
let Some(first) = self.plan.find(hay) else {
return Cow::Borrowed(hay);
};
let mut caps = self.create_captures();
self.each_captures(hay, first.start, &mut caps, |c| {
let Some(m) = c.get(0) else { return true };
put(m, &|dst| rep.write(hay, |i| c.get(i), info, dst))
})
} else {
self.each_match(hay, |m| {
put(m, &|dst| {
rep.write(hay, |i| (i == 0).then_some(m), info, dst);
})
})
};
match out {
Some(mut dst) if complete => {
dst.extend_from_slice(&hay[last..]);
Cow::Owned(dst)
}
_ => Cow::Borrowed(hay),
}
}
#[must_use]
pub fn split<'h>(&self, hay: &'h [u8]) -> std::vec::IntoIter<&'h [u8]> {
self.splitn(hay, usize::MAX)
}
#[must_use]
pub fn splitn<'h>(&self, hay: &'h [u8], limit: usize) -> std::vec::IntoIter<&'h [u8]> {
let mut out: Vec<&'h [u8]> = Vec::new();
if limit == 0 {
return out.into_iter();
}
let mut last = 0;
let complete = self.each_match(hay, |m| {
if out.len() + 1 >= limit {
return false;
}
out.push(&hay[last..m.start]);
last = m.end;
true
});
if !complete {
return vec![hay].into_iter();
}
out.push(&hay[last..]);
out.into_iter()
}
fn fit(&self, caps: &mut Captures) {
let layout = self.plan.layout().unwrap_or(&self.groups.info);
if caps.slots.group_info().slot_len() != layout.slot_len() || caps.len != self.group_len() {
*caps = self.create_captures();
}
}
fn read_groups(&self, hay: &[u8], m: Match, caps: &mut Captures) {
if let Some(r) = &self.groups.anchored {
let input = Input::new(hay).span(m.start..m.end).anchored(Anchored::Yes);
r.search_captures(&input, &mut caps.slots);
if caps.slots.is_match() {
return;
}
}
set_whole(m, &self.groups.info, caps);
}
fn each_captures(
&self,
hay: &[u8],
from: usize,
caps: &mut Captures,
f: impl FnMut(&Captures) -> bool,
) -> bool {
self.fit(caps);
if self.java_empty {
self.each_captures_java(hay, from, caps, f)
} else {
self.each_captures_on(&self.plan, hay, from, caps, f)
}
}
fn each_captures_java(
&self,
hay: &[u8],
from: usize,
caps: &mut Captures,
mut f: impl FnMut(&Captures) -> bool,
) -> bool {
let mut at = from;
while at <= hay.len() {
if !self.captures_from(&self.plan, hay, at, caps) {
return false;
}
let Some(m) = caps.get(0) else { break };
if !f(caps) {
break;
}
at = resume(hay, m);
}
true
}
fn each_captures_on(
&self,
plan: &Plan,
hay: &[u8],
from: usize,
caps: &mut Captures,
mut f: impl FnMut(&Captures) -> bool,
) -> bool {
match plan {
Plan::Meta(r) => {
each_search(
hay,
from,
caps,
|input, caps| {
r.search_captures(input, &mut caps.slots);
},
f,
);
true
}
#[cfg(feature = "strmatch-backtracking")]
Plan::Backtrack(r) => {
for found in r.on(hay).captures_iter(hay) {
let Ok(found) = found else { return false };
fill_backtrack(&found, &self.groups.info, caps);
if !f(caps) {
break;
}
}
true
}
Plan::LineEnd(le) => match (final_terminator(hay), &le.java) {
(None, _) => self.each_captures_on(&le.inner, hay, from, caps, f),
(Some(_), JavaEnd::Regex { find, groups, .. }) => {
let re = groups.as_ref().unwrap_or(find);
each_search(
hay,
from,
caps,
|input, caps| java_captures(re, input, caps),
f,
);
true
}
(Some(t), JavaEnd::Literals { .. }) => {
le.each_at(hay, t, &mut |m| {
self.read_groups(&hay[..m.end], m, caps);
f(caps)
});
true
}
},
plan => plan.for_each_match(hay, |m| {
self.read_groups(hay, m, caps);
f(caps)
}),
}
}
}
fn each_search(
hay: &[u8],
from: usize,
caps: &mut Captures,
search: impl Fn(&Input<'_>, &mut Captures),
mut f: impl FnMut(&Captures) -> bool,
) {
let mut it = Searcher::new(Input::new(hay).span(from..hay.len()));
loop {
let found = it.advance(|input| {
search(input, caps);
Ok(caps.slots.get_match())
});
if found.is_none() || !f(caps) {
return;
}
}
}
fn java_captures(re: &meta::Regex, input: &Input<'_>, caps: &mut Captures) {
if let [.., start, end] = caps.slots.slots_mut() {
(*start, *end) = (None, None);
}
re.search_captures(input, &mut caps.slots);
if !caps.slots.is_match() {
return;
}
let end = input.haystack().len();
let [groups @ .., start, marker_end] = caps.slots.slots_mut() else {
return;
};
let Some(at) = start.take() else { return };
*marker_end = None;
for slot in groups
.iter_mut()
.filter(|s| s.is_some_and(|s| s.get() == end))
{
*slot = Some(at);
}
}
fn set_whole(m: Match, info: &GroupInfo, caps: &mut Captures) {
caps.slots.set_pattern(Some(PatternID::ZERO));
let slots = caps.slots.slots_mut();
slots.fill(None);
if let Some((start, end)) = info.slots(PatternID::ZERO, 0) {
slots[start] = NonMaxUsize::new(m.start);
slots[end] = NonMaxUsize::new(m.end);
}
}
#[cfg(feature = "strmatch-backtracking")]
fn fill_backtrack(found: &fancy_regex::Captures<'_, [u8]>, info: &GroupInfo, caps: &mut Captures) {
caps.slots.set_pattern(Some(PatternID::ZERO));
let slots = caps.slots.slots_mut();
slots.fill(None);
for index in 0..info.group_len(PatternID::ZERO) {
if let (Some((start, end)), Some(m)) =
(info.slots(PatternID::ZERO, index), found.get(index))
{
slots[start] = NonMaxUsize::new(m.start());
slots[end] = NonMaxUsize::new(m.end());
}
}
}