compmd 0.13.0

The CompMD processor: parses, validates and expands CompMD (Component Markdown) documents. In development.
Documentation
//! RE2's syntax (spec §8.2) in the engine's: a pattern as RE2 reads it, written for the `regex` crate, which runs in
//! time linear in the text as RE2 does. The two read a few things differently, which are written out here: RE2's
//! `\d`, `\s`, `\w` and `\b` are ASCII; `\Q…\E` quotes; `\p{^…}` negates; a `{` that starts no repetition is a
//! character; and in a class, `[`, `&`, `~` and a `-` that makes no range are characters. What only the engine reads
//! (`\u0041`, `\<`, `(?x)`, `\p{sc=Greek}`, `a**`) isn't RE2's, and is refused.

use regex_syntax::ast::{
    self, Assertion, AssertionKind, Ast, ClassPerl, ClassPerlKind, ClassSet, ClassSetItem,
    ClassUnicode, ClassUnicodeKind, Flag, Flags, FlagsItemKind, GroupKind, HexLiteralKind, Literal,
    LiteralKind, RepetitionKind, RepetitionRange,
};
use std::ops::Range;

/// The most a counted repetition repeats, as in RE2.
const MOST_REPEATED: u32 = 1000;

/// `pattern`, in RE2's syntax, written in the engine's.
///
/// # Errors
///
/// Why `pattern` isn't an RE2 pattern: what is malformed, or what only the engine reads.
pub(super) fn engine_syntax(pattern: &str) -> Result<String, String> {
    let written = escaped(pattern);
    let ast = ast::parse::ParserBuilder::new()
        .octal(true)
        .build()
        .parse(&written)
        .map_err(|error| error.kind().to_string())?;
    let mut edits = Vec::new();
    walk(&ast, &written, &mut edits)?;
    Ok(edited(&written, edits))
}

/// `pattern` with what RE2 reads as characters, and the engine doesn't, escaped, and `\p{^…}` written `\P{…}`.
fn escaped(pattern: &str) -> String {
    let chars: Vec<char> = pattern.chars().collect();
    let mut out = String::with_capacity(pattern.len());
    let mut i = 0;
    while let Some(&c) = chars.get(i) {
        i = match c {
            '\\' if chars.get(i + 1) == Some(&'Q') => quoted(&chars, i + 2, &mut out),
            '\\' => escape(&chars, i, &mut out),
            '[' => class(&chars, i, &mut out),
            '{' => {
                let length = repetition(&chars[i..]);
                if length == 0 {
                    out.push_str(r"\{");
                    i + 1
                } else {
                    out.extend(&chars[i..i + length]);
                    i + length
                }
            }
            '}' => {
                out.push_str(r"\}");
                i + 1
            }
            c => {
                out.push(c);
                i + 1
            }
        };
    }
    out
}

/// Writes the text quoted from `chars[start]` up to `\E`, or to the end, as characters; gives where it ends.
fn quoted(chars: &[char], start: usize, out: &mut String) -> usize {
    let end = (start..chars.len())
        .find(|&i| chars[i] == '\\' && chars.get(i + 1) == Some(&'E'))
        .unwrap_or(chars.len());
    let text: String = chars[start..end].iter().collect();
    out.push_str(&regex_syntax::escape(&text));
    (end + 2).min(chars.len())
}

/// Writes the escape at `chars[i]`, a `\`; gives where it ends. A braced one, `\p{Greek}` or `\x{41}`, is written
/// whole.
fn escape(chars: &[char], i: usize, out: &mut String) -> usize {
    match (chars.get(i + 1), chars.get(i + 2)) {
        (Some(&letter @ ('p' | 'P' | 'x')), Some('{')) => {
            let end = (i + 3..chars.len())
                .find(|&end| chars[end] == '}')
                .map_or(chars.len(), |end| end + 1);
            let negated = letter != 'x' && chars.get(i + 3) == Some(&'^');
            out.push('\\');
            out.push(match letter {
                'p' if negated => 'P',
                'P' if negated => 'p',
                letter => letter,
            });
            out.push('{');
            out.extend(&chars[i + 3 + usize::from(negated)..end]);
            end
        }
        (Some(&c), _) => {
            out.push('\\');
            out.push(c);
            i + 2
        }
        (None, _) => {
            out.push('\\');
            i + 1
        }
    }
}

/// The length of the counted repetition `{n}`, `{n,}` or `{n,m}` at the start of `chars`, or 0 when it starts none.
fn repetition(chars: &[char]) -> usize {
    let digits = |from: usize| {
        chars[from.min(chars.len())..]
            .iter()
            .take_while(|c| c.is_ascii_digit())
            .count()
    };
    let least = digits(1);
    if least == 0 {
        return 0;
    }
    let mut end = 1 + least;
    if chars.get(end) == Some(&',') {
        end += 1 + digits(end + 1);
    }
    if chars.get(end) == Some(&'}') {
        end + 1
    } else {
        0
    }
}

