use alloc::borrow::Cow;
use alloc::boxed::Box;
use alloc::string::String;
use alloc::sync::Arc;
use core::convert::Infallible;
use core::fmt;
use core::str::FromStr;
use crate::compile::{CompileOptions, DelegateUsage, compile_inner, compile_inner_from_hir};
use crate::parse::NamedGroups;
use crate::{
Assertion, BytesMode, CaptureNames, Captures, CapturesImpl, CompileError, Error, Expr, Input,
IterState, Regex, RegexImpl, RegexInput, RegexOptions, Replacer, Result, WrapEngine,
capture_names_of, plan_captures_into, plan_find, plan_is_match, ra_input, replacen_with,
to_hir,
};
#[derive(Clone)]
pub struct RegularRegex {
engine: WrapEngine,
pattern: String,
set_pattern: String,
named_groups: Arc<NamedGroups>,
}
#[derive(Debug)]
pub struct RegularMatches<'r, 't, S: Input + ?Sized> {
regex: &'r RegularRegex,
state: IterState<'t, S>,
}
#[derive(Debug)]
pub struct RegularCaptureMatches<'r, 't, S: Input + ?Sized>(RegularMatches<'r, 't, S>);
impl RegularRegex {
#[doc(hidden)]
pub fn planned(&self) -> bool {
matches!(self.engine, WrapEngine::Plan(_))
}
pub fn new(pattern: &str) -> Result<RegularRegex> {
Self::new_options(pattern.into(), &RegexOptions::default())
}
pub(crate) fn new_options(pattern: String, options: &RegexOptions) -> Result<RegularRegex> {
if let Some(option) = rich_option(options) {
return Err(CompileError::NotRegular(option).into());
}
let tree = Expr::parse_tree_with_flags(&pattern, options.compute_flags())?;
if let Some(construct) = rich_construct(&tree.expr) {
return Err(CompileError::NotRegular(construct).into());
}
let compile_options = CompileOptions {
bytes_mode: options.bytes_mode,
unicode: options.syntaxc.get_unicode()
&& !matches!(options.bytes_mode, BytesMode::Ascii),
delegate_size_limit: options.delegate_size_limit,
delegate_dfa_size_limit: options.delegate_dfa_size_limit,
..CompileOptions::default()
};
let set_pattern = boundary_free_pattern(&tree.expr);
let utf8 = matches!(options.bytes_mode, BytesMode::Unicode);
let mut hir_ctx = to_hir::HirCtx::new(compile_options.unicode, utf8);
let usage = DelegateUsage::regular_only();
let hir = to_hir::expr_to_hir(&tree.expr, &mut hir_ctx);
let engine = WrapEngine::new(hir.as_ref(), &compile_options, usage, || match &hir {
Some(hir) => compile_inner_from_hir(hir, &compile_options, usage),
None => {
let inner = compile_inner(&set_pattern, &compile_options, usage)?;
if set_pattern_differs(&tree.expr) {
return Err(CompileError::UnexpectedGeneralError(
"word boundaries could not be translated for RegularRegex".into(),
)
.into());
}
Ok(inner)
}
})?;
Ok(RegularRegex {
engine,
pattern,
set_pattern,
named_groups: Arc::new(tree.named_groups),
})
}
pub fn as_str(&self) -> &str {
&self.pattern
}
pub fn is_match<S: Input + ?Sized>(&self, haystack: &S) -> bool {
self.is_match_input(RegexInput::new(haystack))
}
pub fn is_match_input<S: Input + ?Sized>(&self, input: RegexInput<'_, S>) -> bool {
!input.is_done()
&& match &self.engine {
WrapEngine::Plan(plan) => plan_is_match(plan, &input),
WrapEngine::Meta(inner) => inner.is_match(ra_input(&input)),
}
}
pub fn find<'t, S: Input + ?Sized>(&self, haystack: &'t S) -> Option<S::Match<'t>> {
self.find_input(RegexInput::new(haystack))
}
pub fn find_input<'t, S: Input + ?Sized>(
&self,
input: RegexInput<'t, S>,
) -> Option<S::Match<'t>> {
self.find_span(&input)
.map(|(start, end)| input.haystack().make_match(start, end))
}
pub fn find_iter<'r, 't, S: Input + ?Sized>(
&'r self,
haystack: &'t S,
) -> RegularMatches<'r, 't, S> {
self.find_iter_input(RegexInput::new(haystack))
}
pub fn find_iter_input<'r, 't, S: Input + ?Sized>(
&'r self,
input: RegexInput<'t, S>,
) -> RegularMatches<'r, 't, S> {
RegularMatches {
regex: self,
state: IterState::new(input),
}
}
pub fn captures<'t, S: Input + ?Sized>(&self, haystack: &'t S) -> Option<Captures<'t, S>> {
self.captures_input(RegexInput::new(haystack))
}
pub fn captures_input<'t, S: Input + ?Sized>(
&self,
input: RegexInput<'t, S>,
) -> Option<Captures<'t, S>> {
if input.is_done() {
return None;
}
let mut locations = self.engine.create_captures();
match &self.engine {
WrapEngine::Plan(plan) => plan_captures_into(plan, &input, &mut locations),
WrapEngine::Meta(inner) => inner.search_captures(&ra_input(&input), &mut locations),
}
locations.is_match().then(|| Captures {
inner: CapturesImpl::Wrap {
locations,
explicit_capture_group_0: false,
},
named_groups: Arc::clone(&self.named_groups),
input: input.haystack(),
})
}
pub fn captures_iter<'r, 't, S: Input + ?Sized>(
&'r self,
haystack: &'t S,
) -> RegularCaptureMatches<'r, 't, S> {
self.captures_iter_input(RegexInput::new(haystack))
}
pub fn captures_iter_input<'r, 't, S: Input + ?Sized>(
&'r self,
input: RegexInput<'t, S>,
) -> RegularCaptureMatches<'r, 't, S> {
RegularCaptureMatches(self.find_iter_input(input))
}
pub fn captures_len(&self) -> usize {
self.engine.captures_len()
}
pub fn capture_names(&self) -> CaptureNames<'_> {
capture_names_of(&self.named_groups, self.captures_len())
}
pub fn replace<'t, R: Replacer>(&self, text: &'t str, rep: R) -> Cow<'t, str> {
self.replacen(text, 1, rep)
}
pub fn replace_all<'t, R: Replacer>(&self, text: &'t str, rep: R) -> Cow<'t, str> {
self.replacen(text, 0, rep)
}
pub fn replacen<'t, R: Replacer>(&self, text: &'t str, limit: usize, rep: R) -> Cow<'t, str> {
let replaced = replacen_with(
text,
limit,
rep,
|| self.find_iter(text).map(Ok::<_, Infallible>),
|| Captures {
inner: CapturesImpl::Wrap {
locations: self.engine.create_captures(),
explicit_capture_group_0: false,
},
named_groups: Arc::clone(&self.named_groups),
input: text,
},
|input, _, slots| {
let CapturesImpl::Wrap { locations, .. } = slots else {
unreachable!("regular captures are regex-automata's");
};
match &self.engine {
WrapEngine::Plan(plan) => plan_captures_into(plan, input, locations),
WrapEngine::Meta(inner) => inner.search_captures(&ra_input(input), locations),
}
Ok(locations.is_match())
},
);
match replaced {
Ok(replaced) => replaced,
Err(never) => match never {},
}
}
fn find_span<S: Input + ?Sized>(&self, input: &RegexInput<'_, S>) -> Option<(usize, usize)> {
if input.is_done() {
return None;
}
match &self.engine {
WrapEngine::Plan(plan) => plan_find(plan, input, None),
WrapEngine::Meta(inner) => inner
.search(&ra_input(input))
.map(|found| (found.start(), found.end())),
}
}
}
impl<'r, 't, S: Input + ?Sized> Iterator for RegularMatches<'r, 't, S> {
type Item = S::Match<'t>;
fn next(&mut self) -> Option<S::Match<'t>> {
let RegularMatches { regex, state } = self;
let haystack = state.input.haystack();
let found = state.next_with(|input, _| {
Ok::<_, Infallible>(
regex
.find_span(input)
.map(|(start, end)| (haystack.make_match(start, end), (start, end))),
)
})?;
match found {
Ok(found) => Some(found),
Err(never) => match never {},
}
}
}
impl<'r, 't, S: Input + ?Sized> Iterator for RegularCaptureMatches<'r, 't, S> {
type Item = Captures<'t, S>;
fn next(&mut self) -> Option<Captures<'t, S>> {
let RegularMatches { regex, state } = &mut self.0;
let found = state.next_with(|input, _| {
Ok::<_, Infallible>(regex.captures_input(input.clone()).map(|captures| {
let span = captures.get_span(0).expect("a match always has group 0");
(captures, span)
}))
})?;
match found {
Ok(found) => Some(found),
Err(never) => match never {},
}
}
}
impl From<RegularRegex> for Regex {
fn from(regex: RegularRegex) -> Regex {
Regex {
inner: RegexImpl::Wrap {
engine: regex.engine,
pattern: regex.pattern,
explicit_capture_group_0: false,
delegated_pattern: regex.set_pattern,
},
named_groups: regex.named_groups,
#[cfg(all(feature = "native", target_os = "linux", target_arch = "x86_64"))]
native: None,
}
}
}
impl fmt::Debug for RegularRegex {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.pattern)
}
}
impl fmt::Display for RegularRegex {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.pattern)
}
}
impl FromStr for RegularRegex {
type Err = Error;
fn from_str(pattern: &str) -> Result<RegularRegex> {
RegularRegex::new(pattern)
}
}
pub(crate) fn rich_option(options: &RegexOptions) -> Option<&'static str> {
let runtime = &options.hard_regex_runtime_options;
if runtime.find_not_empty {
Some("the find_not_empty option")
} else if runtime.disallow_empty_match_at_eof_after_newline {
Some("the disallow_empty_match_at_eof_after_newline option")
} else if runtime.allow_input_assertion_overrides {
Some("the allow_input_assertion_overrides option")
} else {
None
}
}
pub(crate) fn rich_construct(expr: &Expr) -> Option<&'static str> {
match expr {
Expr::Empty | Expr::Any { .. } | Expr::Literal { .. } | Expr::Delegate { .. } => None,
Expr::Assertion(Assertion::EndTextIgnoreTrailingNewlines { .. }) => {
Some(r"`\Z` (end before trailing newlines)")
}
Expr::Assertion(Assertion::StartLineOniguruma { .. }) => Some("Oniguruma's multi-line `^`"),
Expr::Assertion(_) => None,
Expr::Concat(children) | Expr::Alt(children) => children.iter().find_map(rich_construct),
Expr::Group(child) => rich_construct(child),
Expr::Repeat { child, .. } => rich_construct(child),
Expr::LookAround(..) => Some("lookaround"),
Expr::Backref { .. } | Expr::BackrefWithRelativeRecursionLevel { .. } => {
Some("backreference")
}
Expr::AtomicGroup(_) => Some("atomic group or possessive quantifier"),
Expr::KeepOut => Some(r"`\K`"),
Expr::ContinueFromPreviousMatchEnd => Some(r"`\G`"),
Expr::BackrefExistsCondition { .. } | Expr::Conditional { .. } => Some("conditional"),
Expr::SubroutineCall(_) => Some("subroutine call"),
Expr::BacktrackingControlVerb(_) => Some("backtracking control verb"),
Expr::Absent(_) => Some("absent operator"),
Expr::DefineGroup { .. } => Some("DEFINE group"),
Expr::GeneralNewline { .. } => Some(r"`\R` (general newline)"),
Expr::AstNode(..) => Some("unresolved group reference"),
}
}
fn is_word_boundary(expr: &Expr) -> bool {
matches!(
expr,
Expr::Assertion(
Assertion::WordBoundary
| Assertion::NotWordBoundary
| Assertion::LeftWordBoundary
| Assertion::RightWordBoundary
| Assertion::LeftWordHalfBoundary
| Assertion::RightWordHalfBoundary
)
)
}
fn set_pattern_differs(expr: &Expr) -> bool {
is_word_boundary(expr) || expr.children_iter().any(set_pattern_differs)
}
fn boundary_free_pattern(expr: &Expr) -> String {
let mut pattern = String::new();
if set_pattern_differs(expr) {
without_word_boundaries(expr).to_str(&mut pattern, 0);
} else {
expr.to_str(&mut pattern, 0);
}
pattern
}
fn without_word_boundaries(expr: &Expr) -> Expr {
match expr {
_ if is_word_boundary(expr) => Expr::Empty,
Expr::Concat(children) => {
Expr::Concat(children.iter().map(without_word_boundaries).collect())
}
Expr::Alt(children) => Expr::Alt(children.iter().map(without_word_boundaries).collect()),
Expr::Group(child) => Expr::Group(Arc::new(without_word_boundaries(child))),
Expr::Repeat {
child,
lo,
hi,
greedy,
} => match without_word_boundaries(child) {
Expr::Empty => Expr::Empty,
child => Expr::Repeat {
child: Box::new(child),
lo: *lo,
hi: *hi,
greedy: *greedy,
},
},
leaf => leaf.clone(),
}
}