use std::{borrow::Cow, collections::HashSet};
use fancy_regex::{Regex, escape};
use regex::RegexSet;
use serde::{Deserialize, Serialize};
use crate::{
matcher::{MatchResultTrait, TextMatcherInternal, TextMatcherTrait},
process::process_matcher::{
ProcessType, ProcessTypeBitNode, ProcessedTextSet, build_process_type_tree,
reduce_text_process_with_tree,
},
};
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum RegexMatchType {
SimilarChar,
Acrostic,
Regex,
}
#[derive(Debug, Clone)]
pub struct RegexTable<'a> {
pub table_id: u32,
pub match_id: u32,
pub process_type: ProcessType,
pub regex_match_type: RegexMatchType,
pub word_list: Vec<&'a str>,
}
#[derive(Debug, Clone)]
enum RegexType {
Standard {
regex: Regex,
},
List {
regex_list: Vec<Regex>,
word_list: Vec<String>,
},
Set {
regex_set: RegexSet,
word_list: Vec<String>,
},
}
#[derive(Debug, Clone)]
struct RegexPatternTable {
table_id: u32,
match_id: u32,
process_type: ProcessType,
regex_type: RegexType,
}
#[derive(Debug, Clone)]
pub struct RegexResult<'a> {
pub match_id: u32,
pub table_id: u32,
pub word_id: u32,
pub word: Cow<'a, str>,
}
impl MatchResultTrait<'_> for RegexResult<'_> {
fn match_id(&self) -> u32 {
self.match_id
}
fn table_id(&self) -> u32 {
self.table_id
}
fn word_id(&self) -> u32 {
self.word_id
}
fn word(&self) -> &str {
&self.word
}
fn similarity(&self) -> Option<f64> {
None
}
}
#[derive(Debug, Clone)]
pub struct RegexMatcher {
process_type_tree: Box<[ProcessTypeBitNode]>,
regex_pattern_table_list: Box<[RegexPatternTable]>,
}
impl RegexMatcher {
pub fn new(regex_table_list: &[RegexTable]) -> RegexMatcher {
let mut process_type_set = HashSet::with_capacity(regex_table_list.len());
let mut regex_pattern_table_list = Vec::with_capacity(regex_table_list.len());
for regex_table in regex_table_list {
process_type_set.insert(regex_table.process_type.bits());
let size = regex_table.word_list.len();
match regex_table.regex_match_type {
RegexMatchType::SimilarChar => {
let pattern = regex_table
.word_list
.iter()
.map(|charstr| format!("({})", escape(charstr).replace(',', "|")))
.collect::<Vec<String>>()
.join(".?");
if pattern.len() > 1024 {
eprintln!(
"SimilarChar pattern is too long ({}), potential ReDoS risk. Skipping.",
pattern.len()
);
continue;
}
regex_pattern_table_list.push(RegexPatternTable {
table_id: regex_table.table_id,
match_id: regex_table.match_id,
process_type: regex_table.process_type,
regex_type: RegexType::Standard {
regex: Regex::new(&pattern).unwrap(),
},
});
}
RegexMatchType::Acrostic => {
let mut word_list = Vec::with_capacity(size);
let mut regex_list = Vec::with_capacity(size);
let mut pattern_list = Vec::with_capacity(size);
for &word in ®ex_table.word_list {
let pattern = format!(
r"(?i)(?:^|[\s\pP]+?){}",
escape(word).replace(',', r".*?[\s\pP]+?")
);
if pattern.len() > 1024 {
eprintln!("Acrostic pattern too long for word {}, skipping.", word);
continue;
}
match Regex::new(&pattern) {
Ok(regex) => {
regex_list.push(regex);
word_list.push(word.to_owned());
pattern_list.push(pattern);
}
Err(e) => {
eprintln!("Acrostic word {word} is illegal, ignored. Error: {e}");
}
}
}
let regex_type = RegexSet::new(pattern_list).map_or(
RegexType::List {
regex_list,
word_list: word_list.clone(),
},
|regex_set| RegexType::Set {
regex_set,
word_list,
},
);
regex_pattern_table_list.push(RegexPatternTable {
table_id: regex_table.table_id,
match_id: regex_table.match_id,
process_type: regex_table.process_type,
regex_type,
});
}
RegexMatchType::Regex => {
let mut word_list = Vec::with_capacity(size);
let mut regex_list = Vec::with_capacity(size);
for &word in ®ex_table.word_list {
if word.len() > 1024 {
eprintln!("Regex pattern too long, skipping: {:.20}...", word);
continue;
}
match Regex::new(word) {
Ok(regex) => {
regex_list.push(regex);
word_list.push(word.to_owned());
}
Err(e) => {
eprintln!("Regex word {word} is illegal, ignored. Error: {e}");
}
}
}
let regex_type = RegexSet::new(&word_list).map_or(
RegexType::List {
regex_list,
word_list: word_list.clone(),
},
|regex_set| RegexType::Set {
regex_set,
word_list,
},
);
regex_pattern_table_list.push(RegexPatternTable {
table_id: regex_table.table_id,
match_id: regex_table.match_id,
process_type: regex_table.process_type,
regex_type,
});
}
};
}
let process_type_tree = build_process_type_tree(&process_type_set).into_boxed_slice();
RegexMatcher {
process_type_tree,
regex_pattern_table_list: regex_pattern_table_list.into_boxed_slice(),
}
}
}
impl<'a> TextMatcherTrait<'a, RegexResult<'a>> for RegexMatcher {
fn is_match(&'a self, text: &'a str) -> bool {
if text.is_empty() {
return false;
}
let processed_text_process_type_set =
reduce_text_process_with_tree(&self.process_type_tree, text);
self.is_match_preprocessed(&processed_text_process_type_set)
}
fn process_iter(&'a self, text: &'a str) -> impl Iterator<Item = RegexResult<'a>> + 'a {
gen move {
if text.is_empty() {
return;
}
let processed_text_process_type_set =
reduce_text_process_with_tree(&self.process_type_tree, text);
let mut table_id_index_set = HashSet::new();
for (processed_text, process_type_set) in processed_text_process_type_set {
for regex_pattern_table in self.regex_pattern_table_list.iter() {
if !process_type_set.contains(®ex_pattern_table.process_type.bits()) {
continue;
}
match ®ex_pattern_table.regex_type {
RegexType::Standard { regex } => {
if table_id_index_set.insert(regex_pattern_table.table_id as usize) {
let mut temp = Vec::new();
for caps in regex.captures_iter(&processed_text).flatten() {
temp.push(RegexResult {
match_id: regex_pattern_table.match_id,
table_id: regex_pattern_table.table_id,
word_id: 0,
word: Cow::Owned(
caps.iter()
.skip(1)
.filter_map(|m| m.map(|mc| mc.as_str()))
.collect::<String>(),
),
});
}
for r in temp {
yield r;
}
}
}
RegexType::List {
regex_list,
word_list,
} => {
for (index, regex) in regex_list.iter().enumerate() {
let table_id_index =
((regex_pattern_table.table_id as usize) << 32) | index;
if table_id_index_set.insert(table_id_index)
&& let Ok(true) = regex.is_match(&processed_text)
{
yield RegexResult {
match_id: regex_pattern_table.match_id,
table_id: regex_pattern_table.table_id,
word_id: index as u32,
word: Cow::Borrowed(&word_list[index]),
};
}
}
}
RegexType::Set {
regex_set,
word_list,
} => {
let mut temp = Vec::new();
for index in regex_set.matches(&processed_text) {
let table_id_index =
((regex_pattern_table.table_id as usize) << 32) | index;
if table_id_index_set.insert(table_id_index) {
temp.push(RegexResult {
match_id: regex_pattern_table.match_id,
table_id: regex_pattern_table.table_id,
word_id: index as u32,
word: Cow::Borrowed(&word_list[index]),
});
}
}
for r in temp {
yield r;
}
}
}
}
}
}
}
}
impl<'a> TextMatcherInternal<'a, RegexResult<'a>> for RegexMatcher {
fn is_match_preprocessed(
&'a self,
processed_text_process_type_set: &ProcessedTextSet<'a>,
) -> bool {
for (processed_text, process_type_set) in processed_text_process_type_set {
for regex_pattern_table in &self.regex_pattern_table_list {
if !process_type_set.contains(®ex_pattern_table.process_type.bits()) {
continue;
}
let is_match = match ®ex_pattern_table.regex_type {
RegexType::Standard { regex } => regex.is_match(processed_text).unwrap(),
RegexType::List { regex_list, .. } => regex_list
.iter()
.any(|regex| regex.is_match(processed_text).unwrap()),
RegexType::Set { regex_set, .. } => regex_set.is_match(processed_text),
};
if is_match {
return true;
}
}
}
false
}
fn process_preprocessed(
&'a self,
processed_text_process_type_set: &ProcessedTextSet<'a>,
) -> Vec<RegexResult<'a>> {
let mut result_list = Vec::new();
let mut table_id_index_set = HashSet::new();
for (processed_text, process_type_set) in processed_text_process_type_set {
for regex_pattern_table in &self.regex_pattern_table_list {
if !process_type_set.contains(®ex_pattern_table.process_type.bits()) {
continue;
}
match ®ex_pattern_table.regex_type {
RegexType::Standard { regex } => {
if table_id_index_set.insert(regex_pattern_table.table_id as usize) {
for caps in regex.captures_iter(processed_text).flatten() {
result_list.push(RegexResult {
match_id: regex_pattern_table.match_id,
table_id: regex_pattern_table.table_id,
word_id: 0,
word: Cow::Owned(
caps.iter()
.skip(1)
.filter_map(|m| m.map(|match_char| match_char.as_str()))
.collect::<String>(),
),
});
}
}
}
RegexType::List {
regex_list,
word_list,
} => {
for (index, regex) in regex_list.iter().enumerate() {
let table_id_index =
((regex_pattern_table.table_id as usize) << 32) | index;
if table_id_index_set.insert(table_id_index)
&& let Ok(is_match) = regex.is_match(processed_text)
&& is_match
{
result_list.push(RegexResult {
match_id: regex_pattern_table.match_id,
table_id: regex_pattern_table.table_id,
word_id: index as u32,
word: Cow::Borrowed(&word_list[index]),
});
}
}
}
RegexType::Set {
regex_set,
word_list,
} => {
for index in regex_set.matches(processed_text) {
let table_id_index =
((regex_pattern_table.table_id as usize) << 32) | index;
if table_id_index_set.insert(table_id_index) {
result_list.push(RegexResult {
match_id: regex_pattern_table.match_id,
table_id: regex_pattern_table.table_id,
word_id: index as u32,
word: Cow::Borrowed(&word_list[index]),
});
}
}
}
}
}
}
result_list
}
}