/// Writes the class at `chars[start]`, a `[`, each of its characters as RE2 reads it; gives where it ends.
fn class(chars: &[char], start: usize, out: &mut String) -> usize {
    out.push('[');
    let mut i = start + 1;
    if chars.get(i) == Some(&'^') {
        out.push('^');
        i += 1;
    }
    let mut first = true;
    while let Some(&c) = chars.get(i) {
        if c == ']' && !first {
            out.push(']');
            return i + 1;
        }
        first = false;
        let (end, single) = class_item(chars, i, out);
        i = end;
        // A `-` between two characters makes a range; anywhere else it is a character.
        if single && chars.get(i) == Some(&'-') && chars.get(i + 1).is_some_and(|&c| c != ']') {
            out.push('-');
            i = class_item(chars, i + 1, out).0;
        }
    }
    i
}

/// Writes the item of a class at `chars[i]`: a character, an escape or a `[:name:]`. Gives where it ends, and whether
/// it is a single character, which can start a range.
fn class_item(chars: &[char], i: usize, out: &mut String) -> (usize, bool) {
    match chars[i] {
        '[' if chars.get(i + 1) == Some(&':') => {
            let end = (i + 2..chars.len().saturating_sub(1))
                .find(|&end| chars[end] == ':' && chars[end + 1] == ']');
            if let Some(end) = end {
                out.extend(&chars[i..end + 2]);
                return (end + 2, false);
            }
            out.push_str(r"\[");
            (i + 1, true)
        }
        '\\' => {
            let end = escape(chars, i, out);
            let single = !matches!(
                chars.get(i + 1),
                Some('d' | 'D' | 's' | 'S' | 'w' | 'W' | 'p' | 'P')
            );
            (end, single)
        }
        c @ ('[' | '&' | '~' | '-') => {
            out.push('\\');
            out.push(c);
            (i + 1, true)
        }
        c => {
            out.push(c);
            (i + 1, true)
        }
    }
}

/// A part of the written pattern to write otherwise.
type Edit = (Range<usize>, String);

/// Checks that `ast`, read from `written`, is RE2's, and gathers what to write otherwise for the engine to read it as
/// RE2 does.
fn walk(ast: &Ast, written: &str, edits: &mut Vec<Edit>) -> Result<(), String> {
    match ast {
        Ast::Empty(_) | Ast::Dot(_) => Ok(()),
        Ast::Literal(literal) => literal_is_re2s(literal, written),
        Ast::ClassUnicode(class) => unicode_is_re2s(class, written),
        Ast::Flags(set) => flags(&set.flags, written),
        Ast::Assertion(assertion) => {
            let boundary = assertion_written(assertion, written)?;
            if let Some(boundary) = boundary {
                edits.push((span(&assertion.span), boundary));
            }
            Ok(())
        }
        Ast::ClassPerl(perl) => {
            edits.push((span(&perl.span), format!("[{}]", perl_written(perl))));
            Ok(())
        }
        Ast::ClassBracketed(class) => class_set(&class.kind, written, edits),
        Ast::Repetition(repetition) => {
            if matches!(*repetition.ast, Ast::Repetition(_)) {
                return Err(format!(
                    "'{}' repeats a repetition",
                    &written[span(&repetition.span)]
                ));
            }
            if let RepetitionKind::Range(range) = &repetition.op.kind {
                let (RepetitionRange::Exactly(most)
                | RepetitionRange::AtLeast(most)
                | RepetitionRange::Bounded(_, most)) = *range;
                if most > MOST_REPEATED {
                    return Err(format!(
                        "'{}' repeats more than {MOST_REPEATED} times",
                        &written[span(&repetition.op.span)]
                    ));
                }
            }
            walk(&repetition.ast, written, edits)
        }
        Ast::Group(group) => {
            if let GroupKind::NonCapturing(group_flags) = &group.kind {
                flags(group_flags, written)?;
            }
            walk(&group.ast, written, edits)
        }
        Ast::Alternation(alternation) => all(&alternation.asts, written, edits),
        Ast::Concat(concat) => all(&concat.asts, written, edits),
    }
}

fn all(asts: &[Ast], written: &str, edits: &mut Vec<Edit>) -> Result<(), String> {
    asts.iter().try_for_each(|ast| walk(ast, written, edits))
}

fn class_set(set: &ClassSet, written: &str, edits: &mut Vec<Edit>) -> Result<(), String> {
    // `&&`, `--` and `~~` are escaped, so a class is never an operation on classes.
    let ClassSet::Item(item) = set else {
        return Ok(());
    };
    class_set_item(item, written, edits)
}

