docextract 0.4.0

documentation extractor
Documentation
#[cfg(not(feature = "regex"))]
use super::PatternMatcher;

#[cfg(not(feature = "regex"))]
pub(crate) struct SimpleMatcher {
    pattern: String,
}

#[cfg(not(feature = "regex"))]
impl SimpleMatcher {
    pub(crate) fn new(pattern: &str) -> Self {
        SimpleMatcher {
            pattern: pattern.to_string(),
        }
    }
}

#[cfg(not(feature = "regex"))]
impl PatternMatcher for SimpleMatcher {
    fn matches(&self, target: &str) -> bool {
        glob_matches(&self.pattern, target)
    }
}

/// Hand-rolled regex-compatible pattern matcher.
///
/// Supports: `.*`, `.?`, `[...]` character classes (with `[^...]` negation),
/// `[...]*`/`[...]?` quantifiers, and `\` escapes.
///
/// Uses recursive backtracking. Not optimized for adversarial patterns —
/// tag names are short, so this is fine in practice.
#[cfg(not(feature = "regex"))]
fn glob_matches(pattern: &str, target: &str) -> bool {
    let p = pattern.as_bytes();
    let t = target.as_bytes();
    matches_impl(p, t)
}

#[cfg(not(feature = "regex"))]
fn matches_impl(p: &[u8], t: &[u8]) -> bool {
    // Base cases
    if p.is_empty() {
        return t.is_empty();
    }
    if p.len() >= 2 && p[0] == b'.' && p[1] == b'*' {
        // .* : zero or more of any character
        return matches_impl(&p[2..], t) || (!t.is_empty() && matches_impl(p, &t[1..]));
    }
    if p.len() >= 2 && p[0] == b'.' && p[1] == b'?' {
        // .? : zero or one of any character
        return matches_impl(&p[2..], t) || (!t.is_empty() && matches_impl(&p[2..], &t[1..]));
    }
    if t.is_empty() {
        // Target exhausted, check if remaining pattern is all optional
        return all_optional(p);
    }
    if p[0] == b'\\' && p.len() >= 2 {
        // Escape: next char must match literally (case-sensitive)
        return (p[1] == t[0]) && matches_impl(&p[2..], &t[1..]);
    }
    if p[0] == b'.' {
        // Literal dot (not followed by * or ?)
        return (t[0] == b'.') && matches_impl(&p[1..], &t[1..]);
    }
    if p[0] == b'[' {
        return handle_char_class(p, t);
    }
    // Literal character
    if p[0] != t[0] {
        return false;
    }
    matches_impl(&p[1..], &t[1..])
}

/// Check if the remaining pattern can match an empty target.
#[cfg(not(feature = "regex"))]
fn all_optional(p: &[u8]) -> bool {
    if p.is_empty() {
        return true;
    }
    if p.len() >= 2 && p[0] == b'.' && (p[1] == b'*' || p[1] == b'?') {
        return all_optional(&p[2..]);
    }
    if p[0] == b'[' {
        if let Some((class_end, has_quant)) = parse_char_class_info(p) {
            if !has_quant {
                // Unquantified class ([abc]) requires exactly one character
                // and can never match empty.
                return false;
            }
            return all_optional(&p[class_end + 2..]);
        }
    }
    false
}

/// Parse a character class. Returns `(class_info, position_after_closing_bracket)`.
/// For unclosed brackets, returns `None` (fallback to literal `[`).
#[cfg(not(feature = "regex"))]
fn parse_char_class_info(p: &[u8]) -> Option<(usize, bool)> {
    // p[0] == b'['. Find the closing ']'.
    let end = p.iter().position(|&b| b == b']')?;
    let after_class_base = end + 1;
    // Check for quantifier after the class
    let has_quant =
        after_class_base < p.len() && (p[after_class_base] == b'*' || p[after_class_base] == b'?');
    Some((end, has_quant))
}

/// Handle a character class match.
#[cfg(not(feature = "regex"))]
fn handle_char_class(p: &[u8], t: &[u8]) -> bool {
    let Some((class_end, has_quant)) = parse_char_class_info(p) else {
        // Unclosed bracket — fall back to literal '['
        return p[0] == t[0] && matches_impl(&p[1..], &t[1..]);
    };
    let after_quant = if has_quant {
        class_end + 2
    } else {
        class_end + 1
    };
    let quant = if has_quant {
        Some(p[class_end + 1])
    } else {
        None
    };

    let class_content = &p[1..class_end]; // bytes between [ and ]
    let negated = !class_content.is_empty() && class_content[0] == b'^';
    let effective_class = if negated {
        &class_content[1..]
    } else {
        class_content
    };

    let in_class = |&b: &u8| -> bool {
        let mut i = 0;
        while i < effective_class.len() {
            if effective_class[i] == b'\\' && i + 1 < effective_class.len() {
                // Escaped char in class — match the escaped char literally
                let ch = effective_class[i + 1];
                if b == ch {
                    return !negated;
                }
                i += 2;
                continue;
            }
            if i + 2 < effective_class.len() && effective_class[i + 1] == b'-' {
                // Range: e.g., a-z
                let start = effective_class[i];
                let end = effective_class[i + 2];
                if b >= start && b <= end {
                    return !negated;
                }
                i += 3;
                continue;
            }
            if b == effective_class[i] {
                return !negated;
            }
            i += 1;
        }
        negated
    };

    match quant {
        None => {
            // Exactly one char from the class
            !t.is_empty() && in_class(&t[0]) && matches_impl(&p[after_quant..], &t[1..])
        }
        Some(b'*') => {
            // Zero or more from the class
            matches_impl(&p[after_quant..], t)
                || (!t.is_empty() && in_class(&t[0]) && matches_impl(p, &t[1..]))
        }
        Some(b'?') => {
            // Zero or one from the class
            matches_impl(&p[after_quant..], t)
                || (!t.is_empty() && in_class(&t[0]) && matches_impl(&p[after_quant..], &t[1..]))
        }
        _ => false,
    }
}