use std::borrow::Cow;
use regex_syntax::ast::{
self, AssertionKind, Ast, ClassAsciiKind, ClassBracketed, ClassSet, ClassSetItem,
ClassSetRange, ClassSetUnion, ClassUnicodeKind, Group, GroupKind, LiteralKind, Span,
};
use regex_syntax::hir::translate::TranslatorBuilder;
use regex_syntax::hir::{
Capture, Class, ClassBytes, ClassBytesRange, ClassUnicode, ClassUnicodeRange, Hir, HirKind,
Look, Repetition,
};
pub(super) const VERBOSE_REFUSED: &str =
"verbose mode (the x flag) is not supported with ascii_classes; drop the flag and its comments";
pub(super) const MULTILINE_END_REFUSED: &str = "a multi-line `$` can't be read as Java's, which also \
holds before \\r, U+0085, U+2028 and U+2029: drop the m flag, or build without java_line_end";
pub(super) const NOT_LAST_END_REFUSED: &str = "a `$` followed by more pattern that can match \
text or test a position can't be read as Java's at linear cost: end its branch with the \
`$`, or turn on backtracking (the strmatch-backtracking feature)";
#[cfg(feature = "strmatch-backtracking")]
pub(super) const VERBOSE_END_REFUSED: &str = "verbose mode (the x flag) is not supported with \
java_line_end on the backtracking tier: drop the flag and its comments";
#[cfg(feature = "strmatch-backtracking")]
pub(super) const VERBOSE_DOT_REFUSED: &str = "verbose mode (the x flag) is not supported with \
java_dot on the backtracking tier: drop the flag and its comments";
#[cfg(feature = "strmatch-backtracking")]
const JAVA_END_LOOKAHEAD: &str = r"(?:\z|(?=(?:\r\n|(?<!\r)\n|[\r\x{85}\x{2028}\x{2029}])\z))";
#[cfg(feature = "strmatch-backtracking")]
const JAVA_DOT_CLASS: &str = r"[^\n\r\x{85}\x{2028}\x{2029}]";
const DOT_TERMINATORS: [char; 4] = ['\r', '\u{85}', '\u{2028}', '\u{2029}'];
pub(super) fn ascii_classes(pattern: &str) -> Result<Cow<'_, str>, &'static str> {
rewrite_text(pattern, |spot| match spot {
Spot::Escape(c, in_class) => Ok(ascii_set(c, in_class)),
Spot::Flags(on) if on.contains(&b'x') => Err(VERBOSE_REFUSED),
_ => Ok(None),
})
}
#[cfg(feature = "strmatch-backtracking")]
pub(super) fn java_line_ends_text(pattern: &str) -> Result<Cow<'_, str>, &'static str> {
rewrite_text(pattern, |spot| match spot {
Spot::Dollar => Ok(Some(JAVA_END_LOOKAHEAD)),
Spot::Flags(on) if on.contains(&b'x') => Err(VERBOSE_END_REFUSED),
Spot::Flags(on) if on.contains(&b'm') => Err(MULTILINE_END_REFUSED),
_ => Ok(None),
})
}
#[cfg(feature = "strmatch-backtracking")]
pub(super) fn java_dots_text(pattern: &str) -> Result<Cow<'_, str>, &'static str> {
rewrite_text(pattern, |spot| match spot {
Spot::Dot { dot_all: false } => Ok(Some(JAVA_DOT_CLASS)),
Spot::Flags(on) if on.contains(&b'x') => Err(VERBOSE_DOT_REFUSED),
_ => Ok(None),
})
}
enum Spot<'p> {
Escape(u8, bool),
Dollar,
Dot {
#[cfg_attr(
not(feature = "strmatch-backtracking"),
expect(dead_code, reason = "only the backtracking tier's rewrite reads it")
)]
dot_all: bool,
},
Flags(&'p [u8]),
}
fn rewrite_text<'p>(
pattern: &'p str,
mut edit: impl FnMut(Spot<'p>) -> Result<Option<&'static str>, &'static str>,
) -> Result<Cow<'p, str>, &'static str> {
let b = pattern.as_bytes();
let mut out = String::new();
let mut copied = 0;
let mut depth = 0_usize;
let mut dot_all = false;
let mut outer: Vec<bool> = Vec::new();
let mut i = 0;
while i < b.len() {
let (spot, width) = match b[i] {
b'\\' => {
let Some(&c) = b.get(i + 1) else { break };
(Some(Spot::Escape(c, depth > 0)), 2)
}
b'[' => {
depth += 1;
i += 1;
if b.get(i) == Some(&b'^') {
i += 1;
}
if b.get(i) == Some(&b']') {
i += 1;
}
continue;
}
b']' if depth > 0 => {
depth -= 1;
(None, 1)
}
b'(' if depth == 0 => {
outer.push(dot_all);
if b.get(i + 1) != Some(&b'?') {
i += 1;
continue;
}
let (on, off, rest) = flag_runs(&b[i + 2..]);
edit(Spot::Flags(on))?;
if on.contains(&b's') {
dot_all = true;
}
if off.contains(&b's') {
dot_all = false;
}
if rest.first() == Some(&b')') {
outer.pop();
}
(None, 2)
}
b')' if depth == 0 => {
if let Some(was) = outer.pop() {
dot_all = was;
}
(None, 1)
}
b'$' if depth == 0 => (Some(Spot::Dollar), 1),
b'.' if depth == 0 => (Some(Spot::Dot { dot_all }), 1),
_ => (None, 1),
};
if let Some(spot) = spot
&& let Some(with) = edit(spot)?
{
out.push_str(&pattern[copied..i]);
out.push_str(with);
copied = i + width;
}
i += width;
}
if copied == 0 {
return Ok(Cow::Borrowed(pattern));
}
out.push_str(&pattern[copied..]);
Ok(Cow::Owned(out))
}
fn flag_runs(text: &[u8]) -> (&[u8], &[u8], &[u8]) {
let letters = |t: &[u8]| t.iter().take_while(|f| f.is_ascii_alphabetic()).count();
let (on, rest) = text.split_at(letters(text));
match rest.split_first() {
Some((b'-', after)) => {
let (off, rest) = after.split_at(letters(after));
(on, off, rest)
}
_ => (on, &[], rest),
}
}
const fn ascii_set(letter: u8, in_class: bool) -> Option<&'static str> {
Some(match (letter, in_class) {
(b'd', false) => "[0-9]",
(b'd', true) => "0-9",
(b'w', false) => "[0-9A-Za-z_]",
(b'w', true) => "0-9A-Za-z_",
(b's', false) => r"[\t\n\x0B\x0C\r ]",
(b's', true) => r"\t\n\x0B\x0C\r ",
(b'D', _) => "[^0-9]",
(b'W', _) => "[^0-9A-Za-z_]",
(b'S', _) => r"[^\t\n\x0B\x0C\r ]",
_ => return None,
})
}
pub(super) fn parse(pattern: &str, reading: Reading) -> Result<Hir, Box<regex_syntax::Error>> {
read(pattern, reading, false)
}
#[derive(Debug, Clone, Copy)]
pub(super) struct Reading {
pub(super) fold: bool,
pub(super) java_dot: bool,
}
fn read(
pattern: &str,
reading: Reading,
mark_dollars: bool,
) -> Result<Hir, Box<regex_syntax::Error>> {
let mut ast = parse_ast(pattern)?;
if reading.fold {
fold_ast(&mut ast, pattern);
}
if reading.java_dot {
mark(&mut ast, DOT_MARK, &|a| matches!(a, Ast::Dot(_)));
}
if mark_dollars {
mark(
&mut ast,
MARK,
&|a| matches!(a, Ast::Assertion(x) if x.kind == AssertionKind::EndLine),
);
}
let hir = translate(pattern, &ast)?;
if !reading.java_dot {
return Ok(hir);
}
Ok(rebuild(&hir, &|c, sub| {
if c.index == DOT_MARK {
java_dot(sub)
} else {
Hir::capture(Capture {
index: c.index,
name: c.name.clone(),
sub: Box::new(sub),
})
}
}))
}
fn java_dot(dot: Hir) -> Hir {
match dot.kind() {
HirKind::Class(Class::Unicode(set))
if !set
.ranges()
.iter()
.any(|r| r.start() <= '\n' && '\n' <= r.end()) =>
{
let mut set = set.clone();
set.difference(&ClassUnicode::new(
DOT_TERMINATORS.map(|c| ClassUnicodeRange::new(c, c)),
));
Hir::class(Class::Unicode(set))
}
HirKind::Class(Class::Bytes(set))
if !set
.ranges()
.iter()
.any(|r| r.start() <= b'\n' && b'\n' <= r.end()) =>
{
let mut set = set.clone();
set.difference(&ClassBytes::new([ClassBytesRange::new(b'\r', b'\r')]));
Hir::class(Class::Bytes(set))
}
_ => dot,
}
}
fn parse_ast(pattern: &str) -> Result<Ast, Box<regex_syntax::Error>> {
ast::parse::Parser::new()
.parse(pattern)
.map_err(|e| Box::new(e.into()))
}
fn translate(pattern: &str, ast: &Ast) -> Result<Hir, Box<regex_syntax::Error>> {
TranslatorBuilder::new()
.utf8(false)
.build()
.translate(pattern, ast)
.map_err(|e| Box::new(e.into()))
}
const MARK: u32 = u32::MAX;
const DOT_MARK: u32 = u32::MAX - 1;
pub(super) enum EndRefusal {
Syntax(Box<regex_syntax::Error>),
NotLast,
Multiline,
}
pub(super) struct JavaEnds {
hir: Hir,
pub(super) count: usize,
}
pub(super) fn java_line_ends(
pattern: &str,
reading: Reading,
) -> Result<Option<JavaEnds>, EndRefusal> {
let hir = read(pattern, reading, true).map_err(EndRefusal::Syntax)?;
let mut count = 0;
check_ends(&hir, false, &mut count)?;
Ok((count > 0).then_some(JavaEnds { hir, count }))
}
impl JavaEnds {
pub(super) fn rewrite(&self, marker: u32, keep_groups: bool) -> Hir {
rewrite_ends(&self.hir, marker, keep_groups)
}
}
fn mark(node: &mut Ast, index: u32, hit: &impl Fn(&Ast) -> bool) {
if hit(node) {
let span = *node.span();
let inner = std::mem::replace(node, Ast::empty(span));
*node = Ast::group(Group {
span,
kind: GroupKind::CaptureIndex(index),
ast: Box::new(inner),
});
return;
}
match node {
Ast::Repetition(r) => mark(&mut r.ast, index, hit),
Ast::Group(g) => mark(&mut g.ast, index, hit),
Ast::Alternation(a) => a.asts.iter_mut().for_each(|n| mark(n, index, hit)),
Ast::Concat(c) => c.asts.iter_mut().for_each(|n| mark(n, index, hit)),
_ => {}
}
}
fn rebuild(hir: &Hir, capture: &impl Fn(&Capture, Hir) -> Hir) -> Hir {
match hir.kind() {
HirKind::Capture(c) => capture(c, rebuild(&c.sub, capture)),
HirKind::Concat(parts) => Hir::concat(parts.iter().map(|p| rebuild(p, capture)).collect()),
HirKind::Alternation(branches) => {
Hir::alternation(branches.iter().map(|b| rebuild(b, capture)).collect())
}
HirKind::Repetition(r) => Hir::repetition(Repetition {
min: r.min,
max: r.max,
greedy: r.greedy,
sub: Box::new(rebuild(&r.sub, capture)),
}),
HirKind::Empty | HirKind::Literal(_) | HirKind::Class(_) | HirKind::Look(_) => hir.clone(),
}
}
fn check_ends(hir: &Hir, followed: bool, count: &mut usize) -> Result<(), EndRefusal> {
match hir.kind() {
HirKind::Capture(c) if c.index == MARK => match c.sub.kind() {
HirKind::Look(Look::End) if followed => Err(EndRefusal::NotLast),
HirKind::Look(Look::End) => {
*count += 1;
Ok(())
}
_ => Err(EndRefusal::Multiline),
},
HirKind::Capture(c) => check_ends(&c.sub, followed, count),
HirKind::Concat(parts) => {
let mut followed = followed;
for part in parts.iter().rev() {
check_ends(part, followed, count)?;
followed |= reads_on(part);
}
Ok(())
}
HirKind::Alternation(branches) => branches
.iter()
.try_for_each(|b| check_ends(b, followed, count)),
HirKind::Repetition(r) => {
let again = r.max.is_none_or(|max| max > 1) && reads_on(&r.sub);
check_ends(&r.sub, followed || again, count)
}
HirKind::Empty | HirKind::Literal(_) | HirKind::Class(_) | HirKind::Look(_) => Ok(()),
}
}
fn reads_on(hir: &Hir) -> bool {
hir.properties().maximum_len() != Some(0)
|| (!hir.properties().look_set().is_empty() && asserts(hir))
}
fn asserts(hir: &Hir) -> bool {
match hir.kind() {
HirKind::Look(_) => true,
HirKind::Capture(c) => c.index != MARK && asserts(&c.sub),
HirKind::Concat(parts) | HirKind::Alternation(parts) => parts.iter().any(asserts),
HirKind::Repetition(r) => asserts(&r.sub),
HirKind::Empty | HirKind::Literal(_) | HirKind::Class(_) => false,
}
}
fn rewrite_ends(hir: &Hir, marker: u32, keep: bool) -> Hir {
rebuild(hir, &|c, sub| {
if c.index == MARK {
java_end(marker)
} else if keep {
Hir::capture(Capture {
index: c.index,
name: c.name.clone(),
sub: Box::new(sub),
})
} else {
sub
}
})
}
fn java_end(marker: u32) -> Hir {
let terminator = Hir::alternation(vec![
Hir::literal(*b"\r\n"),
Hir::literal(*b"\r"),
Hir::concat(vec![Hir::look(Look::EndCRLF), Hir::literal(*b"\n")]),
Hir::literal("\u{85}".as_bytes()),
Hir::literal("\u{2028}".as_bytes()),
Hir::literal("\u{2029}".as_bytes()),
]);
let group = Hir::capture(Capture {
index: marker,
name: None,
sub: Box::new(terminator),
});
Hir::concat(vec![
Hir::repetition(Repetition {
min: 0,
max: Some(1),
greedy: true,
sub: Box::new(group),
}),
Hir::look(Look::End),
])
}
#[inline]
pub(super) fn final_terminator(hay: &[u8]) -> Option<usize> {
let n = hay.len();
match hay.last()? {
b'\n' if n >= 2 && hay[n - 2] == b'\r' => Some(n - 2),
b'\n' | b'\r' => Some(n - 1),
0x85 if hay[..n - 1].ends_with(&[0xC2]) => Some(n - 2),
0xA8 | 0xA9 if hay[..n - 1].ends_with(&[0xE2, 0x80]) => Some(n - 3),
_ => None,
}
}
fn fold_ast(node: &mut Ast, pattern: &str) {
match node {
Ast::Literal(lit) if lit.c.is_ascii_alphabetic() => {
let span = lit.span;
*node = Ast::class_bracketed(ClassBracketed {
span,
negated: false,
kind: ClassSet::Item(both_cases(lit)),
});
}
Ast::ClassBracketed(class) => fold_set(&mut class.kind, pattern),
Ast::ClassUnicode(class) => {
if let Some(folded) = fold_unicode(class, pattern) {
*node = Ast::class_bracketed(folded);
}
}
Ast::Repetition(r) => fold_ast(&mut r.ast, pattern),
Ast::Group(g) => fold_ast(&mut g.ast, pattern),
Ast::Alternation(a) => a.asts.iter_mut().for_each(|n| fold_ast(n, pattern)),
Ast::Concat(c) => c.asts.iter_mut().for_each(|n| fold_ast(n, pattern)),
_ => {}
}
}
fn fold_set(set: &mut ClassSet, pattern: &str) {
match set {
ClassSet::Item(item) => fold_item(item, pattern),
ClassSet::BinaryOp(op) => {
fold_set(&mut op.lhs, pattern);
fold_set(&mut op.rhs, pattern);
}
}
}
fn fold_item(item: &mut ClassSetItem, pattern: &str) {
match item {
ClassSetItem::Literal(lit) if lit.c.is_ascii_alphabetic() => {
*item = both_cases(lit);
}
ClassSetItem::Range(range) => {
let extra: Vec<ClassSetItem> =
other_case(u32::from(range.start.c), u32::from(range.end.c))
.map(|(a, z)| range_item(range.span, a, z))
.collect();
if !extra.is_empty() {
let mut items = vec![ClassSetItem::Range(range.clone())];
items.extend(extra);
*item = ClassSetItem::Union(ClassSetUnion {
span: range.span,
items,
});
}
}
ClassSetItem::Ascii(ascii) => {
if matches!(ascii.kind, ClassAsciiKind::Upper | ClassAsciiKind::Lower) {
ascii.kind = ClassAsciiKind::Alpha;
}
}
ClassSetItem::Unicode(class) => {
if let Some(folded) = fold_unicode(class, pattern) {
*item = ClassSetItem::Bracketed(Box::new(folded));
}
}
ClassSetItem::Bracketed(class) => fold_set(&mut class.kind, pattern),
ClassSetItem::Union(union) => union.items.iter_mut().for_each(|i| fold_item(i, pattern)),
_ => {}
}
}
fn both_cases(lit: &ast::Literal) -> ClassSetItem {
let mut other = lit.clone();
other.kind = LiteralKind::Verbatim;
other.c = if lit.c.is_ascii_lowercase() {
lit.c.to_ascii_uppercase()
} else {
lit.c.to_ascii_lowercase()
};
ClassSetItem::Union(ClassSetUnion {
span: lit.span,
items: vec![
ClassSetItem::Literal(lit.clone()),
ClassSetItem::Literal(other),
],
})
}
fn range_item(span: Span, a: u8, z: u8) -> ClassSetItem {
let literal = |c: u8| ast::Literal {
span,
kind: LiteralKind::Verbatim,
c: char::from(c),
};
ClassSetItem::Range(ClassSetRange {
span,
start: literal(a),
end: literal(z),
})
}
fn fold_unicode(class: &ast::ClassUnicode, pattern: &str) -> Option<ClassBracketed> {
let mut positive = class.clone();
positive.negated = false;
if matches!(
positive.kind,
ClassUnicodeKind::NamedValue {
op: ast::ClassUnicodeOpKind::NotEqual,
..
}
) {
return None;
}
let text = &pattern[class.span.start.offset..class.span.end.offset];
let parsed = regex_syntax::ParserBuilder::new()
.build()
.parse(text)
.ok()?;
let HirKind::Class(Class::Unicode(mut set)) = parsed.into_kind() else {
return None;
};
if class.negated {
set.negate();
}
let extra: Vec<ClassSetItem> = set
.iter()
.flat_map(|r| other_case(u32::from(r.start()), u32::from(r.end())))
.map(|(a, z)| range_item(class.span, a, z))
.collect();
if extra.is_empty() {
return None;
}
let mut items = vec![ClassSetItem::Unicode(positive)];
items.extend(extra);
Some(ClassBracketed {
span: class.span,
negated: class.negated,
kind: ClassSet::Item(ClassSetItem::Union(ClassSetUnion {
span: class.span,
items,
})),
})
}
fn other_case(lo: u32, hi: u32) -> impl Iterator<Item = (u8, u8)> {
[
(u32::from(b'a'), u32::from(b'z')),
(u32::from(b'A'), u32::from(b'Z')),
]
.into_iter()
.filter_map(move |(a, z)| {
let (from, to) = (lo.max(a), hi.min(z));
let from = u8::try_from(from).ok()?;
let to = u8::try_from(to).ok()?;
(from <= to).then_some((from ^ 0x20, to ^ 0x20))
})
}
pub(super) fn java_replacement(text: &[u8], group_len: usize) -> Vec<u8> {
let mut out: Vec<u8> = Vec::with_capacity(text.len() + 8);
let mut i = 0;
while i < text.len() {
match text[i] {
b'\\' => {
match text.get(i + 1) {
Some(b'$') => out.extend_from_slice(b"$$"),
Some(&c) => out.push(c),
None => out.push(b'\\'),
}
i += 2;
}
b'$' => i = java_reference(text, i + 1, group_len, &mut out),
c => {
out.push(c);
i += 1;
}
}
}
out
}
fn java_reference(text: &[u8], at: usize, group_len: usize, out: &mut Vec<u8>) -> usize {
match text.get(at) {
Some(d) if d.is_ascii_digit() => {
let mut number = usize::from(d - b'0');
let mut end = at + 1;
while let Some(next) = text.get(end).filter(|c| c.is_ascii_digit()) {
let longer = number * 10 + usize::from(next - b'0');
if longer >= group_len {
break;
}
number = longer;
end += 1;
}
out.extend_from_slice(b"${");
out.extend_from_slice(&text[at..end]);
out.push(b'}');
end
}
Some(b'{') => {
let name_len = text[at + 1..]
.iter()
.take_while(|c| c.is_ascii_alphanumeric() || **c == b'_')
.count();
let close = at + 1 + name_len;
if name_len > 0 && text.get(close) == Some(&b'}') {
out.extend_from_slice(&text[at - 1..=close]);
close + 1
} else {
out.extend_from_slice(b"$$");
at
}
}
_ => {
out.extend_from_slice(b"$$");
at
}
}
}