use fancy_regex::Regex;
pub fn compile(pattern: &str) -> Result<Regex, String> {
let translated = translate(pattern)?;
Regex::new(&translated).map_err(|e| one_line(&e.to_string()))
}
fn one_line(message: &str) -> String {
message.split_whitespace().collect::<Vec<_>>().join(" ")
}
fn translate(pattern: &str) -> Result<String, String> {
let chars: Vec<char> = pattern.chars().collect();
let mut out = String::with_capacity(pattern.len());
let mut i = 0;
let mut in_class = false;
while i < chars.len() {
match chars[i] {
'\\' => {
let Some(&next) = chars.get(i + 1) else {
return Err(format!("trailing backslash at position {i}"));
};
if next == 'p' || next == 'P' {
return Err(format!("unsupported escape \\{next} at position {i}"));
}
if next == 'Z' && !in_class {
out.push_str("\\z");
} else {
out.push('\\');
out.push(next);
}
i += 2;
}
'[' if !in_class => {
in_class = true;
out.push('[');
i += 1;
if chars.get(i) == Some(&'^') {
out.push('^');
i += 1;
}
if chars.get(i) == Some(&']') {
out.push_str("\\]");
i += 1;
}
}
']' if in_class => {
in_class = false;
out.push(']');
i += 1;
}
'{' if !in_class => match repetition_at(&chars, i) {
Some(rep) => {
if let (Some(min), Some(max)) = (rep.min, rep.max) {
if min > max {
return Err(format!("repetition range is inverted at position {i}"));
}
}
if rep.min.is_none() {
out.push_str("{0,");
out.push_str(&rep.max.unwrap_or_default().to_string());
out.push('}');
} else {
out.extend(chars[i..rep.end].iter());
}
i = rep.end;
}
None => {
out.push_str("\\{");
i += 1;
}
},
c => {
out.push(c);
i += 1;
}
}
}
Ok(out)
}
struct Repetition {
end: usize,
min: Option<u64>,
max: Option<u64>,
}
fn repetition_at(chars: &[char], start: usize) -> Option<Repetition> {
let mut i = start + 1;
let min_digits = digits_at(chars, &mut i);
let comma = chars.get(i) == Some(&',');
if comma {
i += 1;
}
let max_digits = if comma {
digits_at(chars, &mut i)
} else {
None
};
if chars.get(i) != Some(&'}') {
return None;
}
if min_digits.is_none() && max_digits.is_none() {
return None;
}
Some(Repetition {
end: i + 1,
min: min_digits,
max: max_digits,
})
}
fn digits_at(chars: &[char], i: &mut usize) -> Option<u64> {
let start = *i;
while chars.get(*i).is_some_and(|c| c.is_ascii_digit()) {
*i += 1;
}
if *i == start {
return None;
}
chars[start..*i].iter().collect::<String>().parse().ok()
}
#[cfg(test)]
mod tests {
use super::*;
fn is_match(pattern: &str, haystack: &str) -> bool {
compile(pattern)
.expect("pattern should compile")
.is_match(haystack)
.expect("match should not error")
}
#[test]
fn translates_the_end_of_string_anchor() {
assert_eq!(translate("x\\Z").unwrap(), "x\\z");
assert!(!is_match("x\\Z", "x\n"));
assert!(is_match("x\\Z", "x"));
}
#[test]
fn leaves_other_escapes_alone() {
assert_eq!(translate("\\A\\w+\\d\\\\").unwrap(), "\\A\\w+\\d\\\\");
}
#[test]
fn rejects_unicode_property_escapes() {
assert_eq!(
compile("\\p{L}").unwrap_err(),
"unsupported escape \\p at position 0"
);
assert_eq!(
compile("ab\\P{L}").unwrap_err(),
"unsupported escape \\P at position 2"
);
}
#[test]
fn a_doubled_backslash_does_not_swallow_the_next_escape() {
assert!(compile("\\\\p").is_ok());
assert!(compile("\\\\\\p{L}").is_err());
}
#[test]
fn rejects_an_inverted_repetition_range() {
assert_eq!(
compile("a{2,1}").unwrap_err(),
"repetition range is inverted at position 1"
);
assert!(compile("a{1,2}").is_ok());
assert!(compile("a{2,}").is_ok());
assert!(compile("a{2}").is_ok());
}
#[test]
fn an_open_ended_lower_bound_means_zero() {
assert_eq!(translate("a{,3}").unwrap(), "a{0,3}");
assert!(is_match("^a{,3}$", "aa"));
}
#[test]
fn a_brace_that_is_not_a_quantifier_is_a_literal() {
assert!(is_match("a{", "a{"));
assert!(is_match("a{}", "a{}"));
assert!(is_match("a{,}", "a{,}"));
}
#[test]
fn braces_inside_a_character_class_are_literal() {
assert!(is_match("[{2,1}]", "{"));
assert!(is_match("[{2,1}]", ","));
}
#[test]
fn a_leading_close_bracket_is_a_class_member() {
assert!(is_match("[]]", "]"));
assert!(is_match("[^]]", "a"));
assert!(!is_match("[^]]", "]"));
}
#[test]
fn rejects_a_property_escape_inside_a_class() {
assert!(compile("[\\p{L}]").is_err());
}
#[test]
fn reports_a_trailing_backslash_rather_than_dropping_it() {
assert_eq!(
compile("ab\\").unwrap_err(),
"trailing backslash at position 2"
);
}
#[test]
fn engine_errors_stay_on_one_line() {
let err = compile("[bad").unwrap_err();
assert!(!err.contains('\n'), "{err:?}");
}
#[test]
fn counts_positions_in_characters_not_bytes() {
assert_eq!(
compile("é\\p{L}").unwrap_err(),
"unsupported escape \\p at position 1"
);
}
}