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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
//! [`SimpleMatcher`] and [`SimpleResult`] — the public matching API.
//!
//! Prefer constructing via [`crate::SimpleMatcherBuilder`]. The type aliases
//! [`SimpleTable`] and [`SimpleTableSerde`] describe the raw rule-map format
//! accepted by [`SimpleMatcher::new`] for advanced use cases (e.g.
//! deserialization from JSON).
//!
//! # Public API Call Graph
//!
//! ```text
//! is_match(text)
//! ├─ fast path: ScanPlan::is_match() ← no transforms, simple literals
//! └─ general: walk_and_scan() ← full trie walk
//!
//! process(text) / process_into(text, buf)
//! └─ walk_and_scan()
//! └─ RuleSet::collect_matches() ← appends to Vec
//!
//! for_each_match(text, callback)
//! └─ walk_and_scan_with(collect = callback)
//! └─ RuleSet::for_each_satisfied() ← zero-allocation
//!
//! find_match(text)
//! └─ for_each_match(text, |r| first = Some(r))
//!
//! batch_*: maybe_par_iter! wrapping the above
//! ```
//!
//! # Module Layout
//!
//! The implementation is split across private child modules:
//!
//! - `build` — [`SimpleMatcher::new`] and rule parsing / deduplication.
//! - `error` — [`MatcherError`] enum for construction failures.
//! - `scan` — Aho-Corasick automaton compilation (bytewise and charwise
//! engines) and density-based dispatch.
//! - `pattern` — Deduplicated pattern storage, entry types, and dispatch.
//! - `rule` — Rule metadata (`Rule`/`RuleSet`) and state machine.
//! - `search` — Hot-path scan loops and rule evaluation.
//! - `state` — Thread-local scan state (`SimpleMatchState`, `ScanContext`,
//! `WalkConfig`).
//! - `tree` — Process-type trie construction for transform prefix sharing.
use ;
use *;
/// Dispatches to `par_iter()` when the `rayon` feature is active, otherwise
/// `iter()`.
pub
pub use MatcherError;
use RuleSet;
pub use ;
use ScanPlan;
use ProcessTypeBitNode;
/// A single match returned by [`SimpleMatcher::process`] or
/// [`SimpleMatcher::process_into`].
///
/// The lifetime `'a` is tied to the [`SimpleMatcher`] that produced this
/// result. The `word` field borrows directly from the matcher's internal rule
/// storage, so no allocation occurs when collecting results.
///
/// # Examples
///
/// ```rust
/// use matcher_rs::{ProcessType, SimpleMatcherBuilder};
///
/// let matcher = SimpleMatcherBuilder::new()
/// .add_word(ProcessType::None, 42, "hello")
/// .add_word(ProcessType::None, 7, "world")
/// .build()
/// .unwrap();
///
/// let results = matcher.process("hello world");
/// assert_eq!(results.len(), 2);
///
/// // Each result carries the caller-assigned word_id and the original pattern string.
/// let ids: Vec<u32> = results.iter().map(|r| r.word_id).collect();
/// assert!(ids.contains(&42));
/// assert!(ids.contains(&7));
///
/// // word is a Cow that borrows from the matcher — no extra allocation.
/// assert!(results.iter().any(|r| r.word == "hello"));
/// ```
/// Multi-pattern matcher with logical operators and text normalization.
///
/// Prefer constructing via [`crate::SimpleMatcherBuilder`] rather than calling
/// [`new`](Self::new) directly.
///
/// # Pattern Syntax
///
/// Each pattern string may contain two special operators:
///
/// | Operator | Meaning |
/// |----------|---------|
/// | `&` | All adjacent sub-patterns must appear (order-independent AND) |
/// | `~` | The following sub-pattern must be **absent** (NOT) |
///
/// ```text
/// "apple&pie" -- fires only when both "apple" and "pie" appear
/// "banana~peel" -- fires when "banana" appears but "peel" does not
/// "a&b~c" -- fires when both "a" and "b" appear and "c" does not
/// "a&a~b~b" -- fires when "a" appears twice and "b" appears fewer than twice
/// ```
///
/// # Two-Pass Matching
///
/// **Pass 1 — Transform and Scan**: The input text is transformed through the
/// configured [`ProcessType`](crate::ProcessType) pipelines, producing the
/// distinct text variants needed for this matcher. Each variant is scanned by
/// the bytewise or charwise engine, selected by SIMD density scan (density
/// ≥ 0.55 → bytewise, < 0.55 → charwise; higher density = more ASCII).
/// Hits update per-rule state;
/// simple rules stay on a bitmask fast path, while more complex rules fall
/// back to a per-rule counter matrix.
///
/// **Pass 2 — Evaluate**: Touched rules are checked: a rule fires if every AND
/// sub-pattern was satisfied in at least one text variant and no NOT
/// sub-pattern was triggered in any variant.
///
/// Composite process types can match across variants. For example,
/// `ProcessType::None | ProcessType::Romanize` lets one sub-pattern match the
/// raw text and another match the Romanize-transformed variant during the same
/// search. NOT segments are global across those variants: if a veto pattern
/// appears in any variant, the rule fails.
///
/// # Thread Safety
///
/// `SimpleMatcher` is [`Send`] + [`Sync`]. All mutable scan state is stored in
/// thread-local `SimpleMatchState` instances (one per thread), so concurrent
/// calls from different threads are fully independent with no contention or
/// locking. The matcher itself is immutable after construction.
///
/// # Performance
///
/// - **O(N) text scan**: All unique sub-patterns across all rules are
/// deduplicated into a single Aho-Corasick automaton, so scan time scales
/// with text length, not rule count.
/// - **O(1) state reset**: Generation-based sparse-set avoids clearing per-rule
/// state between calls (only touched rules are cleaned up).
/// - **Bitmask fast path**: Rules with ≤64 segments use a `u64` bitmask instead
/// of the full matrix, keeping the inner loop branch-free.
/// - **DAG reuse**: The transformation pipeline is structured as a trie so
/// intermediate results (e.g., Delete output) are computed once even when
/// multiple composite `ProcessType`s share a prefix.
///
/// # Examples
///
/// ```rust
/// use matcher_rs::{ProcessType, SimpleMatcherBuilder};
///
/// let matcher = SimpleMatcherBuilder::new()
/// .add_word(ProcessType::None, 1, "apple&pie")
/// .add_word(ProcessType::None, 2, "banana~peel")
/// .build()
/// .unwrap();
///
/// assert!(matcher.is_match("I like apple and pie"));
/// assert!(!matcher.is_match("I like banana peel"));
///
/// let results = matcher.process("apple and pie");
/// assert_eq!(results.len(), 1);
/// assert_eq!(results[0].word_id, 1);
/// assert_eq!(results[0].word, "apple&pie");
/// ```
/// Formats as `SimpleMatcher { rule_count: …, .. }`.
///
/// Internal engine details (automaton sizes, pattern indices) are omitted to
/// keep the output concise and stable across versions.
/// Public query and result APIs for the compiled matcher.