Skip to main content

keyrill_ffi/
vocabulary_host.rs

1//! `kr_vocabulary`: dictionary sources that engines adopt, without scheduling or native editing
2//! authority.
3//!
4//! A vocabulary handle holds six vocabulary sources, the English and Russian Vim spell files and
5//! four learned-word slots, each with a configured path, flags, a generation and a current
6//! snapshot. Two locks keep the slow path away from the controller thread:
7//!
8//! ```text
9//!   acquisition  one Source per slot; held across file I/O by kr_vocabulary_observe
10//!   published    path, flags, generation and snapshot per slot; held briefly by configure,
11//!                adopt, and the start and end of observe
12//! ```
13//!
14//! Observe takes `acquisition` before `published` and nothing takes them in the other order, so
15//! configure and adopt never wait for a file read. A configuration change advances the slot's
16//! generation; an observation that began under the old generation finds the change when it
17//! locks `published` again and publishes nothing (`STALE_CONFIGURATION`). Adoption clones every
18//! snapshot under one lock, so an engine never pairs a language from before a change with one
19//! from after it.
20
21use 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
35// KR_MAX_PATH_BYTES and the status codes and flags of include/keyrill.h that lib.rs lacks
36const 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;
44// Two Vim languages, then the learned-word slots tagged LEARNED + n
45const 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// Vim's first 'runtimepath' entry, where `zg` creates spell files while 'spellfile' is empty
50#[cfg(not(windows))]
51const DEFAULT_DIRECTORY: &str = ".vim";
52#[cfg(windows)]
53const DEFAULT_DIRECTORY: &str = "vimfiles";
54
55// One source's configuration and published snapshot; learned slots use it too
56#[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// A reader per source, with the generation it was created for
66#[derive(Default)]
67struct Acquisition {
68    generation: [u64; SOURCES],
69    sources: [Source; SOURCES],
70}
71
72/// `kr_vocabulary`: six vocabulary sources behind two locks, shared by the acquisition queue and
73/// the controller thread. Free only after every operation has completed.
74#[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
92// Languages are Vim word lists; a learned slot is a plain list whose words are all recognized
93// or, when excluded, all forbidden
94fn 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
102// Unix paths are raw bytes; Windows paths cross the ABI as UTF-8 and are absolute only with a
103// drive or UNC prefix
104fn 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        // Free the old snapshot after unlocking, so a large vocabulary never holds the lock
157        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        // A fresh reader for a new configuration, so a candidate staged for the old path or
172        // parser never publishes under the new one
173        if acquisition.generation[index] != generation {
174            acquisition.sources[index] = Source::new(parser(index, excluded));
175            acquisition.generation[index] = generation;
176        }
177        // Lets a test reconfigure the source while this observation holds no `published` lock
178        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        // An absent file publishes empty protection only until a real file has been published:
185        // editors that save by rename can leave the path briefly absent, which must keep last-good
186        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
212// Shared references are synchronized internally; no native calls occur under either lock.
213// Any POISONED result, a caught panic or a lock poisoned by one, poisons the handle for good.
214unsafe 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    // SAFETY: non-null was checked above; the caller contract requires the live aligned
222    // allocation from kr_vocabulary_new, not yet freed and kept alive for this call. Only shared
223    // references are made, and every mutation goes through a Mutex or the atomic flag, so
224    // concurrent calls on the handle are allowed.
225    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/// Allocate an isolated source handle with no configured paths or file reads.
237///
238/// # Safety
239/// Non-null `out` must be aligned and writable for one distinct handle pointer.
240#[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    // SAFETY: `out` is non-null (checked above), and the caller guarantees it is aligned,
246    // writable for one pointer and distinct from any handle
247    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            // SAFETY: same output contract; transfer the allocation exactly once
254            unsafe { out.write(Box::into_raw(vocabulary)) };
255            OK
256        }
257        Err(_) => POISONED,
258    }
259}
260
261/// Free after all source and adoption operations have completed. Null is a no-op.
262///
263/// # Safety
264/// Non-null `pointer` must be the original live allocation, transferred exactly once, with no
265/// concurrent operation or remaining Rust borrow. Adopted engines own independent Arc references.
266#[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            // SAFETY: the caller transfers the original allocation with every operation drained
271            drop(unsafe { Box::from_raw(pointer) });
272        }));
273    }
274}
275
276/// Configure one logical source without I/O. Changed paths or flags immediately become missing.
277///
278/// `source` is a language, read as a Vim word list, or learned slot `LEARNED + n`, read as a
279/// plain word list. With `MISSING_IS_EMPTY` in `flags`, observing a path that does not exist
280/// (ENOENT) publishes an empty source until a file at that path has been published. `EXCLUDED`,
281/// for learned slots only, makes every word forbidden. Other flag bits are `BAD_TAG`.
282///
283/// # Safety
284/// `pointer` must be null or a live aligned source allocation throughout this call. For nonzero
285/// `len <= MAX_PATH`, a non-null `path` must address readable bytes not aliasing the handle.
286/// Zero/oversized/null arguments are checked without reading the path. No pointer is retained.
287#[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    // SAFETY: forward the live shared handle and bounded readable path contracts
296    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                // SAFETY: `path` is non-null and `len` nonzero and at most MAX_PATH (checked
320                // above); the caller guarantees `len` readable bytes that do not alias the handle
321                // and stay valid for this call, and they are copied into a PathBuf before it ends
322                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/// Configure one language's Vim spell file under the absolute `home` directory, without I/O:
336/// `.vim/spell` (`vimfiles\spell` on Windows) and `en.utf-8.add` or `ru.utf-8.add`. A missing
337/// file there behaves as with `MISSING_IS_EMPTY`; a joined path over `MAX_PATH` is `BOUNDS`.
338///
339/// # Safety
340/// `pointer` must be null or a live aligned source allocation throughout this call. For nonzero
341/// `len <= MAX_PATH`, a non-null `home` must address readable bytes not aliasing the handle.
342/// Zero/oversized/null arguments are checked without reading the path. No pointer is retained.
343#[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    // SAFETY: forward the live shared handle and bounded readable path contracts
351    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            // SAFETY: `home` is non-null and `len` nonzero and at most MAX_PATH (checked above);
368            // the caller guarantees `len` readable bytes that do not alias the handle and stay
369            // valid for this call, and they are copied into a PathBuf before it ends
370            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            // The home is UTF-8 on Windows, so this counts the bytes an adapter passes on every OS
379            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/// Observe on a serialized acquisition queue, outside UI/native input callbacks.
388///
389/// # Safety
390/// `pointer` must be null or a live aligned source allocation for the whole call. Non-null
391/// `observation_out` must be writable/aligned for u32 and not alias any handle or live input.
392#[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    // SAFETY: the caller keeps the handle and the distinct, aligned output alive until this call
399    // completes; `observation_out` is checked for null before the only write
400    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/// Adopt the language views and learned lists together, without changing session state or
425/// authority.
426///
427/// # Safety
428/// `engine` must be null or a live uniquely borrowed engine on its serialized thread. `pointer`
429/// must be null or a distinct live source allocation and may be concurrently observed/configured.
430/// Both allocations must remain alive until the call returns. No native callback occurs.
431#[unsafe(no_mangle)]
432pub unsafe extern "C" fn kr_adopt_vocabulary(
433    engine: *mut Engine,
434    pointer: *const VocabularyHandle,
435) -> u32 {
436    // SAFETY: both allocation contracts are forwarded; locks/borrows end before returning
437    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            // Only `published` is locked, so adoption never waits for an observation's file read
446            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        // SAFETY: both outputs are distinct live pointer-sized local objects
531        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        // SAFETY: the test retains the handle and readable distinct borrowed path for the call
543        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        // SAFETY: the handle remains live and the distinct local output is writable
560        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    // A rejected argument changes nothing; the path is copied (the caller's buffer is overwritten
574    // below); generation exhaustion refuses rather than wrapping; and a poisoned vocabulary
575    // refuses adoption without poisoning the engine
576    #[test]
577    fn path_buffers_versions_generation_exhaustion_and_poison_are_transactional() {
578        // SAFETY: all accepted pointers refer to distinct live local objects/allocations; every
579        // handle is serialized here and freed exactly once after all borrows have ended
580        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            // Each OS rejects the other's absolute form: a rooted path without a drive or UNC
602            // prefix is relative on Windows, and a drive letter is a relative name on Unix
603            #[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            // Unix passes raw bytes through; Windows requires UTF-8
625            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    // Last good after a failed reload, missing after a path change and published after two
699    // observations are different states, and automatic correction follows each. Adoption never
700    // revives a session invalidated by an unknown outcome.
701    #[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        // SAFETY: source paths/outputs are distinct live objects, handles never overlap free,
708        // and no Rust reference to the engine lives across an exported mutable call
709        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    // Adoption is refused while a plan is pending, keeps the history and receipt of the session
803    // it updates, and changes only the engine it is called on; engines keep their snapshots after
804    // the vocabulary handle is freed
805    #[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        // SAFETY: handle lifetimes are retained across all calls; local events/plans/path buffers
812        // are distinct, and engines are each uniquely accessed on this serialized test thread
813        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    // The worker stops inside an observation while holding the acquisition lock. Configure and
913    // adopt still complete on this thread, and the worker's read, left under an old generation,
914    // publishes nothing.
915    #[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        // SAFETY: scoped threads share only synchronized immutable handle references. The engine
921        // stays uniquely on this thread, and free occurs after thread join and every borrow ends.
922        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        // SAFETY: the test retains the handle and readable distinct borrowed path for the call
970        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        // SAFETY: handles and outputs are distinct live objects; the engine is used only on this
987        // thread and every handle is freed once after its last use
988        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            // Without the flag an absent file stays missing and automatic correction abstains
998            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            // Changing only the flag is a new configuration; the absent file is then empty
1003            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            // A file created later replaces the empty source through the usual settling
1016            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            // Once a file was published, its absence is an ordinary failure that keeps last-good
1027            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            // The flag doesn't excuse other errors: a directory is still not a regular file
1037            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        // SAFETY: the test retains the handle and readable distinct borrowed home for the call
1055        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        // SAFETY: every accepted pointer refers to a distinct live local allocation; the handle is
1068        // serialized here and freed once after its last use
1069        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            // The joined file name, not only the home, has to fit in MAX_PATH
1095            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        // SAFETY: handles and outputs are distinct live objects; the engine is used only on this
1120        // thread and every handle is freed once after its last use
1121        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            // Neither file exists, so both languages publish empty and correction runs
1133            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            // A file Vim creates there later replaces the empty source and protects its words
1142            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            // Repeating the default is idempotent and keeps the published file
1149            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        // SAFETY: every accepted pointer refers to a distinct live local allocation; the handle is
1171        // serialized here and freed once after its last use
1172        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            // Dropping only EXCLUDED is a new configuration of the same file
1196            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        // Vim syntax means nothing in a learned list: `ghbdtn/!` is a word, not a forbidden entry
1210        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        // SAFETY: handles and outputs are distinct live objects; the engine is used only on this
1218        // thread and every handle is freed once after its last use
1219        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            // A learned slot that never loads doesn't hold correction back
1234            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            // Unconfiguring the slot removes its words at the next adoption
1249            assert_eq!(configure_flags(vocabulary, LEARNED, Path::new(""), 0), OK);
1250            assert_eq!(typed(engine), corrected());
1251
1252            // An excluded UTF-16 list forbids the candidate
1253            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}