fn class_set_item(item: &ClassSetItem, written: &str, edits: &mut Vec<Edit>) -> Result<(), String> {
    match item {
        ClassSetItem::Literal(literal) => literal_is_re2s(literal, written),
        ClassSetItem::Range(range) => {
            literal_is_re2s(&range.start, written)?;
            literal_is_re2s(&range.end, written)
        }
        ClassSetItem::Unicode(class) => unicode_is_re2s(class, written),
        ClassSetItem::Perl(perl) => {
            let ranges = perl_written(perl);
            let written = if perl.negated {
                format!("[{ranges}]")
            } else {
                ranges.to_string()
            };
            edits.push((span(&perl.span), written));
            Ok(())
        }
        ClassSetItem::Bracketed(class) => class_set(&class.kind, written, edits),
        ClassSetItem::Union(union) => union
            .items
            .iter()
            .try_for_each(|item| class_set_item(item, written, edits)),
        ClassSetItem::Empty(_) | ClassSetItem::Ascii(_) => Ok(()),
    }
}

/// RE2's ASCII class for `\d`, `\s` or `\w`, or its negation, as the inside of a class.
fn perl_written(perl: &ClassPerl) -> &'static str {
    match (&perl.kind, perl.negated) {
        (ClassPerlKind::Digit, false) => "0-9",
        (ClassPerlKind::Digit, true) => "^0-9",
        (ClassPerlKind::Space, false) => r"\t\n\f\r ",
        (ClassPerlKind::Space, true) => r"^\t\n\f\r ",
        (ClassPerlKind::Word, false) => "0-9A-Za-z_",
        (ClassPerlKind::Word, true) => "^0-9A-Za-z_",
    }
}

/// Checks an assertion, and gives RE2's ASCII word boundary for `\b` and `\B`.
fn assertion_written(assertion: &Assertion, written: &str) -> Result<Option<String>, String> {
    match assertion.kind {
        AssertionKind::WordBoundary => Ok(Some(r"(?-u:\b)".to_string())),
        AssertionKind::NotWordBoundary => Ok(Some(r"(?-u:\B)".to_string())),
        AssertionKind::StartLine
        | AssertionKind::EndLine
        | AssertionKind::StartText
        | AssertionKind::EndText => Ok(None),
        _ => Err(not_re2s(&written[span(&assertion.span)])),
    }
}

fn flags(flags: &Flags, written: &str) -> Result<(), String> {
    flags.items.iter().try_for_each(|item| match item.kind {
        FlagsItemKind::Flag(Flag::Unicode | Flag::IgnoreWhitespace | Flag::CRLF) => Err(format!(
            "the flag '{}' isn't RE2's",
            &written[span(&item.span)]
        )),
        _ => Ok(()),
    })
}

fn literal_is_re2s(literal: &Literal, written: &str) -> Result<(), String> {
    let text = &written[span(&literal.span)];
    match literal.kind {
        LiteralKind::HexFixed(HexLiteralKind::UnicodeShort | HexLiteralKind::UnicodeLong)
        | LiteralKind::HexBrace(HexLiteralKind::UnicodeShort | HexLiteralKind::UnicodeLong) => {
            Err(not_re2s(text))
        }
        // `\1` to `\7` alone would be a backreference.
        LiteralKind::Octal if text.len() == 2 && literal.c != '\0' => Err(format!(
            "'{text}' is a backreference, which RE2 doesn't have"
        )),
        _ => Ok(()),
    }
}

/// Checks a `\p` class: RE2's are a general category by its abbreviation (`\pL`, `\p{Lu}`), a script (`\p{Greek}`) or
/// `\p{Any}`.
fn unicode_is_re2s(class: &ClassUnicode, written: &str) -> Result<(), String> {
    let name = match &class.kind {
        ClassUnicodeKind::OneLetter(letter) => letter.to_string(),
        ClassUnicodeKind::Named(name) => name.clone(),
        ClassUnicodeKind::NamedValue { .. } => {
            return Err(not_re2s(&written[span(&class.span)]));
        }
    };
    let is = |property: &str| {
        regex_syntax::Parser::new()
            .parse(&format!(r"\p{{{property}={name}}}"))
            .is_ok()
    };
    let category = name.len() <= 2 && is_capitalized(&name) && is("gc");
    let script = name.split('_').all(is_capitalized) && is("sc");
    if name == "Any" || category || script {
        Ok(())
    } else {
        Err(format!(
            "'{}' is neither a general category, written as its abbreviation, nor a script",
            &written[span(&class.span)]
        ))
    }
}

/// Whether `word` is a capital letter followed by letters, as a script's name and a category's abbreviation are.
fn is_capitalized(word: &str) -> bool {
    let mut chars = word.chars();
    chars.next().is_some_and(|c| c.is_ascii_uppercase()) && chars.all(|c| c.is_ascii_alphabetic())
}

fn not_re2s(text: &str) -> String {
    format!("'{text}' isn't RE2's")
}

fn span(span: &ast::Span) -> Range<usize> {
    span.start.offset..span.end.offset
}

/// `written` with each edit made.
fn edited(written: &str, mut edits: Vec<Edit>) -> String {
    edits.sort_by_key(|(range, _)| range.start);
    let mut out = String::with_capacity(written.len());
    let mut from = 0;
    for (range, text) in edits {
        out.push_str(&written[from..range.start]);
        out.push_str(&text);
        from = range.end;
    }
    out.push_str(&written[from..]);
    out
}

#[cfg(test)]
mod tests;