mod re2;
use super::ast::{Expr, Literal};
use super::library::text;
use super::value::Value;
use super::{Error, Functions};
use regex::{Regex, RegexBuilder};
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
const TAKING_A_PATTERN: [(&str, Whole); 2] = [("matches", false), ("captures", true)];
type Whole = bool;
const KEPT: usize = 64;
thread_local! {
static COMPILED: RefCell<HashMap<(String, Whole), Rc<Regex>>> = RefCell::default();
}
pub(super) fn check(name: &str, args: &[Expr]) -> Result<(), Error> {
let Some((_, whole)) = TAKING_A_PATTERN.iter().find(|(taking, _)| *taking == name) else {
return Ok(());
};
match args.first() {
Some(Expr::Literal(Literal::String(pattern), at)) => compiled(pattern, *whole)
.map(drop)
.map_err(|message| Error::type_error(*at, message)),
other => Err(Error::type_error(
other.map_or(0, Expr::start),
format!(
"{name}()'s pattern must be a string literal, which is checked with the expression"
),
)),
}
}
pub(crate) fn matches(_: &dyn Functions, args: &[Value]) -> Result<Value, String> {
Ok(Value::Bool(
compiled(text(args, 1), false)?.is_match(text(args, 0)),
))
}
pub(crate) fn captures(_: &dyn Functions, args: &[Value]) -> Result<Value, String> {
Ok(Value::optional(groups(args)?.map(|groups| {
Value::list(groups.into_iter().map(Value::string).collect())
})))
}
pub(crate) fn captures_size(args: &[Value]) -> usize {
groups(args).ok().flatten().map_or(0, |groups| {
groups.iter().map(|group| group.chars().count()).sum()
})
}
fn groups(args: &[Value]) -> Result<Option<Vec<&str>>, String> {
let found = compiled(text(args, 1), true)?.captures(text(args, 0));
Ok(found.map(|found| {
found
.iter()
.skip(1)
.map(|group| group.map_or("", |group| group.as_str()))
.collect()
}))
}
fn compiled(pattern: &str, whole: Whole) -> Result<Rc<Regex>, String> {
let key = (pattern.to_string(), whole);
if let Some(regex) = COMPILED.with_borrow(|kept| kept.get(&key).cloned()) {
return Ok(regex);
}
let not_re2 = |reason: String| format!("'{pattern}' isn't an RE2 pattern: {reason}");
let syntax = re2::engine_syntax(pattern).map_err(not_re2)?;
let syntax = if whole {
format!(r"\A(?:{syntax})\z")
} else {
syntax
};
let regex = RegexBuilder::new(&syntax)
.octal(true)
.build()
.map_err(|error| not_re2(reason(&error)))?;
let regex = Rc::new(regex);
COMPILED.with_borrow_mut(|kept| {
if kept.len() >= KEPT {
kept.clear();
}
kept.insert(key, Rc::clone(®ex));
});
Ok(regex)
}
fn reason(error: ®ex::Error) -> String {
let message = error.to_string();
let last = message.lines().last().unwrap_or_default();
last.trim_start_matches("error: ").to_string()
}
#[cfg(test)]
mod tests;