1use crate::vocabulary_source::{Observation, Parser, Source, SourceError};
22use crate::{
23 BAD_TAG, BOUNDS, DICTIONARY_DATA, Engine, NULL, OK, POISONED, STATE, VERSION, compatible_abi,
24 with_engine,
25};
26use keyrill_core::vocabulary::{Membership, Snapshot, Vocabulary};
27use std::io::ErrorKind;
28#[cfg(unix)]
29use std::os::unix::ffi::OsStrExt;
30use std::panic::{AssertUnwindSafe, catch_unwind};
31use std::path::{Path, PathBuf};
32use std::sync::atomic::{AtomicBool, Ordering};
33use std::sync::{Arc, Mutex};
34
35const MAX_PATH: usize = 1024;
37const SOURCE_IO: u32 = 10;
38const SOURCE_CHANGED: u32 = 11;
39const SOURCE_NOT_REGULAR: u32 = 12;
40const PATH: u32 = 13;
41const STALE_CONFIGURATION: u32 = 14;
42const MISSING_IS_EMPTY: u32 = 1;
43const EXCLUDED: u32 = 2;
44const LEARNED: u32 = 16;
46const LEARNED_SOURCES: usize = 4;
47const SOURCES: usize = 2 + LEARNED_SOURCES;
48const DEFAULT_NAMES: [&str; 2] = ["en.utf-8.add", "ru.utf-8.add"];
49#[cfg(not(windows))]
51const DEFAULT_DIRECTORY: &str = ".vim";
52#[cfg(windows)]
53const DEFAULT_DIRECTORY: &str = "vimfiles";
54
55#[derive(Default)]
57struct Language {
58 generation: u64,
59 path: Option<PathBuf>,
60 missing_is_empty: bool,
61 excluded: bool,
62 current: Option<Arc<Vocabulary>>,
63}
64
65#[derive(Default)]
67struct Acquisition {
68 generation: [u64; SOURCES],
69 sources: [Source; SOURCES],
70}
71
72#[derive(Default)]
75pub struct VocabularyHandle {
76 poisoned: AtomicBool,
77 acquisition: Mutex<Acquisition>,
78 published: Mutex<[Language; SOURCES]>,
79}
80
81fn source_index(source: u32) -> Result<usize, u32> {
82 match source {
83 1 => Ok(0),
84 2 => Ok(1),
85 _ => match source.checked_sub(LEARNED) {
86 Some(slot) if (slot as usize) < LEARNED_SOURCES => Ok(2 + slot as usize),
87 _ => Err(BAD_TAG),
88 },
89 }
90}
91
92fn parser(index: usize, excluded: bool) -> Parser {
95 match (index, excluded) {
96 (0 | 1, _) => Vocabulary::parse,
97 (_, false) => |source| Vocabulary::parse_words(source, Membership::Recognized),
98 (_, true) => |source| Vocabulary::parse_words(source, Membership::Forbidden),
99 }
100}
101
102fn host_path(bytes: &[u8]) -> Option<&Path> {
105 if bytes.contains(&0) {
106 return None;
107 }
108 #[cfg(unix)]
109 let path = Path::new(std::ffi::OsStr::from_bytes(bytes));
110 #[cfg(not(unix))]
111 let path = Path::new(std::str::from_utf8(bytes).ok()?);
112 path.is_absolute().then_some(path)
113}
114
115fn source_status(error: SourceError) -> u32 {
116 match error {
117 SourceError::Io(_) => SOURCE_IO,
118 SourceError::NotRegular => SOURCE_NOT_REGULAR,
119 SourceError::TooLarge => BOUNDS,
120 SourceError::Changed => SOURCE_CHANGED,
121 SourceError::Invalid(_) => DICTIONARY_DATA,
122 }
123}
124
125impl VocabularyHandle {
126 fn configure(
127 &self,
128 index: usize,
129 path: Option<PathBuf>,
130 missing_is_empty: bool,
131 excluded: bool,
132 ) -> u32 {
133 let Ok(mut languages) = self.published.lock() else {
134 return POISONED;
135 };
136 let language = &mut languages[index];
137 if language.path == path
138 && language.missing_is_empty == missing_is_empty
139 && language.excluded == excluded
140 {
141 return OK;
142 }
143 let Some(generation) = language.generation.checked_add(1) else {
144 return STATE;
145 };
146 let retired = std::mem::replace(
147 language,
148 Language {
149 generation,
150 path,
151 missing_is_empty,
152 excluded,
153 current: None,
154 },
155 );
156 drop(languages);
158 drop(retired);
159 OK
160 }
161
162 fn observe(&self, index: usize, checkpoint: impl FnOnce()) -> Result<Observation, u32> {
163 let (generation, path, missing_is_empty, excluded) = {
164 let languages = self.published.lock().map_err(|_| POISONED)?;
165 let language = &languages[index];
166 let path = language.path.clone().ok_or(STATE)?;
167 let (missing_is_empty, excluded) = (language.missing_is_empty, language.excluded);
168 (language.generation, path, missing_is_empty, excluded)
169 };
170 let mut acquisition = self.acquisition.lock().map_err(|_| POISONED)?;
171 if acquisition.generation[index] != generation {
174 acquisition.sources[index] = Source::new(parser(index, excluded));
175 acquisition.generation[index] = generation;
176 }
177 checkpoint();
179 let result = acquisition.sources[index].observe(&path);
180 let mut languages = self.published.lock().map_err(|_| POISONED)?;
181 if languages[index].generation != generation {
182 return Err(STALE_CONFIGURATION);
183 }
184 if missing_is_empty
187 && matches!(result, Err(SourceError::Io(ErrorKind::NotFound)))
188 && acquisition.sources[index].current().is_none()
189 {
190 if languages[index].current.is_some() {
191 return Ok(Observation::Unchanged);
192 }
193 languages[index].current = Some(Arc::new(Vocabulary::default()));
194 return Ok(Observation::Published);
195 }
196 let observation = result.map_err(source_status)?;
197 let retired = if observation == Observation::Published {
198 std::mem::replace(
199 &mut languages[index].current,
200 acquisition.sources[index].current(),
201 )
202 } else {
203 None
204 };
205 drop(languages);
206 drop(acquisition);
207 drop(retired);
208 Ok(observation)
209 }
210}
211
212unsafe fn with_vocabulary(
215 pointer: *const VocabularyHandle,
216 operation: impl FnOnce(&VocabularyHandle) -> u32,
217) -> u32 {
218 if pointer.is_null() {
219 return NULL;
220 }
221 let vocabulary = unsafe { &*pointer };
226 if vocabulary.poisoned.load(Ordering::Acquire) {
227 return POISONED;
228 }
229 let status = catch_unwind(AssertUnwindSafe(|| operation(vocabulary))).unwrap_or(POISONED);
230 if status == POISONED {
231 vocabulary.poisoned.store(true, Ordering::Release);
232 }
233 status
234}
235
236#[unsafe(no_mangle)]
241pub unsafe extern "C" fn kr_vocabulary_new(abi: u32, out: *mut *mut VocabularyHandle) -> u32 {
242 if out.is_null() {
243 return NULL;
244 }
245 unsafe { out.write(std::ptr::null_mut()) };
248 if !compatible_abi(abi) {
249 return VERSION;
250 }
251 match catch_unwind(|| Box::new(VocabularyHandle::default())) {
252 Ok(vocabulary) => {
253 unsafe { out.write(Box::into_raw(vocabulary)) };
255 OK
256 }
257 Err(_) => POISONED,
258 }
259}
260
261#[unsafe(no_mangle)]
267pub unsafe extern "C" fn kr_vocabulary_free(pointer: *mut VocabularyHandle) {
268 if !pointer.is_null() {
269 let _ = catch_unwind(AssertUnwindSafe(|| {
270 drop(unsafe { Box::from_raw(pointer) });
272 }));
273 }
274}
275
276#[unsafe(no_mangle)]
288pub unsafe extern "C" fn kr_vocabulary_configure(
289 pointer: *mut VocabularyHandle,
290 source: u32,
291 path: *const u8,
292 len: u32,
293 flags: u32,
294) -> u32 {
295 unsafe {
297 with_vocabulary(pointer, |vocabulary| {
298 let index = match source_index(source) {
299 Ok(index) => index,
300 Err(status) => return status,
301 };
302 let allowed = if index < 2 {
303 MISSING_IS_EMPTY
304 } else {
305 MISSING_IS_EMPTY | EXCLUDED
306 };
307 if flags & !allowed != 0 {
308 return BAD_TAG;
309 }
310 if len as usize > MAX_PATH {
311 return BOUNDS;
312 }
313 let path = if len == 0 {
314 None
315 } else {
316 if path.is_null() {
317 return NULL;
318 }
319 let path = std::slice::from_raw_parts(path, len as usize);
323 let Some(path) = host_path(path) else {
324 return PATH;
325 };
326 Some(path.to_path_buf())
327 };
328 let missing_is_empty = path.is_some() && flags & MISSING_IS_EMPTY != 0;
329 let excluded = path.is_some() && flags & EXCLUDED != 0;
330 vocabulary.configure(index, path, missing_is_empty, excluded)
331 })
332 }
333}
334
335#[unsafe(no_mangle)]
344pub unsafe extern "C" fn kr_vocabulary_configure_default(
345 pointer: *mut VocabularyHandle,
346 language: u32,
347 home: *const u8,
348 len: u32,
349) -> u32 {
350 unsafe {
352 with_vocabulary(pointer, |vocabulary| {
353 let index = match source_index(language) {
354 Ok(index @ 0..2) => index,
355 Ok(_) => return BAD_TAG,
356 Err(status) => return status,
357 };
358 if len as usize > MAX_PATH {
359 return BOUNDS;
360 }
361 if len == 0 {
362 return PATH;
363 }
364 if home.is_null() {
365 return NULL;
366 }
367 let home = std::slice::from_raw_parts(home, len as usize);
371 let Some(home) = host_path(home) else {
372 return PATH;
373 };
374 let path = home
375 .join(DEFAULT_DIRECTORY)
376 .join("spell")
377 .join(DEFAULT_NAMES[index]);
378 if path.as_os_str().len() > MAX_PATH {
380 return BOUNDS;
381 }
382 vocabulary.configure(index, Some(path), true, false)
383 })
384 }
385}
386
387#[unsafe(no_mangle)]
393pub unsafe extern "C" fn kr_vocabulary_observe(
394 pointer: *mut VocabularyHandle,
395 source: u32,
396 observation_out: *mut u32,
397) -> u32 {
398 unsafe {
401 with_vocabulary(pointer, |vocabulary| {
402 let index = match source_index(source) {
403 Ok(index) => index,
404 Err(status) => return status,
405 };
406 if observation_out.is_null() {
407 return NULL;
408 }
409 match vocabulary.observe(index, || {}) {
410 Ok(observation) => {
411 observation_out.write(match observation {
412 Observation::Pending => 0,
413 Observation::Published => 1,
414 Observation::Unchanged => 2,
415 });
416 OK
417 }
418 Err(status) => status,
419 }
420 })
421 }
422}
423
424#[unsafe(no_mangle)]
432pub unsafe extern "C" fn kr_adopt_vocabulary(
433 engine: *mut Engine,
434 pointer: *const VocabularyHandle,
435) -> u32 {
436 unsafe {
438 with_engine(engine, |engine| {
439 if pointer.is_null() {
440 return NULL;
441 }
442 if engine.session.has_pending() {
443 return STATE;
444 }
445 let mut current = [None, None];
447 let mut learned = Vec::new();
448 let status = with_vocabulary(pointer, |vocabulary| {
449 let Ok(sources) = vocabulary.published.lock() else {
450 return POISONED;
451 };
452 current = [sources[0].current.clone(), sources[1].current.clone()];
453 learned = sources[2..]
454 .iter()
455 .filter_map(|s| s.current.clone())
456 .collect();
457 OK
458 });
459 if status != OK {
460 return status;
461 }
462 engine.dictionaries = current.map(Snapshot::from);
463 engine.learned = learned;
464 OK
465 })
466 }
467}
468
469#[cfg(test)]
470mod tests {
471 use super::*;
472 use crate::tests::{apply_event, type_text};
473 use crate::{
474 ABI, NativeEvent, NativePlan, kr_commit, kr_engine_free, kr_engine_new, kr_plan_event,
475 kr_reset, kr_set_automatic_policy, kr_set_dictionary_utf8,
476 };
477 use keyrill_core::vocabulary::Membership;
478 use std::fs;
479 #[cfg(unix)]
480 use std::os::unix::fs::DirBuilderExt;
481 use std::sync::atomic::AtomicUsize;
482 use std::sync::mpsc;
483
484 struct Directory(PathBuf);
485
486 impl Directory {
487 fn new() -> Self {
488 static NEXT: AtomicUsize = AtomicUsize::new(0);
489 let path = std::env::temp_dir().join(format!(
490 "keyrill-host-{}-{}",
491 std::process::id(),
492 NEXT.fetch_add(1, Ordering::Relaxed)
493 ));
494 #[cfg(unix)]
495 fs::DirBuilder::new().mode(0o700).create(&path).unwrap();
496 #[cfg(not(unix))]
497 fs::create_dir(&path).unwrap();
498 Self(path)
499 }
500
501 fn file(&self, name: &str, bytes: &[u8]) -> PathBuf {
502 let path = self.0.join(name);
503 fs::write(&path, bytes).unwrap();
504 path
505 }
506 }
507
508 impl Drop for Directory {
509 fn drop(&mut self) {
510 let _ = fs::remove_dir_all(&self.0);
511 }
512 }
513
514 #[cfg(unix)]
515 const ROOT: &[u8] = b"/";
516 #[cfg(not(unix))]
517 const ROOT: &[u8] = b"C:\\";
518
519 #[cfg(unix)]
520 fn bytes(path: &Path) -> &[u8] {
521 path.as_os_str().as_bytes()
522 }
523
524 #[cfg(not(unix))]
525 fn bytes(path: &Path) -> &[u8] {
526 path.to_str().unwrap().as_bytes()
527 }
528
529 unsafe fn handles() -> (*mut Engine, *mut VocabularyHandle) {
530 unsafe {
532 let mut engine = std::ptr::null_mut();
533 let mut vocabulary = std::ptr::null_mut();
534 assert_eq!(kr_engine_new(ABI, &mut engine), OK);
535 assert_eq!(kr_vocabulary_new(ABI, &mut vocabulary), OK);
536 (engine, vocabulary)
537 }
538 }
539
540 unsafe fn configure(vocabulary: *mut VocabularyHandle, language: u32, path: &Path) {
541 let bytes = bytes(path);
542 unsafe {
544 assert_eq!(
545 kr_vocabulary_configure(
546 vocabulary,
547 language,
548 bytes.as_ptr(),
549 bytes.len() as u32,
550 0
551 ),
552 OK
553 );
554 }
555 }
556
557 unsafe fn observe(vocabulary: *mut VocabularyHandle, language: u32, expected: u32) {
558 let mut observation = u32::MAX;
559 unsafe {
561 assert_eq!(
562 kr_vocabulary_observe(vocabulary, language, &mut observation),
563 OK
564 );
565 }
566 assert_eq!(observation, expected);
567 }
568
569 fn mark(plan: &NativePlan) -> Vec<u16> {
570 plan.mark[..plan.mark_len as usize].to_vec()
571 }
572
573 #[test]
577 fn path_buffers_versions_generation_exhaustion_and_poison_are_transactional() {
578 unsafe {
581 let (engine, vocabulary) = handles();
582 let mut output = 77;
583 assert_eq!(kr_vocabulary_new(ABI, std::ptr::null_mut()), NULL);
584 assert_eq!(
585 kr_vocabulary_observe(std::ptr::null_mut(), 1, &mut output),
586 NULL
587 );
588 assert_eq!(
589 kr_vocabulary_configure(std::ptr::null_mut(), 1, std::ptr::null(), 0, 0),
590 NULL
591 );
592 assert_eq!(kr_adopt_vocabulary(std::ptr::null_mut(), vocabulary), NULL);
593 assert_eq!(kr_adopt_vocabulary(engine, std::ptr::null()), NULL);
594 assert_eq!(kr_vocabulary_observe(vocabulary, 0, &mut output), BAD_TAG);
595 assert_eq!(
596 kr_vocabulary_observe(vocabulary, 1, std::ptr::null_mut()),
597 NULL
598 );
599 assert_eq!(kr_vocabulary_observe(vocabulary, 1, &mut output), STATE);
600 assert_eq!(output, 77);
601 #[cfg(unix)]
604 let foreign = b"C:\\a".as_slice();
605 #[cfg(not(unix))]
606 let foreign = b"/a".as_slice();
607 let nul = [ROOT, b"a\0b"].concat();
608 for (path, language, len, expected) in [
609 (b"relative".as_ptr(), 1, 8, PATH),
610 (foreign.as_ptr(), 1, foreign.len() as u32, PATH),
611 (nul.as_ptr(), 1, nul.len() as u32, PATH),
612 (std::ptr::null(), 1, 1, NULL),
613 (std::ptr::null(), 1, MAX_PATH as u32 + 1, BOUNDS),
614 (std::ptr::null(), 3, 0, BAD_TAG),
615 ] {
616 assert_eq!(
617 kr_vocabulary_configure(vocabulary, language, path, len, 0),
618 expected
619 );
620 }
621 let mut path = ROOT.to_vec();
622 path.resize(MAX_PATH, b'x');
623 path[ROOT.len()] = 0xff;
624 let status = if cfg!(unix) { OK } else { PATH };
626 assert_eq!(
627 kr_vocabulary_configure(vocabulary, 1, path.as_ptr(), path.len() as u32, 0),
628 status
629 );
630 path[ROOT.len()] = b'y';
631 assert_eq!(
632 kr_vocabulary_configure(vocabulary, 1, path.as_ptr(), path.len() as u32, 0),
633 OK
634 );
635 let stored = path.clone();
636 path.fill(b'z');
637 let configured = (*vocabulary).published.lock().unwrap()[0].path.clone();
638 assert_eq!(bytes(configured.as_ref().unwrap()), stored);
639 (*vocabulary).published.lock().unwrap()[0].generation = u64::MAX;
640 let different = [ROOT, b"different"].concat();
641 assert_eq!(
642 kr_vocabulary_configure(
643 vocabulary,
644 1,
645 different.as_ptr(),
646 different.len() as u32,
647 0
648 ),
649 STATE
650 );
651 assert_eq!((*vocabulary).published.lock().unwrap()[0].path, configured);
652 assert_eq!(
653 kr_vocabulary_configure(vocabulary, 2, path.as_ptr(), 0, 0),
654 OK
655 );
656 assert_eq!(kr_adopt_vocabulary(engine, vocabulary), OK);
657 let held = keyrill_core::vocabulary::Vocabulary::parse(b"hello").unwrap();
658 (*engine).dictionaries[0] = Snapshot::from(Some(Arc::new(held)));
659 let old = (*engine).dictionaries[0].current().unwrap();
660 assert_eq!(
661 with_vocabulary(vocabulary, |vocabulary| {
662 let _guard = vocabulary.published.lock().unwrap();
663 panic!("synthetic source containment test")
664 }),
665 POISONED
666 );
667 assert_eq!(kr_adopt_vocabulary(engine, vocabulary), POISONED);
668 assert!(!(*engine).poisoned);
669 assert!(Arc::ptr_eq(
670 &old,
671 &(*engine).dictionaries[0].current().unwrap()
672 ));
673 assert_eq!(kr_reset(engine), OK);
674 (*vocabulary).poisoned.store(false, Ordering::Release);
675 assert_eq!(
676 kr_vocabulary_configure(vocabulary, 1, std::ptr::null(), 0, 0),
677 POISONED
678 );
679 assert!((*vocabulary).poisoned.load(Ordering::Acquire));
680 assert_eq!(kr_vocabulary_observe(vocabulary, 1, &mut output), POISONED);
681 assert_eq!(output, 77);
682 (*engine).poisoned = true;
683 assert_eq!(kr_adopt_vocabulary(engine, std::ptr::null()), POISONED);
684 kr_vocabulary_free(vocabulary);
685 kr_vocabulary_free(std::ptr::null_mut());
686 kr_engine_free(engine);
687
688 let mut rejected = std::ptr::dangling_mut();
689 assert_eq!(kr_vocabulary_new(ABI + 1, &mut rejected), VERSION);
690 assert!(rejected.is_null());
691 assert_eq!(kr_vocabulary_new(0x0001_0000, &mut rejected), VERSION);
692 assert!(rejected.is_null());
693 assert_eq!(kr_vocabulary_new(ABI - 1, &mut rejected), VERSION);
694 assert!(rejected.is_null());
695 }
696 }
697
698 #[test]
702 fn source_configuration_identity_missing_empty_and_last_good_are_distinct() {
703 let directory = Directory::new();
704 let en = directory.file("en.add", b"ghbdtn");
705 let next_en = directory.file("next-en.add", b"hello");
706 let ru = directory.file("ru.add", b"");
707 unsafe {
710 let (engine, vocabulary) = handles();
711 assert_eq!(kr_set_automatic_policy(engine, 2), OK);
712 configure(vocabulary, 1, &en);
713 configure(vocabulary, 2, &ru);
714 for language in [1, 2] {
715 observe(vocabulary, language, 0);
716 observe(vocabulary, language, 1);
717 observe(vocabulary, language, 2);
718 }
719 assert_eq!(kr_adopt_vocabulary(engine, vocabulary), OK);
720 let old = (*engine).dictionaries[0].current().unwrap();
721 assert!((*engine).dictionaries[1].current().unwrap().is_empty());
722 let mut isolated = std::ptr::null_mut();
723 assert_eq!(kr_vocabulary_new(ABI, &mut isolated), OK);
724 assert_eq!(kr_adopt_vocabulary(engine, isolated), OK);
725 assert!((*engine).dictionaries[0].current().is_none());
726 assert!((*engine).dictionaries[1].current().is_none());
727 assert_eq!(kr_adopt_vocabulary(engine, vocabulary), OK);
728 kr_vocabulary_free(isolated);
729 assert_eq!(
730 mark(&type_text(engine, 1, "ghbdtn ")),
731 "ghbdtn ".encode_utf16().collect::<Vec<_>>()
732 );
733 configure(vocabulary, 1, &en);
734 observe(vocabulary, 1, 2);
735 fs::write(&en, b"bad\0entry").unwrap();
736 let mut output = 77;
737 assert_eq!(
738 kr_vocabulary_observe(vocabulary, 1, &mut output),
739 DICTIONARY_DATA
740 );
741 assert_eq!(output, 77);
742 assert_eq!(kr_adopt_vocabulary(engine, vocabulary), OK);
743 assert!(Arc::ptr_eq(
744 &old,
745 &(*engine).dictionaries[0].current().unwrap()
746 ));
747 fs::remove_file(&en).unwrap();
748 assert_eq!(kr_vocabulary_observe(vocabulary, 1, &mut output), SOURCE_IO);
749 assert_eq!(output, 77);
750 configure(vocabulary, 1, &next_en);
751 assert_eq!(kr_adopt_vocabulary(engine, vocabulary), OK);
752 assert!((*engine).dictionaries[0].current().is_none());
753 assert_eq!(kr_reset(engine), OK);
754 assert_eq!(
755 mark(&type_text(engine, 1, "ghbdtn ")),
756 "ghbdtn ".encode_utf16().collect::<Vec<_>>()
757 );
758 observe(vocabulary, 1, 0);
759 observe(vocabulary, 1, 1);
760 assert_eq!(kr_adopt_vocabulary(engine, vocabulary), OK);
761 assert_eq!(kr_reset(engine), OK);
762 assert_eq!(
763 mark(&type_text(engine, 1, "ghbdtn ")),
764 "привет ".encode_utf16().collect::<Vec<_>>()
765 );
766 assert_eq!(
767 kr_vocabulary_configure(vocabulary, 2, std::ptr::null(), 0, 0),
768 OK
769 );
770 assert_eq!(kr_adopt_vocabulary(engine, vocabulary), OK);
771 assert!((*engine).dictionaries[1].current().is_none());
772 configure(vocabulary, 2, &directory.0);
773 assert_eq!(
774 kr_vocabulary_observe(vocabulary, 2, &mut output),
775 SOURCE_NOT_REGULAR
776 );
777 let large = directory.file(
778 "large.add",
779 &vec![b'x'; keyrill_core::vocabulary::MAX_SOURCE_BYTES + 1],
780 );
781 configure(vocabulary, 2, &large);
782 assert_eq!(kr_vocabulary_observe(vocabulary, 2, &mut output), BOUNDS);
783 assert_eq!(output, 77);
784 assert_eq!(kr_reset(engine), OK);
785 let event = NativeEvent {
786 role: 1,
787 mode: 1,
788 context: 0,
789 len: 1,
790 units: [97; 8],
791 };
792 let mut out = std::mem::MaybeUninit::uninit();
793 assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), OK);
794 assert_eq!(kr_commit(engine, out.assume_init_ref().plan_id, 2), OK);
795 assert_eq!(kr_adopt_vocabulary(engine, vocabulary), OK);
796 assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), STATE);
797 kr_vocabulary_free(vocabulary);
798 kr_engine_free(engine);
799 }
800 }
801
802 #[test]
806 fn source_adoption_preserves_pending_history_receipts_and_independent_engines() {
807 let directory = Directory::new();
808 let en = directory.file("en.add", b"");
809 let ru = directory.file("ru.add", b"");
810 let protected = directory.file("protected.add", b"ghbdtn");
811 unsafe {
814 let (engine, vocabulary) = handles();
815 let mut second = std::ptr::null_mut();
816 assert_eq!(kr_engine_new(ABI, &mut second), OK);
817 configure(vocabulary, 1, &en);
818 configure(vocabulary, 2, &ru);
819 for language in [1, 2] {
820 observe(vocabulary, language, 0);
821 observe(vocabulary, language, 1);
822 }
823 for handle in [engine, second] {
824 assert_eq!(kr_set_automatic_policy(handle, 2), OK);
825 assert_eq!(kr_adopt_vocabulary(handle, vocabulary), OK);
826 }
827 let original = (*engine).dictionaries[0].current().unwrap();
828 assert!(Arc::ptr_eq(
829 &original,
830 &(*second).dictionaries[0].current().unwrap()
831 ));
832 type_text(engine, 1, "hello world ");
833 let event = NativeEvent {
834 role: 1,
835 mode: 1,
836 context: 0,
837 len: 1,
838 units: [121; 8],
839 };
840 let mut out = std::mem::MaybeUninit::uninit();
841 assert_eq!(kr_plan_event(engine, &event, out.as_mut_ptr()), OK);
842 let plan: NativePlan = out.assume_init();
843 assert_eq!((plan.action, plan.disposition), (2, 2));
844 assert_eq!(kr_adopt_vocabulary(engine, vocabulary), STATE);
845 assert!(Arc::ptr_eq(
846 &original,
847 &(*engine).dictionaries[0].current().unwrap()
848 ));
849 assert_eq!(kr_commit(engine, plan.plan_id, 0), OK);
850 assert_eq!(kr_adopt_vocabulary(engine, vocabulary), OK);
851 assert_eq!(
852 mark(&type_text(engine, 1, "yfv ")),
853 "yfv ".encode_utf16().collect::<Vec<_>>()
854 );
855 assert_eq!(
856 mark(&type_text(second, 1, "yfv ")),
857 "нам ".encode_utf16().collect::<Vec<_>>()
858 );
859 assert_eq!(kr_reset(engine), OK);
860 assert_eq!(
861 mark(&type_text(engine, 1, "ghbdtn ")),
862 "привет ".encode_utf16().collect::<Vec<_>>()
863 );
864 configure(vocabulary, 1, &protected);
865 observe(vocabulary, 1, 0);
866 observe(vocabulary, 1, 1);
867 assert_eq!(kr_adopt_vocabulary(engine, vocabulary), OK);
868 let reverse = apply_event(
869 engine,
870 &NativeEvent {
871 role: 5,
872 mode: 1,
873 context: 0,
874 len: 0,
875 units: [0; 8],
876 },
877 );
878 assert_eq!(mark(&reverse), "ghbdtn ".encode_utf16().collect::<Vec<_>>());
879 assert!(Arc::ptr_eq(
880 &original,
881 &(*second).dictionaries[0].current().unwrap()
882 ));
883 assert_eq!(kr_adopt_vocabulary(second, vocabulary), OK);
884 assert!(Arc::ptr_eq(
885 &(*engine).dictionaries[0].current().unwrap(),
886 &(*second).dictionaries[0].current().unwrap()
887 ));
888 assert_eq!(kr_reset(second), OK);
889 assert_eq!(kr_set_dictionary_utf8(second, 1, std::ptr::null(), 0), OK);
890 assert_eq!(
891 mark(&type_text(second, 1, "ghbdtn ")),
892 "привет ".encode_utf16().collect::<Vec<_>>()
893 );
894 assert_eq!(kr_adopt_vocabulary(second, vocabulary), OK);
895 kr_vocabulary_free(vocabulary);
896 for handle in [engine, second] {
897 assert_eq!(kr_reset(handle), OK);
898 assert_eq!(
899 mark(&type_text(handle, 1, "ghbdtn ")),
900 "ghbdtn ".encode_utf16().collect::<Vec<_>>()
901 );
902 let units: Vec<_> = "ghbdtn".encode_utf16().collect();
903 assert_eq!(
904 (*handle).dictionaries[0].current().unwrap().lookup(&units),
905 Membership::Recognized
906 );
907 kr_engine_free(handle);
908 }
909 }
910 }
911
912 #[test]
916 fn source_observation_cannot_publish_across_configuration_or_block_adoption_on_io() {
917 let directory = Directory::new();
918 let old = directory.file("old.add", b"old");
919 let new = directory.file("new.add", b"new");
920 unsafe {
923 let (engine, vocabulary) = handles();
924 configure(vocabulary, 1, &old);
925 observe(vocabulary, 1, 0);
926 let shared = &*vocabulary;
927 let (entered_tx, entered_rx) = mpsc::channel();
928 let (release_tx, release_rx) = mpsc::channel();
929 std::thread::scope(|scope| {
930 let worker = scope.spawn(move || {
931 shared.observe(0, || {
932 entered_tx.send(()).unwrap();
933 release_rx.recv().unwrap();
934 })
935 });
936 entered_rx.recv().unwrap();
937 configure(vocabulary, 1, &new);
938 assert_eq!(kr_adopt_vocabulary(engine, vocabulary), OK);
939 assert!((*engine).dictionaries[0].current().is_none());
940 release_tx.send(()).unwrap();
941 assert_eq!(worker.join().unwrap(), Err(STALE_CONFIGURATION));
942 });
943 assert_eq!(kr_adopt_vocabulary(engine, vocabulary), OK);
944 assert!((*engine).dictionaries[0].current().is_none());
945 observe(vocabulary, 1, 0);
946 observe(vocabulary, 1, 1);
947 assert_eq!(kr_adopt_vocabulary(engine, vocabulary), OK);
948 let current = (*engine).dictionaries[0].current().unwrap();
949 assert_eq!(
950 current.lookup(&"new".encode_utf16().collect::<Vec<_>>()),
951 Membership::Recognized
952 );
953 assert_eq!(
954 current.lookup(&"old".encode_utf16().collect::<Vec<_>>()),
955 Membership::Absent
956 );
957 kr_vocabulary_free(vocabulary);
958 kr_engine_free(engine);
959 }
960 }
961
962 unsafe fn configure_flags(
963 vocabulary: *mut VocabularyHandle,
964 language: u32,
965 path: &Path,
966 flags: u32,
967 ) -> u32 {
968 let bytes = bytes(path);
969 unsafe {
971 kr_vocabulary_configure(
972 vocabulary,
973 language,
974 bytes.as_ptr(),
975 bytes.len() as u32,
976 flags,
977 )
978 }
979 }
980
981 #[test]
982 fn source_missing_is_empty_applies_only_to_absent_files_before_a_publication() {
983 let directory = Directory::new();
984 let absent = directory.0.join("absent.add");
985 let configured = directory.0.join("configured.add");
986 unsafe {
989 let (engine, vocabulary) = handles();
990 assert_eq!(kr_set_automatic_policy(engine, 2), OK);
991 let mut output = 77;
992 for flags in [2, 3, u32::MAX] {
993 assert_eq!(configure_flags(vocabulary, 1, &absent, flags), BAD_TAG);
994 }
995 assert!((*vocabulary).published.lock().unwrap()[0].path.is_none());
996
997 assert_eq!(configure_flags(vocabulary, 1, &absent, 0), OK);
999 assert_eq!(kr_vocabulary_observe(vocabulary, 1, &mut output), SOURCE_IO);
1000 assert_eq!(output, 77);
1001
1002 assert_eq!(configure_flags(vocabulary, 1, &absent, 1), OK);
1004 assert_eq!(configure_flags(vocabulary, 2, &configured, 1), OK);
1005 observe(vocabulary, 1, 1);
1006 observe(vocabulary, 1, 2);
1007 observe(vocabulary, 2, 1);
1008 assert_eq!(kr_adopt_vocabulary(engine, vocabulary), OK);
1009 assert!((*engine).dictionaries[0].current().unwrap().is_empty());
1010 assert_eq!(
1011 mark(&type_text(engine, 1, "ghbdtn ")),
1012 "привет ".encode_utf16().collect::<Vec<_>>()
1013 );
1014
1015 fs::write(&configured, b"rjn").unwrap();
1017 observe(vocabulary, 2, 0);
1018 observe(vocabulary, 2, 1);
1019 assert_eq!(kr_adopt_vocabulary(engine, vocabulary), OK);
1020 let published = (*engine).dictionaries[1].current().unwrap();
1021 assert_eq!(
1022 published.lookup(&"rjn".encode_utf16().collect::<Vec<_>>()),
1023 Membership::Recognized
1024 );
1025
1026 fs::remove_file(&configured).unwrap();
1028 assert_eq!(kr_vocabulary_observe(vocabulary, 2, &mut output), SOURCE_IO);
1029 assert_eq!(output, 77);
1030 assert_eq!(kr_adopt_vocabulary(engine, vocabulary), OK);
1031 assert!(Arc::ptr_eq(
1032 &published,
1033 &(*engine).dictionaries[1].current().unwrap()
1034 ));
1035
1036 assert_eq!(configure_flags(vocabulary, 1, &directory.0, 1), OK);
1038 assert_eq!(
1039 kr_vocabulary_observe(vocabulary, 1, &mut output),
1040 SOURCE_NOT_REGULAR
1041 );
1042 assert_eq!(kr_adopt_vocabulary(engine, vocabulary), OK);
1043 assert!((*engine).dictionaries[0].current().is_none());
1044 kr_vocabulary_free(vocabulary);
1045 kr_engine_free(engine);
1046 }
1047 }
1048
1049 unsafe fn configure_default(
1050 vocabulary: *mut VocabularyHandle,
1051 language: u32,
1052 home: &[u8],
1053 ) -> u32 {
1054 unsafe {
1056 kr_vocabulary_configure_default(vocabulary, language, home.as_ptr(), home.len() as u32)
1057 }
1058 }
1059
1060 #[cfg(not(windows))]
1061 const DEFAULT_SUFFIX: &str = "/.vim/spell/en.utf-8.add";
1062 #[cfg(windows)]
1063 const DEFAULT_SUFFIX: &str = "\\vimfiles\\spell\\en.utf-8.add";
1064
1065 #[test]
1066 fn default_home_arguments_are_checked_and_bound_the_joined_path() {
1067 unsafe {
1070 let mut vocabulary = std::ptr::null_mut();
1071 assert_eq!(kr_vocabulary_new(ABI, &mut vocabulary), OK);
1072 assert_eq!(configure_default(std::ptr::null_mut(), 1, ROOT), NULL);
1073 assert_eq!(configure_default(vocabulary, 3, ROOT), BAD_TAG);
1074 assert_eq!(configure_default(vocabulary, 1, b""), PATH);
1075 assert_eq!(configure_default(vocabulary, 1, b"home"), PATH);
1076 assert_eq!(
1077 configure_default(vocabulary, 1, &[ROOT, b"a\0b"].concat()),
1078 PATH
1079 );
1080 assert_eq!(
1081 kr_vocabulary_configure_default(vocabulary, 1, std::ptr::null(), 1),
1082 NULL
1083 );
1084 assert_eq!(
1085 kr_vocabulary_configure_default(
1086 vocabulary,
1087 1,
1088 std::ptr::null(),
1089 MAX_PATH as u32 + 1
1090 ),
1091 BOUNDS
1092 );
1093
1094 let mut home = ROOT.to_vec();
1096 home.resize(MAX_PATH - DEFAULT_SUFFIX.len() + 1, b'h');
1097 assert_eq!(configure_default(vocabulary, 1, &home), BOUNDS);
1098 assert!((*vocabulary).published.lock().unwrap()[0].path.is_none());
1099 home.pop();
1100 assert_eq!(configure_default(vocabulary, 1, &home), OK);
1101 let languages = (*vocabulary).published.lock().unwrap();
1102 let configured = bytes(languages[0].path.as_ref().unwrap());
1103 assert_eq!(configured, [&home, DEFAULT_SUFFIX.as_bytes()].concat());
1104 assert_eq!(configured.len(), MAX_PATH);
1105 assert!(languages[0].missing_is_empty);
1106 drop(languages);
1107 kr_vocabulary_free(vocabulary);
1108 }
1109 }
1110
1111 #[test]
1112 fn source_default_names_vims_spell_files_and_treats_their_absence_as_empty() {
1113 let directory = Directory::new();
1114 let home = bytes(&directory.0).to_vec();
1115 let expected = [
1116 [&home, DEFAULT_SUFFIX.as_bytes()].concat(),
1117 [&home, DEFAULT_SUFFIX.replace("en.", "ru.").as_bytes()].concat(),
1118 ];
1119 unsafe {
1122 let (engine, vocabulary) = handles();
1123 assert_eq!(kr_set_automatic_policy(engine, 2), OK);
1124 for language in [1, 2] {
1125 assert_eq!(configure_default(vocabulary, language, &home), OK);
1126 }
1127 for (index, expected) in expected.iter().enumerate() {
1128 let languages = (*vocabulary).published.lock().unwrap();
1129 assert_eq!(bytes(languages[index].path.as_ref().unwrap()), expected);
1130 }
1131
1132 observe(vocabulary, 1, 1);
1134 observe(vocabulary, 2, 1);
1135 assert_eq!(kr_adopt_vocabulary(engine, vocabulary), OK);
1136 assert_eq!(
1137 mark(&type_text(engine, 1, "ghbdtn ")),
1138 "привет ".encode_utf16().collect::<Vec<_>>()
1139 );
1140
1141 let english = Path::new(std::str::from_utf8(&expected[0]).unwrap());
1143 fs::create_dir_all(english.parent().unwrap()).unwrap();
1144 fs::write(english, b"ghbdtn\n").unwrap();
1145 observe(vocabulary, 1, 0);
1146 observe(vocabulary, 1, 1);
1147
1148 let generation = (*vocabulary).published.lock().unwrap()[0].generation;
1150 assert_eq!(configure_default(vocabulary, 1, &home), OK);
1151 assert_eq!(
1152 (*vocabulary).published.lock().unwrap()[0].generation,
1153 generation
1154 );
1155 observe(vocabulary, 1, 2);
1156 assert_eq!(kr_adopt_vocabulary(engine, vocabulary), OK);
1157 assert_eq!(kr_reset(engine), OK);
1158 assert_eq!(
1159 mark(&type_text(engine, 1, "ghbdtn ")),
1160 "ghbdtn ".encode_utf16().collect::<Vec<_>>()
1161 );
1162 kr_vocabulary_free(vocabulary);
1163 kr_engine_free(engine);
1164 }
1165 }
1166
1167 #[test]
1168 fn learned_slots_accept_only_their_tags_and_flags() {
1169 let path = [ROOT, b"learned"].concat();
1170 unsafe {
1173 let mut vocabulary = std::ptr::null_mut();
1174 assert_eq!(kr_vocabulary_new(ABI, &mut vocabulary), OK);
1175 let configure = |source, flags| {
1176 kr_vocabulary_configure(vocabulary, source, path.as_ptr(), path.len() as u32, flags)
1177 };
1178 for (source, flags, expected) in [
1179 (LEARNED - 1, 0, BAD_TAG),
1180 (LEARNED + LEARNED_SOURCES as u32, 0, BAD_TAG),
1181 (1, EXCLUDED, BAD_TAG),
1182 (LEARNED, 4, BAD_TAG),
1183 (LEARNED, MISSING_IS_EMPTY | EXCLUDED, OK),
1184 (LEARNED + 3, 0, OK),
1185 ] {
1186 assert_eq!(configure(source, flags), expected, "{source} {flags}");
1187 }
1188 assert_eq!(configure_default(vocabulary, LEARNED, ROOT), BAD_TAG);
1189 let generation =
1190 |index: usize| (*vocabulary).published.lock().unwrap()[index].generation;
1191 let first = generation(2);
1192 assert!((*vocabulary).published.lock().unwrap()[2].excluded);
1193 assert_eq!(configure(LEARNED, MISSING_IS_EMPTY | EXCLUDED), OK);
1194 assert_eq!(generation(2), first);
1195 assert_eq!(configure(LEARNED, MISSING_IS_EMPTY), OK);
1197 assert_eq!(generation(2), first + 1);
1198 assert!(!(*vocabulary).published.lock().unwrap()[2].excluded);
1199 assert!((*vocabulary).published.lock().unwrap()[0].path.is_none());
1200 kr_vocabulary_free(vocabulary);
1201 }
1202 }
1203
1204 #[test]
1205 fn source_learned_lists_protect_and_forbid_but_never_gate_correction() {
1206 let directory = Directory::new();
1207 let en = directory.file("en.add", b"");
1208 let ru = directory.file("ru.add", b"");
1209 let learned = directory.file("LocalDictionary", b"ghbdtn/!\nghbdtn\n");
1211 let mut utf16 = vec![0xff, 0xfe];
1212 utf16.extend("привет\r\n".encode_utf16().flat_map(u16::to_le_bytes));
1213 let excluded = directory.file("default.exc", &utf16);
1214 let absent = directory.0.join("absent.dic");
1215 let corrected = || "привет ".encode_utf16().collect::<Vec<_>>();
1216 let kept = || "ghbdtn ".encode_utf16().collect::<Vec<_>>();
1217 unsafe {
1220 let (engine, vocabulary) = handles();
1221 assert_eq!(kr_set_automatic_policy(engine, 2), OK);
1222 let typed = |engine| {
1223 assert_eq!(kr_adopt_vocabulary(engine, vocabulary), OK);
1224 assert_eq!(kr_reset(engine), OK);
1225 mark(&type_text(engine, 1, "ghbdtn "))
1226 };
1227 configure(vocabulary, 1, &en);
1228 configure(vocabulary, 2, &ru);
1229 for language in [1, 2] {
1230 observe(vocabulary, language, 0);
1231 observe(vocabulary, language, 1);
1232 }
1233 assert_eq!(configure_flags(vocabulary, LEARNED + 2, &absent, 0), OK);
1235 let mut output = 77;
1236 assert_eq!(
1237 kr_vocabulary_observe(vocabulary, LEARNED + 2, &mut output),
1238 SOURCE_IO
1239 );
1240 assert_eq!(typed(engine), corrected());
1241
1242 assert_eq!(configure_flags(vocabulary, LEARNED, &learned, 0), OK);
1243 observe(vocabulary, LEARNED, 0);
1244 observe(vocabulary, LEARNED, 1);
1245 assert_eq!(typed(engine), kept());
1246 assert_eq!((*engine).learned.len(), 1);
1247
1248 assert_eq!(configure_flags(vocabulary, LEARNED, Path::new(""), 0), OK);
1250 assert_eq!(typed(engine), corrected());
1251
1252 assert_eq!(
1254 configure_flags(vocabulary, LEARNED + 1, &excluded, EXCLUDED),
1255 OK
1256 );
1257 observe(vocabulary, LEARNED + 1, 0);
1258 observe(vocabulary, LEARNED + 1, 1);
1259 assert_eq!(typed(engine), kept());
1260 let units: Vec<_> = "Привет".encode_utf16().collect();
1261 assert_eq!(
1262 (&(*engine).learned)[0].lookup(&units),
1263 Membership::Forbidden
1264 );
1265 kr_vocabulary_free(vocabulary);
1266 kr_engine_free(engine);
1267 }
1268 }
1269}