Debian Codegraph @

helix-view/src/handlers/word_index.rs

raw symbols SCIP
1 //! Indexing of words from open buffers.
2 //!
3 //! This provides an eventually consistent set of words used in any open buffers. This set is
4 //! later used for lexical completion.
5
6 use std::{borrow::Cow, iter, sync::Arc, time::Duration};
7
8 use foldhash::HashMap;
9 use helix_core::{
10 chars::char_is_word, diff::compare_ropes, fuzzy::fuzzy_match, ChangeSet, Rope, RopeSlice,
11 };
12 use helix_event::{register_hook, AsyncHook, TaskController, TaskHandle};
13 use helix_stdx::rope::RopeSliceExt as _;
14 use parking_lot::RwLock;
15 use tokio::{sync::mpsc, time::Instant};
16
17 use crate::{
18 events::{ConfigDidChange, DocumentDidChange, DocumentDidClose, DocumentDidOpen},
19 DocumentId,
20 };
21
22 use super::Handlers;
23
24 #[derive(Debug)]
25 struct Change {
26 old_text: Rope,
27 text: Rope,
28 changes: ChangeSet,
29 /// Whether `changes` is stale and must be recomputed from `old_text`/`text` before use.
30 ///
31 /// Set when this change is the result of coalescing several observed changes (see
32 /// [`Hook::handle_event`]). The observed changesets cannot be reliably chained, so the
33 /// coalesced changeset is recomputed once, lazily, at [`Hook::finish_debounce`].
34 dirty: bool,
35 }
36
37 #[derive(Debug)]
38 enum Event {
39 Insert(Rope),
40 Update(DocumentId, Change),
41 Delete(DocumentId, Rope),
42 /// Clear the entire word index.
43 /// This is used to clear memory when the feature is turned off.
44 Clear,
45 }
46
47 /// Sends an event to the coordinator task (lossy).
48 ///
49 /// The coordinator stops when its [`Handler`] is dropped. A closed channel means that index is no
50 /// longer in use, so dropping the event is harmless.
51 fn send(coordinator: &mpsc::UnboundedSender<Event>, event: Event) {
52 let _ = coordinator.send(event);
53 }
54
55 #[derive(Debug)]
56 pub struct Handler {
57 pub(super) index: WordIndex,
58 /// A sender into an async hook which debounces updates to the index.
59 hook: mpsc::Sender<Event>,
60 /// A sender to a tokio task which coordinates the indexing of documents.
61 ///
62 /// See [WordIndex::run]. A supervisor-like task is in charge of spawning tasks to update the
63 /// index. This ensures that consecutive edits to a document trigger the correct order of
64 /// insertions and deletions into the word set.
65 coordinator: mpsc::UnboundedSender<Event>,
66 /// Cancels in-flight indexing when the handler is dropped.
67 ///
68 /// Indexing a large document runs on a blocking task which cannot be preempted. Without this,
69 /// dropping the tokio runtime on shutdown would block until that task finishes, keeping the
70 /// process alive and unresponsive. The indexing task holds a [TaskHandle] from this
71 /// controller and checks it periodically.
72 _cancel: TaskController,
73 }
74
75 impl Handler {
76 pub fn spawn() -> Self {
77 let index = WordIndex::default();
78 let (tx, rx) = mpsc::unbounded_channel();
79 let mut cancel = TaskController::new();
80 tokio::spawn(index.clone().run(rx, cancel.restart()));
81 Self {
82 hook: Hook {
83 changes: HashMap::default(),
84 coordinator: tx.clone(),
85 }
86 .spawn(),
87 index,
88 coordinator: tx,
89 _cancel: cancel,
90 }
91 }
92 }
93
94 #[derive(Debug)]
95 struct Hook {
96 changes: HashMap<DocumentId, Change>,
97 coordinator: mpsc::UnboundedSender<Event>,
98 }
99
100 const DEBOUNCE: Duration = Duration::from_secs(1);
101
102 impl AsyncHook for Hook {
103 type Event = Event;
104
105 fn handle_event(&mut self, event: Self::Event, timeout: Option<Instant>) -> Option<Instant> {
106 match event {
107 Event::Insert(_) => unreachable!("inserts are sent to the worker directly"),
108 Event::Update(doc, change) => {
109 if let Some(pending_change) = self.changes.get_mut(&doc) {
110 // There is already a change waiting for this document. Coalesce: keep the
111 // original `old_text` and advance to the latest `text`.
112 //
113 // We deliberately do NOT chain the observed changesets here. The index skips
114 // ghost transactions (see `register_hooks`), so a ghost edit may have altered
115 // the document between these two observed changes, which may leave them
116 // non-contiguous in ways a cheap check can't catch. Instead, mark the change
117 // dirty and recompute the changeset from the real ropes at `finish_debounce`,
118 // i.e. once per debounce window rather than once per keystroke.
119 pending_change.text = change.text;
120 pending_change.dirty = true;
121 Some(Instant::now() + DEBOUNCE)
122 } else if !is_changeset_significant(&change.changes) {
123 // The change is small: debounce so a burst of edits coalesces before the
124 // index updates.
125 self.changes.insert(doc, change);
126 Some(Instant::now() + DEBOUNCE)
127 } else {
128 // The change is large: update the index immediately rather than waiting out
129 // the debounce.
130 send(&self.coordinator, Event::Update(doc, change));
131 timeout
132 }
133 }
134 Event::Delete(doc, text) => {
135 // If there are pending changes that haven't been indexed since the last debounce,
136 // forget them and delete the old text.
137 if let Some(change) = self.changes.remove(&doc) {
138 send(&self.coordinator, Event::Delete(doc, change.old_text));
139 } else {
140 send(&self.coordinator, Event::Delete(doc, text));
141 }
142 timeout
143 }
144 Event::Clear => unreachable!("clear is sent to the worker directly"),
145 }
146 }
147
148 fn finish_debounce(&mut self) {
149 for (doc, mut change) in self.changes.drain() {
150 // A coalesced change carries a stale changeset; recompute it from the real endpoints.
151 // This diff is valid regardless of any ghost edits skipped between observed changes.
152 if change.dirty {
153 change.changes = compare_ropes(&change.old_text, &change.text)
154 .changes()
155 .clone();
156 change.dirty = false;
157 }
158 send(&self.coordinator, Event::Update(doc, change));
159 }
160 }
161 }
162
163 /// Minimum number of grapheme clusters required to include a word in the index
164 const MIN_WORD_GRAPHEMES: usize = 3;
165 /// Maximum word length allowed (in chars)
166 const MAX_WORD_LEN: usize = 50;
167 /// Number of words to index between checks of the cancellation handle.
168 const CANCEL_CHECK_INTERVAL: usize = 4096;
169
170 type Word = kstring::KString;
171
172 #[derive(Debug, Default)]
173 struct WordIndexInner {
174 /// Reference counted storage for words.
175 ///
176 /// Words are very likely to be reused many times. Instead of storing duplicates we keep a
177 /// reference count of times a word is used. When the reference count drops to zero the word
178 /// is removed from the index.
179 words: HashMap<Word, u32>,
180 }
181
182 impl WordIndexInner {
183 fn words(&self) -> impl Iterator<Item = &Word> {
184 self.words.keys()
185 }
186
187 fn insert(&mut self, word: RopeSlice) {
188 let word: Cow<str> = word.into();
189 if let Some(rc) = self.words.get_mut(word.as_ref()) {
190 *rc = rc.saturating_add(1);
191 } else {
192 let word = match word {
193 Cow::Owned(s) => Word::from_string(s),
194 Cow::Borrowed(s) => Word::from_ref(s),
195 };
196 self.words.insert(word, 1);
197 }
198 }
199
200 fn remove(&mut self, word: RopeSlice) {
201 let word: Cow<str> = word.into();
202 match self.words.get_mut(word.as_ref()) {
203 Some(1) => {
204 self.words.remove(word.as_ref());
205 }
206 Some(n) => *n -= 1,
207 None => (),
208 }
209 }
210
211 fn clear(&mut self) {
212 std::mem::take(&mut self.words);
213 }
214 }
215
216 #[derive(Debug, Default, Clone)]
217 pub struct WordIndex {
218 inner: Arc<RwLock<WordIndexInner>>,
219 }
220
221 impl WordIndex {
222 pub fn matches(&self, pattern: &str) -> Vec<String> {
223 let inner = self.inner.read();
224 let mut matches = fuzzy_match(pattern, inner.words(), false);
225 matches.sort_unstable_by_key(|(_, score)| *score);
226 matches
227 .into_iter()
228 .map(|(word, _)| word.to_string())
229 .collect()
230 }
231
232 fn add_document(&self, text: &Rope, cancel: &TaskHandle) {
233 let mut inner = self.inner.write();
234 for (i, word) in words(text.slice(..)).enumerate() {
235 if i % CANCEL_CHECK_INTERVAL == 0 && cancel.is_canceled() {
236 return;
237 }
238 inner.insert(word);
239 }
240 }
241
242 fn update_document(
243 &self,
244 old_text: &Rope,
245 text: &Rope,
246 changes: &ChangeSet,
247 cancel: &TaskHandle,
248 ) {
249 let mut inner = self.inner.write();
250 // A single changed window can span the whole document, so the check is driven by a count
251 // of the words processed rather than the number of windows.
252 let mut since_check = 0;
253 for (old_window, new_window) in changed_windows(old_text.slice(..), text.slice(..), changes)
254 {
255 for word in words(new_window) {
256 inner.insert(word);
257 since_check += 1;
258 }
259 for word in words(old_window) {
260 inner.remove(word);
261 since_check += 1;
262 }
263 if since_check >= CANCEL_CHECK_INTERVAL {
264 if cancel.is_canceled() {
265 return;
266 }
267 since_check = 0;
268 }
269 }
270 }
271
272 fn remove_document(&self, text: &Rope, cancel: &TaskHandle) {
273 let mut inner = self.inner.write();
274 for (i, word) in words(text.slice(..)).enumerate() {
275 if i % CANCEL_CHECK_INTERVAL == 0 && cancel.is_canceled() {
276 return;
277 }
278 inner.remove(word);
279 }
280 }
281
282 fn clear(&self) {
283 let mut inner = self.inner.write();
284 inner.clear();
285 }
286
287 /// Coordinate the indexing of documents.
288 ///
289 /// This task wraps a MPSC queue and spawns blocking tasks which update the index. Updates
290 /// are applied one-by-one to ensure that changes to the index are **serialized**:
291 /// updates to each document must be applied in-order.
292 async fn run(self, mut events: mpsc::UnboundedReceiver<Event>, cancel: TaskHandle) {
293 while let Some(event) = events.recv().await {
294 if cancel.is_canceled() {
295 return;
296 }
297 let this = self.clone();
298 let cancel = cancel.clone();
299 tokio::task::spawn_blocking(move || match event {
300 Event::Insert(text) => {
301 this.add_document(&text, &cancel);
302 }
303 Event::Update(
304 _doc,
305 Change {
306 old_text,
307 text,
308 changes,
309 ..
310 },
311 ) => {
312 this.update_document(&old_text, &text, &changes, &cancel);
313 }
314 Event::Delete(_doc, text) => {
315 this.remove_document(&text, &cancel);
316 }
317 Event::Clear => {
318 this.clear();
319 }
320 })
321 .await
322 .unwrap();
323 }
324 }
325 }
326
327 /// Extracts indexable words from a rope slice.
328 ///
329 /// A word is a run of grapheme clusters whose first character is a
330 /// w[word character][char_is_word], spanning at least [`MIN_WORD_GRAPHEMES`] clusters and at
331 /// most [`MAX_WORD_LEN`] chars. All other text is skipped.
332 ///
333 /// This is a single forward pass over the text's grapheme clusters: each cluster is visited once.
334 /// and the only rope position ever sought is the start of an emitted word, which keeps
335 /// extraction roughly linear in the length of the text.
336 fn words(text: RopeSlice) -> impl Iterator<Item = RopeSlice> {
337 let mut graphemes = text.grapheme_indices();
338 // The in-progress word run: the byte offset of its first cluster, its length in chars, and the
339 // number of graphemes it spans. `graphemes_len == 0` means we are between words.
340 let mut start_byte = 0;
341 let mut char_len = 0;
342 let mut graphemes_len = 0;
343
344 // Yields `text[start_byte..end_byte]` if that run satisfies the length bounds.
345 let qualify = move |start_byte, end_byte, char_len, graphemes_len| {
346 (graphemes_len >= MIN_WORD_GRAPHEMES && char_len <= MAX_WORD_LEN)
347 .then(|| text.byte_slice(start_byte..end_byte))
348 };
349
350 iter::from_fn(move || {
351 loop {
352 let Some((byte_idx, grapheme)) = graphemes.next() else {
353 // Flush a word that runs up to the end of the text.
354 let word = qualify(start_byte, text.len_bytes(), char_len, graphemes_len);
355 graphemes_len = 0;
356 return word;
357 };
358
359 if grapheme.chars().next().is_some_and(char_is_word) {
360 if graphemes_len == 0 {
361 start_byte = byte_idx;
362 char_len = 0;
363 }
364 graphemes_len += 1;
365 char_len += grapheme.len_chars();
366 } else if graphemes_len != 0 {
367 // A non-word cluster ends the current run; `byte_idx` is one past the run's end.
368 let word = qualify(start_byte, byte_idx, char_len, graphemes_len);
369 graphemes_len = 0;
370 if word.is_some() {
371 return word;
372 }
373 }
374 }
375 })
376 }
377
378 /// Finds areas of the old and new texts around each operation in `changes`.
379 ///
380 /// The window is larger than the changed area and can encompass multiple insert/delete operations
381 /// if they are grouped closely together.
382 ///
383 /// The ranges of the old and new text should usually be of different sizes. For example a
384 /// deletion of "foo" surrounded by large retain sections would give a longer window into the
385 /// `old_text` and shorter window of `new_text`. Vice-versa for an insertion. A full replacement
386 /// of a word though would give two slices of the same size.
387 fn changed_windows<'a>(
388 old_text: RopeSlice<'a>,
389 new_text: RopeSlice<'a>,
390 changes: &'a ChangeSet,
391 ) -> impl Iterator<Item = (RopeSlice<'a>, RopeSlice<'a>)> {
392 use helix_core::Operation::*;
393
394 let mut operations = changes.changes().iter().peekable();
395 let mut old_pos = 0;
396 let mut new_pos = 0;
397 iter::from_fn(move || loop {
398 let operation = operations.next()?;
399 let old_start = old_pos;
400 let new_start = new_pos;
401 let len = operation.len_chars();
402 match operation {
403 Retain(_) => {
404 old_pos += len;
405 new_pos += len;
406 continue;
407 }
408 Insert(_) => new_pos += len,
409 Delete(_) => old_pos += len,
410 }
411
412 // Scan ahead until a `Retain` is found which would end a window.
413 while let Some(o) = operations.next_if(|op| !matches!(op, Retain(n) if *n > MAX_WORD_LEN)) {
414 let len = o.len_chars();
415 match o {
416 Retain(_) => {
417 old_pos += len;
418 new_pos += len;
419 }
420 Delete(_) => old_pos += len,
421 Insert(_) => new_pos += len,
422 }
423 }
424
425 let old_window = old_start.saturating_sub(MAX_WORD_LEN)
426 ..(old_pos + MAX_WORD_LEN).min(old_text.len_chars());
427 let new_window = new_start.saturating_sub(MAX_WORD_LEN)
428 ..(new_pos + MAX_WORD_LEN).min(new_text.len_chars());
429
430 return Some((old_text.slice(old_window), new_text.slice(new_window)));
431 })
432 }
433
434 /// Estimates whether a changeset is significant or small.
435 fn is_changeset_significant(changes: &ChangeSet) -> bool {
436 use helix_core::Operation::*;
437
438 let mut diff = 0;
439 for operation in changes.changes() {
440 match operation {
441 Retain(_) => continue,
442 Delete(_) | Insert(_) => diff += operation.len_chars(),
443 }
444 }
445
446 // This is arbitrary and could be tuned further:
447 diff > 1_000
448 }
449
450 pub(crate) fn register_hooks(handlers: &Handlers) {
451 let coordinator = handlers.word_index.coordinator.clone();
452 register_hook!(move |event: &mut DocumentDidOpen<'_>| {
453 let doc = doc!(event.editor, &event.doc);
454 if doc.word_completion_enabled() {
455 send(&coordinator, Event::Insert(doc.text().clone()));
456 }
457 Ok(())
458 });
459
460 let tx = handlers.word_index.hook.clone();
461 register_hook!(move |event: &mut DocumentDidChange<'_>| {
462 if !event.ghost_transaction && event.doc.word_completion_enabled() {
463 helix_event::send_blocking(
464 &tx,
465 Event::Update(
466 event.doc.id(),
467 Change {
468 old_text: event.old_text.clone(),
469 text: event.doc.text().clone(),
470 changes: event.changes.clone(),
471 dirty: false,
472 },
473 ),
474 );
475 }
476 Ok(())
477 });
478
479 let tx = handlers.word_index.hook.clone();
480 register_hook!(move |event: &mut DocumentDidClose<'_>| {
481 if event.doc.word_completion_enabled() {
482 helix_event::send_blocking(
483 &tx,
484 Event::Delete(event.doc.id(), event.doc.text().clone()),
485 );
486 }
487 Ok(())
488 });
489
490 let coordinator = handlers.word_index.coordinator.clone();
491 register_hook!(move |event: &mut ConfigDidChange<'_>| {
492 // The feature has been turned off. Clear the index and reclaim any used memory.
493 if event.old.word_completion.enable && !event.new.word_completion.enable {
494 send(&coordinator, Event::Clear);
495 }
496
497 // The feature has been turned on. Index open documents.
498 if !event.old.word_completion.enable && event.new.word_completion.enable {
499 for doc in event.editor.documents() {
500 if doc.word_completion_enabled() {
501 send(&coordinator, Event::Insert(doc.text().clone()));
502 }
503 }
504 }
505
506 Ok(())
507 });
508 }
509
510 // See `benches/word_index.rs`.
511 #[cfg(feature = "bench")]
512 pub mod bench {
513 use helix_core::{Rope, RopeSlice};
514
515 pub use super::WordIndex;
516
517 pub fn add_document(index: &WordIndex, text: &Rope) {
518 let mut cancel = helix_event::TaskController::new();
519 index.add_document(text, &cancel.restart());
520 }
521
522 pub fn words(text: RopeSlice) -> impl Iterator<Item = RopeSlice> {
523 super::words(text)
524 }
525 }
526
527 #[cfg(test)]
528 mod tests {
529 use std::collections::HashSet;
530
531 use super::*;
532 use quickcheck::{Arbitrary, Gen};
533
534 impl WordIndex {
535 fn words(&self) -> HashSet<String> {
536 let inner = self.inner.read();
537 inner.words().map(|w| w.to_string()).collect()
538 }
539
540 /// The full reference-counted word multiset. Unlike [`WordIndex::words`] this keeps the
541 /// counts, which the incremental update path must hold exactly in step with a fresh index:
542 /// a word is only freed once its count falls to zero, so any drift leaks stale words.
543 fn counts(&self) -> std::collections::HashMap<String, u32> {
544 let inner = self.inner.read();
545 inner
546 .words
547 .iter()
548 .map(|(w, c)| (w.to_string(), *c))
549 .collect()
550 }
551 }
552
553 #[track_caller]
554 fn assert_words<I: ToString, T: IntoIterator<Item = I>>(text: &str, expected: T) {
555 let text = Rope::from_str(text);
556 let index = WordIndex::default();
557 let mut cancel = TaskController::new();
558 index.add_document(&text, &cancel.restart());
559 let actual = index.words();
560 let expected: HashSet<_> = expected.into_iter().map(|i| i.to_string()).collect();
561 assert_eq!(expected, actual);
562 }
563
564 #[test]
565 fn parse() {
566 assert_words("one two three", ["one", "two", "three"]);
567 assert_words("a foo c", ["foo"]);
568 }
569
570 #[track_caller]
571 fn assert_diff<S, R, I>(before: &str, after: &str, expect_removed: R, expect_inserted: I)
572 where
573 S: ToString,
574 R: IntoIterator<Item = S>,
575 I: IntoIterator<Item = S>,
576 {
577 let before = Rope::from_str(before);
578 let after = Rope::from_str(after);
579 let diff = compare_ropes(&before, &after);
580 let expect_removed: HashSet<_> =
581 expect_removed.into_iter().map(|i| i.to_string()).collect();
582 let expect_inserted: HashSet<_> =
583 expect_inserted.into_iter().map(|i| i.to_string()).collect();
584
585 let index = WordIndex::default();
586 let mut cancel = TaskController::new();
587 let handle = cancel.restart();
588 index.add_document(&before, &handle);
589 let words_before = index.words();
590 index.update_document(&before, &after, diff.changes(), &handle);
591 let words_after = index.words();
592
593 let actual_removed = words_before.difference(&words_after).cloned().collect();
594 let actual_inserted = words_after.difference(&words_before).cloned().collect();
595
596 eprintln!("\"{before}\" {words_before:?} => \"{after}\" {words_after:?}");
597 assert_eq!(
598 expect_removed, actual_removed,
599 "expected {expect_removed:?} to be removed, instead {actual_removed:?} was"
600 );
601 assert_eq!(
602 expect_inserted, actual_inserted,
603 "expected {expect_inserted:?} to be inserted, instead {actual_inserted:?} was"
604 );
605 }
606
607 #[test]
608 fn diff() {
609 assert_diff("one two three", "one five three", ["two"], ["five"]);
610 assert_diff("one two three", "one to three", ["two"], []);
611 assert_diff("one two three", "one three", ["two"], []);
612 assert_diff("one two three", "one t{o three", ["two"], []);
613 assert_diff("one foo three", "one fooo three", ["foo"], ["fooo"]);
614 }
615
616 fn build_change(old: &str, new: &str) -> Change {
617 let old_text = Rope::from_str(old);
618 let text = Rope::from_str(new);
619 let changes = compare_ropes(&old_text, &text).changes().clone();
620 Change {
621 old_text,
622 text,
623 changes,
624 dirty: false,
625 }
626 }
627
628 /// Drives a [`Hook`] through a sequence of observed `(old_text, new_text)` changes to a single
629 /// document, flushes the debounce, and returns the change the hook hands to the indexer (with
630 /// its changeset recomputed if the observed changes were coalesced). Returns `None` if no
631 /// change was emitted.
632 fn coalesce<'a>(observations: impl IntoIterator<Item = (&'a str, &'a str)>) -> Option<Change> {
633 let (coordinator, mut rx) = mpsc::unbounded_channel();
634 let mut hook = Hook {
635 changes: HashMap::default(),
636 coordinator,
637 };
638 let doc = DocumentId::default();
639 for (old, new) in observations {
640 hook.handle_event(Event::Update(doc, build_change(old, new)), None);
641 }
642 hook.finish_debounce();
643 match rx.try_recv() {
644 Ok(Event::Update(_, change)) => Some(change),
645 _ => None,
646 }
647 }
648
649 #[track_caller]
650 fn assert_coalesces(observations: &[(&str, &str)]) {
651 let change = coalesce(observations.iter().copied())
652 .expect("a coalesced change should have been emitted");
653 let first = observations.first().unwrap();
654 let last = observations.last().unwrap();
655
656 // The coalesced change spans from the first text observed to the last.
657 assert_eq!(change.old_text, Rope::from_str(first.0));
658 assert_eq!(change.text, Rope::from_str(last.1));
659
660 // Its changeset must faithfully map `old_text` -> `text`; `update_document` relies on this
661 // to locate the windows it reindexes.
662 let mut applied = change.old_text.clone();
663 assert!(change.changes.apply(&mut applied));
664 assert_eq!(applied, change.text);
665
666 // Reindexing must converge onto exactly the word multiset of the final text (words and
667 // refcounts) matching a fresh index built from scratch.
668 let mut cancel = TaskController::new();
669 let handle = cancel.restart();
670 let index = WordIndex::default();
671 index.add_document(&change.old_text, &handle);
672 index.update_document(&change.old_text, &change.text, &change.changes, &handle);
673
674 let fresh = WordIndex::default();
675 fresh.add_document(&change.text, &handle);
676
677 assert_eq!(index.counts(), fresh.counts());
678 }
679
680 #[test]
681 fn hook_coalesces_contiguous_changes() {
682 // Two real edits that chain cleanly: the text after the first edit is the text before the
683 // second, so the changesets compose directly.
684 assert_coalesces(&[
685 ("the quick brown fox", "the slowish brown fox"),
686 ("the slowish brown fox", "the slowish green fox"),
687 ]);
688 }
689
690 #[test]
691 fn hook_coalesces_across_skipped_ghost_edit() {
692 // A ghost transaction edited the document between the two real edits and was not reported
693 // to the index, so the text before the second edit no longer matches the text after the
694 // first. Here it is longer, which would make a chained `ChangeSet::compose` panic on its
695 // `len_after == len` precondition.
696 assert_coalesces(&[
697 ("the quick brown fox", "the quick brown foxes"),
698 ("the quick brown foxes jumped over", "the lazy brown foxes"),
699 ]);
700 }
701
702 #[test]
703 fn hook_coalesces_across_length_preserving_ghost_edit() {
704 // The subtle case: a ghost edit changes content without changing length, in a region the
705 // next real edit leaves untouched. The two observed changes then have matching lengths
706 // but different contents, so a length check alone cannot tell they are non-contiguous.
707 let p = ".".repeat(60);
708 assert_coalesces(&[
709 (&format!("aaa{p}ggg"), &format!("bbb{p}ggg")),
710 (&format!("bbb{p}hhh"), &format!("ccc{p}hhh")),
711 ]);
712 }
713
714 const CORPORA: &[(&str, &str)] = &[
715 ("arabic", include_str!("../../benches/texts/arabic.txt")),
716 ("english", include_str!("../../benches/texts/english.txt")),
717 ("hindi", include_str!("../../benches/texts/hindi.txt")),
718 ("japanese", include_str!("../../benches/texts/japanese.txt")),
719 ("korean", include_str!("../../benches/texts/korean.txt")),
720 ("mandarin", include_str!("../../benches/texts/mandarin.txt")),
721 ("russian", include_str!("../../benches/texts/russian.txt")),
722 (
723 "source_code",
724 include_str!("../../benches/texts/source_code.txt"),
725 ),
726 ];
727
728 #[track_caller]
729 fn assert_extracts(text: &str, expected: &[&str]) {
730 let rope = Rope::from_str(text);
731 let got: Vec<String> = words(rope.slice(..)).map(|w| w.to_string()).collect();
732 assert_eq!(got, expected, "extracting words from {text:?}");
733 }
734
735 /// `words` categorizes whole grapheme clusters, so a word boundary never falls inside a
736 /// cluster. A non-word combining mark stays attached to the word character it modifies.
737 #[test]
738 fn extract_respects_grapheme_clusters() {
739 // Whitespace and punctuation separate words. Runs under MIN_WORD_GRAPHEMES are dropped.
740 assert_extracts("a foo c", &["foo"]);
741 assert_extracts(
742 "foo.bar.baz qux::quux",
743 &["foo", "bar", "baz", "qux", "quux"],
744 );
745 assert_extracts("snake_case_id CamelCase", &["snake_case_id", "CamelCase"]);
746 // Precomposed and decomposed accents both keep the whole word: the combining mark rides
747 // along with the letter it attaches to rather than truncating the word before it.
748 assert_extracts("naïve café résumé", &["naïve", "café", "résumé"]);
749 assert_extracts(
750 "nai\u{0308}ve cafe\u{0301}",
751 &["nai\u{0308}ve", "cafe\u{0301}"],
752 );
753 // A Devanagari conjunct is joined by a virama (itself a non-word char) yet stays one word.
754 assert_extracts("ज्ञानकोश है", &["ज्ञानकोश"]);
755 // Hangul syllables are word characters.
756 assert_extracts("한국어 위키백과", &["한국어", "위키백과"]);
757 // An emoji cluster is not.
758 assert_extracts("emoji 👍🏽 word", &["emoji", "word"]);
759 }
760
761 /// Every word extracted from the corpora must satisfy the documented invariants.
762 #[test]
763 fn extract_corpora_invariants() {
764 for (name, text) in CORPORA {
765 let rope = Rope::from_str(text);
766 let mut count = 0;
767 for word in words(rope.slice(..)) {
768 count += 1;
769 let clusters = word.graphemes().count();
770 assert!(
771 clusters >= MIN_WORD_GRAPHEMES,
772 "{name}: {word:?} spans only {clusters} grapheme cluster(s)"
773 );
774 assert!(
775 word.len_chars() <= MAX_WORD_LEN,
776 "{name}: {word:?} is {} chars long",
777 word.len_chars()
778 );
779 assert!(
780 word.chars().next().is_some_and(char_is_word),
781 "{name}: {word:?} starts with a non-word character"
782 );
783 }
784 assert!(count > 0, "{name}: expected to extract some words");
785 }
786 }
787
788 /// Grapheme-cluster edge cases which the prose corpora underrepresent: combining marks at
789 /// word starts and seams, a skin-tone emoji, a ZWJ family sequence, a Devanagari conjunct,
790 /// and a lone Hangul syllable.
791 const SPICE: &[&str] = &[
792 "a\u{0301}", // base + combining acute
793 "\u{0301}lead", // leading combining mark
794 "mid\u{0308}dle", // combining diaeresis mid-word
795 "👍🏽", // emoji + skin-tone modifier
796 "👨\u{200D}👩\u{200D}👧", // ZWJ family sequence
797 "क्ष", // Devanagari conjunct (virama)
798 "한", // Hangul syllable
799 ];
800
801 /// Picks a chunk of text: usually a random char span sliced out of one of the multilingual
802 /// corpora (real grapheme complexity for free, and slicing on char boundaries deliberately
803 /// frays some clusters), occasionally an adversarial cluster from [`SPICE`].
804 fn sample_text(g: &mut Gen) -> String {
805 if usize::arbitrary(g) % 4 == 0 {
806 return g.choose(SPICE).unwrap().to_string();
807 }
808 let (_, corpus) = g.choose(CORPORA).unwrap();
809 let chars: Vec<char> = corpus.chars().collect();
810 if chars.is_empty() {
811 return String::new();
812 }
813 let span = usize::arbitrary(g) % 200;
814 let start = usize::arbitrary(g) % chars.len();
815 let end = (start + span).min(chars.len());
816 chars[start..end].iter().collect()
817 }
818
819 /// Applies one random splice to `text`: delete a random char range and insert a fresh chunk.
820 fn random_edit(g: &mut Gen, text: &str) -> String {
821 let chars: Vec<char> = text.chars().collect();
822 let len = chars.len();
823 let del_start = usize::arbitrary(g) % (len + 1);
824 let del_len = usize::arbitrary(g) % (len - del_start + 1);
825 let mut out: String = chars[..del_start].iter().collect();
826 out.push_str(&sample_text(g));
827 out.extend(&chars[del_start + del_len..]);
828 out
829 }
830
831 /// An obvious, independent reimplementation of [`words`]: walk grapheme clusters, accumulate
832 /// a run of consecutive word-character clusters, and emit it when it ends if it satisfies the
833 /// length bounds. Used as an oracle for the optimized single-pass extractor.
834 fn reference_words(text: &str) -> Vec<String> {
835 let rope = Rope::from_str(text);
836 let mut out = Vec::new();
837 let mut run = String::new();
838 let mut clusters = 0usize;
839 let flush = |run: &mut String, clusters: &mut usize, out: &mut Vec<String>| {
840 if *clusters >= MIN_WORD_GRAPHEMES && run.chars().count() <= MAX_WORD_LEN {
841 out.push(run.clone());
842 }
843 run.clear();
844 *clusters = 0;
845 };
846 for cluster in rope.slice(..).graphemes() {
847 if cluster.chars().next().is_some_and(char_is_word) {
848 run.extend(cluster.chars());
849 clusters += 1;
850 } else {
851 flush(&mut run, &mut clusters, &mut out);
852 }
853 }
854 flush(&mut run, &mut clusters, &mut out);
855 out
856 }
857
858 #[derive(Clone, Debug)]
859 struct SampledText(String);
860
861 impl Arbitrary for SampledText {
862 fn arbitrary(g: &mut Gen) -> Self {
863 SampledText(sample_text(g))
864 }
865 fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
866 Box::new(self.0.shrink().map(SampledText))
867 }
868 }
869
870 #[derive(Clone, Debug)]
871 struct EditPair {
872 old: String,
873 new: String,
874 }
875
876 impl Arbitrary for EditPair {
877 fn arbitrary(g: &mut Gen) -> Self {
878 let old = sample_text(g);
879 let new = random_edit(g, &old);
880 EditPair { old, new }
881 }
882 fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
883 Box::new(
884 (self.old.clone(), self.new.clone())
885 .shrink()
886 .map(|(old, new)| EditPair { old, new }),
887 )
888 }
889 }
890
891 /// A sequence of `(old_text, new_text)` changes as the hook observes them. Some steps leave
892 /// a gap (the next change's `old_text` differs from the previous `new_text`) modelling an
893 /// unobserved ghost edit applied to the document between two real ones.
894 #[derive(Clone, Debug)]
895 struct Observations(Vec<(String, String)>);
896
897 impl Arbitrary for Observations {
898 fn arbitrary(g: &mut Gen) -> Self {
899 let steps = usize::arbitrary(g) % 5 + 1;
900 let mut current = sample_text(g);
901 let mut observations = Vec::with_capacity(steps);
902 for _ in 0..steps {
903 let observed_old = if bool::arbitrary(g) {
904 // A ghost edit perturbed the document before this real edit, so the observed
905 // `old_text` no longer matches the previous `new_text`.
906 random_edit(g, &current)
907 } else {
908 current.clone()
909 };
910 let new = random_edit(g, &observed_old);
911 observations.push((observed_old, new.clone()));
912 current = new;
913 }
914 Observations(observations)
915 }
916 fn shrink(&self) -> Box<dyn Iterator<Item = Self>> {
917 Box::new(self.0.shrink().map(Observations))
918 }
919 }
920
921 quickcheck::quickcheck! {
922 /// The optimized single-pass extractor agrees with the obvious reference on arbitrary
923 /// (multilingual, cluster-frayed) text.
924 fn prop_words_match_reference(text: SampledText) -> bool {
925 let rope = Rope::from_str(&text.0);
926 let got: Vec<String> = words(rope.slice(..)).map(|w| w.to_string()).collect();
927 got == reference_words(&text.0)
928 }
929
930 /// Incrementally updating across one edit lands on exactly the same word multiset (words
931 /// and refcounts) as reindexing the new text from scratch.
932 fn prop_update_document_matches_fresh(pair: EditPair) -> bool {
933 let old = Rope::from_str(&pair.old);
934 let new = Rope::from_str(&pair.new);
935 let changes = compare_ropes(&old, &new).changes().clone();
936
937 let mut cancel = TaskController::new();
938 let handle = cancel.restart();
939 let incremental = WordIndex::default();
940 incremental.add_document(&old, &handle);
941 incremental.update_document(&old, &new, &changes, &handle);
942
943 let fresh = WordIndex::default();
944 fresh.add_document(&new, &handle);
945
946 incremental.counts() == fresh.counts()
947 }
948
949 /// Coalescing a sequence of observed changes (gaps and all) and flushing yields a change
950 /// that maps its `old_text` to its `text` and drives the index to the same multiset as a
951 /// fresh index of the final text.
952 fn prop_hook_coalescing_matches_fresh(obs: Observations) -> bool {
953 let Some(change) = coalesce(obs.0.iter().map(|(o, n)| (o.as_str(), n.as_str()))) else {
954 return true;
955 };
956
957 let mut applied = change.old_text.clone();
958 if !change.changes.apply(&mut applied) || applied != change.text {
959 return false;
960 }
961
962 let mut cancel = TaskController::new();
963 let handle = cancel.restart();
964 let incremental = WordIndex::default();
965 incremental.add_document(&change.old_text, &handle);
966 incremental.update_document(&change.old_text, &change.text, &change.changes, &handle);
967
968 let fresh = WordIndex::default();
969 fresh.add_document(&change.text, &handle);
970
971 incremental.counts() == fresh.counts()
972 }
973 }
974 }