Skip to main content

keyrill_core/
vocabulary.rs

1//! Read-only Vim word-list parsing and immutable last-good vocabulary snapshots.
2//!
3//! A vocabulary source is the user's own word list. It marks a word as correct, recognized or
4//! rare, which protects the word when it is typed, or as wrong (forbidden): a forbidden typed
5//! word loses its protection, and a forbidden candidate is never written automatically. A source
6//! carries no frequency, so membership can stop a correction but never justify one.
7//!
8//! [`Vocabulary::parse`] reads a Vim `.add` list line by line, as Vim reads its `spellfile`;
9//! [`Vocabulary::parse_words`] reads the words a user taught the OS spell checker, one per line.
10//! An entry's form decides which cases of the word it matches:
11//!
12//! ```text
13//! entry         rule              matches              does not match
14//! hello         lowercase         hello Hello HELLO    hElLo
15//! iPhone        cased             iPhone IPHONE        iphone Iphone
16//! Exact/=       exact (`=`)       Exact                exact EXACT
17//! ```
18//!
19//! Across the entries that match a word, forbidden (`!`) wins, then recognized, then rare (`?`).
20//! A source is parsed whole before anything sees it: a bad line is skipped and counted, and a
21//! file that cannot be a word list is rejected with a [`ParseError`]. A [`Snapshot`] publishes
22//! only a successful parse, as one immutable [`Arc`], so a reader keeps the vocabulary it
23//! started with and a failed candidate leaves the last good one in place.
24
25use std::collections::HashMap;
26use std::sync::Arc;
27
28/// Largest source, in bytes, that either parser accepts.
29pub const MAX_SOURCE_BYTES: usize = 1024 * 1024;
30
31/// Personal vocabulary membership, without invented corpus frequency.
32#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub enum Membership {
34    /// No matching case-aware entry.
35    Absent,
36    /// Correct word; protects the typed word.
37    Recognized,
38    /// Correct but rare word (`?` in Vim); protects the typed word like [`Self::Recognized`].
39    Rare,
40    /// Wrong word (`!` in Vim); overrides other matching entries.
41    Forbidden,
42}
43
44/// Content-free whole-candidate rejection; a failed parse never publishes a partial list.
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub enum ParseError {
47    /// The source is larger than [`MAX_SOURCE_BYTES`].
48    TooLarge,
49    /// NUL is not a word-list character; it marks a binary, UTF-16 or partly written file.
50    Nul,
51    /// A leading `/encoding=` names an encoding other than UTF-8, or a byte-order mark names one
52    /// other than UTF-8 or UTF-16 LE.
53    Encoding,
54}
55
56impl std::fmt::Display for ParseError {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        f.write_str(match self {
59            Self::TooLarge => "word list exceeds 1 MiB",
60            Self::Nul => "word list contains NUL",
61            Self::Encoding => "unsupported word-list encoding",
62        })
63    }
64}
65
66impl std::error::Error for ParseError {}
67
68/// Which cases of an entry match, from the entry's own form.
69#[derive(Clone, Copy)]
70enum CaseRule {
71    /// A lowercase entry: lowercase, initial capital or all capitals.
72    Lower,
73    /// An entry with a capital: exactly as written or all capitals.
74    ExactOrUpper,
75    /// An entry with `=`: exactly as written.
76    Exact,
77}
78
79struct Entry {
80    word: Vec<u16>,
81    uppercase: Vec<u16>,
82    case: CaseRule,
83    membership: Membership,
84}
85
86/// Parsed personal entries. Region declarations and flags are validated but not kept, so lookup
87/// is locale-neutral. Entries are grouped by lowercase form, so a lookup compares case rules
88/// within one group.
89#[derive(Default)]
90pub struct Vocabulary {
91    entries: HashMap<Vec<u16>, Vec<Entry>>,
92    count: usize,
93    skipped: usize,
94}
95
96/// Lowercase the EN/RU letters and keep every other UTF-16 unit; no locale or Unicode case
97/// mapping is applied.
98pub fn lowercase(units: &[u16]) -> Vec<u16> {
99    units
100        .iter()
101        .map(|&u| match u {
102            0x41..=0x5a | 0x410..=0x42f => u + 32,
103            0x401 => 0x451,
104            _ => u,
105        })
106        .collect()
107}
108
109/// Uppercase the EN/RU letters and keep every other UTF-16 unit; no locale or Unicode case
110/// mapping is applied.
111pub fn uppercase(units: &[u16]) -> Vec<u16> {
112    units
113        .iter()
114        .map(|&u| match u {
115            0x61..=0x7a | 0x430..=0x44f => u - 32,
116            0x451 => 0x401,
117            _ => u,
118        })
119        .collect()
120}
121
122impl Vocabulary {
123    /// Parse a Vim word list line by line, including BOM, CRLF, case and forbidden flags.
124    ///
125    /// A line whose first byte is `#` is a comment whatever follows it, because Vim's `zw`, `zug`
126    /// and `zuw` comment out an entry by overwriting its first byte. A line that isn't UTF-8, an
127    /// unknown `/` directive, an unsupported flag or another invalid line is skipped and counted
128    /// in [`Vocabulary::skipped`].
129    ///
130    /// ```
131    /// use keyrill_core::vocabulary::{Membership, Vocabulary};
132    ///
133    /// # fn main() -> Result<(), keyrill_core::vocabulary::ParseError> {
134    /// let words = Vocabulary::parse("# personal\nrustc\nNeovim/=\nteh/!\nbad/*\n".as_bytes())?;
135    /// let units = |s: &str| s.encode_utf16().collect::<Vec<u16>>();
136    /// assert_eq!(words.lookup(&units("RUSTC")), Membership::Recognized);
137    /// assert_eq!(words.lookup(&units("neovim")), Membership::Absent);
138    /// assert_eq!(words.lookup(&units("teh")), Membership::Forbidden);
139    /// assert_eq!((words.len(), words.skipped()), (3, 1));
140    /// # Ok(())
141    /// # }
142    /// ```
143    ///
144    /// # Errors
145    ///
146    /// A [`ParseError`] for oversized input, NUL anywhere or a leading non-UTF-8 `/encoding=`;
147    /// nothing is partially kept.
148    pub fn parse(source: &[u8]) -> Result<Self, ParseError> {
149        if source.len() > MAX_SOURCE_BYTES {
150            return Err(ParseError::TooLarge);
151        }
152        if source.contains(&0) {
153            return Err(ParseError::Nul);
154        }
155        let source = source.strip_prefix("\u{feff}".as_bytes()).unwrap_or(source);
156        let mut result = Self::default();
157        'lines: for line in source.split(|&byte| byte == b'\n') {
158            // Checked before decoding: a Vim comment-out overwrites the first byte of the line,
159            // which leaves a Cyrillic word that follows invalid UTF-8
160            if line.first() == Some(&b'#') {
161                continue;
162            }
163            let Ok(line) = std::str::from_utf8(line) else {
164                result.skipped += 1;
165                continue;
166            };
167            // Also drops the CR of CRLF and Unicode whitespace such as NBSP at the edges
168            let line = line.trim();
169            if line.is_empty() || line.starts_with('#') {
170                continue;
171            }
172            if let Some(encoding) = line.strip_prefix("/encoding=") {
173                if result.count != 0 {
174                    // Vim ignores a declaration after the first word
175                    result.skipped += 1;
176                } else if encoding != "utf-8" {
177                    return Err(ParseError::Encoding);
178                }
179                continue;
180            }
181            // Up to nine distinct two-letter region names; validated, then dropped
182            if let Some(regions) = line.strip_prefix("/regions=") {
183                if regions.is_empty()
184                    || regions.len() > 18
185                    || !regions.len().is_multiple_of(2)
186                    || !regions.bytes().all(|b| b.is_ascii_alphabetic())
187                {
188                    result.skipped += 1;
189                    continue;
190                }
191                let mut names = Vec::new();
192                for pair in regions.as_bytes().as_chunks::<2>().0 {
193                    if names.contains(&pair) {
194                        result.skipped += 1;
195                        continue 'lines;
196                    }
197                    names.push(pair);
198                }
199                continue;
200            }
201            let (word, flags) = line.split_once('/').unwrap_or((line, ""));
202            if word.is_empty() || word.chars().any(char::is_control) {
203                result.skipped += 1;
204                continue;
205            }
206            let mut membership = Membership::Recognized;
207            let mut exact = false;
208            // `?` never weakens an earlier `!`; region digits are accepted and dropped
209            for flag in flags.chars() {
210                match flag {
211                    '=' => exact = true,
212                    '?' if membership != Membership::Forbidden => membership = Membership::Rare,
213                    '?' | '1'..='9' => (),
214                    '!' => membership = Membership::Forbidden,
215                    _ => {
216                        result.skipped += 1;
217                        continue 'lines;
218                    }
219                }
220            }
221            result.push(word, membership, exact);
222        }
223        Ok(result)
224    }
225
226    /// Parse a plain word list, one word per line, as OS spell checkers keep learned words: UTF-8
227    /// with an optional BOM, or UTF-16 LE with its BOM. Every word gets `membership` and the case
228    /// rule of an unflagged Vim entry; `#` and `/` are ordinary characters. A line that doesn't
229    /// decode or holds a control character is skipped and counted.
230    ///
231    /// ```
232    /// use keyrill_core::vocabulary::{Membership, Vocabulary};
233    ///
234    /// # fn main() -> Result<(), keyrill_core::vocabulary::ParseError> {
235    /// let units = |s: &str| s.encode_utf16().collect::<Vec<u16>>();
236    /// let learned = Vocabulary::parse_words(b"km/h\r\nrustc\n", Membership::Recognized)?;
237    /// assert_eq!(learned.lookup(&units("km/h")), Membership::Recognized);
238    /// assert_eq!(learned.lookup(&units("Rustc")), Membership::Recognized);
239    ///
240    /// let mut utf16 = vec![0xff, 0xfe];
241    /// utf16.extend("teh\r\n".encode_utf16().flat_map(u16::to_le_bytes));
242    /// let excluded = Vocabulary::parse_words(&utf16, Membership::Forbidden)?;
243    /// assert_eq!(excluded.lookup(&units("teh")), Membership::Forbidden);
244    /// # Ok(())
245    /// # }
246    /// ```
247    ///
248    /// # Errors
249    ///
250    /// A [`ParseError`] for oversized input, NUL anywhere, a UTF-16 LE source of odd length or a
251    /// big-endian UTF-16 BOM; nothing is partially kept.
252    pub fn parse_words(source: &[u8], membership: Membership) -> Result<Self, ParseError> {
253        if source.len() > MAX_SOURCE_BYTES {
254            return Err(ParseError::TooLarge);
255        }
256        if source.starts_with(&[0xfe, 0xff]) {
257            return Err(ParseError::Encoding);
258        }
259        let mut result = Self::default();
260        // In either encoding a NUL rejects the whole source, while a line that does not decode,
261        // such as one with a lone surrogate, is skipped alone
262        if let Some(utf16) = source.strip_prefix(&[0xff, 0xfe]) {
263            let (units, rest) = utf16.as_chunks::<2>();
264            if !rest.is_empty() {
265                return Err(ParseError::Encoding);
266            }
267            let units: Vec<u16> = units.iter().map(|&pair| u16::from_le_bytes(pair)).collect();
268            if units.contains(&0) {
269                return Err(ParseError::Nul);
270            }
271            for line in units.split(|&unit| unit == u16::from(b'\n')) {
272                match String::from_utf16(line) {
273                    Ok(line) => result.push_word(&line, membership),
274                    Err(_) => result.skipped += 1,
275                }
276            }
277            return Ok(result);
278        }
279        if source.contains(&0) {
280            return Err(ParseError::Nul);
281        }
282        let source = source.strip_prefix("\u{feff}".as_bytes()).unwrap_or(source);
283        for line in source.split(|&byte| byte == b'\n') {
284            match std::str::from_utf8(line) {
285                Ok(line) => result.push_word(line, membership),
286                Err(_) => result.skipped += 1,
287            }
288        }
289        Ok(result)
290    }
291
292    fn push_word(&mut self, line: &str, membership: Membership) {
293        let word = line.trim();
294        if word.is_empty() {
295            return;
296        }
297        if word.chars().any(char::is_control) {
298            self.skipped += 1;
299            return;
300        }
301        self.push(word, membership, false);
302    }
303
304    fn push(&mut self, word: &str, membership: Membership, exact: bool) {
305        let word: Vec<_> = word.encode_utf16().collect();
306        let lower = lowercase(&word);
307        let case = if exact {
308            CaseRule::Exact
309        } else if word == lower {
310            CaseRule::Lower
311        } else {
312            CaseRule::ExactOrUpper
313        };
314        let entry = Entry {
315            uppercase: uppercase(&word),
316            word,
317            case,
318            membership,
319        };
320        self.entries.entry(lower).or_default().push(entry);
321        self.count += 1;
322    }
323
324    /// Number of accepted entries; a word declared twice counts twice.
325    pub fn len(&self) -> usize {
326        self.count
327    }
328
329    /// Whether a valid source explicitly contains no entries.
330    pub fn is_empty(&self) -> bool {
331        self.count == 0
332    }
333
334    /// Number of skipped lines that weren't comments, blank or accepted entries and directives.
335    pub fn skipped(&self) -> usize {
336        self.skipped
337    }
338
339    /// Membership of `word` under the case rule of each entry that matches it; across matching
340    /// entries, forbidden wins, then recognized, then rare.
341    pub fn lookup(&self, word: &[u16]) -> Membership {
342        let lower = lowercase(word);
343        let Some(entries) = self.entries.get(&lower) else {
344            return Membership::Absent;
345        };
346        let mut result = Membership::Absent;
347        for entry in entries {
348            let matched = match entry.case {
349                CaseRule::Exact => word == entry.word,
350                CaseRule::ExactOrUpper => word == entry.word || word == entry.uppercase,
351                CaseRule::Lower => {
352                    word == entry.word
353                        || word == entry.uppercase
354                        || (word.first() == entry.uppercase.first()
355                            && word.get(1..) == entry.word.get(1..))
356                }
357            };
358            if matched {
359                result = match (result, entry.membership) {
360                    (Membership::Forbidden, _) | (_, Membership::Forbidden) => {
361                        Membership::Forbidden
362                    }
363                    (Membership::Recognized, _) | (_, Membership::Recognized) => {
364                        Membership::Recognized
365                    }
366                    _ => Membership::Rare,
367                };
368            }
369        }
370        result
371    }
372}
373
374/// Atomically replaceable immutable vocabulary, initially missing rather than silently empty.
375#[derive(Default)]
376pub struct Snapshot {
377    current: Option<Arc<Vocabulary>>,
378}
379
380impl From<Option<Arc<Vocabulary>>> for Snapshot {
381    fn from(current: Option<Arc<Vocabulary>>) -> Self {
382        Self { current }
383    }
384}
385
386impl Snapshot {
387    /// Clone the current immutable snapshot; absence keeps automatic policy unready.
388    pub fn current(&self) -> Option<Arc<Vocabulary>> {
389        self.current.clone()
390    }
391
392    /// Parse `source` as a Vim word list and publish it whole; a candidate with skipped lines is
393    /// still published. Readers that cloned the previous snapshot keep it unchanged.
394    ///
395    /// # Errors
396    ///
397    /// The candidate's [`ParseError`]; the current snapshot is left unchanged.
398    pub fn replace(&mut self, source: &[u8]) -> Result<(), ParseError> {
399        let candidate = Vocabulary::parse(source)?;
400        self.current = Some(Arc::new(candidate));
401        Ok(())
402    }
403}
404
405#[cfg(test)]
406mod tests {
407    use super::*;
408    fn word(s: &str) -> Vec<u16> {
409        s.encode_utf16().collect()
410    }
411
412    fn utf16le(text: &str) -> Vec<u8> {
413        let mut bytes = vec![0xff, 0xfe];
414        bytes.extend(text.encode_utf16().flat_map(u16::to_le_bytes));
415        bytes
416    }
417
418    #[test]
419    fn plain_word_lists_take_every_line_literally_in_utf8_and_utf16() {
420        let text = "#hashtag\r\n/usr\r\n\r\nw/o\r\niPhone\r\nпривет\r\nbad\u{7}word\r\n𝔘nicode\r\n";
421        let utf8 = [b"\xef\xbb\xbf".as_slice(), text.as_bytes()].concat();
422        for source in [utf8, utf16le(text)] {
423            let v = Vocabulary::parse_words(&source, Membership::Recognized).unwrap();
424            assert_eq!((v.len(), v.skipped()), (6, 1));
425            for s in [
426                "#hashtag",
427                "/usr",
428                "w/o",
429                "iPhone",
430                "IPHONE",
431                "Привет",
432                "𝔘nicode",
433            ] {
434                assert_eq!(v.lookup(&word(s)), Membership::Recognized, "{s}");
435            }
436            assert_eq!(v.lookup(&word("iphone")), Membership::Absent);
437            assert_eq!(v.lookup(&word("w")), Membership::Absent);
438        }
439        let excluded = Vocabulary::parse_words(&utf16le("teh"), Membership::Forbidden).unwrap();
440        assert_eq!(excluded.lookup(&word("Teh")), Membership::Forbidden);
441    }
442
443    #[test]
444    fn plain_word_lists_reject_whole_sources_and_skip_undecodable_lines() {
445        let mut lone = utf16le("ok\n");
446        lone.extend([0x00, 0xd8, b'\n', 0x00]);
447        let v = Vocabulary::parse_words(&lone, Membership::Recognized).unwrap();
448        assert_eq!((v.len(), v.skipped()), (1, 1));
449        let v = Vocabulary::parse_words(b"ok\n\xff\xfe\xfd\n", Membership::Recognized);
450        assert_eq!(v.map(|v| (v.len(), v.skipped())), Ok((1, 1)));
451        let mut odd = utf16le("ok");
452        odd.push(b'x');
453        let big_endian = [0xfe, 0xff, 0x00, b'o'];
454        let mut too_large = utf16le("");
455        too_large.resize(MAX_SOURCE_BYTES + 1, b'a');
456        for (source, error) in [
457            (odd.as_slice(), ParseError::Encoding),
458            (&big_endian, ParseError::Encoding),
459            (&utf16le("a\0b"), ParseError::Nul),
460            (b"a\0b", ParseError::Nul),
461            (&too_large, ParseError::TooLarge),
462        ] {
463            assert_eq!(
464                Vocabulary::parse_words(source, Membership::Recognized).err(),
465                Some(error)
466            );
467        }
468    }
469
470    #[test]
471    fn case_flags_and_duplicates_are_preserved() {
472        let v = Vocabulary::parse(b"/regions=usgb\nhello/?1\nhello/2\niPhone\nExact/=\nbad/?!\n")
473            .unwrap();
474        assert_eq!(v.len(), 5);
475        for s in ["hello", "Hello", "HELLO"] {
476            assert_eq!(v.lookup(&word(s)), Membership::Recognized);
477        }
478        assert_eq!(v.lookup(&word("hElLo")), Membership::Absent);
479        assert_eq!(v.lookup(&word("iphone")), Membership::Absent);
480        assert_eq!(v.lookup(&word("iPhone")), Membership::Recognized);
481        assert_eq!(v.lookup(&word("IPHONE")), Membership::Recognized);
482        assert_eq!(v.lookup(&word("Exact")), Membership::Recognized);
483        assert_eq!(v.lookup(&word("EXACT")), Membership::Absent);
484        assert_eq!(v.lookup(&word("Bad")), Membership::Forbidden);
485    }
486
487    #[test]
488    fn invalid_candidates_never_replace_last_good_or_mutate_existing_readers() {
489        let mut s = Snapshot::default();
490        assert!(s.current().is_none());
491        s.replace(b"old\n").unwrap();
492        let old = s.current().unwrap();
493        for (bytes, expected) in [
494            (b"new\na\0b".as_slice(), ParseError::Nul),
495            (b"# \0".as_slice(), ParseError::Nul),
496            (b"/encoding=latin1\nnew".as_slice(), ParseError::Encoding),
497            (b"# head\n/encoding=UTF-8".as_slice(), ParseError::Encoding),
498        ] {
499            assert_eq!(s.replace(bytes), Err(expected));
500            assert!(Arc::ptr_eq(&old, &s.current().unwrap()));
501        }
502        assert_eq!(
503            s.replace(&vec![b'a'; MAX_SOURCE_BYTES + 1]),
504            Err(ParseError::TooLarge)
505        );
506        s.replace(b"new").unwrap();
507        assert_eq!(old.lookup(&word("old")), Membership::Recognized);
508        assert_eq!(
509            s.current().unwrap().lookup(&word("old")),
510            Membership::Absent
511        );
512        s.replace(b"").unwrap();
513        assert!(s.current().unwrap().is_empty());
514    }
515
516    #[test]
517    fn vim_commented_out_cyrillic_entry_keeps_the_rest_of_the_file() {
518        // zug, zw and zuw overwrite the first byte of the entry's line with '#'
519        let mut removed = "привет/!".as_bytes().to_vec();
520        removed[0] = b'#';
521        assert!(std::str::from_utf8(&removed).is_err());
522        let mut source = "ёж\r\n".as_bytes().to_vec();
523        source.extend_from_slice(&removed);
524        source.extend_from_slice("\r\nПривет\nмир/?\n".as_bytes());
525        let v = Vocabulary::parse(&source).unwrap();
526        assert_eq!((v.len(), v.skipped()), (3, 0));
527        assert_eq!(v.lookup(&word("ЁЖ")), Membership::Recognized);
528        assert_eq!(v.lookup(&word("Привет")), Membership::Recognized);
529        assert_eq!(v.lookup(&word("привет")), Membership::Absent);
530        assert_eq!(v.lookup(&word("Мир")), Membership::Rare);
531    }
532
533    #[test]
534    fn invalid_lines_are_skipped_and_counted_without_dropping_entries() {
535        let source = b"/encoding=utf-8\nkeep\n/unknown\nbad/*\nTCP\\/IP\nzap/!x\n\xd0\n\
536            /regions=usus\n/regions=u\n/\nhello\rworld\n/encoding=utf-8\n/encoding=latin1\n\
537            \xff# indented\nlast/!";
538        let v = Vocabulary::parse(source).unwrap();
539        assert_eq!((v.len(), v.skipped()), (2, 12));
540        assert_eq!(v.lookup(&word("keep")), Membership::Recognized);
541        assert_eq!(v.lookup(&word("last")), Membership::Forbidden);
542        for absent in ["bad", "TCP\\", "TCP\\/IP", "TCP/IP", "zap", "hello"] {
543            assert_eq!(v.lookup(&word(absent)), Membership::Absent, "{absent}");
544        }
545        let v = Vocabulary::parse(b"\xff\n").unwrap();
546        assert!(v.is_empty());
547        assert_eq!(v.skipped(), 1);
548    }
549
550    #[test]
551    fn bom_crlf_russian_case_and_unknown_units() {
552        let v = Vocabulary::parse("\u{feff}/encoding=utf-8\r\nёж/?\r\n".as_bytes()).unwrap();
553        for s in ["ёж", "Ёж", "ЁЖ"] {
554            assert_eq!(v.lookup(&word(s)), Membership::Rare);
555        }
556        assert_eq!(v.lookup(&[0xd800]), Membership::Absent);
557        assert_eq!(lowercase(&[0x401, 0xd800]), [0x451, 0xd800]);
558        assert_eq!(uppercase(&[0x451, 0xdc00]), [0x401, 0xdc00]);
559    }
560
561    #[test]
562    fn cross_case_precedence_and_supported_text_edges() {
563        let v = Vocabulary::parse(b"Hello/!\nhello\n").unwrap();
564        for text in ["Hello", "HELLO"] {
565            assert_eq!(v.lookup(&word(text)), Membership::Forbidden);
566        }
567        assert_eq!(v.lookup(&word("hello")), Membership::Recognized);
568        assert_eq!(v.skipped(), 0);
569        let v = Vocabulary::parse("\u{a0}hello\u{a0}\n/regions=usgb\nMac/9".as_bytes()).unwrap();
570        assert_eq!(v.lookup(&word("hello")), Membership::Recognized);
571        assert_eq!(v.lookup(&word("Mac")), Membership::Recognized);
572    }
573}