1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
//! Construction of [`super::SimpleMatcher`] — rule parsing, emitted-pattern deduplication,
//! and matcher compilation.
//!
//! [`SimpleMatcher::new`](super::SimpleMatcher::new) is the entry point; the helpers in this
//! module parse rules, emit transformed sub-patterns, compile the scan engines, and flatten
//! the rule metadata used during search.
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
#[cfg(feature = "dfa")]
use aho_corasick::{AhoCorasickBuilder, AhoCorasickKind, MatchKind as AhoCorasickMatchKind};
use daachorse::{
DoubleArrayAhoCorasickBuilder, MatchKind as DoubleArrayAhoCorasickMatchKind,
charwise::CharwiseDoubleArrayAhoCorasickBuilder,
};
use crate::process::process_matcher::reduce_text_process_emit;
use crate::process::{ProcessType, build_process_type_tree};
use super::SimpleMatcher;
#[cfg(feature = "dfa")]
use super::types::AC_DFA_PATTERN_THRESHOLD;
use super::types::{
AsciiMatcher, BITMASK_CAPACITY, NonAsciiMatcher, PROCESS_TYPE_TABLE_SIZE, PatternEntry,
PatternKind, RuleCold, RuleHot,
};
/// Intermediate outputs of [`SimpleMatcher::parse_rules`], bundling all data
/// that [`SimpleMatcher::new`] needs to proceed to automaton compilation.
pub(super) struct ParsedRules<'a> {
pub(super) dedup_patterns: Vec<Cow<'a, str>>,
pub(super) dedup_entries: Vec<Vec<PatternEntry>>,
pub(super) rule_hot: Vec<RuleHot>,
pub(super) rule_cold: Vec<RuleCold>,
}
impl SimpleMatcher {
/// Compiles a new [`SimpleMatcher`] from a `{ProcessType → {word_id → pattern}}` map.
///
/// Prefer [`crate::SimpleMatcherBuilder`] for a more ergonomic API.
///
/// Construction cost scales with the number of rules and the number of emitted
/// sub-pattern variants, so it is intended to happen once and then be reused.
/// The steps are:
/// 1. Parse `&`/`~` operators in each pattern into AND and NOT sub-patterns.
/// 2. For each sub-pattern, generate all normalized text variants via
/// [`reduce_text_process_emit`].
/// 3. Deduplicate all variants across all rules and process types into a single
/// pattern set.
/// 4. Partition that pattern set into ASCII and charwise buckets, then compile the
/// corresponding matcher engines.
/// 5. Build the transformation trie (`ProcessTypeBitNode` tree) for fast text
/// pre-processing at match time.
///
/// One subtle detail: sub-patterns are indexed under `process_type - ProcessType::Delete`,
/// not the full `process_type`. Each sub-pattern is transformed with all steps except
/// Delete, so it lives in the same coordinate space as the delete-transformed input text.
/// Applying Delete a second time to the sub-pattern would corrupt the match.
///
/// # Arguments
/// * `process_type_word_map` — input rule table; the value type `I` must implement
/// `AsRef<str>` so both `&str` and `Cow<str>` are accepted.
///
/// # Panics
/// Panics if one of the internal matcher builders rejects the deduplicated pattern set.
/// With normal UTF-8 input this should not happen.
pub fn new<'a, I, S1, S2>(
process_type_word_map: &'a HashMap<ProcessType, HashMap<u32, I, S1>, S2>,
) -> SimpleMatcher
where
I: AsRef<str> + 'a,
{
let pt_index_table = Self::build_pt_index_table(process_type_word_map.keys().copied());
let process_type_set: HashSet<ProcessType> =
process_type_word_map.keys().copied().collect();
let single_pt_index = if process_type_set.len() == 1 {
process_type_set
.iter()
.next()
.map(|pt| pt_index_table[pt.bits() as usize])
} else {
None
};
let parsed = Self::parse_rules(process_type_word_map, &pt_index_table);
let (ascii_matcher, non_ascii_matcher) = Self::compile_automata(&parsed.dedup_patterns);
let (ac_dedup_entries, ac_dedup_ranges) = Self::flatten_dedup_entries(parsed.dedup_entries);
let mut process_type_tree = build_process_type_tree(&process_type_set);
for node in &mut process_type_tree {
node.recompute_mask_with_index(&pt_index_table);
}
let all_simple = process_type_tree[0].children.is_empty()
&& ac_dedup_entries
.iter()
.all(|e| e.kind == PatternKind::Simple);
SimpleMatcher {
process_type_tree,
ascii_matcher,
non_ascii_matcher,
single_pt_index,
ac_dedup_entries,
ac_dedup_ranges,
rule_hot: parsed.rule_hot,
rule_cold: parsed.rule_cold,
all_simple,
}
}
/// Builds the sequential [`ProcessType`] index table.
///
/// Maps `pt.bits()` → a compact sequential index (0, 1, 2, …) for every composite
/// `ProcessType` used in `process_type_word_map`. [`ProcessType::None`] always gets
/// index 0. Unused slots contain `u8::MAX`.
fn build_pt_index_table(
process_type_keys: impl Iterator<Item = ProcessType>,
) -> [u8; PROCESS_TYPE_TABLE_SIZE] {
let mut pt_index_table = [u8::MAX; PROCESS_TYPE_TABLE_SIZE];
let mut next_pt_idx: u8 = 0;
// None first — it always occupies a slot (root node always emits it).
pt_index_table[ProcessType::None.bits() as usize] = next_pt_idx;
next_pt_idx += 1;
for pt in process_type_keys {
let bits = pt.bits() as usize;
if bits < PROCESS_TYPE_TABLE_SIZE && pt_index_table[bits] == u8::MAX {
pt_index_table[bits] = next_pt_idx;
next_pt_idx += 1;
}
}
pt_index_table
}
/// Parses all rules, deduplicates sub-patterns, and builds `PatternEntry` records.
///
/// For each word in `process_type_word_map`:
/// - splits the pattern string on `&` and `~` operators into AND and NOT sub-patterns
/// - generates all normalized text variants of each sub-pattern via [`reduce_text_process_emit`]
/// - deduplicates variants across all rules into a flat pattern list
/// - records a [`PatternEntry`] linking each variant back to its rule and sub-pattern offset
fn parse_rules<'a, I, S1, S2>(
process_type_word_map: &'a HashMap<ProcessType, HashMap<u32, I, S1>, S2>,
pt_index_table: &[u8; PROCESS_TYPE_TABLE_SIZE],
) -> ParsedRules<'a>
where
I: AsRef<str> + 'a,
{
let word_size: usize = process_type_word_map.values().map(|m| m.len()).sum();
let mut dedup_entries: Vec<Vec<PatternEntry>> = Vec::with_capacity(word_size);
let mut rule_hot: Vec<RuleHot> = Vec::with_capacity(word_size);
let mut rule_cold: Vec<RuleCold> = Vec::with_capacity(word_size);
let mut word_id_to_idx: HashMap<(ProcessType, u32), usize> =
HashMap::with_capacity(word_size);
let mut next_pattern_id: usize = 0;
let mut dedup_patterns = Vec::with_capacity(word_size);
let mut pattern_id_map: HashMap<Cow<str>, usize> = HashMap::with_capacity(word_size);
for (&process_type, simple_word_map) in process_type_word_map {
let word_process_type = process_type - ProcessType::Delete;
for (&simple_word_id, simple_word) in simple_word_map {
if simple_word.as_ref().is_empty() {
continue;
}
let mut and_splits: HashMap<&str, i32> = HashMap::new();
let mut not_splits: HashMap<&str, i32> = HashMap::new();
let mut start = 0;
let mut current_is_not = false;
let mut add_sub_word = |word: &'a str, is_not: bool| {
if word.is_empty() {
return;
}
if is_not {
let entry = not_splits.entry(word).or_insert(1);
*entry -= 1;
} else {
let entry = and_splits.entry(word).or_insert(0);
*entry += 1;
}
};
for (index, char) in simple_word.as_ref().match_indices(['&', '~']) {
add_sub_word(&simple_word.as_ref()[start..index], current_is_not);
current_is_not = char == "~";
start = index + 1;
}
add_sub_word(&simple_word.as_ref()[start..], current_is_not);
if and_splits.is_empty() && not_splits.is_empty() {
continue;
}
let and_count = and_splits.len();
let segment_counts = and_splits
.values()
.copied()
.chain(not_splits.values().copied())
.collect::<Vec<i32>>();
let use_matrix = and_count > BITMASK_CAPACITY
|| segment_counts.len() > BITMASK_CAPACITY
|| segment_counts[..and_count].iter().any(|&v| v != 1)
|| segment_counts[and_count..].iter().any(|&v| v != 0);
let has_not = and_count != segment_counts.len();
let rule_idx = if let Some(&existing_idx) =
word_id_to_idx.get(&(process_type, simple_word_id))
{
rule_hot[existing_idx] = RuleHot {
segment_counts,
and_count,
use_matrix,
has_not,
};
rule_cold[existing_idx] = RuleCold {
word_id: simple_word_id,
word: simple_word.as_ref().to_owned(),
};
existing_idx
} else {
let idx = rule_hot.len();
word_id_to_idx.insert((process_type, simple_word_id), idx);
rule_hot.push(RuleHot {
segment_counts,
and_count,
use_matrix,
has_not,
});
rule_cold.push(RuleCold {
word_id: simple_word_id,
word: simple_word.as_ref().to_owned(),
});
idx
};
let is_simple = and_count == 1 && !has_not && !use_matrix;
for (offset, &split_word) in and_splits.keys().chain(not_splits.keys()).enumerate()
{
let kind = if is_simple {
PatternKind::Simple
} else if offset < and_count {
PatternKind::And
} else {
PatternKind::Not
};
for ac_word in reduce_text_process_emit(word_process_type, split_word) {
let pt_index = pt_index_table[process_type.bits() as usize];
let Some(&existing_dedup_id) = pattern_id_map.get(ac_word.as_ref()) else {
pattern_id_map.insert(ac_word.clone(), next_pattern_id);
dedup_entries.push(vec![PatternEntry {
rule_idx: rule_idx as u32,
offset: offset as u16,
pt_index,
kind,
}]);
dedup_patterns.push(ac_word);
next_pattern_id += 1;
continue;
};
dedup_entries[existing_dedup_id].push(PatternEntry {
rule_idx: rule_idx as u32,
offset: offset as u16,
pt_index,
kind,
});
}
}
}
}
ParsedRules {
dedup_patterns,
dedup_entries,
rule_hot,
rule_cold,
}
}
/// Partitions deduplicated patterns by character content and compiles the scan engines.
///
/// ASCII-only patterns go to the ASCII matcher. The non-ASCII matcher is compiled
/// over:
/// - the non-ASCII subset when there are no ASCII patterns, or
/// - the full pattern set when both ASCII and non-ASCII patterns exist, so non-ASCII
/// text needs only one charwise scan.
///
/// With the `dfa` feature, small ASCII sets use AC DFA and larger ones use the DAAC
/// ASCII matcher.
fn compile_automata(
dedup_patterns: &[Cow<'_, str>],
) -> (Option<AsciiMatcher>, Option<NonAsciiMatcher>) {
let mut ascii_patvals: Vec<(&str, u32)> = Vec::new();
let mut non_ascii_patvals: Vec<(&str, u32)> = Vec::new();
#[cfg(feature = "dfa")]
let mut ascii_ac_to_dedup: Vec<u32> = Vec::new();
for (dedup_id, pattern) in dedup_patterns.iter().enumerate() {
if pattern.as_ref().is_ascii() {
#[cfg(feature = "dfa")]
ascii_ac_to_dedup.push(dedup_id as u32);
ascii_patvals.push((pattern.as_ref(), dedup_id as u32));
} else {
non_ascii_patvals.push((pattern.as_ref(), dedup_id as u32));
}
}
// When both ASCII and non-ASCII patterns exist, the charwise matcher
// must contain all patterns so one scan covers everything for non-ASCII text.
let full_charwise_patvals = if ascii_patvals.is_empty() || non_ascii_patvals.is_empty() {
None
} else {
Some(
dedup_patterns
.iter()
.enumerate()
.map(|(dedup_id, pattern)| (pattern.as_ref(), dedup_id as u32))
.collect::<Vec<_>>(),
)
};
let ascii_matcher = if !ascii_patvals.is_empty() {
#[cfg(feature = "dfa")]
let engine = if ascii_patvals.len() <= AC_DFA_PATTERN_THRESHOLD {
AsciiMatcher::AcDfa {
matcher: AhoCorasickBuilder::new()
.kind(Some(AhoCorasickKind::DFA))
.match_kind(AhoCorasickMatchKind::Standard)
.build(ascii_patvals.iter().map(|(p, _)| p))
.unwrap(),
to_dedup: ascii_ac_to_dedup,
}
} else {
AsciiMatcher::DaacBytewise(
DoubleArrayAhoCorasickBuilder::new()
.match_kind(DoubleArrayAhoCorasickMatchKind::Standard)
.build_with_values(ascii_patvals)
.unwrap(),
)
};
#[cfg(not(feature = "dfa"))]
let engine = AsciiMatcher::DaacBytewise(
DoubleArrayAhoCorasickBuilder::new()
.match_kind(DoubleArrayAhoCorasickMatchKind::Standard)
.build_with_values(ascii_patvals)
.unwrap(),
);
Some(engine)
} else {
None
};
let non_ascii_patvals = full_charwise_patvals
.as_deref()
.unwrap_or(non_ascii_patvals.as_slice());
let non_ascii_matcher = if !non_ascii_patvals.is_empty() {
Some(NonAsciiMatcher::DaacCharwise(
CharwiseDoubleArrayAhoCorasickBuilder::new()
.match_kind(DoubleArrayAhoCorasickMatchKind::Standard)
.build_with_values(non_ascii_patvals.iter().copied())
.unwrap(),
))
} else {
None
};
(ascii_matcher, non_ascii_matcher)
}
/// Flattens `Vec<Vec<PatternEntry>>` into one contiguous entry array plus per-pattern ranges.
///
/// Returns `(ac_dedup_entries, ac_dedup_ranges)` where `ac_dedup_ranges[i] = (start, len)`
/// maps automaton pattern index `i` to its slice of [`PatternEntry`] records.
fn flatten_dedup_entries(
dedup_entries: Vec<Vec<PatternEntry>>,
) -> (Vec<PatternEntry>, Vec<(usize, usize)>) {
let mut ac_dedup_entries = Vec::with_capacity(dedup_entries.iter().map(|v| v.len()).sum());
let mut ac_dedup_ranges = Vec::with_capacity(dedup_entries.len());
for entries in dedup_entries {
let start = ac_dedup_entries.len();
let len = entries.len();
ac_dedup_entries.extend(entries);
ac_dedup_ranges.push((start, len));
}
(ac_dedup_entries, ac_dedup_ranges)
}
}