Skip to main content

keyrill_core/
inference.rs

1//! Whether a complete word was typed in the wrong layout, and what it should read instead.
2//!
3//! [`infer`] compares two readings of one key sequence: the word as typed, in the language of the
4//! active input mode (the source), and the same keys read in the other layout (the candidate). A
5//! false change rewrites a word the user typed correctly, and that costs far more than a missed
6//! correction, so abstention is the default. Each step in the table either ends the decision or
7//! passes it on, and all but two of them can only abstain.
8//!
9//! ```text
10//! step, in order                                                 result
11//! -------------------------------------------------------------  ------------------------
12//! manual or reversal intent at this boundary                     7 ExplicitIntent
13//! no mode, over 32 units, no letters or letters outside the
14//!   mode's script, invalid policy, mixed case or a multi-letter
15//!   capital word                                                 1 Ineligible
16//! the English or the Russian Vim source is missing               6 DictionariesMissing
17//! word or core recognized or rare in a vocabulary source         2 Personal
18//! core in the source lexicon and not yielding                    3 Known
19//! candidate not all in the target script                         1 Ineligible
20//! candidate forbidden in a vocabulary source                     4 Forbidden
21//! candidate not in the target lexicon, or below minimum Zipf     5 Weak
22//! core in the source lexicon and yielding                        0 Correction, Zipf margin
23//! score below log10(cost) + length penalty                       5 Weak, with the score
24//! otherwise                                                      0 Correction, with the score
25//! ```
26//!
27//! Frequencies are compared on the Zipf scale, log10 of occurrences per billion words, which is
28//! the stored log10 frequency plus 9. The score of the last two steps is a log10 odds:
29//!
30//! ```text
31//! score = log10 f(candidate) - log10 P(letters) + provisional penalties
32//!       + log10(prior / (1 - prior)) + log10(context factor)
33//! ```
34//!
35//! Here `f` is the candidate's corpus frequency in the target lexicon and `P` the source
36//! language's character chain over the typed letters. The context factor is 19 when the
37//! session's recent words are in the target language, 1/19 when they are in the source language
38//! and 1 without context. The score must reach log10 of the false-correction cost, plus 4, 2 or
39//! 1 for a word of one, two or three units. The prior, the cost and the penalties are ranking
40//! parameters, not calibrated probabilities; the policy is evaluated on pinned corpora
41//! (`docs/engine.md`).
42//!
43//! A typed string that is itself a word of the source lexicon is protected by that alone, and
44//! the chain is never consulted for it. It yields only when it is rare (Zipf below
45//! [`Policy::known_ceiling`]) and the candidate is more frequent by a wide margin; the decision
46//! then rests on that frequency ratio, and the margin is its score. A word of one unit never
47//! yields.
48//!
49//! In English mode the keys `[ ] ; ' , .` and the ё key type punctuation, but in Russian they
50//! type letters, so they are provisional: they can start or continue a word (see
51//! [`is_provisional`]). For such a word the candidate is the whole key sequence read in Russian,
52//! and the source reading is the letters alone, with a penalty per provisional unit for how
53//! rarely English words carry that punctuation in that position. The core is the word up to its
54//! last letter. Only when every provisional unit trails, as in `it.`, is the core all letters,
55//! and only then can lexicon protection apply.
56//! A three-unit provisional word whose candidate has Zipf at least 4 gets another 3 log10 units
57//! of evidence per leading provisional unit, unless context supports the source language.
58
59use crate::mapping::{self, Keyboard, Mapping};
60use crate::model::{MAX_MODEL_WORD, Model};
61use crate::session::Mode;
62use crate::vocabulary::{self, Membership, Vocabulary};
63use std::sync::Arc;
64
65/// Reference scoring parameters. These are ranking hypotheses, not calibrated probabilities.
66/// Zipf values are log10 occurrences per billion words.
67#[derive(Clone, Copy, Debug)]
68pub struct Policy {
69    /// Assumed layout-error prior, strictly between zero and one; the score adds its log10 odds.
70    pub error_prior: f64,
71    /// Cost of a false automatic change, positive and finite; the score must reach its log10.
72    pub false_correction_cost: f64,
73    /// Minimum candidate corpus Zipf score, finite and in 0..=9.
74    pub minimum_zipf: f64,
75    /// A known source word yields to the other reading only below this Zipf score, in 0..=9.
76    pub known_ceiling: f64,
77    /// Zipf margin by which the other reading must exceed a yielding known word, in 0..=9.
78    pub known_margin: f64,
79    /// Margin for a known word of two units without target-language context, in 0..=9.
80    pub short_known_margin: f64,
81}
82
83impl Default for Policy {
84    fn default() -> Self {
85        Self {
86            error_prior: 0.001,
87            false_correction_cost: 100.0,
88            minimum_zipf: 2.5,
89            known_ceiling: 3.0,
90            known_margin: 2.5,
91            short_known_margin: 3.5,
92        }
93    }
94}
95
96impl Policy {
97    /// Whether all numeric policy values are finite and in their supported domains.
98    pub fn is_valid(&self) -> bool {
99        self.error_prior.is_finite()
100            && self.error_prior > 0.0
101            && self.error_prior < 1.0
102            && self.false_correction_cost.is_finite()
103            && self.false_correction_cost > 0.0
104            && [
105                self.minimum_zipf,
106                self.known_ceiling,
107                self.known_margin,
108                self.short_known_margin,
109            ]
110            .iter()
111            .all(|value| (0.0..=9.0).contains(value))
112    }
113}
114
115/// Ready protection sources. `None` means missing; an explicitly empty vocabulary is ready.
116///
117/// Every source is consulted for every word, whatever its language: the English source can
118/// protect a Russian word. The split names the two Vim files whose readiness gates correction.
119#[derive(Clone, Copy, Default)]
120pub struct Dictionaries<'a> {
121    /// English Vim vocabulary source.
122    pub en: Option<&'a Vocabulary>,
123    /// Russian Vim vocabulary source.
124    pub ru: Option<&'a Vocabulary>,
125    /// Words learned through the OS spell checker. They protect and forbid like the personal
126    /// sources, but readiness never waits for them.
127    pub learned: &'a [Arc<Vocabulary>],
128}
129
130/// One word to decide. The caller establishes that the word is complete and owned; [`infer`]
131/// still checks its length, script and case.
132#[derive(Clone, Copy)]
133pub struct Request<'a> {
134    /// Complete word, without delimiter or normalization.
135    pub word: &'a [u16],
136    /// Input mode the word was typed in; `None`, an unknown mode, is ineligible.
137    pub active: Option<Mode>,
138    /// Language of the recent finished words, from [`detect_context`], if known.
139    pub context: Option<Mode>,
140    /// Russian layout variant, which places the ё key.
141    pub keyboard: Keyboard,
142    /// An explicit manual/reversal choice forbids reinference at this boundary.
143    pub explicit_intent: bool,
144}
145
146/// Decision reasons, numbered as in the reference vectors and the probe output.
147#[derive(Clone, Copy, Debug, PartialEq, Eq)]
148#[repr(u8)]
149pub enum Reason {
150    /// Candidate passed the reference ranking threshold.
151    Correction = 0,
152    /// Token, mode, case or policy is ineligible.
153    Ineligible = 1,
154    /// The typed word, or its core, is recognized or rare in a vocabulary source.
155    Personal = 2,
156    /// The core is a word of the source lexicon and does not yield.
157    Known = 3,
158    /// The candidate is forbidden in a vocabulary source.
159    Forbidden = 4,
160    /// The candidate is absent from the target lexicon, below the minimum Zipf score, or its
161    /// score is below the length-adjusted threshold.
162    Weak = 5,
163    /// The English or the Russian Vim source is missing; learned words do not count.
164    DictionariesMissing = 6,
165    /// Preserve explicit manual/reversal intent.
166    ExplicitIntent = 7,
167}
168
169/// A correction proposal; never grants native write authority.
170#[derive(Clone, Debug)]
171pub struct Decision {
172    /// Why the word is corrected or left as typed.
173    pub reason: Reason,
174    /// The log10 score of the final comparison, or the Zipf margin of a yielding known word;
175    /// zero when the decision ended before either.
176    pub score: f64,
177    /// The candidate, present only with [`Reason::Correction`]. The map converts key by key, so
178    /// shifted keys stay capitals.
179    pub replacement: Option<Vec<u16>>,
180}
181
182impl Decision {
183    fn abstain(reason: Reason) -> Self {
184        Self {
185            reason,
186            score: 0.0,
187            replacement: None,
188        }
189    }
190}
191
192/// The one script all units of `word` belong to, or `None` for an empty or mixed word.
193fn script(word: &[u16]) -> Option<Mode> {
194    if word.is_empty() {
195        return None;
196    }
197    if word.iter().all(|&u| matches!(u, 0x41..=0x5a | 0x61..=0x7a)) {
198        return Some(Mode::En);
199    }
200    if word
201        .iter()
202        .all(|&u| matches!(u, 0x410..=0x44f | 0x401 | 0x451))
203    {
204        return Some(Mode::Ru);
205    }
206    None
207}
208
209// log10 of the per-word rate of punctuation from these keys before, inside and after the letters
210// of English words, measured on the UD English EWT dev split
211const PROVISIONAL_LOG10: [f64; 3] = [-2.3, -1.6, -1.0];
212
213/// Whether `unit` is typed in English mode by a key that types a Russian letter: `[ ] ; ' , .`,
214/// the ё key of `keyboard` and their shifted forms. In English mode such a unit can start or
215/// continue a word, which keeps its typed form unless the whole word reads as Russian.
216pub fn is_provisional(unit: u16, keyboard: Keyboard) -> bool {
217    let yo: &[u8] = match keyboard {
218        Keyboard::Apple => b"\\|",
219        Keyboard::Pc => b"`~",
220    };
221    u8::try_from(unit).is_ok_and(|byte| b"[];',.{}:\"<>".contains(&byte) || yo.contains(&byte))
222}
223
224/// Membership across all sources, with the precedence a single source applies to its own
225/// entries: forbidden, then recognized, then rare.
226fn membership(dictionaries: Dictionaries<'_>, word: &[u16]) -> Membership {
227    let learned = dictionaries.learned.iter().map(|v| v.lookup(word));
228    [dictionaries.en, dictionaries.ru]
229        .into_iter()
230        .map(|v| v.map_or(Membership::Absent, |v| v.lookup(word)))
231        .chain(learned)
232        .fold(Membership::Absent, |result, next| match (result, next) {
233            (Membership::Forbidden, _) | (_, Membership::Forbidden) => Membership::Forbidden,
234            (Membership::Recognized, _) | (_, Membership::Recognized) => Membership::Recognized,
235            (Membership::Rare, _) | (_, Membership::Rare) => Membership::Rare,
236            _ => Membership::Absent,
237        })
238}
239
240/// Decide one word under `policy`, following the steps in the [module
241/// docs](crate::inference). The result is a proposal only: the caller still controls every
242/// native effect.
243///
244/// ```
245/// use keyrill_core::inference::{infer, Dictionaries, Policy, Reason, Request};
246/// use keyrill_core::mapping::Keyboard;
247/// use keyrill_core::model::Model;
248/// use keyrill_core::session::Mode;
249/// use keyrill_core::vocabulary::Vocabulary;
250///
251/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
252/// let model = Model::embedded()?;
253/// let empty = Vocabulary::parse(b"")?;
254/// let ready = Dictionaries { en: Some(&empty), ru: Some(&empty), learned: &[] };
255/// let word: Vec<u16> = "ghbdtn".encode_utf16().collect();
256/// let request = Request {
257///     word: &word,
258///     active: Some(Mode::En),
259///     context: None,
260///     keyboard: Keyboard::Apple,
261///     explicit_intent: false,
262/// };
263///
264/// let decision = infer(&model, ready, Policy::default(), request);
265/// assert_eq!(decision.reason, Reason::Correction);
266/// let replacement = decision.replacement.ok_or("no replacement")?;
267/// assert_eq!(String::from_utf16(&replacement)?, "привет");
268///
269/// // Without both personal sources the engine abstains.
270/// let missing = infer(&model, Dictionaries::default(), Policy::default(), request);
271/// assert_eq!(missing.reason, Reason::DictionariesMissing);
272/// # Ok(())
273/// # }
274/// ```
275pub fn infer(
276    model: &Model<'_>,
277    dictionaries: Dictionaries<'_>,
278    policy: Policy,
279    request: Request<'_>,
280) -> Decision {
281    if request.explicit_intent {
282        return Decision::abstain(Reason::ExplicitIntent);
283    }
284    let word = request.word;
285    let Some(active) = request.active else {
286        return Decision::abstain(Reason::Ineligible);
287    };
288    let keyboard = request.keyboard;
289    let provisional = active == Mode::En && word.iter().any(|&unit| is_provisional(unit, keyboard));
290    // Provisional units carry no English letters, so the source reading drops them; the core
291    // keeps every unit up to the last letter and is plain English only when they all trail
292    let letters: Vec<u16> = word
293        .iter()
294        .copied()
295        .filter(|&unit| !provisional || !is_provisional(unit, keyboard))
296        .collect();
297    let core = if provisional {
298        let end = word
299            .iter()
300            .rposition(|&unit| !is_provisional(unit, keyboard))
301            .map_or(0, |at| at + 1);
302        &word[..end]
303    } else {
304        word
305    };
306    if word.len() > MAX_MODEL_WORD || script(&letters) != Some(active) || !policy.is_valid() {
307        return Decision::abstain(Reason::Ineligible);
308    }
309    let (target, mapping) = match active {
310        Mode::En => (Mode::Ru, Mapping::EnToRu),
311        Mode::Ru => (Mode::En, Mapping::RuToEn),
312    };
313    let candidate = mapping::convert(word, keyboard, mapping);
314    // A provisional word's case is judged on its target reading, where every unit is a letter
315    let cased = if provisional { &candidate } else { word };
316    let lower = vocabulary::lowercase(cased);
317    let upper = vocabulary::uppercase(cased);
318    let initial_capital = cased.first() == upper.first() && cased.get(1..) == lower.get(1..);
319    if (cased.len() > 1 && *cased == upper) || (*cased != lower && !initial_capital) {
320        return Decision::abstain(Reason::Ineligible);
321    }
322    if dictionaries.en.is_none() || dictionaries.ru.is_none() {
323        return Decision::abstain(Reason::DictionariesMissing);
324    }
325    let original_membership = membership(dictionaries, word);
326    let core_membership = membership(dictionaries, core);
327    if [original_membership, core_membership]
328        .iter()
329        .any(|m| matches!(m, Membership::Recognized | Membership::Rare))
330    {
331        return Decision::abstain(Reason::Personal);
332    }
333    let candidate_valid = script(&candidate) == Some(target);
334    let frequency = candidate_valid
335        .then(|| {
336            model
337                .language(target)
338                .frequency(&vocabulary::lowercase(&candidate))
339        })
340        .flatten();
341    // A typed word the user declared forbidden loses its lexicon protection
342    let known = (original_membership != Membership::Forbidden && script(core) == Some(active))
343        .then(|| {
344            model
345                .language(active)
346                .frequency(&vocabulary::lowercase(core))
347        })
348        .flatten();
349    let mut ratio = None;
350    if let Some(source) = known {
351        let margin = if word.len() == 2 && request.context != Some(target) {
352            policy.short_known_margin
353        } else {
354            policy.known_margin
355        };
356        ratio = frequency
357            .map(|frequency| frequency - source)
358            // Stored values are log10 frequencies; adding 9 gives Zipf
359            .filter(|&ratio| {
360                word.len() > 1 && source + 9.0 < policy.known_ceiling && ratio >= margin
361            });
362        if ratio.is_none() {
363            return Decision::abstain(Reason::Known);
364        }
365    }
366    if !candidate_valid {
367        return Decision::abstain(Reason::Ineligible);
368    }
369    if membership(dictionaries, &candidate) == Membership::Forbidden {
370        return Decision::abstain(Reason::Forbidden);
371    }
372    let Some(frequency) = frequency else {
373        return Decision::abstain(Reason::Weak);
374    };
375    if frequency + 9.0 < policy.minimum_zipf {
376        return Decision::abstain(Reason::Weak);
377    }
378    // A rare known word is word-level evidence; its character chain says nothing more
379    if let Some(score) = ratio {
380        return Decision {
381            reason: Reason::Correction,
382            score,
383            replacement: Some(candidate),
384        };
385    }
386    let Some(mut source_likelihood) = model
387        .language(active)
388        .log_likelihood(&vocabulary::lowercase(&letters))
389    else {
390        // Unreachable after the script and length checks; kept as an abstention, not a panic
391        return Decision::abstain(Reason::Ineligible);
392    };
393    if provisional {
394        let first = word
395            .iter()
396            .position(|&unit| !is_provisional(unit, keyboard));
397        for (at, &unit) in word.iter().enumerate() {
398            if is_provisional(unit, keyboard) {
399                let leading = first.is_some_and(|first| at < first);
400                source_likelihood += PROVISIONAL_LOG10[if leading {
401                    0
402                } else if at < core.len() {
403                    1
404                } else {
405                    2
406                }];
407                if word.len() == 3
408                    && request.context != Some(active)
409                    && leading
410                    && frequency + 9.0 >= 4.0
411                {
412                    source_likelihood -= 3.0;
413                }
414            }
415        }
416    }
417    let context_factor: f64 = match request.context {
418        Some(context) if context == target => 19.0,
419        Some(_) => 1.0 / 19.0,
420        None => 1.0,
421    };
422    let score = frequency - source_likelihood
423        + (policy.error_prior / (1.0 - policy.error_prior)).log10()
424        + context_factor.log10();
425    let short_penalty = match word.len() {
426        1 => 4.0,
427        2 => 2.0,
428        3 => 1.0,
429        _ => 0.0,
430    };
431    if score >= policy.false_correction_cost.log10() + short_penalty {
432        Decision {
433            reason: Reason::Correction,
434            score,
435            replacement: Some(candidate),
436        }
437    } else {
438        Decision {
439            reason: Reason::Weak,
440            score,
441            replacement: None,
442        }
443    }
444}
445
446/// Language of the last two words in `prefix`, the session's own finished text.
447///
448/// The scan runs back over at most the last 256 UTF-16 units, skips non-letters and gives up at
449/// LF or CR. It returns a language only when the last two letter runs are both words of the same
450/// language's lexicon; fewer than two runs, a mixed-script run, a word the lexicon lacks or a run
451/// cut by the 256-unit window gives `None`. This consumes supplied context, never reads a
452/// document, and does not define automatic token eligibility or authorize a replacement range.
453pub fn detect_context(model: &Model<'_>, prefix: &[u16]) -> Option<Mode> {
454    let start = prefix.len().saturating_sub(256);
455    let mut cursor = prefix.len();
456    let mut language = None;
457    for _ in 0..2 {
458        while cursor > start && !mapping::is_letter(prefix[cursor - 1]) {
459            if matches!(prefix[cursor - 1], 10 | 13) {
460                return None;
461            }
462            cursor -= 1;
463        }
464        let end = cursor;
465        while cursor > start && mapping::is_letter(prefix[cursor - 1]) {
466            cursor -= 1;
467        }
468        if cursor == end || (cursor == start && start > 0 && mapping::is_letter(prefix[start - 1]))
469        {
470            return None;
471        }
472        let word = &prefix[cursor..end];
473        let mode = script(word)?;
474        if word.len() > MAX_MODEL_WORD
475            || model
476                .language(mode)
477                .frequency(&vocabulary::lowercase(word))
478                .is_none()
479            || language.is_some_and(|previous| previous != mode)
480        {
481            return None;
482        }
483        language = Some(mode);
484    }
485    language
486}
487
488#[cfg(test)]
489mod tests {
490    use super::*;
491
492    #[test]
493    fn punctuated_context_preserves_source_language_protection() {
494        let model = Model::embedded().unwrap();
495        for (prefix, expected) in [
496            ("hello, world : ", Some(Mode::En)),
497            ("привет - мир! ", Some(Mode::Ru)),
498            ("hello\nworld ", None),
499            ("hello мир ", None),
500        ] {
501            assert_eq!(
502                detect_context(&model, &prefix.encode_utf16().collect::<Vec<_>>()),
503                expected,
504                "{prefix}"
505            );
506        }
507        let empty = Vocabulary::parse(b"").unwrap();
508        let word: Vec<_> = "ghbdtn".encode_utf16().collect();
509        let request = Request {
510            word: &word,
511            active: Some(Mode::En),
512            context: None,
513            keyboard: Keyboard::Apple,
514            explicit_intent: false,
515        };
516        let dictionaries = Dictionaries {
517            en: Some(&empty),
518            ru: Some(&empty),
519            learned: &[],
520        };
521        let neutral = infer(&model, dictionaries, Policy::default(), request);
522        let source = infer(
523            &model,
524            dictionaries,
525            Policy::default(),
526            Request {
527                context: detect_context(
528                    &model,
529                    &"hello, world : ".encode_utf16().collect::<Vec<_>>(),
530                ),
531                ..request
532            },
533        );
534        assert!((neutral.score - source.score - 19.0_f64.log10()).abs() < 1e-12);
535        // Single letters are lexicon words and never yield
536        for raw in ["A", "B", "Ф"] {
537            let word: Vec<_> = raw.encode_utf16().collect();
538            let mode = script(&word).unwrap();
539            assert_eq!(
540                infer(
541                    &model,
542                    dictionaries,
543                    Policy::default(),
544                    Request {
545                        word: &word,
546                        active: Some(mode),
547                        ..request
548                    }
549                )
550                .reason,
551                Reason::Known
552            );
553        }
554        // б and ж read as `,` and `;`, outside the English alphabet
555        let word: Vec<_> = "Абаж".encode_utf16().collect();
556        assert_eq!(
557            infer(
558                &model,
559                dictionaries,
560                Policy::default(),
561                Request {
562                    word: &word,
563                    active: Some(Mode::Ru),
564                    ..request
565                }
566            )
567            .reason,
568            Reason::Ineligible
569        );
570    }
571
572    #[test]
573    fn learned_words_protect_and_forbid_without_making_sources_ready() {
574        let model = Model::embedded().unwrap();
575        let empty = Vocabulary::parse(b"").unwrap();
576        let protects =
577            Arc::new(Vocabulary::parse_words(b"ghbdtn", Membership::Recognized).unwrap());
578        let forbids =
579            Arc::new(Vocabulary::parse_words("привет".as_bytes(), Membership::Forbidden).unwrap());
580        let word: Vec<_> = "ghbdtn".encode_utf16().collect();
581        let request = Request {
582            word: &word,
583            active: Some(Mode::En),
584            context: None,
585            keyboard: Keyboard::Apple,
586            explicit_intent: false,
587        };
588        let reason = |en, ru, learned: &[Arc<Vocabulary>]| {
589            infer(
590                &model,
591                Dictionaries { en, ru, learned },
592                Policy::default(),
593                request,
594            )
595            .reason
596        };
597        let ready = (Some(&empty), Some(&empty));
598        assert_eq!(reason(ready.0, ready.1, &[]), Reason::Correction);
599        assert_eq!(
600            reason(ready.0, ready.1, &[forbids.clone(), protects.clone()]),
601            Reason::Personal
602        );
603        assert_eq!(
604            reason(ready.0, ready.1, std::slice::from_ref(&forbids)),
605            Reason::Forbidden
606        );
607        // A learned list overrides a Vim entry the same way a second Vim entry would
608        let vim = Vocabulary::parse("привет".as_bytes()).unwrap();
609        assert_eq!(
610            reason(Some(&empty), Some(&vim), std::slice::from_ref(&forbids)),
611            Reason::Forbidden
612        );
613        assert_eq!(
614            reason(None, None, &[protects, forbids]),
615            Reason::DictionariesMissing
616        );
617    }
618
619    #[test]
620    fn missing_dictionaries_abstain_unless_intent_is_explicit() {
621        let model = Model::embedded().unwrap();
622        let word: Vec<_> = "ghbdtn".encode_utf16().collect();
623        let request = Request {
624            word: &word,
625            active: Some(Mode::En),
626            context: None,
627            keyboard: Keyboard::Apple,
628            explicit_intent: false,
629        };
630        let policy = Policy::default();
631        assert_eq!(
632            infer(&model, Dictionaries::default(), policy, request).reason,
633            Reason::DictionariesMissing
634        );
635        assert_eq!(
636            infer(
637                &model,
638                Dictionaries::default(),
639                policy,
640                Request {
641                    explicit_intent: true,
642                    ..request
643                }
644            )
645            .reason,
646            Reason::ExplicitIntent
647        );
648    }
649
650    #[test]
651    fn rare_known_words_and_provisional_letters_yield_only_to_frequent_readings() {
652        let model = Model::embedded().unwrap();
653        let empty = Vocabulary::parse(b"").unwrap();
654        let dictionaries = Dictionaries {
655            en: Some(&empty),
656            ru: Some(&empty),
657            learned: &[],
658        };
659        let decide = |raw: &str, active, context, keyboard| {
660            let word: Vec<_> = raw.encode_utf16().collect();
661            let decision = infer(
662                &model,
663                dictionaries,
664                Policy::default(),
665                Request {
666                    word: &word,
667                    active: Some(active),
668                    context,
669                    keyboard,
670                    explicit_intent: false,
671                },
672            );
673            let replacement = decision
674                .replacement
675                .map(|units| String::from_utf16(&units).unwrap());
676            (decision.reason, replacement)
677        };
678        let corrected = |text: &str| (Reason::Correction, Some(text.to_owned()));
679        let apple = Keyboard::Apple;
680        for (raw, active, context, keyboard, expected) in [
681            // Rare lexicon entries yield; a two-letter one needs a wider margin or context
682            ("ghb", Mode::En, None, apple, corrected("при")),
683            ("ult", Mode::En, Some(Mode::En), apple, corrected("где")),
684            ("yf", Mode::En, None, apple, corrected("на")),
685            ("ещ", Mode::Ru, None, apple, corrected("to")),
686            ("uj", Mode::En, None, apple, (Reason::Known, None)),
687            ("uj", Mode::En, Some(Mode::En), apple, (Reason::Known, None)),
688            ("uj", Mode::En, Some(Mode::Ru), apple, corrected("го")),
689            // Known words at or above the ceiling keep their protection
690            ("lf", Mode::En, Some(Mode::Ru), apple, (Reason::Known, None)),
691            ("шт", Mode::Ru, Some(Mode::En), apple, (Reason::Known, None)),
692            // Keys that type Russian letters can begin, continue and end a word
693            ("[jhjij", Mode::En, None, apple, corrected("хорошо")),
694            (";bpym", Mode::En, None, apple, corrected("жизнь")),
695            ("gj'njve", Mode::En, None, apple, corrected("поэтому")),
696            ("pyf.", Mode::En, None, apple, corrected("знаю")),
697            ("{jhjij", Mode::En, None, apple, corrected("Хорошо")),
698            ("\"nj", Mode::En, None, apple, corrected("Это")),
699            ("\\krf", Mode::En, None, apple, corrected("ёлка")),
700            ("[eq", Mode::En, None, apple, corrected("хуй")),
701            (",kz", Mode::En, None, apple, corrected("бля")),
702            ("'[j", Mode::En, None, apple, corrected("эхо")),
703            ("[eq", Mode::En, Some(Mode::Ru), apple, corrected("хуй")),
704            ("[eq", Mode::En, Some(Mode::En), apple, (Reason::Weak, None)),
705            ("'qh", Mode::En, None, apple, (Reason::Weak, None)),
706            ("e[j", Mode::En, None, apple, (Reason::Weak, None)),
707            (
708                "cerf",
709                Mode::En,
710                Some(Mode::Ru),
711                apple,
712                (Reason::Known, None),
713            ),
714            ("pft,bcm", Mode::En, None, apple, corrected("заебись")),
715            ("[eq", Mode::En, None, Keyboard::Pc, corrected("хуй")),
716            (",kz", Mode::En, None, Keyboard::Pc, corrected("бля")),
717            ("`krf", Mode::En, None, Keyboard::Pc, corrected("ёлка")),
718            ("`krf", Mode::En, None, apple, (Reason::Ineligible, None)),
719            (
720                "\\krf",
721                Mode::En,
722                None,
723                Keyboard::Pc,
724                (Reason::Ineligible, None),
725            ),
726            // An English word before trailing punctuation stays protected
727            ("it.", Mode::En, None, apple, (Reason::Known, None)),
728            (
729                "he,",
730                Mode::En,
731                Some(Mode::Ru),
732                apple,
733                (Reason::Known, None),
734            ),
735            ("hello,", Mode::En, None, apple, (Reason::Known, None)),
736            ("ghbdtn,", Mode::En, None, apple, (Reason::Weak, None)),
737            ("don't", Mode::En, None, apple, (Reason::Weak, None)),
738            // Punctuation alone, capitals and Russian mode are not provisional words
739            ("...", Mode::En, None, apple, (Reason::Ineligible, None)),
740            ("'", Mode::En, None, apple, (Reason::Ineligible, None)),
741            ("[JHJIJ", Mode::En, None, apple, (Reason::Ineligible, None)),
742            ("[jhjij", Mode::Ru, None, apple, (Reason::Ineligible, None)),
743        ] {
744            assert_eq!(decide(raw, active, context, keyboard), expected, "{raw}");
745        }
746    }
747
748    #[test]
749    fn colloquial_candidates_keep_vocabulary_and_intent_guards() {
750        let model = Model::embedded().unwrap();
751        let empty = Vocabulary::parse(b"").unwrap();
752        for (raw, target) in [("[eq", "хуй"), (",kz", "бля"), ("pft,bcm", "заебись")] {
753            let word: Vec<_> = raw.encode_utf16().collect();
754            let request = Request {
755                word: &word,
756                active: Some(Mode::En),
757                context: None,
758                keyboard: Keyboard::Apple,
759                explicit_intent: false,
760            };
761            let ready = Dictionaries {
762                en: Some(&empty),
763                ru: Some(&empty),
764                learned: &[],
765            };
766            let protected = Vocabulary::parse(raw.as_bytes()).unwrap();
767            let forbidden = Vocabulary::parse(format!("{target}/!").as_bytes()).unwrap();
768            for (dictionaries, request, expected) in [
769                (
770                    Dictionaries {
771                        en: Some(&protected),
772                        ..ready
773                    },
774                    request,
775                    Reason::Personal,
776                ),
777                (
778                    Dictionaries {
779                        ru: Some(&forbidden),
780                        ..ready
781                    },
782                    request,
783                    Reason::Forbidden,
784                ),
785                (
786                    Dictionaries::default(),
787                    request,
788                    Reason::DictionariesMissing,
789                ),
790                (
791                    ready,
792                    Request {
793                        explicit_intent: true,
794                        ..request
795                    },
796                    Reason::ExplicitIntent,
797                ),
798            ] {
799                let decision = infer(&model, dictionaries, Policy::default(), request);
800                assert_eq!(decision.reason, expected, "{raw}");
801                assert!(decision.replacement.is_none(), "{raw}");
802            }
803        }
804    }
805
806    #[test]
807    fn dictionary_membership_alone_never_promotes_a_weak_candidate() {
808        let model = Model::embedded().unwrap();
809        // The candidate is in the Russian source but not in the model; membership supplies no
810        // frequency, so the decision stays Weak
811        let en = Vocabulary::parse(b"").unwrap();
812        let word: Vec<_> = "qqqqqq".encode_utf16().collect();
813        let ru = Vocabulary::parse("йййййй\n".as_bytes()).unwrap();
814        let request = Request {
815            word: &word,
816            active: Some(Mode::En),
817            context: None,
818            keyboard: Keyboard::Apple,
819            explicit_intent: false,
820        };
821        assert_eq!(
822            infer(
823                &model,
824                Dictionaries {
825                    en: Some(&en),
826                    ru: Some(&ru),
827                    learned: &[]
828                },
829                Policy::default(),
830                request
831            )
832            .reason,
833            Reason::Weak
834        );
835    }
836}