use regex_syntax::ast::{AssertionKind, Ast, Flag};
use regex_syntax::hir::{Class, Hir, HirKind, Look};
use std::fmt::Write;
pub fn compile(name: &str, pattern: &str, insensitive: bool) -> anyhow::Result<String> {
let hir = regex_syntax::ParserBuilder::new()
.case_insensitive(insensitive)
.build()
.parse(pattern)
.map_err(|error| {
let (span, message) = match &error {
regex_syntax::Error::Parse(e) => (e.span(), e.kind().to_string()),
regex_syntax::Error::Translate(e) => (e.span(), e.kind().to_string()),
_ => return anyhow::anyhow!("{name}: invalid regex pattern"),
};
anyhow::anyhow!(
"{name}: invalid regex pattern at bytes {}..{}: {message}",
span.start.offset,
span.end.offset
)
})?;
let ast = regex_syntax::ast::parse::Parser::new().parse(pattern)?;
check(name, &ast)?;
let mut captures = Vec::new();
collect_captures(&ast, &mut captures);
let mut output = String::from(if insensitive { "(?-i)" } else { "" });
let mut next_capture = 0;
render(&hir, &mut output, &captures, &mut next_capture).map_err(|error| {
anyhow::anyhow!(
"{name}: invalid regex pattern at bytes 0..{}: {error}",
pattern.len()
)
})?;
missing_captures(&mut output, &captures, &mut next_capture, captures.len());
Ok(output)
}
fn check(name: &str, ast: &Ast) -> anyhow::Result<()> {
let flags = match ast {
Ast::Flags(flags) => Some(&flags.flags),
Ast::Group(group) => group.flags(),
_ => None,
};
let reason = if flags.is_some_and(|flags| flags.flag_state(Flag::CRLF) == Some(true)) {
Some("CRLF flag R has no supported portable translation")
} else {
match ast {
Ast::Assertion(a) if matches!(a.kind,
AssertionKind::WordBoundaryStart | AssertionKind::WordBoundaryEnd |
AssertionKind::WordBoundaryStartAngle | AssertionKind::WordBoundaryEndAngle |
AssertionKind::WordBoundaryStartHalf | AssertionKind::WordBoundaryEndHalf
) => Some("word-boundary extensions have no supported portable translation"),
Ast::Repetition(r) if matches!(*r.ast, Ast::Repetition(_)) =>
Some("stacked quantifiers are ambiguous across engines; group the repeated expression explicitly"),
_ => None,
}
};
if let Some(reason) = reason {
let span = ast.span();
anyhow::bail!(
"{name}: invalid regex pattern at bytes {}..{}: {reason}",
span.start.offset,
span.end.offset
);
}
match ast {
Ast::Group(g) => check(name, &g.ast)?,
Ast::Repetition(r) => check(name, &r.ast)?,
Ast::Concat(c) => {
for child in &c.asts {
check(name, child)?;
}
}
Ast::Alternation(a) => {
for child in &a.asts {
check(name, child)?;
}
}
_ => {}
}
Ok(())
}
fn collect_captures(ast: &Ast, captures: &mut Vec<Option<String>>) {
match ast {
Ast::Group(g) => {
if g.is_capturing() {
captures.push(match &g.kind {
regex_syntax::ast::GroupKind::CaptureName { name, .. } => {
Some(name.name.clone())
}
_ => None,
});
}
collect_captures(&g.ast, captures);
}
Ast::Repetition(r) => collect_captures(&r.ast, captures),
Ast::Concat(c) => {
for child in &c.asts {
collect_captures(child, captures);
}
}
Ast::Alternation(a) => {
for child in &a.asts {
collect_captures(child, captures);
}
}
_ => {}
}
}
fn missing_captures(out: &mut String, captures: &[Option<String>], next: &mut usize, end: usize) {
while *next < end {
out.push('(');
if let Some(name) = &captures[*next] {
out.push_str("?<");
out.push_str(name);
out.push('>');
}
out.push_str("){0}");
*next += 1;
}
}
fn render(
hir: &Hir,
out: &mut String,
captures: &[Option<String>],
next: &mut usize,
) -> anyhow::Result<()> {
match hir.kind() {
HirKind::Empty => out.push_str("(?:)"),
HirKind::Literal(literal) => {
out.push_str(®ex_syntax::escape(std::str::from_utf8(&literal.0)?));
}
HirKind::Class(class) => {
out.push('[');
match class {
Class::Unicode(class) => {
if class.ranges().is_empty() {
out.push_str("a&&b");
}
for r in class.ranges() {
write!(
out,
"\\x{{{:X}}}-\\x{{{:X}}}",
r.start() as u32,
r.end() as u32
)?;
}
}
Class::Bytes(class) => {
if class.ranges().is_empty() {
out.push_str("a&&b");
}
for r in class.ranges() {
anyhow::ensure!(
r.end().is_ascii(),
"byte matching has no supported portable translation"
);
write!(out, "\\x{{{:X}}}-\\x{{{:X}}}", r.start(), r.end())?;
}
}
}
out.push(']');
}
HirKind::Look(look) => out.push_str(match look {
Look::Start => r"\A",
Look::End => r"\z",
Look::StartLF => "(?m:^)",
Look::EndLF => "(?m:$)",
Look::WordUnicode => r"\b",
Look::WordUnicodeNegate => r"\B",
_ => anyhow::bail!(
"this word-boundary or line-ending mode has no supported portable translation"
),
}),
HirKind::Capture(capture) => {
missing_captures(out, captures, next, capture.index as usize - 1);
*next += 1;
if let Some(name) = &capture.name {
write!(out, "(?<{name}>")?;
} else {
out.push('(');
}
render(&capture.sub, out, captures, next)?;
out.push(')');
}
HirKind::Repetition(repetition) => {
out.push_str("(?:");
render(&repetition.sub, out, captures, next)?;
out.push(')');
match (repetition.min, repetition.max) {
(0, Some(1)) => out.push('?'),
(0, None) => out.push('*'),
(1, None) => out.push('+'),
(min, Some(max)) => write!(out, "{{{min},{max}}}")?,
(min, None) => write!(out, "{{{min},}}")?,
}
if !repetition.greedy {
out.push('?');
}
}
HirKind::Concat(children) | HirKind::Alternation(children) => {
out.push_str("(?:");
for (i, child) in children.iter().enumerate() {
if i > 0 && matches!(hir.kind(), HirKind::Alternation(_)) {
out.push('|');
}
render(child, out, captures, next)?;
}
out.push(')');
}
}
Ok(())
}