| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 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 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
dirty: bool, |
| 35 |
} |
| 36 |
|
| 37 |
#[derive(Debug)] |
| 38 |
enum Event { |
| 39 |
Insert(Rope), |
| 40 |
Update(DocumentId, Change), |
| 41 |
Delete(DocumentId, Rope), |
| 42 |
|
| 43 |
|
| 44 |
Clear, |
| 45 |
} |
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 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 |
|
| 59 |
hook: mpsc::Sender<Event>, |
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
coordinator: mpsc::UnboundedSender<Event>, |
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 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 |
|
| 111 |
|
| 112 |
|
| 113 |
|
| 114 |
|
| 115 |
|
| 116 |
|
| 117 |
|
| 118 |
|
| 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 |
|
| 124 |
|
| 125 |
self.changes.insert(doc, change); |
| 126 |
Some(Instant::now() + DEBOUNCE) |
| 127 |
} else { |
| 128 |
|
| 129 |
|
| 130 |
send(&self.coordinator, Event::Update(doc, change)); |
| 131 |
timeout |
| 132 |
} |
| 133 |
} |
| 134 |
Event::Delete(doc, text) => { |
| 135 |
|
| 136 |
|
| 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 |
|
| 151 |
|
| 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 |
|
| 164 |
const MIN_WORD_GRAPHEMES: usize = 3; |
| 165 |
|
| 166 |
const MAX_WORD_LEN: usize = 50; |
| 167 |
|
| 168 |
const CANCEL_CHECK_INTERVAL: usize = 4096; |
| 169 |
|
| 170 |
type Word = kstring::KString; |
| 171 |
|
| 172 |
#[derive(Debug, Default)] |
| 173 |
struct WordIndexInner { |
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
|
| 178 |
|
| 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 |
|
| 251 |
|
| 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 |
|
| 288 |
|
| 289 |
|
| 290 |
|
| 291 |
|
| 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 |
|
| 328 |
|
| 329 |
|
| 330 |
|
| 331 |
|
| 332 |
|
| 333 |
|
| 334 |
|
| 335 |
|
| 336 |
fn words(text: RopeSlice) -> impl Iterator<Item = RopeSlice> { |
| 337 |
let mut graphemes = text.grapheme_indices(); |
| 338 |
|
| 339 |
|
| 340 |
let mut start_byte = 0; |
| 341 |
let mut char_len = 0; |
| 342 |
let mut graphemes_len = 0; |
| 343 |
|
| 344 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 379 |
|
| 380 |
|
| 381 |
|
| 382 |
|
| 383 |
|
| 384 |
|
| 385 |
|
| 386 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 493 |
if event.old.word_completion.enable && !event.new.word_completion.enable { |
| 494 |
send(&coordinator, Event::Clear); |
| 495 |
} |
| 496 |
|
| 497 |
|
| 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 |
|
| 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 |
|
| 541 |
|
| 542 |
|
| 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 |
|
| 629 |
|
| 630 |
|
| 631 |
|
| 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 |
|
| 657 |
assert_eq!(change.old_text, Rope::from_str(first.0)); |
| 658 |
assert_eq!(change.text, Rope::from_str(last.1)); |
| 659 |
|
| 660 |
|
| 661 |
|
| 662 |
let mut applied = change.old_text.clone(); |
| 663 |
assert!(change.changes.apply(&mut applied)); |
| 664 |
assert_eq!(applied, change.text); |
| 665 |
|
| 666 |
|
| 667 |
|
| 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 |
|
| 683 |
|
| 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 |
|
| 693 |
|
| 694 |
|
| 695 |
|
| 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 |
|
| 705 |
|
| 706 |
|
| 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 |
|
| 736 |
|
| 737 |
#[test] |
| 738 |
fn extract_respects_grapheme_clusters() { |
| 739 |
|
| 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 |
|
| 747 |
|
| 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 |
|
| 754 |
assert_extracts("ज्ञानकोश है", &["ज्ञानकोश"]); |
| 755 |
|
| 756 |
assert_extracts("한국어 위키백과", &["한국어", "위키백과"]); |
| 757 |
|
| 758 |
assert_extracts("emoji 👍🏽 word", &["emoji", "word"]); |
| 759 |
} |
| 760 |
|
| 761 |
|
| 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 |
|
| 789 |
|
| 790 |
|
| 791 |
const SPICE: &[&str] = &[ |
| 792 |
"a\u{0301}", |
| 793 |
"\u{0301}lead", |
| 794 |
"mid\u{0308}dle", |
| 795 |
"👍🏽", fier |
| 796 |
"👨\u{200D}👩\u{200D}quence |
| 797 |
"क्ष", irama) |
| 798 |
"한", le |
| 799 |
]; |
| 800 |
|
| 801 |
|
| 802 |
|
| 803 |
|
| 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 |
|
| 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 |
|
| 832 |
|
| 833 |
|
| 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 |
|
| 892 |
|
| 893 |
|
| 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 |
|
| 905 |
|
| 906 |
random_edit(g, ¤t) |
| 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 |
|
| 923 |
|
| 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 |
|
| 931 |
|
| 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 |
|
| 950 |
|
| 951 |
|
| 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 |
} |