compmd 0.12.0

The CompMD processor: parses, validates and expands CompMD (Component Markdown) documents. In development.
Documentation
//! CEL's `matches` and the profile's `captures` (spec ยง8.2): a pattern in RE2's syntax, a string literal checked and
//! compiled with the expression, and matched in time linear in the text.

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;

/// The functions whose argument is a pattern, and whether the whole text must match it.
const TAKING_A_PATTERN: [(&str, Whole); 2] = [("matches", false), ("captures", true)];

/// Whether a pattern matches only the whole text.
type Whole = bool;

/// How many compiled patterns are kept; once there are more, they are compiled again as they are used.
const KEPT: usize = 64;

thread_local! {
    static COMPILED: RefCell<HashMap<(String, Whole), Rc<Regex>>> = RefCell::default();
}

/// Checks the pattern of a call of the function `name`, when it takes one: a string literal in RE2's syntax.
/// Compiling it there keeps it for the evaluation.
///
/// # Errors
///
/// A type error at the pattern when it isn't a string literal, or isn't RE2's.
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)),
        // The function's overloads take one argument, so there is one.
        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"
            ),
        )),
    }
}

/// Whether a part of the text matches the pattern.
pub(crate) fn matches(_: &dyn Functions, args: &[Value]) -> Result<Value, String> {
    Ok(Value::Bool(
        compiled(text(args, 1), false)?.is_match(text(args, 0)),
    ))
}

/// The pattern's groups when the whole text matches it, `""` for a group that took no part; none when it doesn't.
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())
    })))
}

/// The characters of the groups `captures` gives.
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()
    }))
}

/// `pattern` compiled, matching only the whole text when `whole` is.
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(&regex));
    });
    Ok(regex)
}

/// The reason the engine gives for refusing a pattern: the last line of its message, without its pattern.
fn reason(error: &regex::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;