use regex::{Captures, Regex};
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum JavaReplacementError {
#[error("character to be escaped is missing")]
MissingEscapedCharacter,
#[error("Illegal group reference: group index is missing")]
MissingGroupIndex,
#[error("Illegal group reference")]
IllegalGroupReference,
#[error("named capturing group has 0 length name")]
EmptyGroupName,
#[error("named capturing group is missing trailing '}}'")]
UnterminatedGroupName,
#[error("capturing group name {{{0}}} starts with digit character")]
GroupNameStartsWithDigit(String),
#[error("No group with name {{{0}}}")]
NoGroupNamed(String),
#[error("No group {0}")]
NoGroup(usize),
}
#[derive(Debug, Clone)]
pub struct JavaPattern {
source: String,
unanchored: Regex,
whole: Regex,
}
impl JavaPattern {
pub fn new(pattern: &str) -> Result<Self, regex::Error> {
let translated = ascii_predefined_classes(pattern);
Ok(Self {
source: pattern.to_owned(),
unanchored: Regex::new(&translated)?,
whole: Regex::new(&format!(r"\A(?:{translated})\z"))?,
})
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.source
}
#[must_use]
pub fn group_count(&self) -> usize {
self.unanchored.captures_len() - 1
}
#[must_use]
pub fn matches(&self, text: &str) -> bool {
self.whole.is_match(text)
}
pub fn replace_all(
&self,
text: &str,
replacement: &str,
) -> Result<String, JavaReplacementError> {
self.replace(text, replacement, usize::MAX)
}
pub fn replace_first(
&self,
text: &str,
replacement: &str,
) -> Result<String, JavaReplacementError> {
self.replace(text, replacement, 1)
}
fn replace(
&self,
text: &str,
replacement: &str,
limit: usize,
) -> Result<String, JavaReplacementError> {
let mut out = String::with_capacity(text.len());
let mut appended = 0;
let mut search = 0;
let mut replaced = 0;
while replaced < limit && search <= text.len() {
let Some(captures) = self.unanchored.captures_at(text, search) else {
break;
};
let whole = captures.get(0).expect("group 0 always participates");
out.push_str(&text[appended..whole.start()]);
self.expand(&captures, replacement, &mut out)?;
appended = whole.end();
replaced += 1;
search = if whole.is_empty() {
match text[whole.end()..].chars().next() {
Some(next) => whole.end() + next.len_utf8(),
None => break,
}
} else {
whole.end()
};
}
out.push_str(&text[appended..]);
Ok(out)
}
fn expand(
&self,
captures: &Captures<'_>,
replacement: &str,
out: &mut String,
) -> Result<(), JavaReplacementError> {
let group_count = self.group_count();
let mut chars = replacement.chars().peekable();
while let Some(character) = chars.next() {
match character {
'\\' => out.push(
chars
.next()
.ok_or(JavaReplacementError::MissingEscapedCharacter)?,
),
'$' => {
let group = match chars.next() {
None => return Err(JavaReplacementError::MissingGroupIndex),
Some('{') => {
let mut name = String::new();
while let Some(&next) = chars.peek()
&& next.is_ascii_alphanumeric()
{
name.push(next);
chars.next();
}
if name.is_empty() {
return Err(JavaReplacementError::EmptyGroupName);
}
if chars.next() != Some('}') {
return Err(JavaReplacementError::UnterminatedGroupName);
}
if name.starts_with(|c: char| c.is_ascii_digit()) {
return Err(JavaReplacementError::GroupNameStartsWithDigit(name));
}
self.unanchored
.capture_names()
.position(|candidate| candidate == Some(name.as_str()))
.ok_or(JavaReplacementError::NoGroupNamed(name))?
}
Some(first) => {
let mut group = first
.to_digit(10)
.ok_or(JavaReplacementError::IllegalGroupReference)?
as usize;
while let Some(digit) = chars.peek().and_then(|c| c.to_digit(10)) {
let longer = group * 10 + digit as usize;
if longer > group_count {
break;
}
group = longer;
chars.next();
}
if group > group_count {
return Err(JavaReplacementError::NoGroup(group));
}
group
}
};
if let Some(text) = captures.get(group) {
out.push_str(text.as_str());
}
}
literal => out.push(literal),
}
}
Ok(())
}
}
fn ascii_predefined_classes(pattern: &str) -> String {
let mut out = String::with_capacity(pattern.len());
let mut class_depth = 0_usize;
let mut chars = pattern.chars();
while let Some(character) = chars.next() {
match character {
'\\' => {
let Some(escaped) = chars.next() else {
out.push('\\');
break;
};
match escaped {
'd' => out.push_str("[0-9]"),
'D' => out.push_str("[^0-9]"),
'w' => out.push_str("[0-9A-Za-z_]"),
'W' => out.push_str("[^0-9A-Za-z_]"),
's' => out.push_str(r"[\t\n\x0B\f\r ]"),
'S' => out.push_str(r"[^\t\n\x0B\f\r ]"),
'b' if class_depth == 0 => out.push_str(r"(?-u:\b)"),
'B' if class_depth == 0 => out.push_str(r"(?-u:\B)"),
other if !other.is_ascii_alphanumeric() => {
out.push_str(®ex::escape(other.encode_utf8(&mut [0; 4])));
}
other => {
out.push('\\');
out.push(other);
}
}
}
'[' => {
class_depth += 1;
out.push('[');
}
']' => {
class_depth = class_depth.saturating_sub(1);
out.push(']');
}
other => out.push(other),
}
}
out
}
#[cfg(test)]
mod tests {
use assert2::check;
use super::*;
#[test]
fn replace_all_follows_java() {
let cases: &[(&str, &str, &str, Result<&str, JavaReplacementError>)] = &[
("(a)(b)", "ab", "$1_$2", Ok("a_b")),
("(a)(b)", "ab", "$1suffix", Ok("asuffix")),
("(a)(b)", "ab", "$12", Ok("a2")),
(
"(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)",
"abcdefghijk",
"$11,$111,$1a",
Ok("k,k1,aa"),
),
("(a)(b)", "ab", "$3", Err(JavaReplacementError::NoGroup(3))),
("(a)(b)", "ab", r"\$1", Ok("$1")),
("(a)", "a", r"x\\", Ok(r"x\")),
("(a)", "a", r"x\/y", Ok("x/y")),
(
"(a)",
"a",
"x$",
Err(JavaReplacementError::MissingGroupIndex),
),
(
"(a)",
"a",
r"x\",
Err(JavaReplacementError::MissingEscapedCharacter),
),
(
"(a)",
"a",
"$x",
Err(JavaReplacementError::IllegalGroupReference),
),
("(?<nm>a)(b)", "ab", "${nm}-$2", Ok("a-b")),
("(a)", "a", "${}", Err(JavaReplacementError::EmptyGroupName)),
(
"(a)",
"a",
"${nm",
Err(JavaReplacementError::UnterminatedGroupName),
),
(
"(a)",
"a",
"${1a}",
Err(JavaReplacementError::GroupNameStartsWithDigit(
"1a".to_owned(),
)),
),
(
"(a)",
"a",
"${zz}",
Err(JavaReplacementError::NoGroupNamed("zz".to_owned())),
),
("(a)|(b)", "b", "[$1]", Ok("[]")),
("a|ab", "ab", "X", Ok("Xb")),
("x*", "xx", "[$0]", Ok("[xx][]")),
("x*", "", "-", Ok("-")),
("", "ab", "-", Ok("-a-b-")),
("a*", "baaa", "X", Ok("XbXX")),
("z", "ab", "$", Ok("ab")),
];
for (pattern, text, replacement, expected) in cases {
let compiled = JavaPattern::new(pattern).expect("pattern compiles");
check!(
compiled.replace_all(text, replacement).as_deref() == expected.as_deref(),
"{pattern} over {text} with {replacement}"
);
}
}
#[test]
fn replace_first_stops_after_one_match() {
let compiled = JavaPattern::new("a").expect("pattern compiles");
check!(compiled.replace_first("banana", "o").as_deref() == Ok("bonana"));
}
#[test]
fn matches_is_a_whole_input_match() {
let cases = [
("a|ab", "ab", true),
("CN=(.*?)", "CN=alice", true),
("CN=(.*?),", "CN=alice,OU=x", false),
("ali", "alice", false),
("^DC=(a)|(b)$", "DC=b", false),
("", "", true),
(r"CN=(\d+)", "CN=12", true),
(r"CN=(\d+)", "CN=\u{663}", false),
(r"\w+", "\u{e9}", false),
(r"\W", "\u{e9}", true),
(r"\s", "\u{a0}", false),
(r"[\d\s]+", "1 2", true),
(r"a\b.", "a\u{e9}", true),
(r"\[\d\]", "[1]", true),
(r"CN=a\,b\@c\/d", "CN=a,b@c/d", true),
(r"[\,\]\-]+", ",]-", true),
(r"\\,", r"\,", true),
];
for (pattern, text, expected) in cases {
let compiled = JavaPattern::new(pattern).expect("pattern compiles");
check!(
compiled.matches(text) == expected,
"{pattern} against {text}"
);
}
}
#[test]
fn group_count_excludes_the_whole_match() {
check!(
JavaPattern::new("(a)(?:b)(?<c>c)")
.expect("compiles")
.group_count()
== 2
);
}
}