forge
Explore
Log in

Don't you dare go Hollow

project_note

Clone
★ 0

0 watching0 forksRust3.6 MiBc49f5e7Tahinli1 month ago2 commits

matcher.rs545 lines, 20.1 KiBHistoryRawDownload
1//! Matching a search query against note text: case and Turkish-letter folding, typo
2//! tolerance, and the search filters (match case, whole word, exact phrase, regex).
3//!
4//! Positions are char indices into the original text. Folding maps one char to one
5//! char, so they line up.
6
7use regex::{Regex, RegexBuilder};
8
9/// Most words used from one query; longer queries are cut down.
10const MAX_TERMS: usize = 16;
11/// Longest word kept from a query.
12const MAX_TERM_CHARS: usize = 64;
13/// Longest query kept as an exact phrase or a regular expression.
14const MAX_PATTERN_CHARS: usize = 256;
15
16/// The search filters. All off is the forgiving default: any case, Turkish letters as
17/// plain ones, inside words, typos allowed.
18#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
19pub struct Options {
20 /// Letters must match in case (and Turkish letters exactly).
21 pub case: bool,
22 /// Matches must be whole words.
23 pub word: bool,
24 /// The query is one phrase, matched as written. No typos.
25 pub exact: bool,
26 /// The query is a regular expression.
27 pub regex: bool,
28}
29
30impl Options {
31 /// Typos are only forgiven with every filter off; any filter asks for precision.
32 fn typos(self) -> bool {
33 !(self.case || self.word || self.exact)
34 }
35}
36
37/// A compiled query.
38#[derive(Clone)]
39pub enum Matcher {
40 Terms { terms: Vec<Vec<char>>, opts: Options },
41 Regex(Regex),
42}
43
44/// Where a word a match needs lies in a word of the text: see [`Matcher::required_words`].
45#[derive(Clone, Copy)]
46pub enum Part {
47 Whole,
48 /// The text's word ends with it.
49 End,
50 /// The text's word starts with it.
51 Start,
52 Inside,
53}
54
55impl Part {
56 /// Whether `word` of a text can hold `piece` this way.
57 pub fn holds(self, word: &[char], piece: &[char]) -> bool {
58 match self {
59 Part::Whole => word == piece,
60 Part::End => word.ends_with(piece),
61 Part::Start => word.starts_with(piece),
62 Part::Inside => word.windows(piece.len()).any(|w| w == piece),
63 }
64 }
65}
66
67/// The query is not a valid regular expression.
68#[derive(Debug)]
69pub struct InvalidRegex;
70
71/// Whether every match of `hir` is a run of ASCII letters and digits or decimal digits
72/// (so, inside one word), with assertions that hold at least as often at a word's edges.
73fn within_word(hir: &regex_syntax::hir::Hir) -> bool {
74 use regex_syntax::hir::{Class, HirKind, Look};
75 let alnum = |c: u32| char::from_u32(c).is_some_and(|c| c.is_ascii_alphanumeric());
76 match hir.kind() {
77 HirKind::Empty => true,
78 HirKind::Literal(lit) => lit.0.iter().all(|&b| alnum(b.into())),
79 HirKind::Class(Class::Unicode(class)) => {
80 class.ranges().iter().all(|r| (r.start()..=r.end()).all(|c| alnum(c.into())))
81 || class.ranges().iter().all(|r| (r.start()..=r.end()).all(|c| c.is_numeric() && c.is_alphanumeric()))
82 }
83 HirKind::Class(Class::Bytes(_)) => false,
84 HirKind::Look(look) => !matches!(look, Look::WordAsciiNegate | Look::WordUnicodeNegate),
85 HirKind::Repetition(rep) => within_word(&rep.sub),
86 HirKind::Capture(cap) => within_word(&cap.sub),
87 HirKind::Concat(hs) | HirKind::Alternation(hs) => hs.iter().all(within_word),
88 }
89}
90
91/// The words of `piece`, a run of text: those at its edges may run on in the text. None
92/// when it holds no word.
93fn piece_words(piece: &[char]) -> Option<Vec<(Vec<char>, Part)>> {
94 let piece: Vec<char> = piece.iter().map(|&c| match_fold(c)).collect();
95 let mut words = Vec::new();
96 let mut i = 0;
97 while i < piece.len() {
98 if !piece[i].is_alphanumeric() {
99 i += 1;
100 continue;
101 }
102 let start = i;
103 while i < piece.len() && piece[i].is_alphanumeric() {
104 i += 1;
105 }
106 let part = match (start == 0, i == piece.len()) {
107 (true, true) => Part::Inside,
108 (true, false) => Part::End,
109 (false, true) => Part::Start,
110 (false, false) => Part::Whole,
111 };
112 words.push((piece[start..i].to_vec(), part));
113 }
114 (!words.is_empty()).then_some(words)
115}
116
117impl Matcher {
118 /// None when the query holds nothing to search for.
119 pub fn new(query: &str, opts: Options) -> Result<Option<Self>, InvalidRegex> {
120 let query = query.trim();
121 if query.is_empty() {
122 return Ok(None);
123 }
124 if opts.regex {
125 let pattern: String = query.chars().take(MAX_PATTERN_CHARS).collect();
126 let pattern = if opts.word {
127 format!(r"\b(?:{pattern})\b")
128 } else {
129 pattern
130 };
131 return RegexBuilder::new(&pattern)
132 .case_insensitive(!opts.case)
133 .size_limit(1 << 20)
134 .build()
135 .map(|re| Some(Self::Regex(re)))
136 .map_err(|_| InvalidRegex);
137 }
138 let fold = |c: char| if opts.case { c } else { match_fold(c) };
139 let mut terms: Vec<Vec<char>> = if opts.exact {
140 let phrase = query.split_whitespace().collect::<Vec<_>>().join(" ");
141 vec![phrase.chars().take(MAX_PATTERN_CHARS).map(fold).collect()]
142 } else {
143 query
144 .split(|c: char| !c.is_alphanumeric())
145 .filter(|w| !w.is_empty())
146 .map(|w| w.chars().take(MAX_TERM_CHARS).map(fold).collect())
147 .collect()
148 };
149 terms.sort();
150 terms.dedup();
151 terms.truncate(MAX_TERMS);
152 Ok((!terms.is_empty()).then_some(Self::Terms { terms, opts }))
153 }
154
155 /// The words a text must hold to match, folded like [`fold_word`], with where each
156 /// lies in a word of the text: any one of the alternatives, each word of it. For an
157 /// exact phrase its words; for a regex those of the literals every match starts
158 /// with. None when nothing is required.
159 pub fn required_words(&self) -> Option<Vec<Vec<(Vec<char>, Part)>>> {
160 match self {
161 Self::Terms { terms, opts } if opts.exact => Some(vec![piece_words(terms.first()?)?]),
162 Self::Terms { .. } => None,
163 Self::Regex(re) => {
164 use regex_syntax::hir::literal::{ExtractKind, Extractor};
165 let hir = regex_syntax::parse(re.as_str()).ok()?;
166 let seq = Extractor::new().kind(ExtractKind::Prefix).extract(&hir);
167 seq.literals()?
168 .iter()
169 .map(|lit| {
170 // Folding only agrees with the regex's own case rules on ASCII.
171 let text = std::str::from_utf8(lit.as_bytes()).ok().filter(|t| t.is_ascii())?;
172 piece_words(&text.chars().collect::<Vec<_>>())
173 })
174 .collect()
175 }
176 }
177 }
178
179 /// For a regex whose every match lies inside one word as [`words`] splits text: the
180 /// regex to try on folded words. A text can only match if one of its words matches it.
181 pub fn word_regex(&self) -> Option<Regex> {
182 let Self::Regex(re) = self else { return None };
183 let hir = regex_syntax::parse(re.as_str()).ok()?;
184 if !within_word(&hir) {
185 return None;
186 }
187 // Folding lowercases, and maps a few letters to plain ones that are still letters.
188 RegexBuilder::new(re.as_str()).case_insensitive(true).size_limit(1 << 20).build().ok()
189 }
190
191 /// The options of a term query, None for a regex.
192 pub fn options(&self) -> Option<Options> {
193 match self {
194 Self::Terms { opts, .. } => Some(*opts),
195 Self::Regex(_) => None,
196 }
197 }
198
199 /// The default matcher for `query`, as the palette and `[[` use it.
200 pub fn simple(query: &str) -> Option<Self> {
201 Self::new(query, Options::default()).ok().flatten()
202 }
203
204 /// The cheapest match of each term in `text`, by term (None where it doesn't occur).
205 /// See [`occurrences`] for costs.
206 pub fn term_costs(&self, text: &str) -> Vec<Option<usize>> {
207 match self {
208 Self::Terms { terms, opts } => {
209 let hay = fold_text(text, *opts);
210 terms
211 .iter()
212 .map(|t| cheapest(&hay, t, *opts))
213 .collect()
214 }
215 Self::Regex(re) => vec![re.find_iter(text).any(|m| !m.is_empty()).then_some(0)],
216 }
217 }
218
219 /// The terms, when every match lies inside one word as [`words`] splits text, so
220 /// the query can be matched word by word: not for case, phrase or regex searches.
221 pub fn word_terms(&self) -> Option<&[Vec<char>]> {
222 match self {
223 Self::Terms { terms, opts } if !opts.case && !opts.exact => Some(terms),
224 _ => None,
225 }
226 }
227
228 /// The cheapest match of `term` (one of [`word_terms`](Self::word_terms)) inside
229 /// one folded `word`. The cheapest match of a term in a text is the cheapest in
230 /// any of its words.
231 pub fn word_cost(&self, term: &[char], word: &[char]) -> Option<usize> {
232 let Self::Terms { opts, .. } = self else { return None };
233 cheapest(word, term, *opts)
234 }
235
236 /// Char ranges `(start, end)` of the matches in `text`, merged and sorted.
237 pub fn ranges(&self, text: &str) -> Vec<(usize, usize)> {
238 let mut ranges: Vec<(usize, usize)> = match self {
239 Self::Terms { terms, opts } => {
240 let hay = fold_text(text, *opts);
241 terms
242 .iter()
243 .flat_map(|t| occurrences(&hay, t, *opts))
244 .map(|(s, e, _)| (s, e))
245 .collect()
246 }
247 Self::Regex(re) => {
248 // Byte offsets to char indices.
249 let (mut ranges, mut byte, mut char) = (Vec::new(), 0, 0);
250 for m in re.find_iter(text).filter(|m| !m.is_empty()) {
251 char += text[byte..m.start()].chars().count();
252 byte = m.start();
253 ranges.push((char, char + m.as_str().chars().count()));
254 }
255 ranges
256 }
257 };
258 ranges.sort_unstable();
259 let mut merged: Vec<(usize, usize)> = Vec::new();
260 for (start, end) in ranges {
261 match merged.last_mut() {
262 Some(last) if start <= last.1 => last.1 = last.1.max(end),
263 _ => merged.push((start, end)),
264 }
265 }
266 merged
267 }
268}
269
270/// Lowercase form of one char.
271fn fold(c: char) -> char {
272 if c.is_ascii() {
273 return c.to_ascii_lowercase();
274 }
275 c.to_lowercase().next().unwrap_or(c)
276}
277
278/// One char as the default search compares it: lowercase, Turkish letters as plain ones.
279fn match_fold(c: char) -> char {
280 match fold(c) {
281 'ı' => 'i',
282 'ş' => 's',
283 'ğ' => 'g',
284 'ç' => 'c',
285 'ö' => 'o',
286 'ü' => 'u',
287 c => c,
288 }
289}
290
291/// A title folded for matching: lowercase, with Turkish letters as their plain forms,
292/// so "izmir" finds "İzmir" and "isik", "ışık" and "Işık" find each other.
293pub fn title_fold(title: &str) -> String {
294 title.chars().map(match_fold).collect()
295}
296
297/// The words of `text` as [`Matcher::word_cost`] takes them: runs of letters and
298/// digits, folded like the default search folds them.
299pub fn words(text: &str) -> impl Iterator<Item = &str> {
300 text.split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty())
301}
302
303/// One word folded for [`Matcher::word_cost`].
304pub fn fold_word(word: &str) -> Box<[char]> {
305 word.chars().map(match_fold).collect()
306}
307
308fn fold_text(text: &str, opts: Options) -> Vec<char> {
309 if opts.case {
310 text.chars().collect()
311 } else {
312 text.chars().map(match_fold).collect()
313 }
314}
315
316/// Typos a term of `len` chars may have and still match: none up to 4 chars (except one
317/// swap of neighbours, see [`occurrences`]), one up to 8, two beyond. Short words with any
318/// other typo match too much else.
319fn max_typos(len: usize) -> usize {
320 match len {
321 0..=4 => 0,
322 5..=8 => 1,
323 _ => 2,
324 }
325}
326
327/// Where `term` occurs in `hay` (both already folded). Exact occurrences (whole words
328/// only with `opts.word`), or, when there are none and typos are allowed, word
329/// beginnings within [`max_typos`] edits of the term (insertions, deletions,
330/// substitutions and swapped neighbours). The `usize` is the match's cost: 0 exact at a
331/// word start, 1 exact inside a word, 1 + typos otherwise.
332fn occurrences(hay: &[char], term: &[char], opts: Options) -> Vec<(usize, usize, usize)> {
333 let mut found = Vec::new();
334 each_occurrence(hay, term, opts, |o| {
335 found.push(o);
336 true
337 });
338 found
339}
340
341/// The cheapest of [`occurrences`], without collecting them: 0 ends the search.
342fn cheapest(hay: &[char], term: &[char], opts: Options) -> Option<usize> {
343 let mut best: Option<usize> = None;
344 each_occurrence(hay, term, opts, |(_, _, cost)| {
345 best = Some(best.map_or(cost, |b| b.min(cost)));
346 cost > 0
347 });
348 best
349}
350
351/// Calls `f` with each of [`occurrences`] until it returns false.
352fn each_occurrence(hay: &[char], term: &[char], opts: Options, mut f: impl FnMut((usize, usize, usize)) -> bool) {
353 let n = term.len();
354 if n == 0 {
355 return;
356 }
357 let word_start = |i: usize| i == 0 || !hay[i - 1].is_alphanumeric();
358 let word_end = |i: usize| i == hay.len() || !hay[i].is_alphanumeric();
359 let mut any = false;
360 if n <= hay.len() {
361 for start in 0..=hay.len() - n {
362 let end = start + n;
363 if hay[start] != term[0] || hay[start..end] != term[..] {
364 continue;
365 }
366 if opts.word && !(word_start(start) && word_end(end)) {
367 continue;
368 }
369 any = true;
370 if !f((start, end, usize::from(!word_start(start)))) {
371 return;
372 }
373 }
374 }
375 if any || !opts.typos() {
376 return;
377 }
378 let d = max_typos(n);
379 // Short words only forgive swapped neighbours: "mlik" finds "milk".
380 let swap_only = d == 0;
381 if swap_only && n < 3 {
382 return;
383 }
384 let mut i = 0;
385 while i < hay.len() {
386 if !hay[i].is_alphanumeric() {
387 i += 1;
388 continue;
389 }
390 let mut end = i;
391 while end < hay.len() && hay[end].is_alphanumeric() {
392 end += 1;
393 }
394 if swap_only {
395 let word = &hay[i..end];
396 let swapped = word.len() >= n
397 && (1..n).any(|k| {
398 word[k - 1] == term[k]
399 && word[k] == term[k - 1]
400 && term[k] != term[k - 1]
401 && (0..n).all(|x| x == k || x == k - 1 || word[x] == term[x])
402 });
403 if swapped && !f((i, i + n, 2)) {
404 return;
405 }
406 } else if let Some((typos, len)) =
407 Some(&hay[i..end.min(i + n + d)]).filter(|w| shares_enough(term, w, d)).and_then(|w| prefix_distance(term, w, d))
408 && !f((i, i + len, 1 + typos))
409 {
410 return;
411 }
412 i = end;
413 }
414}
415
416/// Whether `word` could be within `max` edits of `term` (or have a prefix that is): an
417/// edit removes at most one char the two have in common, so more than `max` chars of
418/// `term` missing from `word` rule it out. Far cheaper than [`prefix_distance`], which
419/// almost every word of a search fails.
420fn shares_enough(term: &[char], word: &[char], max: usize) -> bool {
421 if word.len() > 64 {
422 return true;
423 }
424 let mut used = 0u64;
425 let mut missing = 0;
426 for &c in term {
427 match (0..word.len()).find(|&j| used & (1 << j) == 0 && word[j] == c) {
428 Some(j) => used |= 1 << j,
429 None => {
430 missing += 1;
431 if missing > max {
432 return false;
433 }
434 }
435 }
436 }
437 true
438}
439
440/// The fewest edits turning `term` into some prefix of `word`, and that prefix's length,
441/// if at most `max`. Optimal string alignment distance, so a swap counts as one edit.
442fn prefix_distance(term: &[char], word: &[char], max: usize) -> Option<(usize, usize)> {
443 let (n, m) = (term.len(), word.len());
444 if m + max < n {
445 return None;
446 }
447 // One flat table, row `i` at `i * w`.
448 let w = m + 1;
449 let mut d = vec![0usize; (n + 1) * w];
450 for i in 0..=n {
451 d[i * w] = i;
452 }
453 for j in 0..=m {
454 d[j] = j;
455 }
456 for i in 1..=n {
457 for j in 1..=m {
458 let cost = usize::from(term[i - 1] != word[j - 1]);
459 let mut v = (d[(i - 1) * w + j] + 1).min(d[i * w + j - 1] + 1).min(d[(i - 1) * w + j - 1] + cost);
460 if i > 1 && j > 1 && term[i - 1] == word[j - 2] && term[i - 2] == word[j - 1] {
461 v = v.min(d[(i - 2) * w + j - 2] + 1);
462 }
463 d[i * w + j] = v;
464 }
465 }
466 (n.saturating_sub(max).max(1)..=m)
467 .map(|j| (d[n * w + j], j))
468 .min_by_key(|&(dist, j)| (dist, j.abs_diff(n)))
469 .filter(|&(dist, _)| dist <= max)
470}
471
472#[cfg(test)]
473mod tests {
474 use super::*;
475
476 fn cost(text: &str, q: &str, opts: Options) -> Option<usize> {
477 Matcher::new(q, opts).unwrap().unwrap().term_costs(text).into_iter().sum()
478 }
479
480 #[test]
481 fn typo_tolerance() {
482 let d = Options::default();
483 assert_eq!(cost("Groceries list", "groc", d), Some(0));
484 assert_eq!(cost("Groceries list", "grcoeries", d), Some(2)); // swapped letters
485 assert_eq!(cost("Groceries list", "grocerues", d), Some(2)); // one substitution
486 assert_eq!(cost("Project kickoff", "porject kikcoff", d), Some(4));
487 assert_eq!(cost("İzmir gezisi", "izmr", d), None); // 4 chars: only a swap
488 assert_eq!(cost("Plan", "plna", d), Some(2));
489 assert_eq!(cost("Plan", "plen", d), None);
490 assert_eq!(cost("Işık listesi", "isik listsi", d), Some(2));
491 }
492
493 #[test]
494 fn filters() {
495 let case = Options { case: true, ..Default::default() };
496 let word = Options { word: true, ..Default::default() };
497 let exact = Options { exact: true, ..Default::default() };
498 let regex = Options { regex: true, ..Default::default() };
499 assert_eq!(cost("Groceries", "groceries", case), None);
500 assert_eq!(cost("Groceries", "Groceries", case), Some(0));
501 assert_eq!(cost("Groceries", "Groc", word), None);
502 assert_eq!(cost("milk, eggs", "milk", word), Some(0));
503 assert_eq!(cost("buy milk and eggs", "milk eggs", exact), None);
504 assert_eq!(cost("buy milk and eggs", "milk and", exact), None); // text not collapsed
505 assert_eq!(cost("buy milk and eggs", "MILK AND", exact), Some(0));
506 assert_eq!(cost("Groceries", "grcoeries", exact), None); // no typos
507 assert_eq!(cost("order #42", r"#\d+", regex), Some(0));
508 assert!(Matcher::new("(", regex).is_err());
509 let within = |q: &str| Matcher::new(q, regex).unwrap().unwrap().word_regex().is_some();
510 assert!(within(r"\d{9}") && within(r"\bv9[0-9]+") && within("ab|cd"));
511 assert!(!within(r"\w+") && !within("a b") && !within(r"a\B") && !within("é"));
512 let m = Matcher::new("ş", Options::default()).unwrap().unwrap();
513 assert_eq!(m.ranges("Işık"), vec![(1, 2)]);
514 }
515}
516
517#[cfg(test)]
518mod word_tests {
519 use super::*;
520
521 #[test]
522 fn word_costs_equal_text_costs() {
523 let texts = [
524 "Işık İzmir'de, milk and honey; asdadasxd foo_bar x2y alpha42 gamma-ray",
525 "Paragraph 12 with some ordinary words in it. note_12() -> usize",
526 "",
527 ];
528 let queries = ["isik", "izmr", "mlik", "dadas", "alpha42", "gama", "bar", "ordinery wrds", "12", "ray gamma x2"];
529 for opts in [Options::default(), Options { word: true, ..Options::default() }] {
530 for q in queries {
531 let m = Matcher::new(q, opts).unwrap().unwrap();
532 for text in texts {
533 let words: Vec<Box<[char]>> = words(text).map(fold_word).collect();
534 let by_word: Vec<Option<usize>> = m
535 .word_terms()
536 .unwrap()
537 .iter()
538 .map(|t| words.iter().filter_map(|w| m.word_cost(t, w)).min())
539 .collect();
540 assert_eq!(by_word, m.term_costs(text), "{q:?} in {text:?} with {opts:?}");
541 }
542 }
543 }
544 }
545}