Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Keyrill

Русская версия

Keyrill fixes English/Russian keyboard-layout mistakes as you type. It runs offline and is available as an alpha for macOS and Windows. Linux is planned.

Install on macOS · Install on Windows

With automatic correction enabled, press Space after the word.

How it works

Select a Keyrill input source for English or Russian. Keyrill uses a built-in frequency model to decide whether a word belongs in the other layout and protects words in your personal dictionaries. It does not log, save or send what you type.

Keyboard shortcuts

ActionmacOSWindows
Convert the current word⌃ Control+⌥ Option+KLeft Ctrl+Left Alt+K
Reverse the correction immediately⌃ Control+⌥ Option+ZLeft Ctrl+Left Alt+Z
Restore the original and finish the marked wordEscEsc

The shortcuts work on the current word in supported fields. On Windows, use the physical K and Z positions in either layout.

macOS

Select Keyrill EN or Keyrill RU. The input menu shows whether correction is ready. Correction in This App changes the mode for the current application. Source switching after automatic correction can be turned off in Settings.

  • Composition (TextEdit, Safari, Firefox) edits only the marked word after checking its text, range and caret. See the composition edit contract.
  • Compatibility (terminals, editors, Microsoft Office and other unlisted applications) uses simulated Backspaces and typing. Unlisted apps default to manual correction, with automatic correction available in Settings. This mode needs Accessibility and Input Monitoring. Typing during a rewrite, focus changes, autocompletion and terminal interfaces can lose keystrokes or corrupt the word. See ADR 006.
  • Off passes keys through in excluded apps such as password managers and remote desktops.

The macOS application tiers list the built-in defaults.

Windows

Select Keyrill English or Keyrill Русский. Automatic correction starts off. To turn it on, select Enable automatic correction in admitted controls in Keyrill Settings.

Note

Windows correction was verified in the main editing field of Notepad 11.2609.11.0 x64. Fields outside the supported set pass input through. See the Windows application checks for tested versions and fields.

Install from source

macOS setup

You need Apple Silicon macOS with Command Line Tools and Rust (rustup installs the exact toolchain from rust-toolchain.toml on first use).

  1. Build, sign and copy the alpha bundle to your Input Methods folder:

    $ make install
    

    The bundle is signed ad hoc, which gives every build a different code requirement, so macOS may ask for the compatibility permissions again after each update. Create a self-signed code-signing certificate in Keychain Access and pass its name to keep the requirement stable: make install SIGN_IDENTITY="Keyrill Local". make bundle builds and signs target/alpha.noindex/KeyrillAlpha.app without installing it.

  2. In System Settings > Keyboard > Input Sources, add Keyrill EN and Keyrill RU and select one of them. A newly installed input method sometimes appears only after logging out and back in.

  3. Open Settings… from the Keyrill input menu and enable automatic correction.

    The default dictionary paths are ~/.vim/spell/en.utf-8.add and ~/.vim/spell/ru.utf-8.add. A missing file at a default path counts as empty. A missing file at a path you chose keeps automatic correction off, so a typo there doesn’t silently drop your protected words.

    Use words added with Learn Spelling is off by default. To protect those words, click Choose… beside the checkbox, select Apple’s LocalDictionary in the folder the picker opens, then click Save. macOS may grant access when the file is selected; Cancel in Settings does not revoke access already granted. Check the input menu for read failures. If access is lost after a restart or update, choose the file again. Without access, correction works without those words.

  4. For compatibility mode, grant Keyrill Alpha access under Privacy & Security > Accessibility and Input Monitoring. Keyrill checks both without prompting when a compatibility application is active, and the input menu shows what is missing. Without them, those applications get plain typing and no correction.

To update, select stock U.S. and run make install again, with the same SIGN_IDENTITY. It quits the running server before replacing the bundle, because copying over the bundle of a running server can get it killed for an invalid code signature.

The new server starts when you select a Keyrill mode again. Settings are kept.

To uninstall, remove both modes from Input Sources, quit the server, delete ~/Library/Input Methods/KeyrillAlpha.app and, if you want the settings gone too, run defaults delete org.keyrill.inputmethod.alpha. Keyrill never modifies your dictionary files.

Windows setup

Use an x64 Windows host with the build prerequisites. The package includes TSF adapters for 64-bit and 32-bit applications.

  1. Build and verify the package.
  2. Add the standard U.S. and Russian keyboard layouts, then install the package as administrator.
  3. Enable and select a Keyrill input profile in Windows.

Known limitations on macOS

Warning

Secure Input stops correction. Compatibility mode can hold sensitive typing in memory in password fields or hidden terminal prompts that leave Secure Input off.

  • Only the word being typed can be corrected: the mark in composition, the word Keyrill tracks in compatibility mode. An arbitrary committed range or a selection can’t be converted.
  • In English mode, the keys that type [ ] ; ' , . and \ count as letters, because they are х, ъ, ж, э, б, ю and ё in Russian: [jhjij becomes хорошо. While the word is marked, an editor’s smart quotes and automatic bracket pairing may not apply to them.
  • In raw-key terminals, the manual shortcuts can reach the terminal as well.

Documentation

The same documents, with the Rust API, are published at https://megabyde.github.io/keyrill/.

License

Keyrill’s source is MIT-licensed. The language model is derived from wordfreq data under CC BY-SA 4.0, and the evaluation corpora carry their own licenses; MIT does not relicense them. See assets and model.

How Keyrill works

This page follows one word, ghbdtn typed with Space in TextEdit, from the key press to the verified edit, and stops at each check Keyrill makes before and after the edit. Read it before the reference pages; they assume the terms defined here. The numbers come from the shipped model and the real C ABI, not from an illustration.

Two readings of the same keys

A layout mistake leaves no trace in the keys themselves. The user meant to type привет with the Russian layout active, the US layout was active instead, and the same six physical keys produced Latin letters:

KeyGHBDTN
US layoutghbdtn
Russian ЙЦУКЕНпривет

So the conversion itself is a table lookup (crates/keyrill-core/src/mapping.rs), and the whole difficulty is deciding when to apply it. hello and руддщ are also the same keys, and only the first is a word anyone means. A wrong correction costs the user more than a missed one, so Keyrill is built to abstain when in doubt (ADR 003); the release target is fewer than one false correction per 10,000 correctly typed words.

Why an input method

Keyrill doesn’t watch the screen and fix text afterwards. It is the layout: you select Keyrill EN or Keyrill RU in place of the stock US and Russian sources, so every key reaches Keyrill before the application. Keyrill holds the word being typed as marked text, the underlined composition an input method owns, and replaces only that mark. On the composition path, text the application has already committed is never rewritten: each way of doing it (counted Backspaces, a temporary selection, the clipboard) fails under some schedule, by deleting a key typed meanwhile, overwriting a selection or leaving text in clipboard history; see architecture and ADR 005. The compatibility backend described below is the one exception. The price is visible: an underline under the current word and an input source to select.

Who does what

flowchart TD
    App["Application<br/>(TextEdit)"] <-->|"IMK client calls:<br/>read, setMarkedText, insertText"| Adapter
    subgraph Adapter["macOS adapter, Objective-C++"]
        Controller[KRController] --> Session[KRSession]
    end
    Session <-->|"kr_event in, kr_plan out,<br/>kr_commit outcome"| ABI["C ABI<br/>keyrill-ffi"]
    ABI <--> Core["Rust core<br/>keyrill-core"]
    Core --- Model[("Model and<br/>vocabulary snapshots")]

The two halves have different powers. The Rust core decides: it knows the layouts, the model, your protected words and the state of the current word, and it answers each key with a plan. It never touches the document. The adapter acts: it talks to the application, checks that the document is what the plan expects, performs the write, reads the result back and reports what happened. A plan is a proposal, never editing authority.

Important

Rust state advances only on a verified acknowledgement: every check the write requires passed, and for a write a key causes that includes reading the document back and finding the expected text. A commit the platform requests on focus loss writes back the text last verified in the mark without reading it again. The edit contract lists the checks for every write. A write that was attempted but can’t be confirmed is reported as unknown, and correction stops. Nothing is guessed, repaired or replayed.

Typing the word

Each key goes through the same loop. Here is the third key, b, with gh already marked:

sequenceDiagram
    participant App as TextEdit
    participant S as KRSession
    participant R as Rust (C ABI)
    App->>S: key "b"
    S->>R: kr_plan_event(TEXT "b", EN)
    R-->>S: plan: MARK, expected "gh", mark "ghb", key consumed
    S->>App: markedRange, selectedRange, stringFromRange
    Note over S: same client and generation?<br/>mark holds exactly "gh"? caret at its end?
    S->>App: setMarkedText("ghb")
    S->>App: markedRange, selectedRange, stringFromRange
    Note over S: mark now holds exactly "ghb"?
    S->>R: kr_commit(plan, APPLIED_VERIFIED)
    S-->>App: key handled

Before the write the session checks the client, the exact marked range, the caret at its end and the exact UTF-16 text in the mark. After the write it reads the mark back. Between these calls it compares a generation counter: every client call can call back into the input method (a focus change, a commit request), and a callback that invalidates the session bumps the generation, so work that started under the old one is dropped instead of acting on a stale document.

The very first letter is planned differently, because nothing is owned yet: the session reads the character before the caret, and a word starts only at the document start or after whitespace. A caret inside foo|bar starts nothing, since there would be no complete word to judge.

Typing the whole word, the engine returns these plans (the adapter verifies and acknowledges each one):

KeyActionExpected in the markNew markKey
gMARKgconsumed
hMARKgghconsumed
bMARKghghbconsumed
dMARKghbghbdconsumed
tMARKghbdghbdtconsumed
nMARKghbdtghbdtnconsumed
SpaceMARKghbdtnпривет consumed

The decision at Space

Space ends the word, and only Space: a word followed by Return or Tab is committed as typed. The engine then runs inference::infer, which looks for a reason to not correct before it looks for evidence to correct:

flowchart TD
    W["ghbdtn"] --> E{"One script, plain case,<br/>at most 32 units?"}
    E -->|no| A1[Leave: ineligible]
    E -->|yes| D{"Both personal<br/>sources ready?"}
    D -->|no| A6[Leave: dictionary missing]
    D -->|yes| P{"In your Vim or<br/>learned words?"}
    P -->|yes| A2[Leave: protected]
    P -->|no| K{"A word in its<br/>own layout?"}
    K -->|"yes, but rare, and the other<br/>reading is far more frequent"| F
    K -->|"yes, otherwise"| A3[Leave: known word]
    K -->|no| F{"Other reading<br/>forbidden by you?"}
    F -->|yes| A4[Leave: forbidden]
    F -->|no| Z{"Other reading in the lexicon,<br/>Zipf at least 2.5?"}
    Z -->|no| A5[Leave: too weak]
    Z -->|yes| S{"A yielding known word,<br/>or score above the threshold?"}
    S -->|no| A5
    S -->|yes| C[Correct]

ghbdtn is not an English word, so the decision falls to the score. It compares how likely the user meant привет with how likely they meant the letters as typed, in log10 units:

\[ \text{score} = \log_{10} f_{RU}(\text{привет}) - \log_{10} P_{EN}(\text{ghbdtn}) + \log_{10}\frac{p}{1-p} + \log_{10} c \]
TermMeaningValue
log₁₀ fFrequency of привет among Russian words (Zipf 5.13)−3.87
log₁₀ PHow English the letter sequence looks to an order-2 character chain−16.75
pPrior that any given word was typed in the wrong layout, 0.001−3.00
cContext: 19 if the previous words were Russian, 1/19 if English, 1 if none0
score9.88

A correction needs a score of at least log₁₀ 100 = 2, the cost of a false correction, plus a penalty for short words (4, 2 and 1 for one, two and three letters). ghbdtn clears it by a wide margin. руддщ read as hello scores 4.59, also a correction.

Note

These are ranking scores with chosen parameters, not calibrated probabilities. The minimum Zipf and the known-word rule below are checked by the offline evaluation, where the same sentences typed correctly get no false corrections; that is a synthetic measurement, not precision on real typing.

Three-unit words with leading provisional punctuation get additional evidence when the Russian candidate has Zipf at least 4 and the context does not support English. This corrects [jl to ход and ,sk to был after Space, even as a first word; engine gives the scoring rule and its limits.

The harder case is a string that is a word in both layouts. yf is a rare English entry (Zipf 2.37) and the keys for на, one of the most frequent Russian words (Zipf 7.25). A known word yields only when it is rare (below Zipf 3) and the other reading is at least 2.5 Zipf more frequent, 3.5 for a two-letter word without Russian context; here the difference is 4.88, so yf becomes на. lf (Zipf 3.40) is above the rarity bar and stays lf, even though да is far more frequent. A yielding word is corrected on that frequency difference alone, which becomes its score; the character chain adds nothing for a string the lexicon already has.

The write, and the mark that stays

The plan for Space replaces the mark ghbdtn with привет and consumes the Space: the Space is inside the new mark. The word and its Space stay marked until the next key. Two things depend on that. The correction can still be undone exactly, because Keyrill still owns the text it would restore over; and the engine keeps a receipt, the original ghbdtn, valid only while that mark is owned. After the correction Keyrill also asks macOS to switch to Keyrill RU, so the next word is typed in the layout the user evidently wanted.

The next key first finishes the mark, then is planned as a new word:

KeyActionExpectedNew textKey
xFINISHпривет привет committedreplan
xMARKxconsumed

KR_KEY_REPLAN tells the adapter that the first write handled only the old mark and the same key must be planned again. Each plan permits at most one write.

Undo

Control+Option+Z right after the correction is planned against the same mark:

KeyActionExpectedNew markKey
Control+Option+ZMARKпривет ghbdtn consumed

The input mode switches back too, since the switch was a consequence of the correction. Once the next key finishes the mark, the receipt expires; a late undo makes no write at all, because the text is now the application’s and Keyrill can no longer prove what it would be replacing.

When the application disagrees

The checks around each write sort every outcome into one of three kinds, and only one of them lets Rust move on:

stateDiagram-v2
    [*] --> Planned: kr_plan_event
    Planned --> Refused: check before the write fails
    Planned --> Written: write performed
    Written --> Verified: checks after the write pass,<br/>readback included for a typed key
    Written --> Unknown: readback differs, is missing,<br/>or a callback intervened
    Refused --> [*]: REFUSED_BEFORE_WRITE,<br/>key passes, document untouched
    Verified --> [*]: APPLIED_VERIFIED,<br/>Rust state advances
    Unknown --> Stopped: ATTEMPTED_UNKNOWN
    Stopped --> [*]: after a failed check on the app's answer,<br/>commit its own readback once

Unknown is the case that needs care. The write happened, but what the document contains is not what Keyrill expected, and nothing Keyrill could write next is known to be safe. If the failed check was the readback after the write, with no reentrant call in between, Keyrill does the one thing that keeps what the user sees: it reads the marked text as the application reports it and, if that text still covers exactly the marked range, commits it unchanged. Otherwise it writes nothing. Either way it stops correcting that word. The key that carried the write is consumed, not replayed, because it may already be in the document. Correction resumes with the next word only if an earlier write in this activation was verified; otherwise, or after a second unknown outcome, it stays off until you switch away and back. The input menu’s first line says so.

Applications that can’t do this

Composition needs an application that reflects marked text and reads it back faithfully. TextEdit, Safari and Firefox have been tested for that; terminals, code editors and Microsoft Office are handled differently. For those, Keyrill has a compatibility backend: it watches the keys it passes through and, on Control+Option+K, rewrites the word by posting Backspaces and the replacement as synthetic key events. It can’t read the result, so it can’t verify it:

sequenceDiagram
    participant U as You
    participant K as Keyrill
    participant T as Terminal
    K->>T: Backspace ×6 (delete "ghbdtn")
    U->>T: "x" typed during the rewrite
    K->>T: "привет"
    Note over T: the x may land between the Backspaces:<br/>a wrong character is deleted

Warning

The compatibility backend gives up the guarantees above: typing during a rewrite, autocompletion or a focus change can delete the wrong characters. That is why automatic correction is off there by default and the backend is documented as an exception (ADR 006).

Each application gets one tier when it gains focus: composition, compatibility (manual only, or also automatic) or off. Password managers, remote desktops and virtual machines are off: keys pass through untouched.

Terms

The glossary has the full list, with the abbreviations.

TermMeaning
Mark, owned compositionThe underlined text Keyrill placed with setMarkedText and still owns; the only text the composition path may change
Boundary markThe corrected word plus Space, kept marked until the next key so the correction can be undone
PlanRust’s proposal for one key: an action, the text the mark must hold, the new mark and what to do with the key
AcknowledgementThe adapter’s report of a plan’s outcome: verified, refused before the write, or unknown
GenerationA counter the adapter bumps on every invalidating callback; work from an older generation is dropped
ReceiptThe original word kept for undo; valid only while its boundary mark is owned
TierHow an application is handled: composition, compatibility or off
SnapshotAn immutable, fully parsed copy of the model or a dictionary; published whole and never edited in place
Zipflog10 of a word’s frequency per billion words; 7 is very common, 3 is rare

Reading on

Architecture has the full state table and the safety invariants these steps implement. Engine covers the mapping, inference rules, vocabulary formats and evaluation; macOS adapter the checks around IMK clients, tiers and dictionaries; porting what another platform must reproduce. In the code, start with crates/keyrill-ffi/tests/abi_smoke.c: in under 200 lines of C it drives the same plan, check, write and commit loop against an in-memory document.

Architecture

Keyrill is a portable Rust engine behind a narrow C ABI, with one native adapter per platform. The adapter owns everything native: focus, permissions, objects, API calls, event disposition and verification of what the host document actually contains. Rust owns conversion, segmentation, lexical protection, scoring, abstention, bounded language context, manual intent and reversal data. A Rust plan is a proposal, never editing authority. How Keyrill works follows one word through all of this; this page is the reference it leads to.

flowchart TD
    K[Physical input and host lifecycle] --> M[macOS IMK, Objective-C++]
    K --> W[Windows TSF, Rust]
    M -->|bounded UTF-16 facts| F[C ABI, keyrill-ffi]
    W -->|bounded UTF-16 facts| F
    F --> R[Rust session and policy, keyrill-core]
    R --> D[Immutable model and vocabulary snapshots]
    R -->|plan| F
    F -->|copied plan| M
    F -->|copied plan| W
    M -->|owned composition| H[Host text client]
    M -->|"compatibility backend:<br/>synthetic keys, ADR 006"| H
    W -->|owned composition only| H

Linux support is planned. The macOS compatibility backend is the one path that edits committed text, under the terms of ADR 006.

PathContents
crates/keyrill-coreMapping, model loader, inference, Vim vocabulary, word session; std only, forbid(unsafe_code)
crates/keyrill-ffiC ABI over the core, panic containment, dictionary-file acquisition
include/keyrill.hThe ABI contract: layouts, ownership, versioning, every status code
native/macosInputMethodKit server, controller, settings window, compatibility backend, tests
native/windows/rustwindows-rs TSF service, owned-composition executor, registrar, vocabulary worker, diagnostics, raw COM HRESULT calls and typed reference leases
native/windows/proofRust proof editor, UIA inspectors, independent raw COM providers and controlled schedules
native/windows/build-supportRust source and artifact identities shared by runtime and proof tools
native/windows/setupExplicit machine installation, durable recovery, and dual-architecture package validation
tools/xtaskRust Windows build, model checker, scenario coverage and sanitizer runner
assets/model.binFrozen EN/RU model, generated from model/ by tools/pack-model.py
model/Hash-pinned model source, generator, evaluator and evaluation corpora
tools/inference-probeStdin probe the evaluator drives; not part of any build product

There is no shared document-editing abstraction across platforms, by design (ADR 001): IMK, TSF and Linux input frameworks differ in locks, callbacks, focus and composition identity, and a common facade would hide authority rather than prove it.

Word session

Each input context has one engine handle and one word session. Its states are Idle, Composing, BoundaryRetained and Invalidated; in session.rs the middle two are one State::Owned told apart by its boundary flag. The native generation is tracked separately, by the adapter.

stateDiagram-v2
    [*] --> Idle
    Idle --> Composing: letter at a word boundary
    Composing --> Composing: letter, Backspace,<br/>manual conversion
    Composing --> BoundaryRetained: Space, word plus Space<br/>marked, corrected or not
    BoundaryRetained --> BoundaryRetained: reversal
    Composing --> Idle: other key, Escape,<br/>Backspace to empty
    BoundaryRetained --> Idle: next key finishes the mark
    Idle --> Invalidated: refused or unknown outcome
    Composing --> Invalidated: refused or unknown outcome,<br/>key in another mode
    BoundaryRetained --> Invalidated: refused or unknown outcome,<br/>key in another mode
    Invalidated --> Idle: reset

Every arrow among the first three states is a plan that takes effect only when the adapter acknowledges it as verified. Any other outcome, from any of them, moves the session to Invalidated, and so does a key planned in a mode other than the owned word’s. Invalidated refuses every plan until the adapter resets it.

State and eventEffect
Idle, eligible letterAcquire context facts; start a new composition only if nothing is selected or foreign-marked
Composing, letterUpdate the owned mark, preserving case and the previous verified text
Composing, SpaceInfer or abstain, then mark the exact word plus one Space; keep the original only if converted
BoundaryRetained, reversalRestore the exact original and Space while the same mark is still owned
BoundaryRetained, next inputFinish the mark once, expire the receipt, then process or pass the new input in order
Composing, manual commandDeterministic conversion with explicit intent; inference never undoes it
Composing, BackspaceRemove only owned text; empty composition is its own native operation
EscapeWith a receipt, restore the original, finish and consume the key; otherwise finish the word as typed and pass Escape
Focus, source or client changeInvalidate stale plans; finish only a still-valid old mark; never carry a word to a new field. The echo of a mode switch Keyrill requested keeps the boundary mark and its receipt
Foreign mark, mismatch, exception, unknown outcomeStop correction for that word, with no speculative repair; the edit contract says what may still be written and when correction resumes

propose copies a latest-only token, expected text, desired text, operation and key disposition without changing confirmed state. acknowledge advances state only on a verified result. A refused or unknown outcome invalidates the session; reset expires tokens and receipts; a panic poisons the handle permanently. A plan permits at most one native write.

Ordinary Windows finalization can end an unchanged owned TSF composition without a text write. The native executor requires exact equality with its last verified text and checks context, generation, composition identity, range extent, text and full selection around termination. It marks the effect attempted before EndComposition. Failed or unknown termination stops correction without replay, another termination attempt or a recovery write. Changed finishes, retirement and platform-requested focus-loss commits retain their replacement protocols.

When a write was attempted and its result is unknown, the key that carried it is consumed and not replayed, because it may already be in the document. An unknown finish passes the next ordinary key once, since the finish did not include it. Reserved commands stay consumed. This contains ambiguity; it does not prove the host preserved input, and a client that produces unknown outcomes cannot be admitted for automatic correction.

Callbacks are not a document lock. Every native client call can reenter or invalidate state: snapshot the generation before a query, recheck it after each call and before any effect.

sequenceDiagram
    participant S as Session
    participant C as Client
    Note over S: g = generation
    S->>C: markedRange
    C-)S: callback during the call: focus moved, generation + 1
    C-->>S: a range, from a context that is no longer current
    Note over S: g ≠ generation: drop the work, write nothing

Never hold a Rust borrow or dictionary lock across a native callback. Retained native objects keep memory alive, not focus or document identity.

Edit contract

A plan permits at most one native write, and this section is what an adapter must check around it. The mark is owned when the client, the start offset and the exact text match the adapter’s local authority, the mark it verified last. Exact text is a readback over the expected range that returns the expected UTF-16 units and reports that same range. The generation and Secure Input are rechecked after every client call: a change before the write refuses the plan, and a change after it makes the outcome unknown.

WriteChecked beforeChecked after, for a verified outcomeKey
Start a word: the first letter sets the markNothing owned, marked or selected; caret where the context was readMark at that offset, caret at its end, exact textConsumed
Update the word: letter, Space, Backspace, manual conversion, reversalOwned mark, caret at its end, exact textMark at the same offset, caret at its end, exact textConsumed
Empty the word: Backspace on the last letterOwned mark, caret at its end, exact textNo mark, caret at the startConsumed
Finish with new text: Escape restores the originalOwned mark, caret at its end, exact textNo mark, caret after the text, exact textConsumed
Finish unchanged before a typed keyOwned mark and exact text; caret not checkedNo mark, exact text over the same rangePasses to the host, or is planned again when it starts the next word
Finish unchanged on a lifecycle request: commit, deactivation, mode change, clickOwned mark range; text not readNo mark; text not readNone

Each write ends in one of three acknowledgements, and only the first advances Rust:

  • Verified. Every check in the row passed. Rust advances, and after a mark write the adapter takes local authority over the new mark. If Rust then refuses the acknowledgement, the contract is broken and correction stops until reactivation.
  • Refused before the write. A check before the write failed. Nothing is written, the key goes to the host as typed, Rust drops the word and the next word starts fresh.
  • Unknown. The write may have happened and nothing confirms what it did. Rust drops the word, correction stops and nothing is retried. A key the write carried is consumed, not replayed; a finish carried only the previous mark, so the key after it passes once. Reserved commands stay consumed.

After an unknown outcome the adapter makes at most one more write, and only when the failed check came after the write, on the client’s own answer, with the generation unchanged and Secure Input off: it reads the marked text back and, if the readback covers exactly the marked range, commits it unchanged so that the next key can’t replace it. This keeps what the user sees and repairs nothing. Correction resumes at the next text key only if a write in this activation was already verified and this was the first unknown outcome; otherwise it stays off until the input source is activated again. These rules contain the ambiguity without proving that the host kept the input, so a client that produces unknown outcomes is not admitted for automatic correction.

The macOS adapter maps each row to IMK calls and explains why the two unchanged finishes relax their checks. The compatibility backend is outside this contract: it submits a bounded batch of synthetic events whose outcome is dispatched, never verified, and it never runs to repair an unknown composition outcome (ADR 006).

Safety invariants

IDRequirementFalsifying test
S1Preserve unrelated document content and input orderWhole-document, prefix, suffix and selection oracle with input and focus changes injected at each native boundary
S2Never treat a stale or foreign composition as ownedMatch client, generation, mark, exact UTF-16 text and caret (an unchanged commit by range skips the caret, and on focus loss the text readback); reject foreign-range and reused-proxy schedules
S3No write under uncertain target authorityVerify before the effect and after reentrant queries; zero writes after an ownership loss
S4Do not lose, duplicate, redirect or reorder keysSeparate refused-before-write from attempted-unknown; assert key disposition and documents, not return codes
S5Report evidence, not accepted API callsSeparate requested, attempted, readback-matched and document-verified outcomes
S6No committed-text rewrite on the composition pathNo temporary selection, whole-value set, counted deletion, clipboard or stale absolute range
S7Reversal authority expiresA receipt belongs to one owned mark and generation; a late reversal makes zero writes
S8No private text persisted or transmittedContent-free logs and status, bounded memory, no network, no clipboard
S9Native/FFI lifetime is explicitOne owner per mutable session, callbacks drained before free, ABI bounds and exception containment tested
S10Refusal is visible and safeUnsupported status with unchanged documents; never switch transport silently

These are acceptance requirements, not a proof that arbitrary clients obey a transaction protocol. An already dispatched request to a misbehaving client cannot be withdrawn, so admit a client only under a tested contract and exclude the ones that cannot preserve the invariants.

Warning

The macOS compatibility backend is the one explicit exception: it does counted deletion and retyping, outside S1, S4 and S6, under the terms in ADR 006. It is chosen before any edit and never used to repair a failed composition write.

Mechanisms rejected as generic fallbacks, each with a reproduced or source-level failure:

MechanismFailure
Accessibility temporary selection, then replaceInput typed after selecting overwrites the exposed selection before revalidation
Whole-field accessibility set from a snapshotConcurrent input disappears when the old value is written back
Counted Backspaces, then insertContinued input changes what gets deleted; tags and pacing don’t serialize the host
Absolute range over committed textThe host can change text after validation; a generation check detects but can’t retract
Clipboard paste and restoreExposes text to clipboard history; a late restore overwrites a newer clipboard
Input suppression and replayFocus can move while queued; replay can duplicate, redirect or drop input

docs/regressions.json holds the negative and state-machine schedules for these. A test passes by detecting the prohibited transport’s damage or by refusing the schedule; it must not make Keyrill reproduce the unsafe edit.

Eligibility and key disposition

Automatic correction requires an enabled policy, an admitted control, no Secure Input, a known input mode, a complete whitespace-delimited token and no foreign composition. Exclusion is checked before any text is read or composition starts. Secure, read-only and uncertain controls must get neither, but the macOS adapter can’t tell them apart within an application: admission is per application by bundle identifier, and Secure Input is one global flag, so it detects neither per-field passwords nor read-only or sensitive fields (macOS).

A key is consumed only under a reviewed handling contract. A plan rejected before any write passes the key unchanged. Punctuation, Tab and Enter are not correction triggers: a still-owned word is finished under the native lifecycle and the key goes through. Never delay or replay Enter, Tab, navigation or shortcuts to gain inference context.

Configuration and snapshots

Disk reads stay out of keyboard callbacks. The model is embedded and validated once per process, before the input server starts. Personal vocabulary is parsed off the input thread into immutable snapshots and published whole; an invalid candidate keeps the last good snapshot. Each decision uses one snapshot. Invalid configuration keeps the last valid configuration and reports a content-free error; safety settings are never partially applied.

Privacy and trust boundary

An input method sees everything typed in a client that selects it. Safe Rust doesn’t change that: native code, dependencies, the model, installation and updates are all inside the trust boundary. Keyrill keeps at most one word, one reversal receipt and 256 UTF-16 units of its own finished words in memory, clears them when the session is invalidated or reset, and writes none of it anywhere. Diagnostics are content-free counters and status. Private text can still exist in a crash dump; Keyrill doesn’t claim secure erasure. Personal dictionaries stay user-owned, read-only and out of release assets. No telemetry, remote configuration, automatic update or privileged helper.

Lifetime

Quit stops new operations, finishes only a valid owned mark, detaches native sinks and releases handles after callbacks drain. An engine is never freed while a callback can still reach it. Rust panics are contained at the ABI and poison the handle. Windows callbacks also contain Rust panics. Windows foreign COM implementations must obey the HRESULT and no-throw contract. The macOS adapter contains native exceptions on its side of the ABI. A caught panic does not recover allocation aborts or a partially mutated host.

Engine

keyrill-core converts text between layouts, decides whether a typed word is a layout mistake, parses personal vocabulary and tracks the word session. It makes proposals and never reads or edits a native document. The C ABI over it is described in porting and include/keyrill.h; how Keyrill works walks one decision through with real numbers.

Layout mapping

Layouts are US QWERTY and Russian ЙЦУКЕН. Apple’s Russian layout and the PC Russian layout differ on the ё key and are separate Keyboard values; the macOS adapter uses the Apple map. A verified Windows or Linux layout table is the adapter’s job, not something to infer from Apple’s Russian-PC layout.

Mapping::EnToRu and RuToEn convert physical key positions. Mapping::Manual converts each supported letter and leaves punctuation and unsupported UTF-16 units, including unpaired surrogates, unchanged. It is not an involution; don’t test it as one.

A word is a run of EN/RU letters (mapping::is_letter). In English mode the keys that type х, ъ, ж, э, б, ю and ё in Russian ([ ] ; ' , ., the ё key for the session’s keyboard, \ on Apple and ` on PC, and their shifted forms) are provisional letters: inference::is_provisional units can start or continue a word, so [jhjij becomes хорошо and ;bpym becomes жизнь. A word that isn’t corrected is committed exactly as typed, so hello, stays hello, and a lone ... or ; stays punctuation. Such a key is part of the composition rather than passed to the host, so host behavior tied to the key itself, such as smart quotes or bracket pairing, doesn’t apply to it. In Russian mode these keys are letters and nothing else changes.

US key[];',.\ (Apple), ` (PC)
Russian letterхъжэбюё

Inference

At Space, Session::propose_with_inference evaluates the owned complete word against borrowed model and vocabulary snapshots and keeps no borrowed input in its pending plan. After the eligibility, personal-vocabulary and known-word checks below, a typed word w whose other-layout reading c is in the target lexicon with Zipf at least 2.5 is corrected when

\[ \log_{10} f_{\text{target}}(c) - \log_{10} P_{\text{source}}(w) + \log_{10}\frac{p}{1-p} + \log_{10} k \;\ge\; \log_{10} C + \pi(|w|) \]

where f is the candidate’s word frequency, P the order-2 character chain’s likelihood of the typed letters, p = 0.001 the error prior, k the context factor (19 when the session’s recent words are in the target language, 1/19 when they are in the source language, 1 otherwise), C = 100 the false-change cost, and π a length penalty of 4, 2 and 1 for one, two and three UTF-16 units. Policy holds p, C, the minimum Zipf and the known-word gate values.

Note

These are uncalibrated ranking parameters, not probabilities; the numeric domain limits the Zipf values and margins to 0..=9. The evaluation records their measured behavior and the limits of the policy experiments.

A typed string that is a word in its own layout’s lexicon (Known, reason 3) yields to the other reading only when it is rare and the other reading is far more frequent: its Zipf score must be below 3 and the candidate’s must exceed it by at least 2.5, or 3.5 for a word of two UTF-16 units without context in the target language. A yielding word is corrected on the frequencies alone, scored by the difference of the two Zipf values, which is the base-10 logarithm of their frequency ratio; the character chain adds nothing for a string the lexicon already has. So yf (Zipf 2.37) becomes на (7.25) and ghb becomes при, while lf (3.40) stays lf. A word of one unit never yields; the rule counts the whole word, so e. is two units.

For a provisional word the candidate is the whole key sequence read in Russian. Case is judged on that reading. The English reading is the letters alone: the character chain scores them, and each provisional unit before, inside or after the letters adds log10 of how often such punctuation appears there in English words (−2.3, −1.6 and −1.0, measured on the EWT dev split). Only punctuation at the end leaves an English core, and that core gets known-word protection, so it. doesn’t become шею and he, doesn’t become руб. A word without letters is ineligible.

A three-unit word with a candidate Zipf of at least 4 gets another 3 log10 units of evidence per leading provisional unit, unless context supports the source language. This lets [jl become ход and ,sk become был without preceding context. It can also convert an intentional literal fragment; personal-vocabulary and known-word protection still apply before scoring.

The engine abstains on unknown modes, unsupported or mixed-script tokens, mixed case, multi-letter all-capital words and invalid policy values. A single initial capital is eligible (Ghbdtn becomes Привет). Decision reasons are numbered for the reference vectors:

ReasonMeaning
0Correction
1Ineligible token
2Protected by personal vocabulary
3Known word in the source language
4Candidate forbidden by personal vocabulary
5Evidence too weak
6A configured dictionary is missing
7Explicit manual or reversal intent

Personal recognized and rare words are protected. A forbidden entry overrides personal and general protection, and a forbidden candidate is rejected. Candidate membership doesn’t supply a frequency or justify a correction by itself. Mapped punctuation outside the target alphabet is ineligible.

Both personal sources must be ready before automatic correction runs. A valid empty source is ready; a missing one is not, though a host may publish a missing default-path file as empty (macOS does, with KR_SOURCE_MISSING_IS_EMPTY). Manual conversion works regardless. Manual and reversal intent stop reinference of that word; a typo fix alone doesn’t.

Context

Language context comes from the session’s own verified finished words, at most 256 UTF-16 units, never from reading the document. A finished word plus Space is appended on an acknowledged finish; a still-reversible Space mark is not. Refusal, unknown effects, reset, mode changes and unowned host actions clear it. So does printable punctuation, because the host’s action on it isn’t acknowledged. The context scan takes the last two known same-language letter runs on the current line, skipping non-letters and stopping at LF/CR; dropping punctuated context can remove the protective factor of 19, so change that scan only with a new evaluation.

Personal vocabulary

The engine reads Vim .add word lists (:help spell), UTF-8, at most 1 MiB, line by line as Vim reads them. Supported: an initial BOM, LF/CRLF, blank and comment lines, /encoding=utf-8, /regions=, and the flags =, ?, ! and 1 through 9. A line whose first byte is # is a comment whatever follows, because Vim’s zw, zug and zuw comment out an entry by overwriting that byte. A line that isn’t UTF-8, an unknown directive or flag, a word with a control character and other bad lines are skipped and counted (Vocabulary::skipped). NUL anywhere, oversized input or a leading /encoding= other than utf-8 rejects the whole file. Unicode whitespace at line edges, including NBSP, is stripped.

A lowercase entry protects lowercase, capitalized and uppercase forms; a cased entry protects its exact and uppercase forms; /= requires exact case. Across matching entries, forbidden (!) wins, then recognized, then rare (?).

EntryMatchesEffect
hellohello, Hello, HELLORecognized: never corrected
iPhoneiPhone, IPHONERecognized
iPhone/=iPhone onlyRecognized
colour/?as for helloRare: still protected
ghbdtn/!as for helloForbidden: overrides any protection and is never a correction’s result

A /regions= line and the region flags 1 through 9 are validated and then dropped, so lookup doesn’t depend on locale; the flags are accepted even without a declared region name. A malformed /regions= line is skipped like any other bad line.

vocabulary::Snapshot::replace parses the whole candidate before publishing it. Readers keep the old immutable Arc and a failed candidate never partially replaces it. keyrill-ffi reads the files for the adapter; see macOS.

Words the user taught the OS spell checker (Learn Spelling on macOS, Add to dictionary on Windows) are a second kind of source. Vocabulary::parse_words reads such a list as one word per line, UTF-8 with an optional BOM or UTF-16 LE with its BOM; every line is a word, so # and / are ordinary characters. Each word takes the case rule of an unflagged Vim entry and is recognized, or forbidden when the list holds excluded words. The lists go into Dictionaries::learned and protect and forbid together with the Vim sources, but readiness depends only on the two Vim sources: a learned list that is missing or unreadable never holds correction back.

Model

flowchart TD
    W["wordfreq 3.1.1"] -->|"model/tools/build_model.py"| I["model/data/model.inc.gz<br/>pinned by hash"]
    I -->|"tools/pack-model.py"| B["assets/model.bin"]
    B -->|"include_bytes!"| C["keyrill-core"]
    C -->|"Model::parse, once per process"| M["Model, borrowed<br/>by every decision"]

assets/model.bin holds 89,656 English and 241,624 Russian words with log10 frequencies, plus an order-2 character chain per language. It is derived from wordfreq 3.1.1 large lists. The loader checks the magic, version, source-hash field, alphabets, counts, offsets, word indices, ordering, section bounds and trailing bytes, and validates once outside input callbacks. Header checks are consistency, not authentication: tools/pack-model.py --check regenerates every asset from the pinned source in model/data/model.inc.gz and compares bytes. Its docstring specifies the format.

The packer stores every value as a signed integer in micro-units and reproduces all 396,107 source values bit-exactly as f64. It doesn’t retrain, recalibrate or renormalize anything. To regenerate the source itself, see model/README.md.

Evaluation

./tools/verify evaluate runs model/tools/evaluate.py against tools/inference-probe, offline, over the pinned Universal Dependencies dev and test splits of English EWT and Russian Taiga, and fails if a gate below fails. Reports, including every false correction, go to target/evaluation/docs/results/. No personal dictionary is read. The current policy was selected on dev after inspecting earlier holdout and test failures; repeated test results are exploratory, not independent confirmation.

The evaluation types text through the real Session the way the macOS adapter drives it: a word starts only after whitespace or at the start of the document, a write is applied only if the simulated composition holds exactly the plan’s expected text and is acknowledged after it is applied, and a mode change finishes the word and resets the session. A mismatch, or a passed key that would land inside the composition, stops the evaluation with an error. Each sentence is one document, typed in one go with a Space after it.

  • Wrong-layout replay. Every sentence (# text) is typed on the keys of its own Apple layout while the other mode is active, so Russian , arrives as ^ in English mode and English , as б in Russian mode. Per language: token recall is the share of whitespace tokens that changed under the wrong layout and come out exactly as intended; word recall is the same over tokens that are letters only; first-error recall is the share of sentences whose first wrong token is fixed, the one that matters when a correction switches the input source. A token changed to anything else is a miscorrection.
  • Right-layout replay. The same sentences typed correctly, each token in the mode of its script, so Latin words in Russian text switch modes. Any change is a false correction.
  • Negative set. Isolated tokens, each typed as token in a fresh session, so no context protects them: corpus words the model knows (known) and doesn’t know (oov), proper nouns (names), simple Latin transliterations of the Russian words (translit), and every single-edit keyboard typo of the corpus words, made by deletion, transposition, or substituting or inserting a neighboring key, including the keys that are provisional letters (typo). The report also counts how many tokens reach the scoring step.

Results with the default policy:

SplitRU token / first-error recallEN token / first-error recallRight-layout falseTypo false (per 10,000)Other negatives false
dev54.5% / 54.2%62.0% / 48.4%0 of 35,03123 EN (0.92), 29 RU (0.73)1 translit of 5,197
test49.7% / 50.7%61.6% / 48.0%0 of 33,89924 EN (0.97), 23 RU (0.66)0

Correct corpus words, known or not, never reach the scoring step; names reach it once on test and never on dev. These cases guard against regressions but supply little evidence for choosing a threshold. Typos and transliterations do: about 600 of the roughly 600,000 typos per split reach scoring, and they are what bounds the minimum candidate Zipf. The known-word gate can only open for lexicon words, so its whole exposure is the list of lexicon words whose other reading passes it, which the negative set below pins.

Remaining misses include words finished by punctuation rather than Space, protected lexicon words such as lf for да, candidates absent from the model or below the frequency floor, and candidates whose scores remain below the length-adjusted threshold. Return and Tab also finish the word without running inference.

The gates, in tools/evaluate-model.py, apply to both splits:

GateBoundWhy
Token recall, RU / EN≥ 44% / ≥ 58%About two points under the original policy’s lower split
First-error recall, RU and EN≥ 45%About two points under the original policy’s lower split
Right-layout false corrections, both languages≤ 2Measured 0; 2 of about 34,000 tokens is under 1 per 10,000
Wrong-layout miscorrections≤ 2Measured 0
Known, OOV and name false corrections≤ 2Measured 0
Transliteration false corrections≤ 3Measured 1 on dev, 0 on test
Typo false corrections, per language≤ 1 per 10,000Measured 0.66 to 0.97

Important

Errors are synthetic, typos and transliterations are generated, every sentence is typed without Backspace or source switching, and wordfreq’s sources may overlap these corpora. None of this estimates precision on real typing.

The release target is fewer than one false automatic correction per 10,000 eligible correct words. No offline source with a redistribution license covers real chat, code review, identifiers or Russian social text beyond Taiga; adding one means pinning it by hash with its license next to the existing corpora.

A policy change needs the evaluation rerun on dev, the reference vectors still passing and the negative set below unchanged except for cases the change is meant to open. Don’t edit expected values to remove failures.

Reference tests

crates/keyrill-core/tests/fixtures/engine-vectors.jsonl has 1,217 expected outputs: 90 mapping, 120 vocabulary, 7 context and 1,000 inference requests. Inference scores are compared with a relative tolerance of 1e-12 and an absolute tolerance of 1e-10. The request protocol:

RequestResponse
map K MODE TEXTMODE 0 manual, 1 EN→RU, 2 RU→EN; output as UTF-16 hex
vocab SOURCE WORDParse success 0/1, entry count, lookup (0 absent, 1 recognized, 2 rare, 3 forbidden)
context PREFIXLanguage tag
infer K ACTIVE CONTEXT PRIOR COST MINZIPF EN_ADD RU_ADD WORDReason, score, replacement hex or -

Hex strings are UTF-16 units, - is empty, keyboards are 0 Apple and 1 PC, languages are 0 unknown, 1 EN, 2 RU. negative-words.md describes 766 words and model collisions that must never be corrected, run under three contexts and both keyboards. Inference requests set three policy values; the known-word gate takes its defaults.

Model source and evaluation

Build-time data and tools behind assets/model.bin. Nothing here is read at runtime. Every file is byte-pinned: the top-level tools/pack-model.py checks the model source by hash, evaluate.py checks the corpora against data/evaluation-sources.json, and data/model-manifest.json records the hashes of the generator and its locked requirements. Don’t reformat, re-encode or trim anything here; .gitattributes keeps Git from converting line endings or whitespace.

PathContents
data/model.inc.gzWord frequencies and order-2 character chains for EN and RU, gzip-compressed
data/model-manifest.jsonGenerator, requirements, Python and source hashes; package versions; model parameters
data/model-notice.txtCC BY-SA 4.0 attribution for the wordfreq-derived data
data/wordfreq-code-license.txtwordfreq’s Apache-2.0 code notice; it doesn’t change the data license
data/evaluation-sources.jsonPinned upstream URL, size and SHA-256 of every corpus file
corpora/UD English EWT and UD Russian Taiga dev/test splits with their READMEs and licenses
tools/build_model.pyGenerates model.inc from wordfreq 3.1.1
tools/model-requirements.{in,txt}Hash-locked Python environment for the generator
tools/evaluate.pySession replay and negative-set evaluator, run by the top-level tools/evaluate-model.py, which also checks the gates

The vocabulary is wordfreq’s unfiltered usage data, so it includes profanity and slurs. That is deliberate: the engine never suggests a word, it only decides whether to read the user’s own keystrokes in the other layout, and a filtered word typed in the wrong layout would stay uncorrected.

To inspect the source, decompress it and compare the plaintext SHA-256 with model_sha256 in the manifest; the compressed file’s hash is a different value.

$ python3 -c 'import gzip,pathlib; p=pathlib.Path("model/data/model.inc.gz"); p.with_suffix("").write_bytes(gzip.decompress(p.read_bytes()))'
$ shasum -a 256 model/data/model.inc

To regenerate, create a separate virtual environment, install tools/model-requirements.txt with --require-hashes, and run tools/build_model.py. It writes model.inc and short-words.json into data/; compress the first with gzip and compare hashes. A different Python version changes the manifest even when the model bytes agree. Then update the pinned hashes in the top-level tools/pack-model.py and rerun the evaluation.

flowchart TD
    G["tools/evaluate-model.py<br/>gates"] --> E["model/tools/evaluate.py<br/>replays, negative set"]
    E <-->|"stdin, one line<br/>per request"| P["tools/inference-probe<br/>real Session and infer"]
    C[("corpora/<br/>pinned by hash")] --> E
    E --> R["target/evaluation/<br/>reports"]

The evaluator talks to tools/inference-probe over stdin, one response line per request line, with four hex digits per UTF-16 unit and - for empty. The first argument picks the protocol; optional NAME=VALUE arguments override fields of the default Policy, such as minimum_zipf=3.5, for parameter sweeps on the dev split.

ProtocolRequest lineResponse line
worden|ru WORD_HEX CONTEXT_HEXREASON<TAB>LOG10_SCORE<TAB>REPLACEMENT_HEX
sessionMODE:HEX segments separated by spacesThe document after typing every segment, as hex

session types each segment unit by unit in its mode (en or ru) through a fresh Session, acting as an adapter that verifies every plan, starts a word only after whitespace and finishes and resets the session when the mode changes, and finishes the word at the end. The evaluation generates its typos and transliterations from the pinned corpora at run time, so it adds no data files and needs no network.

Licenses

The derived frequency and character data is CC BY-SA 4.0, from wordfreq 3.1.1 by Robyn Speer; keep model-notice.txt and its source credits with the data and any binary that embeds it. EWT and Taiga are CC BY-SA 4.0 with their own READMEs and license files in corpora/. The EWT README links to files in its upstream repository that aren’t copied here; see the pinned EWT source.

macOS adapter

native/macos is an InputMethodKit input method written in Objective-C++ with ARC. It links the keyrill-ffi static library and calls Rust only through include/keyrill.h. Building, signing and installing it are covered in the README; the walkthrough shows one correction through these files.

FileRole
src/main.mmReads configuration, prewarms the model, starts IMKServer
src/KRController.mmIMKInputController: lifecycle, input menu, tier routing, source switching
src/KRSession.mmOwned-composition session: client checks, plan/acknowledge loop with Rust
src/KRCompatibility.mmCompatibility backend: observed input, event posting, metadata guard
src/KRRuntime.mmPolicy and tier snapshot, dictionary acquisition worker, deferred adoption
src/KRPreferences.mmSettings window and preference merging
src/KRKeys.mmNSEvent to kr_event translation, including the two command chords
tools/input_icons (icon checks and generation), source_status, source_enable --plan
tests/Controlled session, runtime and preferences tests; browser fixture

Bundle identity

The bundle is KeyrillAlpha.app, identifier org.keyrill.inputmethod.alpha, connection org.keyrill.inputmethod.alpha_Connection, with modes .English and .Russian shown as Keyrill EN and Keyrill RU. Info.plist declares the controller class, the connection name, ComponentInputModeDict with both modes and TISIntendedLanguage, and the Latin and Cyrillic repertoire. Keep the plist and the server initialization in agreement. build.sh reads CFBundleIdentifier from the plist and compiles it in as KR_BUNDLE_IDENTIFIER; the mode identifiers and Keyrill’s own Off tier derive from it, and the server refuses to start from a bundle with a different identifier.

Registration, enablement, appearance in Settings, selection, server launch, controller activation, key delivery and correct document output are eight separate checks. native/macos/build.sh status reads the TIS identities and flags without changing anything. A mode needs both its own and its parent’s enabled state to be selectable. Don’t edit AppleEnabledInputSources, reset input-source databases or mint new identifiers to work around a registration failure; start with read-only diagnostics.

The deployment target is macOS 13.0, which is a compile setting, not a tested OS range. Ad-hoc or self-signed code signing checks integrity only. There is no Developer ID signing, notarization or stapling yet.

Application tiers

Every application falls in one tier, chosen by bundle identifier when a client activates and before any edit:

flowchart TD
    A[Client activates] --> SI{Secure Input on?}
    SI -->|yes| WAIT[Route at the first key<br/>that arrives with it off]
    SI -->|no| ID{Bundle identifier}
    WAIT --> ID
    ID -->|"missing, or Keyrill itself"| OFF[Off]
    ID -->|in ApplicationTiers| USER[Your choice]
    ID -->|in a built-in list| LIST[Listed tier]
    ID -->|unlisted| UN{UnlistedAutomatic-<br/>CorrectionEnabled?}
    UN -->|no| MAN[Manual only]
    UN -->|yes| AUTO[Automatic]
    USER --> CE{"Manual only or Automatic,<br/>with CompatibilityEnabled off?"}
    LIST --> CE
    MAN --> CE
    AUTO --> CE
    CE -->|yes| OFF
    CE -->|no| DONE[Tier for this activation]
TierBehaviorBuilt-in applications
Composition (direct editing)Owned composition: automatic and manual correction, reversal, exact checksTextEdit, Safari, Firefox
Manual onlyCompatibility backend on Control+Option+K and Control+Option+Z onlyTerminals, editors and IDEs with completion, Microsoft Office
AutomaticCompatibility backend, also correcting on SpaceNone
OffPass-through, no client inspectionPassword managers, remote desktops and virtual machines, Keyrill itself

An unlisted application gets Manual only, or Automatic when UnlistedAutomaticCorrectionEnabled is on. A missing, empty or non-string bundle identifier is Off. With CompatibilityEnabled off, Manual only and Automatic become Off; an unlisted application never gets composition. Secure Input passes every key whatever the tier.

The built-in lists live in KRRuntime.mm. Composition entries match the bundle identifier exactly. The others ignore case, and an entry ending in a dot matches a prefix:

TierBundle identifiers
Compositioncom.apple.TextEdit, com.apple.Safari, org.mozilla.firefox
Manual onlycom.apple.Terminal, com.googlecode.iterm2, com.mitchellh.ghostty, com.github.wez.wezterm, org.alacritty, net.kovidgoyal.kitty, dev.warp.Warp-Stable, dev.warp.Warp-Preview, co.zeit.hyper, com.umputun.agterm, com.umputun.agterm.debug, com.apple.dt.Xcode, com.microsoft.VSCode, com.microsoft.VSCodeInsiders, com.jetbrains. (prefix), com.sublimetext.3, com.sublimetext.4, dev.zed.Zed, dev.zed.Zed-Preview, org.vim.MacVim, org.gnu.Emacs, com.microsoft.Word, com.microsoft.Excel, com.microsoft.Powerpoint, com.microsoft.Outlook
Offcom.1password.1password, com.agilebits.onepassword7, com.apple.Passwords, com.apple.keychainaccess, com.apple.ScreenSharing, com.microsoft.rdc.macos (Microsoft Remote Desktop and Windows App), com.parallels.desktop.console, com.utmapp.UTM, com.vmware.fusion

Correction in This App in the input menu overrides the active application’s tier, or returns it to the default. The choice is stored in ApplicationTiers and applied at once: the controller installs a runtime built from the new preferences, finishes an owned mark through the verified path and routes the application again. Any tier can be chosen for any application except Keyrill itself. Choosing Composition for an application outside the built-in list admits a client that hasn’t been tested; one that can’t reflect and read back marked text stops correction at its first word.

Admission is per application, not per field: every surface of an admitted application is eligible, including address bars and inspectors. Routing reads only the client’s bundle identifier. IsSecureEventInputEnabled is checked before routing and before a key’s characters are read; when it is on at activation, routing waits for the first key that arrives with it off. It is a global guard, not per-field password detection. agterm is Manual only because its client gives preedit-relative ranges without substring readback, so even the first marked update can’t be verified.

Composition

Before starting, the session requires an admitted client, a known mode, a collapsed valid caret, no foreign mark and a complete token context. After that, every write is bracketed by checks of the same client and generation, and the generation is rechecked after every client call. The edit contract lists every check, key disposition and outcome; KRSession apply:client:generation: implements it with these IMK calls:

WriteIMK call
Start, update or empty the wordsetMarkedText:selectionRange:replacementRange: over the current selection
Finish with new textinsertText:replacementRange: over the current selection
Finish unchangedinsertText:replacementRange: over the exact marked range

The mark and caret checks read markedRange and selectedRange. “Exact text” is a readback through stringFromRange:actualRange: that must return the expected UTF-16 units over the expected range, and the range IMK actually returned must be that range.

The two unchanged finishes relax checks for a reason Firefox supplies. It moves the caret on focus loss before IMK asks for the commit, so an unchanged commit, which replaces the exact marked range with the same text, skips the caret. When IMK or the controller requests the commit (commit request, deactivation, a mode change or a click) rather than a typed key, Firefox’s readback over the exact range matches nothing typed at that moment, and after committing on its own it keeps reporting the old marked range, which would block every later word in the field. So the session writes back the text it last verified in the mark without reading it again. Only Keyrill changes its own mark, and the exact marked range is still required.

Secure Input is checked at entry and again after each client query that precedes a text read or a write. Range units, NSNotFound sentinels and mark-relative selection are kept distinct; arithmetic is checked against overflow and surrogate splits.

setMarkedText gets the attributed value with a selection relative to that value. The tested clients update their active composition under the NSNotFound replacement range; this is used only for the owned composition, never to replace a selection or a remembered committed range. Clients that lack document access can ignore explicit ranges, so selector availability is no reason to admit a client.

After Space, the word and Space stay marked until the next event. That keeps reversal possible and avoids Firefox returning empty ranges for immediately committed text, at the cost of a longer underline and per-host Undo grouping. An empty composition uses an empty owned setMarkedText; empty insertText left a stray character in TextEdit.

The controller handles activation, mode changes, commit requests, cancellation, deactivation and shutdown, invalidating generations before stale work can run. It recognizes left mouse-down so it can finish a valid mark and return unhandled: a keyboard-only event mask swallowed clicks in Firefox. Ordinary keys arrive already translated by the host and the selected layout; only supported letters are composed, and dead keys, Option input and shortcuts pass through after a finish. An uncertain update stops correction for that word and shows a pause in the input menu; the next text key starts a new word from the same fresh client checks as a first one. The session stays stopped until reactivation after a second uncertain update in the activation, or when no write has verified since activation, as in a client that ignores writes.

When the client’s readback after a write doesn’t match, the effect is unknown. An NSTextView replaces marked text with the next key the input method passes, so a stopped session would lose the word on the following key. Keyrill therefore reads the marked range and its exact text once and commits that readback with insertText(readback, markedRange), then stops.

Important

This is the only write after an unknown effect, and it repairs nothing: it keeps what the client shows. Nothing is written when the mark, its exact readback or the range IMK returns is unavailable, after a reentrant callback or client exception, or once Secure Input is on. The key keeps its disposition: a mark that carried it consumed it, a finish passes it.

Compatibility

The compatibility session watches passed-through input in bounded memory and rewrites the observed run by posting Backspace and Unicode key events to the captured foreground process. Automatic correction also requires that run to start after a Space observed since reset. The original Space passes and is counted in the deletion; the replacement carries its own Space. A listen-only event tap, the guard, observes mouse, navigation, shortcut and source changes without reading characters and expires tracking on them; each such event, and the tap being switched off by a timeout, advances the process-wide guard generation. Secure Input, foreground identity, the guard generation and the session generation are rechecked before each post. Synthetic events are tagged, and a bounded expected-key sequence suppresses replanning when a tag is stripped.

It needs Accessibility (event posting) and Input Monitoring (the guard tap) already granted, and only for applications in the Manual only or Automatic tier. Keyrill preflights both without prompting when such an application activates and shows each missing permission in the input menu; missing access disables compatibility and leaves typing alone. The guard tap starts on main after an activation, outside the callback, so permissions granted later take effect at the next activation. A tap the system disables by timeout or user input is re-enabled and tracking restarts. Permissions are preflighted once per handled key, not before each posted event: a revocation between two posts of one synchronous batch is a race that a check before each post can’t close either.

Warning

None of this verifies the host’s result. The guarantees the compatibility backend gives up are listed in ADR 006.

Configuration

main.mm reads the defaults domain org.keyrill.inputmethod.alpha at startup. External defaults edits need a restart; the Settings window applies changes in-process.

KeyMeaning
AutomaticCorrectionEnabledtrue selects the model policy. Default off
AutomaticInputSourceSwitchingEnabledSwitch modes after an automatic correction. Default on
LearnedWordsEnabledRead the Learn Spelling list. Default off
EnglishDictionaryPathAbsolute path, at most 1,024 bytes. Default ~/.vim/spell/en.utf-8.add
RussianDictionaryPathSame, default ~/.vim/spell/ru.utf-8.add
CompatibilityEnabledAllow the Manual only and Automatic tiers. Default on; off makes them Off
UnlistedAutomaticCorrectionEnabledUnlisted applications get Automatic instead of Manual only. Default off
ApplicationTiersDictionary of bundle identifier to composition, automatic, manual or off. Written by the input menu

Boolean keys take an NSNumber; any other type disables the feature. ApplicationTiers entries with another key or value type, an unknown tier name or Keyrill’s own identifier are ignored. A file that doesn’t exist at a default path is an empty dictionary until one is created there; a file that doesn’t exist at a configured path, or a present but unusable path, leaves that language missing and never falls back to another file. The home directory comes from getpwuid_r, not $HOME. With the model selected, the asset is validated on the main thread before IMKServer starts; a failure leaves automatic correction off.

Settings… in the input menu opens a non-modal window with the automatic-correction switch, source switching, compatibility options and both dictionary paths. Save merges these keys into the domain, keeping unrelated ones such as ApplicationTiers, and installs a replacement runtime. Each controller finishes its old owned mark through the verified path and picks up the new configuration on its next activation. Dictionary contents are never displayed or logged.

Input-source switching

After an automatic correction Keyrill asks IMK for the Keyrill mode of the corrected language; manual conversion doesn’t switch. Composition requests the switch with the verified word and Space still marked. The request runs on main after the input callback, rechecks controller, runtime, generation, mode, guard generation and Secure Input, and is cancelled by newer real input or any lifecycle callback. It doesn’t consult TIS: in the input method’s process TISCopyCurrentKeyboardInputSource reports the overridden keyboard layout, such as com.apple.keylayout.US, not the Keyrill mode. selectInputMode: reports nothing, so a mode that isn’t enabled in Input Sources silently stays unselected. _mode changes only on IMK’s mode echo, and keys typed before the echo arrives still use the old mode.

sequenceDiagram
    participant S as KRSession
    participant C as KRController
    participant I as IMK
    S->>C: Space verified, "привет " still marked
    Note over C: after the input callback returns
    C->>I: selectInputMode: Keyrill RU
    I-->>C: mode echo: Russian
    Note over C: matches the pending request:<br/>keep the mark and its receipt
    C->>S: next key, planned in the mark's own mode first

When the echo matches Keyrill’s own pending request, with no guard event other than source changes since, the controller keeps the session, the owned mark and its reversal. The mark is still planned in its own mode: reversal or Escape restores the typed word there, and any other key finishes the mark before it is planned in the new mode. Any other mode change finishes the mark first. Reversing a correction in the mode Keyrill switched to also requests the original mode again, because the switch was a consequence of the correction: keeping the new mode would type the next word in the layout the user just rejected.

Compatibility requests the switch after full dispatch and keeps its tracked word at the echo in the same way: a reversal in the new mode rewrites in the word’s mode and switches back, and any other input first restarts tracking in the new mode with the already-observed Space as the boundary.

Whether IMK calls commitComposition: or the client commits its mark during selectInputMode: hasn’t been observed on a physical host. Either way the result is safe: a commitComposition: finishes the mark through the verified path, and a mark the client dropped makes the next update’s readback check fail before any write, so reversal is refused rather than written over committed text.

Dictionaries

keyrill-ffi’s vocabulary_source (exported as kr_vocabulary_*) reads the two files on one serial utility queue, right after configuration and then every 2 seconds. It follows symlinks, requires a regular file before and after opening, opens read-only with O_NONBLOCK | O_NOCTTY, reads at most 1 MiB plus one byte, and compares descriptor and path identity, size, mtime and ctime around the read. Two equal observations of identity and bytes publish an immutable snapshot; failures keep the last good one. For a default path the adapter passes the account’s home directory to kr_vocabulary_configure_default, which names ~/.vim/spell/{en,ru}.utf-8.add: while no file there has been published, a path that doesn’t exist publishes an empty source. Once a file has been published, its absence keeps the last good snapshot, since an editor that saves by rename can leave the path briefly absent.

The same queue reads the list Learn Spelling writes only when LearnedWordsEnabled is a true NSNumber, set by Use words added with Learn Spelling in Settings. It is off by default, including for existing installations without the key: the learned source stays unconfigured and its path is neither configured nor read. When enabled, the list at ~/Library/Group Containers/group.com.apple.AppleSpell/Library/Spelling/LocalDictionary goes into slot KR_LEARNED, with a missing file counted as empty. It is one list for all languages, and the path is undocumented; the older ~/Library/Spelling/LocalDictionary isn’t read.

The container belongs to Apple’s spell service. On macOS 27 or later, access to another team’s container is denied by default without an authorization prompt. A Files & Folders entry is not guaranteed, so it is not the setup route. See Apple’s macOS 27 release notes.

Choose… beside the learned-words checkbox opens NSOpenPanel in AppleSpell’s Spelling folder, with LocalDictionary named. The chooser and runtime derive the expected path from the same KRRuntime method and the account home. Selecting that exact file checks the opt-in; another path shows an error without changing the opt-in or either language path. Canceling the picker leaves the settings unchanged. macOS may grant access when the file is selected, before Save: Cancel in Settings discards its edits but does not revoke access already granted. The runtime read determines whether the source is usable. Save applies whether Keyrill uses the source. No selected path or bookmark is stored, and the picker neither imports nor copies the word list.

Keyrill’s periodic observations retry the read. Access after selection, across process restarts or signing changes is not guaranteed. Choose the file again if the source becomes unavailable. A denied read leaves the source missing, which the menu shows; correction continues without it.

On earlier releases, macOS may request access to data from other apps. The bundle’s NSAppDataUsageDescription explains that Keyrill reads learned words to leave them as typed, never changes the list or sends it over the network, and lets the user turn this off in Settings. CFBundleDisplayName explicitly names the application Keyrill Alpha; the displayed requester name and purpose message still need physical confirmation on a release that prompts.

For a permission-recovery test, macOS 27’s per-container decisions use tccutil reset SystemPolicyAppDataDetailed org.keyrill.inputmethod.alpha; older decisions use SystemPolicyAppData instead. Resetting does not grant access, create a Files & Folders entry or make macOS 27 show an authorization prompt. See Apple’s purpose-string documentation, permission reset instructions and Mozilla’s macOS 27 file-picker flow.

Each source is in one of these states; the input menu shows a source only when it is missing or retained:

stateDiagram-v2
    [*] --> Loading
    [*] --> Missing: configured path unusable
    Loading --> Ready: two equal reads published,<br/>or an absent default file as empty
    Loading --> Missing: read fails before<br/>anything was published
    Missing --> Loading: a read succeeds
    Ready --> Retained: a later read fails
    Retained --> Ready: the next read succeeds

Retained shows as “update rejected, previous kept”: correction goes on with the last good snapshot. Only Missing on an English or Russian source keeps automatic correction off.

Caution

Two equal observations are a settling heuristic, not proof that a save finished: a writer paused after truncation across both reads can publish an empty file and drop protection.

Snapshots are adopted on main, outside any input callback, outside client dispatch and with no pending Rust plan; a refused adoption retries on the next observation. Adoption keeps history and the reversal receipt and makes no client calls. Shutdown never waits for a read in progress.

The input menu leads with one line saying whether automatic correction runs on the next Space in the active application, or the first reason it doesn’t: Keyrill off there, correction paused after a failed check, manual only, missing permissions, policy off, a missing dictionary, or dictionaries still loading. Below it the menu lists only what explains a failure: a tier that couldn’t be saved, a failed layout switch, each missing permission, a compatibility status other than ready, why the last word was left alone (excluded field, Secure Input, no word boundary, the app changing the mark, caret or text, no readback, engine refusal, client exception), and each missing or retained source. The Correction in This App submenu opens with the application’s tier and where it comes from (built-in, unlisted or the user’s setting). None of it contains text, offsets, bundle identifiers or paths, and none of it queries the client; the tier comes from the bundle identifier read at routing.

Bundle

native/macos/build.sh bundle builds the one bundle; tiers and preferences decide admission. The browser fixture is a test file and isn’t bundled. Use a fresh .noindex output directory so Spotlight and LaunchServices don’t pick up build products as a second input method.

Icons

Each mode declares a TISIconLabels text label, EN or RU, requesting a badge rendered by macOS. The key is undocumented; whether a release honors it needs physical confirmation. resources/icons holds the fallback: Template and Selected masters for the menu bar, drawn as a rounded badge with the letters cut out, and black-on-white palette badges for the switcher, at 16 and 32 pixels each. Builds check references, representations, transparency and monochrome ink but never render them. To regenerate, run input_icons --write (masters) or input_icons --write-palette (badges) from the native output directory against native/macos/resources/icons, then review the new files.

Porting to Windows and Linux

A new platform needs a native input-method adapter and nothing else: the engine, model, vocabulary parser, word session and C ABI are shared. Read architecture first; its state table, safety invariants and rejected mechanisms apply to every adapter. Don’t write a second inference engine, and don’t build a cross-platform editing abstraction before two adapters have shown the same real contract (ADR 001).

The Windows C++ backend passed controlled-editor and bounded ordinary Notepad acceptance before the windows-rs migration. The full Rust runtime and proof tools passed complete native and experimental sanitizer suites. Fresh automated Rust editor checks passed correction, reversal, continuation, native Undo, focus preservation, exclusions, native lock denial, and bounded owned shutdown. Current Rust Notepad 11.2609.11.0 checks passed fixture correction, manual commands, continuation, native Undo, Find exclusion, a focus round trip, both model directions, and vocabulary reload. Physical boundary correction, reversal, and a rapid-typing and native Undo sequence also passed. The broader physical acceptance matrix remains pending. Historical packaged x64 Notepad 11.2607.14.0 acceptance covered the owned-composition executor, shared model, and vocabulary integration. Exact UIA checks covered both model directions, retained reversal, rapid continuation, native Undo, and vocabulary reloads. Physical command checks covered conversion and held reversal within one focus interval. Other versions now pass input under bounded-only containment, as do generic TSF hosts. Editing requires the compiled proof-editor or exact-version Notepad main-field contract, fresh native identity, writable state, scope, owned-range verification and revocation subscriptions. Browser and other generic application correction remains unimplemented pending authoritative per-field semantic evidence. Full Windows qualification remains in progress. No Linux adapter exists. An explicit-PID inspector supplies independent field evidence and named public-document checks. The evidence limits are recorded with Windows admission. Each platform starts with the same first slice: one real editor, physical keys, an owned composition, a Rust decision, a verified update, commit, then rapid continuation and a focus change, all checked against the whole document. Use the fixture policy (kr_set_automatic_policy with KR_POLICY_FIXTURE, which corrects only ghbdtn and руддщ) before the model and real dictionaries. Tray icons, settings UI and packaging come after that works.

Building the library

The Rust side builds with the pinned toolchain on any host. On Windows use an MSVC developer shell; on Linux any C toolchain.

$ cargo test --locked --workspace
$ cargo build --locked --release -p keyrill-ffi
$ cargo rustc --locked --release -p keyrill-ffi -- --print native-static-libs

Link keyrill_ffi.lib or libkeyrill_ffi.a together with the system libraries the last command prints. Include include/keyrill.h rather than copying its declarations; its static_asserts pin the struct layouts. CI runs the portable checks on windows-2025 and ubuntu-24.04 as well as macos-15.

Starting an adapter

Put the code in native/windows/ or native/linux/, next to native/macos/, with its own build script, tests and packaging. The Rust crates change only when the ABI does.

crates/keyrill-ffi/tests/abi_smoke.c is the smallest working caller and the place to start. It runs the whole loop against an in-memory document: plan a key, check the composition against expected, write mark, commit the outcome, and honor the key disposition, including KR_FINISH with KR_KEY_REPLAN. Its scenarios type ghbdtn and руддщ with Space under the fixture policy, restore with Escape, leave an unlisted word alone, and convert ёлка and [jhjij manually, including under the PC keyboard. ./tools/verify links and runs the C caller on macOS and Linux, with the system libraries --print native-static-libs reports. Windows has an independent Rust caller in crates/keyrill-ffi/tests/windows_abi.rs. It declares the published C structs and signatures, checks their literal layouts, and runs all nine original smoke scenarios against the ABI.

Wire the adapter into tools/verify through the host branch in the default mode. Windows dispatches to cargo xtask windows check, while its separate sanitize mode dispatches to cargo xtask windows sanitize. Desktop acceptance remains a separate gate. Platform setup goes in the Toolchain step of .github/workflows/verify.yml. Clippy and rustdoc run on every lane, so shared docs can’t link to an item that exists on one OS only (development).

The C ABI

include/keyrill.h is the authoritative contract; this is the map. Every key an adapter handles goes through one loop, the one abi_smoke.c implements and how Keyrill works traces on a real word:

flowchart TD
    K[Key or lifecycle event] --> P["kr_plan_event → kr_plan"]
    P --> A{action}
    A -->|"PASS, UNAVAILABLE"| C0["kr_commit APPLIED_VERIFIED"]
    A -->|"MARK, FINISH"| V{"Composition holds<br/>expected exactly?"}
    V -->|no| R["kr_commit REFUSED_BEFORE_WRITE;<br/>the key passes"]
    V -->|yes| W[One native write]
    W --> RB{"Checks after the write pass?<br/>Readback, except an unchanged lifecycle commit"}
    RB -->|yes| OK["kr_commit APPLIED_VERIFIED"]
    RB -->|"no, or can't tell"| U["kr_commit ATTEMPTED_UNKNOWN;<br/>stop, never replay"]
    OK --> D{disposition}
    C0 --> D
    D -->|KEY_PASS| HP[Pass the key to the host]
    D -->|KEY_CONSUMED| HC[Consume the key]
    D -->|"KEY_REPLAN, after FINISH only, once"| P
  • Versioning. Pass KR_ABI_VERSION from the header to kr_engine_new(abi, &engine). Before 1.0 there is no compatibility promise: any other version is refused with KR_VERSION, and a change that breaks callers bumps the minor version.
  • Threading. One engine per input context, called serially from the thread that owns that context. Buffers are copied in both directions and borrowed only for the call; no pointer into Rust storage crosses the boundary. Lengths are UTF-16 units.
  • Composition path. Send each key as a kr_event (KR_TEXT, KR_BACKSPACE, KR_ESCAPE, KR_MANUAL, KR_REVERSE, or KR_FINISH_REQUEST for any other key or lifecycle request) with the mode and a context tag to kr_plan_event: KR_CTX_BOUNDARY when the caret is at the document start or follows whitespace, KR_CTX_INELIGIBLE otherwise, including when you didn’t read the prefix. The kr_plan says what to do (KR_PASS, KR_MARK, KR_FINISH, KR_UNAVAILABLE), what the composition must contain beforehand, the new mark and what to do with the key (KR_KEY_PASS, KR_KEY_CONSUMED, KR_KEY_REPLAN). The caret goes at the end of the mark, mark_len; KR_MARK with mark_len 0 empties the composition. Perform at most that one write, verify it, then kr_commit with KR_APPLIED_VERIFIED, KR_REFUSED_BEFORE_WRITE or KR_ATTEMPTED_UNKNOWN.
  • Policy and dictionaries. kr_set_automatic_policy selects off, fixture or model while idle. kr_prepare_model warms the existing process-wide model cache on a worker without an engine. kr_dictionary_parse_utf8 creates an immutable dictionary handle off the input thread; kr_adopt_dictionaries borrows a pair on the engine owner and retains independent references. Free handles with kr_dictionary_free after their borrows drain, even after adoption. A null language handle means missing; a parsed empty source means ready. Pair adoption rejects any pending proposal and preserves policy, word history and reversal receipts. kr_set_dictionary_utf8 publishes a whole dictionary (at most 1 MiB, NULL+0 is a valid empty source); kr_clear_dictionary makes a language missing. The kr_vocabulary_* handle reads and settles the files for you, as macOS describes; the adapter owns the serial queue it observes on and adopts snapshots outside input callbacks. Paths are UTF-8 on Windows. kr_vocabulary_configure_default takes the home directory and names Vim’s own files under it, ~/vimfiles/spell/{en,ru}.utf-8.add on Windows and ~/.vim/spell elsewhere. std has no stable file identity on Windows, so a read there is checked against size and the modified and creation times; the byte comparison between two observations still catches a same-size replacement. Learned slots KR_LEARNED through KR_LEARNED + 3 take the OS spell checker’s own lists as plain word lists. On Windows these are %AppData%\Microsoft\Spelling\<tag>\default.dic for added words and default.exc, configured with KR_SOURCE_EXCLUDED, for excluded ones; the adapter picks the language tags.
  • Failures. Status codes are content-free. A Rust panic is caught at the boundary and permanently poisons the handle (KR_POISONED).
  • Compatibility path. kr_plan_compatibility_event and kr_commit_compatibility are the macOS synthetic-rewrite backend. An adapter doesn’t need them, and must not fall back to them when a native edit fails.

Dictionaries cross threads the one way that keeps file I/O out of key handling:

flowchart TD
    subgraph Worker["Serial worker queue"]
        O["kr_vocabulary_observe:<br/>read, settle, parse"]
    end
    O -->|immutable snapshot| V[("kr_vocabulary")]
    subgraph Input["Input thread, outside callbacks, no pending plan"]
        A["kr_adopt_vocabulary"] --> E["kr_engine,<br/>one per input context"]
    end
    V --> A

The session uses the Apple Russian map unless kr_set_keyboard selects KR_KEYBOARD_PC; they differ only on the ё key (\ on Apple, ` on PC).

Adapter obligations

These follow from the architecture and apply on every platform:

  • Track a generation for each input context; invalidate it on focus, context, composition and source changes, and recheck it after every native call that can reenter.
  • Before a write, check that the composition you own still contains exactly the plan’s expected text, at the expected position, with the caret where you left it. A commit that leaves the text unchanged can replace the exact composition range without the caret check. After the write, read the result back. If you can’t read it back, the client can’t be admitted.
  • Report KR_ATTEMPTED_UNKNOWN when you can’t tell what happened, and never replay the key or try to repair the document.
  • Set key disposition from what actually happened, not from whether a request was accepted.
  • Exclude password, secure and read-only fields before reading anything or starting a composition. Recheck current scope, writability, exact field identity, and generation after callback-capable preparation before every character read or native effect. Metadata checks cannot make document authority atomic. Exclusion after an attempted character write forbids further character reads and yields Unknown without replan, replay, or repair.
  • Never hold a Rust borrow, a dictionary lock or the engine across a callback into the host. Contain native exceptions on the native side.
  • Keep raw input, personal vocabulary and paths out of logs and status.

Windows: Text Services Framework

The windows-rs implementation is in native/windows/rust/. Its build, maintainer-only registration commands, evidence limits, and physical acceptance matrix are in Windows TSF proof. The bounded first-editor proof includes observed owned termination on focus loss in the historical C++ backend. The Rust Notepad physical results are recorded separately from the pending completion-candidate matrix. Bounded field admission requires the native contract, including coherent metadata and revocation notifications. Generic TSF scope admission is disabled. Granted edit sessions, explicit contexts, and owned compositions provide the native editing mechanism. TSF design.

Exact version recognition includes 11.2607.14.0 and 11.2609.11.0. The updated version has matching live native-field and unavailable-scope evidence. The current Rust DLL passed the fixture-policy Notepad checks.

The windows-rs adapter uses windows and windows-core 0.62.2 for generated COM identity and SDK types. Typed leases in foreign.rs own host COM references. Raw SDK vtables preserve exact HRESULTs. The service contains Rust panics at callbacks and requires foreign COM implementations to obey the standard HRESULT and no-throw contract. The C++ exception-recovery layer is retired. The proof editor, independent raw COM providers, and UIA diagnostics are Rust in native/windows/proof. native/windows/build-support owns source and artifact identities, and tools/xtask owns the Windows Cargo build and verification commands. Public COM diagnostic and wire versions retain their contracts. The private test API is version 3. The scenario inventory maps all 25 former CTest entries and 111 families to Rust tests or explicit retirement reasons. Full native execution and the complete experimental Rust ASan suite have passed. The ASan memory-error canary and byte-for-byte Rust model regeneration have passed. UIA supplies test and diagnostic observations. Unsupported, secure, excluded, and uncertain controls pass input. A hook or SendInput backend requires a separate decision.

The Windows executor replaces the exact owned range once for each MARK or changed FINISH. Ordinary unchanged FINISH ends the exact verified composition without SetText. Retirement retains its unchanged replacement protocol. Unchanged FINISH has no expected end-caret requirement and does not force selection collapse. It captures immutable selection coordinates and style, verifies range extent and UTF-16 text before and after EndComposition, and checks that no composition remains. After those checks succeed, it preserves the complete selection using a metadata-only range clone and at most one SetSelection. Failed checks stop without retry or another character write. A FINISH followed by a replanned MARK writes once on the new composition. Controlled providers cover selection movement, clone gravity, exact selection styles, fresh policy refusal, and attempted-unknown termination without replay or recovery. Historical C++ Notepad checks cover rapid continuation, native Undo, caret movement, and whole-document selection. The complete selection-style matrix has controlled coverage.

The Windows branch uses bounded PreserveKey delivery for manual conversion and reversal. Two exact left Ctrl + left Alt commands and one declined Alt-press observer belong to one activation through a shared binding table. A provisional stack owner accounts for late successful registrations before rollback, and reactivation waits for the whole activation call and all captured releases. Unknown mandatory acquisition or cleanup effects fault the instance. Ordinary and preserved callbacks share native admission and the existing executor. A command GUID supplies no modifier, repeat, or document-authority facts. Historical C++ physical Notepad runs observed command delivery and retained ownership through modifier release, as described in the command contract. The Windows host probe uses a separate protocol-4 command and modifier-release observation window. Callback-local tickets preserve command identity through reentry. Lifecycle anchors order those content-free observations against owned termination. Dispatch records executor entry. Separate completion records distinguish verified manual MARK, no-write reservation, refusal and unknown effects. The observer witnesses an Alt cycle before a verified command can grant one release permission on its owned composition. Release validation performs metadata queries only. Missing original release plus missing later observer is an excluded indistinguishable host schedule. Historical C++ Notepad checks observed delivery and retention, with separate generated bare-Alt checks and the physical coverage limits recorded in Notepad acceptance.

InterfaceDocumented behaviorObligation
ITfContext::RequestEditSessionSeparate request HRESULT and session result; sync and async grants differCheck both; handle denial or deferral without a speculative edit or a wrongly eaten key
ITfEditSession::DoEditSessionSupplies an edit cookie for that sessionUse it for that session only; never cache a cookie
StartCompositionNeeds a write cookie; an owner can reject with success and a null compositionRequire a non-null composition and the exact context before updating
ITfRange::SetTextMutates under edit accessUse the owned range; the HRESULT is not a document check
OnKeyDown / pfEatenKey consumption is explicitSet it from actual handling, not from an accepted lock request
OnCompositionTerminatedIdentifies the terminated compositionCompare with the captured composition; don’t end a newer one

Start with synchronous read/write edit sessions on the key path. If a path needs asynchronous grants, capture the exact context, composition and generation, revalidate on grant and prove key order; don’t queue and replay input to make async easier. Edit-session locks regulate access, not rollback, Undo grouping or focus after a later callback. An in-process TSF DLL shares the editor’s process: a crash takes down the editor, and process-global Rust state such as a panic hook affects the host, so don’t install one.

Warning

A text service runs inside every application that uses it. A crash, a leak or a blocked callback in the adapter is the editor’s crash, leak or hang.

Determine COM registration, profile registration, enablement and activation separately, and look for a per-user installation before anything that needs elevation. The Microsoft textservice-step06-3 sample is a reference for structure, not error handling: it reports keys eaten too early, uses a composition without checking it started, ends the current rather than the captured composition and translates keys inadequately. A sample that turns virtual keys into uppercase letters is not an EN/RU input method; verify Shift, Caps Lock, dead keys and the EN/RU layouts against real input. Intel/AMD x64 and x86 clients have separate artifacts and execution results. ARM64 is outside the current Windows scope.

Acceptance for the first slice includes edit-session denial, a rejected composition, focus A→B→A, rapid continuation, read-only and password fields, a source change and service teardown, each with the whole document, caret, composition identity and key disposition recorded.

Linux

There is no Linux design yet; this is the starting point, not a decision. The likely target is an IBus engine or a Fcitx 5 addon, both of which have preedit text (the counterpart of a marked composition), commit, focus and reset callbacks, and a surrounding-text API. Questions to answer with real clients before choosing:

  • Does the preedit stay owned and readable across the GTK, Qt, Electron, Firefox and Chromium frontends, under X11 and under Wayland’s text-input-v3? Surrounding text is optional for clients, so readback may be unavailable exactly where it’s needed.
  • Can the word plus Space stay in preedit until the next key, as on macOS, without breaking completion or Undo?
  • Do content-type hints (IBus input purpose, Fcitx capability flags such as password and sensitive data) give a per-field secure-input signal? macOS only has a global one.
  • Is IBus or Fcitx 5 the right first target for the desktops that matter?

The acknowledgement contract is the open decision: a Linux adapter has to give every row of the edit contract a check that proves its outcome. On macOS Keyrill reads the client’s marked text back after every write a key causes; only an unchanged commit that IMK requests is written without that read. On Linux the client draws the preedit the engine sends, and GTK’s surrounding text explicitly leaves the preedit out (set_surrounding_with_selection), so there’s nothing to read back.

Important

Echoing the engine’s own preedit as KR_APPLIED_VERIFIED would verify bookkeeping, not the document.

Before writing the adapter, decide whether engine-owned preedit gets its own, weaker acknowledgement in the ABI, or whether those clients stay pass-through. Until then a client without readback of the owned preedit gets pass-through, not correction.

Development

Rust is pinned to 1.99.1 in rust-toolchain.toml, edition 2024, resolver 3. Cargo.lock is committed and every check runs with --locked; nothing refreshes dependencies silently. The core uses only std. keyrill-ffi adds libc on macOS for file-open constants. The Windows adapter package keyrill-windows uses windows and windows-core 0.62.2. The Windows proof tools, independent COM providers, build identities, and verification runner are Rust packages in the same workspace. Proptest is test-only. The verification runner uses serde_json and flate2, and build identities use sha2. Don’t add an async runtime, a UI framework or a second engine.

On macOS you also need Command Line Tools and clang-format 23.1.3 (pip install clang-format==23.1.3 in a virtual environment). Xcode is not required.

Note

Run the checks as an ordinary user: one test depends on a file-permission denial, which root doesn’t get.

$ ./tools/verify

make check runs the same thing, and each mode below is also a make target (make sanitize). make help lists the rest: format, bundle, status and install.

On macOS and Linux the default check runs pack-model.py --check, check-excerpts.py (the walkthrough’s code excerpts against their sources), rustfmt, Clippy with warnings as errors, all tests including doctests, rustdoc with warnings as errors, a release build and a C syntax check of the header, and it links and runs the C ABI smoke test. On macOS it also checks native formatting, lints the plists, runs Clang static analysis with findings as errors, builds the app and tools, and runs the controlled native tests.

On Windows x64, the default check dispatches to cargo xtask windows check. It checks the Windows source closure, regenerates and compares the model in Rust, runs the workspace checks, builds the Rust TSF service, registrar, and independent proof tools, and runs controlled COM, ABI, worker, diagnostic, and registration-free DLL tests with scenario-coverage checks. See Windows TSF proof for prerequisites and the separate desktop gate.

ModeRequiresWhat it does
sanitizemacOSNative tests under ASan/UBSan; the Rust library is not instrumented
sanitizeWindows x64, MSVC ASan runtime, pinned RustExperimental Rust AddressSanitizer with child-local RUSTC_BOOTSTRAP and a required detected memory-error canary. Prebuilt std and Windows code remain uninstrumented
browser-fixtureNode 18+Deterministic JavaScript checks of the browser fixture
markdownuvmdformat and pymarkdown over the docs, at pinned versions, and the Russian translations against their sources; markdown fix reformats
sitemdbook 0.5.4, mdbook-mermaid 0.17.1Builds the site that pages.yml publishes into target/site/book; stops on a broken link
auditcargo-deny 0.20.2Advisories, sources, licenses and bans for the app and fuzz graphs
coveragecargo-llvm-cov 0.6.21, llvm-tools-previewPortable core and FFI line and region coverage, 95% floor
evaluatePython 3Offline model evaluation, see engine
fuzzcargo-fuzz 0.13.2, nightly-2026-10-2610,000 text/parser/state and 200 model-asset cases, seed 126283
miriMiri and rust-src for nightly-2026-10-26FFI pointer and protocol tests

The full Rust Windows native suite and complete experimental sanitizer suite have passed. Fresh automated Rust editor checks passed correction, reversal, continuation, native Undo, focus preservation, exclusions, native lock denial, and bounded owned shutdown. Current Rust Notepad checks passed fixture correction, manual commands, continuation, native Undo, Find exclusion, a focus round trip, both model directions, and vocabulary reload. Physical boundary correction, reversal, and a rapid-typing and native Undo sequence passed. The broader physical acceptance matrix remains pending. The sanitizer canary detected its heap-use-after-free. The Rust model checker passed byte-for-byte regeneration of the unchanged model assets. Historical C++ desktop results are recorded separately in Windows TSF proof.

Fuzzing prints a temporary directory with logs, evolved corpora and crash artifacts; replay a crash with the same target and artifact path. Model fuzz inputs are bounded patches applied to the real asset. Miri skips filesystem acquisition tests and the full immutable-model walk, which takes about 26 minutes under Miri; those run in the normal suite. Coverage is Rust only; native coverage doesn’t count toward it.

The compatibility tests construct real Quartz events and need a WindowServer session. A sandboxed shell can get null from CGEventSourceCreate even though the tests pass outside it; report that as an environment failure rather than mocking the encoder.

Style

Default rustfmt and Clippy lints, plus missing_docs, clippy::missing_errors_doc and clippy::missing_panics_doc, with scoped #[allow] only where a reason is written next to it. The core forbids unsafe; keyrill-ffi denies unsafe_op_in_unsafe_fn and every unsafe block states its preconditions. Objective-C++ and C code follow .clang-format (LLVM, 2 spaces); Rust uses rustfmt’s 4. .editorconfig gives editors those widths. Comment the why, not the what.

Public Rust items follow the API Guidelines: a summary line, # Errors (and # Panics or # Safety where they apply), and a runnable example on entry points. Examples are doctests, so cargo test compiles and runs them; use ? with hidden # fn main() -> Result<...> lines rather than unwrap. Error types implement std::error::Error with messages that contain no user data. Intra-doc links to macOS-only items break the Windows docs build, so name those in plain code spans. See also the Rust Style Guide and the Rustonomicon for FFI.

Tests should constrain behavior: whole-document oracles for native schedules, exact reasons and replacements for inference, property tests with fixed seeds, and no sleeps or wall-clock time in state tests. See testing.

Changes

Use Conventional Commits with a scope where it helps (feat(macos):, fix(core):), stage exact paths, and update docs in the same change as the behavior. Native and ABI changes also need ./tools/verify sanitize and a review of the actual diff and its negative schedules. A policy or model change needs the evaluation rerun.

Every page the site lists has a Russian translation beside it, named with .ru.md (docs/engine.ru.md translates docs/engine.md); the site’s own pages have theirs in site/ru/. Change a Russian page in the same commit as its English source and copy the new git hash-object of the source into the Russian page’s first line; ./tools/verify markdown fails until the two agree. The English page is authoritative: where a translation differs from it, the English text applies, and only the English text and the license and notice files carry legal effect.

CI (.github/workflows/verify.yml) runs the default check on macos-15, windows-2025 and ubuntu-24.04, sanitizers on macOS, the Markdown check on Linux, and separate audit, coverage, Miri, fuzz and evaluation jobs. Actions are pinned by commit, the token is read-only and checkout doesn’t persist credentials. No job signs, publishes or installs anything. The coverage job attaches the single-page HTML report (target/llvm-cov/keyrill-coverage.html), which opens in the browser from the run page, and puts the per-file table in the run summary. Dependabot proposes Cargo and Actions updates monthly; the Rust toolchains, the nightly date, the cargo install tool versions and the model generator’s Python requirements stay manual pins, the last because updating them means regenerating the model.

Testing

A native API call that returns success is not a document result, a controlled NSTextView is not system IMK, and a generated event in a real editor is not physical input. Record which of these a result is. Results belong to the binary that produced them, not to later builds.

flowchart TD
    A["API call<br/>returned success"] --> B["Controlled client:<br/>scripted IMK, whole document"]
    B --> C["Generated events<br/>in a real editor"]
    C --> D["Physical keys<br/>in a real editor"]

Each step to the right is stronger evidence, and only the last one shows that an application works.

Layers

LayerWhereCovers
Unit and propertycrates/*/src, crates/keyrill-core/testsMapping, vocabulary flags, policy, session transitions, ABI bounds; fixed proptest seeds
Reference vectorstests/fixtures/engine-vectors.jsonl1,217 mapping, vocabulary, context and inference outputs, see engine
Negative settests/fixtures/negative-words.jsonl, tests/negative_words.rs766 words automatic correction must leave alone
Evaluation./tools/verify evaluateSession replays and a negative set over held-out corpora, with recall and false-correction gates
C ABI smokecrates/keyrill-ffi/tests/abi_smoke.cThe plan, check, write, commit loop from C against an in-memory document
Fuzz and Mirifuzz/, ./tools/verify miriParsers, state, model asset, FFI pointer contract
Controlled nativenative/macos/testsScripted IMK clients with whole-document oracles; ASan/UBSan
Browser fixturenative/macos/tests/browser-fixture.htmlField and caret oracle for physical browser runs
PhysicalReal applications, real keysThe only evidence that an application works

The controlled native tests drive KRSession, the compatibility session and the controller with scripted clients that hold a whole document, and an offscreen NSTextView for the readback commit after a failed check. They check correction, protection, forbidden targets, reversal, reentrant callbacks that change generation or client, unknown effects, empty composition, dictionary reload and adoption deferral, key disposition, and compatibility rewrites including missing echoes and a terminal that forwards consumed keys. One test, compatibility_known_interleaving_hazard, keeps a schedule where a typed character is deleted and the word corrupted; it documents the backend’s limit and is not integrity evidence.

Regression schedules

regressions.json lists sixteen schedules (R01–R16) any adapter has to answer. R01–R04 are negative controls for the rejected transports: a test passes by showing the damage in the rejected mechanism or by refusing the schedule, never by reproducing the unsafe edit. The rest cover reentrant invalidation, foreign marks on reused proxies, caret disagreement, empty composition, manual boundaries, rapid continuation, focus reuse, source selection versus delivery, dictionary reload, key disposition, TSF grants, and secure fields and shutdown. Use deterministic barriers and callbacks, not shorter sleeps.

Invariants and evidence

Each safety invariant guards against one hazard. The table ties it to the regression schedules above, the tests that would catch a violation today, the strongest evidence obtained so far and what is still missing. Controlled means the native tests’ scripted IMK clients with whole-document oracles; physical means the maintainer typing in a real application, as recorded under Status. The compatibility backend gives up S1, S4 and S6 by design (ADR 006); its compatibility_* tests record that, and it has no physical result yet.

IDHazardSchedulesTestsStrongest evidenceOpen gap
S1A correction deletes, doubles or reorders text outside the wordR03, R08, R10, R13model_whole_document_en, model_whole_document_ru, empty_composition, reenter_*, throw_*; session property testsPhysical, v0.1.0: TextEdit, Safari, FirefoxNothing physical after v0.1.0; rapid typing across a boundary (V06) and two fields (V08) not recorded; Safari’s fixture once came out one unit short
S2Keyrill edits a mark it doesn’t own: another input method’s, a reused proxy’s, or one a focus change left behindR06, R07, R11foreign_mark, foreign_mark_after_context, moved_caret, caret_moved_after_context, client_changeControlledA foreign mark in a reused client (V09) not run physically
S3A write lands after a callback moved focus or changed the generation mid-callR05, R15reenter_*, throw_*, owner_release_during_callback, secure_input_during_client_calls; exercise 9Controlled, also under ASan and UBSanNested commands and source changes during a request (V10) not run physically; Windows (R15) has no adapter
S4A key is lost, doubled, sent elsewhere or reorderedR10, R14unknown_finish_then_letter, unknown_finish_then_shortcut, unknown_escape_consumed, ignored_write, readback_commit_after_failed_checkControlled; ordinary typing physically at v0.1.0Navigation, shortcuts, Tab and Enter (V12) not recorded physically
S5An API’s success return is taken as a document editR07, R12ignored_write, finish_altered_text, lifecycle_commit_unreadable_text, typed_finish_unreadable_text; the C ABI smoke test; exercise 8ControlledA physical test shows only the result, so this stays a controlled-test property
S6Committed text is rewritten on the composition pathR01–R04No code path exists; R01 to R04 are the negative controls for the rejected transportsSource reviewNone while those transports stay absent
S7A late reversal edits a word Keyrill no longer ownsR09manual_reversal_expiry, escape_restores_original, kept_mark_across_mode_change, model_reversal_dictionary_change, runtime_reload_whole_document_and_receiptPhysical, v0.1.0: Control+Option+Z in all three applicationsReversal after continued typing (V05) not recorded physically
S8Typed text reaches disk, a log or the networkR16input_status, controller_status_line; error messages carry no user data; there is no network codeSource review and controlledA crash dump can still hold text; compatibility mode holds typing in memory while Secure Input is off
S9A native or FFI object is used after it is freed, or across a panicNoneMiri, fuzzing, the C ABI smoke test, ASan and UBSan runs of the native tests, owner_release_during_callbackSanitizers and MiriQuitting the application and server termination (V13) not recorded physically
S10A refusal changes the document or switches transport silentlyR16secure_input, unlisted_client, controller_secure_input_before_characters, lifecycle_interruption_status, compatibility_refusal_interruption_secureControlledRead-only, password and custom controls (V14) not run physically

Physical scenarios

Observe whole synthetic documents or fields, prefix and suffix, and the UTF-16 caret; for two-field cases observe both. Native readback is the client’s view: prefer an independent oracle such as a saved file or the browser fixture. Classify each result as passed, failed, unsupported, untested or setup-blocked. A permission or activation problem with no keys typed is not a correction failure, and input that never reached Rust is not an abstention.

IDScenarioExpected
V01EN mode: ghbdtn Space hello Space ghbdtn Spaceпривет hello привет , caret after the last Space; repeat without restarting
V02RU mode: руддщ Space цщкдв Spacehello world
V03Ghbdtn, all-caps, acronyms, identifiers, URLsTitle case converted; the rest unchanged
V04Manual before Space and right after the boundaryDeterministic conversion; inference never undoes it
V05Reversal before and after Space, then keep typingExact original restored; no re-correction at that boundary
V06Rapid typing straight through a boundary, repeatedNo lost, duplicated or reordered characters
V07Backspace inside a word and to empty, then typeOnly owned units removed
V08Half a word in field A, click B, correct in B, return to ABoth fields intact; nothing carried across
V09Foreign mark in a reused client; caret and mark disagreeRefusal, no new writes
V10Generation change inside a query, nested commands, source switchNo stale follow-on effect or revived receipt
V11Clamped or ignored range, partial write, delayed readback, exceptionUnknown result; no rollback or replay
V12Navigation, selection, punctuation, Tab, Enter, shortcutsHost action happens once; no trigger, no stale receipt
V13Escape, host cancel, app quit, server quit, source away and backDocuments stable; lifetimes drained
V14Read-only, password, custom, code, terminal, remote controlsNo prohibited read or write; input not swallowed
V15Emoji, non-BMP, combining marks, multi-line textPreserved exactly
V16Dictionary edit, Learn Spelling and Unlearn, atomic save, symlink, missing, invalid, oversized, restoreLast good data kept; manual conversion unaffected
V17Fresh install, enable, select, restart, log out and inActual typing works, not just registration
V18Windows: denied lock, async grant, null composition, terminated contextCorrect key disposition; no stale edit

For each application record the OS and app versions, control type, backend, automatic and manual correction, reversal, native Undo, source switching, focus behavior and failures. Start with TextEdit, Safari and Firefox text areas, then a contenteditable editor, a native text field, an Electron app and an office editor. Treat IDEs, terminals and remote sessions as exclusion and manual-availability checks first.

Browser fixture

browser-fixture.html is a standalone page with one textarea holding fixed prefix and suffix text (including a surrogate pair), with spellcheck, autocorrect and autocomplete off. Its four scenarios (EN automatic, manual, reversal, RU automatic) record ordered full-field checkpoints, composition events and the final UTF-16 caret, and give a pass or fail verdict. The report holds flags, positions and counts, never text. It can’t prove which input method produced the input. ./tools/verify browser-fixture checks the oracle itself, not a browser.

Performance targets

Targets for a release build on Apple Silicon, to measure rather than assume: pure inference p99 under 1 ms for the longest eligible word; Space to verified visible update p95 under 20 ms and p99 under 50 ms over at least 1,000 boundaries per control; idle under 0.5% of one core over five minutes with dictionary monitoring; RSS under 100 MiB; ready in under a second. None has been measured end to end yet.

Status

CI runs on each change: the default check on macOS, Windows and Linux, the sanitizers, audit, coverage, Miri, fuzzing and evaluation on macOS, and the Markdown check and the site build on Linux. The browser fixture’s self-check runs only locally (./tools/verify browser-fixture). The run page has the results and the line-level coverage report, so this page doesn’t repeat numbers that go stale.

Physical results, for the build that produced them: on the v0.1.0 source the maintainer typed by hand with the model policy in TextEdit, in a Safari text field and address bar, and in a Firefox text area. Automatic correction, Control+Option+K, Control+Option+Z and the mode switch after a correction behaved as expected in all three. Nothing since has a physical result: the default paths computed in Rust, the Learn Spelling list and the input menu’s status line. Known open questions, to check first:

  • The Learn Spelling list lives in Apple’s spell-service group container; whether the input method’s read raises an “access data from other apps” prompt is unknown.
  • VoiceOver uses Control+Option as its modifier, so Control+Option+K is also VoiceOver’s Keyboard Help; which one receives the key with VoiceOver on is untested.
  • Safari: in the browser fixture, manual conversion and reversal once left the field one UTF-16 unit short, consistent with a missing trailing Space. The hand run didn’t show it, but the fixture hasn’t been rerun.
  • ChatGPT desktop gets no automatic correction; the cause is unknown.
  • Compatibility: repeated corrections in Notes, terminal behavior, live source switching and permission retention across updates.

When reporting a problem from real use, include the application and version, the backend, the input menu’s first line, its “Last word left alone” row and dictionary state, and a synthetic reproduction (what you typed and what you got). Don’t paste private text.

Frozen language model

model.bin re-encodes the frequency and character-chain data in model/data/model.inc.gz as little-endian alphabet indices and signed integer micro-units. It preserves all 396,107 six-decimal values exactly; it does not retrain, recalibrate or renormalize them. model-provenance.json binds the frozen source, packer, output bytes and language counts. tools/pack-model.py --check regenerates all assets offline and compares their bytes.

The model data is derived from wordfreq 3.1.1 under CC-BY-SA-4.0. Retain model-notice.txt and its source attributions with derived data and binaries. wordfreq-code-license.txt preserves the separate upstream code notice; it does not change the data license. This format translation is a Keyrill modification. Application source is MIT-licensed; that does not relicense the model data or its upstream inputs.

Learning Rust and Objective-C++ through Keyrill

This is a guided reading of a real program, written for a programmer who knows C++, Python or JavaScript and wants to learn Rust and Objective-C++ on working input-method code. Keyrill is an input method, the kind of program that sits between the keyboard and every application and decides what text a key produces; this one fixes words typed in the wrong keyboard layout, such as ghbdtn typed on the US layout when привет was meant.

The walkthrough asks for work. Read every excerpt, not only the text around it; run the commands; do the exercises at the end before you look at the answers. A chapter read without the code teaches the words and not the language.

How to read this walkthrough

Goal: know what the formatting means before you start.

Every top-level section of this page and the five chapters opens with a line like the one above: what you will be able to do once you have read it. A subsection may add its own goal line, and the exercises chapter has one goal for the whole workbook. A new term is set in bold where it first appears and is defined in the same sentence or the next; later chapters link back to it, and the glossary lists them all. Where an idea has a counterpart in C++, Python or JavaScript, the text names it and says where the comparison stops being true. Each of those sections ends with a box of one or two facts to keep.

Every code excerpt is copied from this repository and captioned with its path and line numbers; the caption links to the same lines on GitHub. tools/check-excerpts.py compares each excerpt with its source on every build and fails when they differ, so what you read here is what the code contains today.

Tip

Remember. Bold marks a new term. An excerpt is the real code, checked on every build.

Objective-C++? I’ve only heard of Objective-C

Goal: know what Objective-C++ is and why this project needs it.

Objective-C is the language Apple’s frameworks were written in before Swift: C plus a small object system borrowed from Smalltalk, in which you call a method by sending a message, [object doSomething]. Everything C allows is still allowed. Most macOS programs written before 2014 are Objective-C, and the input-method framework this project uses, InputMethodKit, is an Objective-C framework.

Objective-C++ is not a separate language with its own rules. It is what Apple’s compiler, clang, produces when a file ends in .mm instead of .m: Objective-C and C++ mixed in one source file, so a C++ object may hold an Objective-C object and an Objective-C method may take a C++ argument. Keyrill’s macOS code is in .mm files, compiled by native/macos/build.sh with clang++ -std=c++20 -fobjc-arc.

The reason is concrete. A host application can raise an exception inside a call Keyrill makes, and Keyrill must clean up and keep running. In Objective-C++, a C++ destructor, the function that cleans up when an object is destroyed, runs while an Objective-C exception passes through, and the automatic memory management releases objects on that path; in plain Objective-C, neither is true by default. The Objective-C chapter teaches the Objective-C half, and the Objective-C++ chapter shows what C++ adds and where this code depends on it.

Tip

Remember. Objective-C++ is Objective-C and C++ in one .mm file. Keyrill uses it so that cleanup still happens when a host application raises an exception.

One rule before any syntax

Goal: know which half of the program does what, and why each half got its language.

Keyrill is split between two languages, and the split follows one rule: the Rust side may only propose, and the native side may only act on a proposal after checking it. Here native means the platform’s own code, the part written against Apple’s frameworks.

Rust holds the decision and the state, because its compiler can prove things about them: that a function can’t change what it only reads, that every case of a choice is handled, that no reference outlives its data. Objective-C++ holds the conversation with macOS and with the application being typed into. The Rust compiler can’t prove anything about the host application, because it is someone else’s program, so the adapter checks every answer it gives.

flowchart TD
    App["Host application<br/>IMKTextInput client"] -->|key| Controller
    subgraph Native["Objective-C++, owns the text"]
        Controller["KeyrillAlphaController<br/>routes the key"] --> Session["KRSession<br/>checks, writes, reads back"]
    end
    Session -->|"kr_plan_event"| FFI["keyrill-ffi<br/>C ABI, copies, catches panics"]
    FFI -->|"Session::propose_*"| Core["keyrill-core<br/>safe Rust, decides"]
    Core -->|Plan| FFI -->|kr_plan| Session
    Session -->|"the one write, then readback"| App
    Session -->|"kr_commit(plan_id, outcome)"| FFI -->|"Session::acknowledge"| Core

One key goes round this loop once, sometimes twice. Rust answers the key with a plan: the text the application must show now, the one change Keyrill may make, and what to do with the key afterwards. The native side, the adapter, checks the application’s text against the plan, makes the change, reads the text back, and reports the outcome. Only a verified outcome moves Rust’s state forward.

Note

A comparison for a reader from hardware design: the loop is speculative execution with a reorder buffer of depth one. A proposal issues into pending, a verified acknowledgement retires it into architectural state, and any other outcome is a flush. The native side’s _generation counter plays the epoch tag that squashes work still in flight. The comparison is this walkthrough’s, not a term the project uses.

The code is divided into four parts. A crate is Rust’s unit of compilation: one library or one program, compiled as a whole, much like a Python package or an npm package; Keyrill has two that matter here.

PartLanguageOwnsNever does
crates/keyrill-coreSafe Rust, standard library onlyLayout maps, word model, inference, dictionaries, the word sessionSee a document, a native object or a pointer
crates/keyrill-ffiRust with unsafe code, which the compiler can’t fully checkThe C interface: handles, struct copies, panic containment, dictionary filesCall back into native code
include/keyrill.hCThe contract both sides compile againstChange incompatibly without a version bump
native/macos/srcObjective-C++InputMethodKit, the application’s text, Secure Input (the macOS mode for password fields), each change and its readbackDecide what a word should become

The C header in the middle is how the two languages meet, through C’s ABI, the agreement on function names and the byte layout of structs (records of named fields) that compiled code from different languages shares; the C boundary chapter explains it in full. A panic, in the table and the diagram, is Rust’s way of stopping on a bug, and it must never cross into C.

Tip

Remember. Rust proposes, the adapter checks and acts, and only a verified outcome advances Rust’s state.

Chapters

Goal: choose where to start, and set up the tools.

ChapterWhat it teaches
Rust in the coreEditions and crates, enums and match, ownership and borrowing, lifetimes, Arc, errors, iterators and closures
The C boundaryABIs, unsafe, struct layouts pinned from both sides, handles, panics at the boundary, threads and locks
Objective-CMessages, classes, properties, protocols, reference counting, blocks, dispatch queues and exceptions
Objective-C++C linkage, destructors that run during Objective-C exceptions, C++ types inside Objective-C objects and back
Reentrancy and testsWhy every call to the application is followed by a check, one word end to end, property tests and a hostile fake client
ExercisesNine predict-then-run changes, each reproduced on this code

Read the chapters in order; each one uses what the previous one taught. You need a Rust toolchain (its version is pinned in rust-toolchain.toml, and rustup installs it on first use) and, for the native parts, macOS with Command Line Tools. Run both commands once before you start; each should finish with its tests passing:

cargo test -p keyrill-core     # the Rust core and the examples in its documentation
native/macos/build.sh check    # the adapter, built and tested against a fake application

None of the chapters installs the input method or selects an input source, the macOS name for a keyboard layout or input method chosen from the menu bar.

Tip

Remember. Read in order, run the code, and predict before you check an answer.

Rust in the core

keyrill-core is the crate that decides. It is safe Rust with no dependencies outside the standard library, the library every Rust program gets with the compiler, and it knows nothing about macOS, pointers (raw memory addresses) or documents. That makes it the right place to learn the language: every idea below is one the compiler checks, and the chapter shows the place where breaking it would stop the build. The full reference is The Rust Programming Language (the Book); the links go to the chapter that treats each idea at length.

Before the first excerpt: editions and checks

Goal: know what “Rust 2024” means and what the compiler does before a program runs.

Rust changes in small steps, and the steps that would break old code are collected into an edition: Rust 2015, 2018, 2021 and 2024. Each crate names its edition in its Cargo.toml, the manifest that Rust’s build tool, Cargo, reads; Keyrill’s workspace, the set of crates built together from the root Cargo.toml, sets edition = "2024". Crates of different editions link together freely, so an edition is a choice of dialect per crate, not a fork of the language (Edition Guide). When this walkthrough says “Rust 2024 requires…”, it means a rule of that dialect.

Much of what follows happens at compile time, while the compiler translates the program, rather than at run time, while the program runs. Python and JavaScript find most mistakes at run time, when the faulty line executes; C++ finds some at compile time. Rust moves as much as it can to compile time, and this crate is built to take advantage of it: when a rule below is broken, the program doesn’t build.

Tip

Remember. An edition is a per-crate dialect of Rust; Keyrill uses 2024. The type and borrow checks in this chapter happen at compile time, before anything runs.

Types that carry their meaning

Goal: read an enum with fields and the match that takes it apart.

A struct is a record of named fields, like a C++ struct, a Python dataclass or a JavaScript object with a fixed shape. An enum in Rust is a choice between variants, and each variant may carry its own fields, which exist only while the value is that variant. The general name is a tagged union: C++ has it as std::variant, TypeScript as a discriminated union, and Python and plain JavaScript only by convention, an object with a kind field. Here is the state of the word being typed:

crates/keyrill-core/src/session.rs:164-182

#![allow(unused)]
fn main() {
#[derive(Clone, Debug, Default, PartialEq, Eq)]
enum State {
    #[default]
    Idle,
    /// Composing while `boundary` is clear, BoundaryRetained once the Space has joined the mark.
    Owned {
        /// What the owned mark holds, including the Space once `boundary` is set.
        text: Vec<u16>,
        /// The receipt: the text before the word was first converted; `None` if it was never
        /// converted, or after an edit or a Reverse.
        original: Option<Vec<u16>>,
        boundary: bool,
        /// Set by Manual or Reverse; Space then keeps the word without inference.
        explicit: bool,
        /// Input mode the word was started in.
        mode: Mode,
    },
    Invalidated,
}
}

Look at what can’t be written. There is no text while the state is Idle, because the field doesn’t exist there. A class with a state member and a separate text member would allow the nonsensical pair “idle, with text” and rely on every programmer to avoid it; here the type rules it out.

The first line is an attribute, an annotation for the compiler written #[...]. derive asks the compiler to generate code for the listed traits. A trait is a named set of methods a type can provide, close to a C++ concept, a Python protocol and a TypeScript interface at once; Clone provides copying, Debug printing for programmers, PartialEq the == operator, Default a default value. #[default] names the variant that Default produces, which is how Session::default() starts in Idle without a constructor.

Option<T> is an enum from the standard library with two variants, Some(T) and None. It replaces the null pointer, Python’s None and JavaScript’s null everywhere in safe Rust, with one difference that matters: the compiler will not let you use the value inside without first saying what happens when there is none. original above is either a receipt or nothing, and code that forgets the “nothing” case doesn’t compile.

Small enums take the place of integer codes, even where a number would be shorter. The plan says what to do with the key, and the adapter reports what happened, each as its own type:

crates/keyrill-core/src/session.rs:121-141

#![allow(unused)]
fn main() {
/// What happens to the key event once the plan's action is verified.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Disposition {
    /// Let the host handle the event once.
    Pass,
    /// The event is handled; the host does not see it.
    Consumed,
    /// Finish was acknowledged; plan the same event again from Idle.
    Replan,
}

/// Native effect acknowledgement.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Outcome {
    /// Native effect and readback verified, or the plan had no native effect.
    Verified,
    /// Rejected before any native write.
    Refused,
    /// Write attempted but outcome cannot be established.
    Unknown,
}
}

Two integers could carry both, and a function could then be handed a disposition where an outcome was meant. With two types, that mistake doesn’t compile. Copy in the derive list says these values are plain bits, copied on assignment like a C int; the next section explains what happens to values that aren’t.

match keeps count

Goal: see why adding a variant breaks the build, and why that is good.

match compares a value against patterns, one per arm, and runs the first arm that fits. It must cover every variant, so adding a variant turns every incomplete match into a compile error, even in another crate. Python has a match statement with similar syntax, but it doesn’t check that the cases are complete; TypeScript can, with an exhaustiveness check you write yourself. This is the place where the C boundary turns Rust’s enums back into the numbers of keyrill.h:

crates/keyrill-ffi/src/lib.rs:668-685

#![allow(unused)]
fn main() {
            let mut copied = NativePlan {
                plan_id: plan.id,
                action: match plan.action {
                    Action::Pass => 0,
                    Action::Mark => 1,
                    Action::Finish => 2,
                    Action::Unavailable => 3,
                },
                disposition: match plan.disposition {
                    Disposition::Pass => 0,
                    Disposition::Consumed => 1,
                    Disposition::Replan => 2,
                },
                expected_len: plan.expected.len() as u32,
                mark_len: plan.text.len() as u32,
                expected: [0; 128],
                mark: [0; 128],
            };
}

match is an expression: it produces a value, so it can sit inside a struct literal. There is no default: arm, and that is the point. A fifth action added to the core can’t cross to the C side unnoticed, because this file stops compiling until someone decides which number it gets. Exercise 2 shows the error.

A pattern can look inside a variant and add a condition, a guard, written after if. This one recognizes a key that starts or continues a word:

crates/keyrill-core/src/session.rs:449-460

#![allow(unused)]
fn main() {
        // In English mode the keys that type Russian letters can start or continue a word
        let letter = match event {
            Event::Text(units)
                if units.len() == 1
                    && (mapping::is_letter(units[0])
                        || (mode == Mode::En
                            && inference::is_provisional(units[0], self.keyboard))) =>
            {
                Some(units[0])
            }
            _ => None,
        };
}

Event::Text(units) matches only the text variant and names its contents units; the guard then requires exactly one unit that is a letter, or, in English mode, a key such as [ that types a Russian letter on the Russian layout. _ matches everything else. The result is an Option<u16>: a letter, or none.

Ranges are patterns too, and matches! turns a pattern into a bool. The ! marks a macro, code that the compiler expands into more code before compiling it; matches!, assert! and include_bytes! below are all macros. The letter set of the whole engine is one line:

crates/keyrill-core/src/mapping.rs:42-46

#![allow(unused)]
fn main() {
/// Whether a unit is an EN/RU letter: `A`-`Z`, `a`-`z`, `А`-`я`, `Ё` or `ё`. [`Mapping::Manual`],
/// the word session and language context detection all use this letter set.
pub fn is_letter(unit: u16) -> bool {
    matches!(unit, 0x41..=0x5a | 0x61..=0x7a | 0x410..=0x44f | 0x401 | 0x451)
}
}

u16 is an unsigned 16-bit integer, and the text is a sequence of them throughout: UTF-16 code units, the encoding macOS and Windows use for text, in which most characters take one unit and some take two. An offset that means the same thing on both sides of the C boundary is worth more here than the convenience of Rust’s UTF-8 String.

Tip

Remember. An enum’s fields exist only in their variant, so impossible states can’t be built. A match must cover every variant, so a new variant can’t be forgotten.

Ownership and borrowing

Goal: tell from a method’s signature whether it can change its object.

Python and JavaScript free memory with a garbage collector, which finds objects nobody refers to and reclaims them later; C++ leaves it to the programmer and to destructors. Rust has neither a garbage collector nor manual free. Every value has one owner, a variable or a field, and the value is destroyed, dropped, when its owner goes out of scope.

Other code gets access by borrowing: it takes a reference to the value without owning it. There are two kinds, and the compiler’s borrow checker enforces one rule about them: any number of shared references &T, or exactly one exclusive reference &mut T, never both at the same time. Python and JavaScript have nothing like this; any function you hand a list to may change it. The rule is short, and this project builds its central guarantee on it. Compare the first parameter of two methods in the same impl block, the block that defines a type’s methods:

crates/keyrill-core/src/session.rs:438-446

#![allow(unused)]
fn main() {
    /// The transition table: the plan's action, disposition and text, and the proposed state.
    /// Reads the confirmed state and changes nothing.
    fn transition(
        &self,
        event: &Event,
        mode: Mode,
        context: Context,
        automatic: Automatic<'_>,
    ) -> (Action, Disposition, Vec<u16>, State) {
}

A method’s first parameter, self, is the object it was called on, like Python’s self and JavaScript’s this. transition takes &self, a shared borrow of the session, and since Session holds no Cell, RefCell, Mutex or other type with interior mutability (mutation through a shared reference), it cannot change the session. The doc comment says “changes nothing”, and for once a comment needs no trust: the compiler enforces it, as exercise 1 shows. The whole transition table, more than 150 lines, is therefore a pure function of the confirmed state and the event. Its caller takes &mut self, and it stores the result as a proposal, leaving the confirmed state alone:

crates/keyrill-core/src/session.rs:363

#![allow(unused)]
fn main() {
        let (action, disposition, text, next) = self.transition(event, mode, context, automatic);
}

crates/keyrill-core/src/session.rs:381-393

#![allow(unused)]
fn main() {
        self.pending = Some(Pending {
            id,
            state: next,
            history,
            mode,
        });
        Ok(Plan {
            id,
            action,
            disposition,
            expected,
            text,
        })
}

state: next moves the proposed state into pending. After that line next can no longer be used, and the compiler says so if you try. Moving is what assignment does for any type that isn’t Copy: the value changes owner, and its heap buffers go with it without being copied. The heap is the memory for data whose size or lifetime isn’t known in advance, such as the contents of a growable Vec; the stack holds a function’s local variables and is freed when the function returns. In Python, b = a makes a second name for the same object and both stay usable; in Rust, let b = a; hands the value over, and a is dead. C++’s std::move is the nearest relative, except that the moved-from variable there is “valid but unspecified” rather than unusable.

Because transition only borrows the session, it can’t take the current text out of it to build the next state. It copies instead, and says so in the code:

crates/keyrill-core/src/session.rs:498-501

#![allow(unused)]
fn main() {
                let mut text = text.clone();
                let mut original = original.clone();
                let mut boundary = *boundary;
                let mut explicit = *explicit;
}

What clone() copies is up to each type. For the Vec<u16> here it copies the whole buffer, like Python’s copy.deepcopy or JavaScript’s structuredClone; for the Arc later in this chapter it copies only a pointer and shares the value. Rust writes it out every time, and only Copy types such as bool and integers, plain bits, are copied implicitly; nothing runs behind your back the way a C++ copy constructor can. *boundary reads the bool that boundary refers to. The copies make the next property possible: the Plan returned to the adapter owns its text and borrows nothing from the session. A borrowed plan would keep the session locked for as long as the adapter held it, and the adapter must stay free to reset the session in the middle of a call to the application.

Taking a value out exactly once

Goal: see how a value that may be used only once is made impossible to use twice.

The acknowledgement is where a proposal becomes the truth, and it must happen at most once per plan. Option::take moves the value out of an Option and leaves None in its place:

crates/keyrill-core/src/session.rs:405-410

#![allow(unused)]
fn main() {
    pub fn acknowledge(&mut self, id: u64, outcome: Outcome) -> Result<(), Error> {
        if self.pending.as_ref().map(|p| p.id) != Some(id) {
            return Err(Error::Stale);
        }
        let pending = self.pending.take().ok_or(Error::Stale)?;
        if outcome == Outcome::Verified {
}

crates/keyrill-core/src/session.rs:428-436

#![allow(unused)]
fn main() {
            self.mode = Some(pending.mode);
            self.state = pending.state;
        } else {
            self.state = State::Invalidated;
            self.history.clear();
            self.mode = None;
        }
        Ok(())
    }
}

Read the first check twice. self.pending.as_ref() turns a reference to an Option<Pending> into an Option holding a reference, so the closure |p| p.id, an anonymous function like Python’s lambda p: p.id or JavaScript’s p => p.id, can read the id without taking the proposal. The result is compared with Some(id). Only then does take() move the proposal out. A second acknowledgement of the same id finds None and returns Stale. Nothing in this code needs a “has been used” flag, because the value itself is gone.

Tip

Remember. Through &self a type without interior mutability can be read but not changed; &mut self can do both, and only one may exist at a time. Assignment moves a value unless its type is Copy.

Lifetimes

Goal: read 'a in a type and say what it protects against.

A reference must never outlive the value it points to. A garbage-collected language guarantees that by keeping the value alive as long as anything refers to it; Rust instead refuses to compile a program in which a reference could outlive its value. Most of the time the compiler works this out without help. When a type stores a reference, it needs a name for how long that reference stays valid, and that name is a lifetime, written with an apostrophe: 'a. A lifetime generates no code. It is a constraint the compiler solves and then forgets.

The word model is a good first example, because nothing in it is copied at all. Every field is a slice, &'a [u8], a view of part of one byte array, made of a pointer and a length. Python’s memoryview and JavaScript’s subarray are views of the same kind, with the difference that they keep the underlying buffer alive and a Rust slice doesn’t:

crates/keyrill-core/src/model.rs:92-107

#![allow(unused)]
fn main() {
/// One language's frequency table and character chain, borrowed from a validated asset.
#[derive(Clone, Copy)]
pub struct LanguageModel<'a> {
    alphabet: &'a [u8],
    offsets: &'a [u8],
    words: &'a [u8],
    frequencies: &'a [u8],
    chain: &'a [u8],
}

/// Validated EN and RU models.
#[derive(Clone, Copy)]
pub struct Model<'a> {
    en: LanguageModel<'a>,
    ru: LanguageModel<'a>,
}
}

Model<'a> reads “a model that may not outlive the bytes it was parsed from”. In C++ the same design is a struct of std::span members and a comment warning about dangling pointers. Here a program in which the bytes die first doesn’t compile. Copying the whole Model copies ten slices, twenty machine words and no data, which is why it can derive Copy.

The parser shows a subtler point. A Reader holds the bytes not yet read, and take hands out the next piece:

crates/keyrill-core/src/model.rs:109-122

#![allow(unused)]
fn main() {
/// Cursor over the asset; a read past the end is [`ModelError::Truncated`].
struct Reader<'a> {
    bytes: &'a [u8],
}

impl<'a> Reader<'a> {
    fn take(&mut self, length: usize) -> Result<&'a [u8], ModelError> {
        if length > self.bytes.len() {
            return Err(ModelError::Truncated);
        }
        let (head, tail) = self.bytes.split_at(length);
        self.bytes = tail;
        Ok(head)
    }
}

take borrows the reader exclusively (&mut self), yet the slice it returns has the lifetime 'a, tied to the asset, not to the reader. So the caller may keep the slice after the reader moves on, and Model::parse keeps every section this way without copying a byte. Had the return type been written &[u8], with no name, the compiler would have tied it to the borrow of the reader, and the reader would have stayed locked as long as any section was alive. One annotation says which of the two is meant.

The asset itself is compiled into the program with include_bytes!, so it lives as long as the program, and that is what the special lifetime 'static says:

crates/keyrill-core/src/model.rs:32

#![allow(unused)]
fn main() {
static EMBEDDED: &[u8] = include_bytes!("../../../assets/model.bin");
}

crates/keyrill-core/src/model.rs:327-329

#![allow(unused)]
fn main() {
    pub fn embedded() -> Result<Model<'static>, ModelError> {
        Model::parse(EMBEDDED)
    }
}

Result<..., ModelError> is the return type of a function that can fail; the section on errors below covers it.

A type without a lifetime can’t hold a short-lived borrow

Goal: read a missing lifetime as a promise.

Lifetimes also let a type promise what it does not keep. Automatic correction needs the model and the user’s dictionaries for the length of one call, so the enum that carries them has a lifetime:

crates/keyrill-core/src/session.rs:184-188

#![allow(unused)]
fn main() {
/// Automatic correction at Space: the fixture policy, on or off, or the model.
enum Automatic<'a> {
    Fixture(bool),
    Model(&'a Model<'a>, Dictionaries<'a>, Policy),
}
}

The proposal that waits for acknowledgement has none:

crates/keyrill-core/src/session.rs:197-203

#![allow(unused)]
fn main() {
/// The proposed state of the latest plan, adopted only by a verified acknowledgement.
struct Pending {
    id: u64,
    state: State,
    history: HistoryEffect,
    mode: Mode,
}
}

Pending has no lifetime parameter, so none of its fields can be a reference with a limited lifetime. The documentation of propose_with_inference says that “the pending operation retains no model, vocabulary reference or native callback” (a callback is a function handed to other code for it to call later), and the type definition is the proof. Between a plan and its acknowledgement the adapter calls into a foreign application, which may reset the session or replace the dictionaries; nothing in the session can point at the old ones.

Tip

Remember. A lifetime names how long a borrowed reference stays valid. A type without one can’t hold a reference that lives shorter than 'static, and the compiler holds it to that.

Shared data that never changes

Goal: share one value between readers without copying it and without locks.

Personal dictionaries change while Keyrill runs: the user adds a word in Vim while Keyrill holds the old list. A reader that started with the old list must keep a consistent view, and a broken file must not replace a good one. The tool is Arc, an atomically reference-counted pointer: it counts how many owners share the value, frees the value when the count reaches zero, and updates the count safely from several threads, the independent sequences of execution inside one running program. It is the counterpart of C++’s std::shared_ptr<const T>. CPython counts references to every object in the same way, and adds a collector for reference cycles that Rust doesn’t have. Keyrill never changes the value inside an Arc; that is its snapshot policy, not something Arc itself forbids, since a value with interior mutability can still change behind one:

crates/keyrill-core/src/vocabulary.rs:374-403

#![allow(unused)]
fn main() {
/// Atomically replaceable immutable vocabulary, initially missing rather than silently empty.
#[derive(Default)]
pub struct Snapshot {
    current: Option<Arc<Vocabulary>>,
}

impl From<Option<Arc<Vocabulary>>> for Snapshot {
    fn from(current: Option<Arc<Vocabulary>>) -> Self {
        Self { current }
    }
}

impl Snapshot {
    /// Clone the current immutable snapshot; absence keeps automatic policy unready.
    pub fn current(&self) -> Option<Arc<Vocabulary>> {
        self.current.clone()
    }

    /// Parse `source` as a Vim word list and publish it whole; a candidate with skipped lines is
    /// still published. Readers that cloned the previous snapshot keep it unchanged.
    ///
    /// # Errors
    ///
    /// The candidate's [`ParseError`]; the current snapshot is left unchanged.
    pub fn replace(&mut self, source: &[u8]) -> Result<(), ParseError> {
        let candidate = Vocabulary::parse(source)?;
        self.current = Some(Arc::new(candidate));
        Ok(())
    }
}
}

Cloning an Arc copies the pointer and adds one to the count; the vocabulary itself is shared. Publishing replaces the pointer, never the contents, so a reader holding the old Arc keeps the old list until it lets go. Note the order inside replace: the ? leaves the function on a parse error before the assignment, so a bad file can’t disturb the good snapshot. The doc comment says “initially missing rather than silently empty”, and the Option makes the difference representable: a user who has no dictionary yet is not the same as one whose dictionary is empty.

From is the standard trait for conversions. Implementing it lets the C boundary write current.map(Snapshot::from) later; in Python it would be a constructor that takes the other type.

The engine takes the snapshots apart into plain references for the length of one proposal:

crates/keyrill-ffi/src/lib.rs:364-380

#![allow(unused)]
fn main() {
    match &engine.automatic {
        Automatic::Model(model) => {
            let en = engine.dictionaries[0].current();
            let ru = engine.dictionaries[1].current();
            engine.session.propose_with_inference(
                input,
                mode,
                context,
                model,
                Dictionaries {
                    en: en.as_deref(),
                    ru: ru.as_deref(),
                    learned: &engine.learned,
                },
                Policy::default(),
            )
        }
}

en is an Option<Arc<Vocabulary>>, a counted owner held in a local variable for the whole call. as_deref() borrows through it and gives an Option<&Vocabulary>, which is what Dictionaries stores. The borrow checker accepts this only because en outlives the call that uses the reference. Build Dictionaries in a let statement straight from engine.dictionaries[0].current().as_deref() instead, and the Arc becomes a temporary dropped at the end of that statement; the compiler rejects the dangling reference with error[E0716]: temporary value dropped while borrowed.

Tip

Remember. An Arc shares one value. Keyrill’s snapshots never change it: updating means publishing a new Arc, while code holding the old one keeps it.

Errors as values

Goal: read Result, ? and let ... else, and know where a panic fits.

Python and JavaScript report most failures with exceptions, which travel up the stack until someone catches them, invisible in the function’s signature. Rust has no exceptions for failures a program expects. A function that can fail returns Result<T, E>, an enum of Ok(T) and Err(E), so the failure is part of the return type and the caller must handle it. The ? operator says “on failure, return the error to my caller”, which is what an uncaught exception does, except that it is written at each place it can happen. It works on Option as well, where failure is None. The model parser uses both:

crates/keyrill-core/src/model.rs:128-145

#![allow(unused)]
fn main() {
    fn u32(&mut self) -> Result<u32, ModelError> {
        u32_at(self.take(4)?, 0).ok_or(ModelError::Truncated)
    }
}

fn u16_at(bytes: &[u8], index: usize) -> Option<u16> {
    let at = index.checked_mul(2)?;
    Some(u16::from_le_bytes(
        bytes.get(at..at.checked_add(2)?)?.try_into().ok()?,
    ))
}

fn u32_at(bytes: &[u8], index: usize) -> Option<u32> {
    let at = index.checked_mul(4)?;
    Some(u32::from_le_bytes(
        bytes.get(at..at.checked_add(4)?)?.try_into().ok()?,
    ))
}
}

u16_at has four ways to fail, and each is one ?: the multiplication overflows, the addition overflows, the range lies outside the slice (get returns None instead of crashing the way bytes[at] would), or the piece has the wrong length for a two-byte array. The asset comes from the build, yet every read is checked, because the same parser must be safe on a damaged file, and the project’s fuzzer, a tool that feeds a program generated and damaged inputs, does exactly that.

let ... else and arithmetic that can’t wrap

Goal: handle an unlikely case that must not be skipped.

let ... else binds a pattern if it matches and otherwise runs the else block, which must not continue past the statement: it has to return, break, continue or panic. This one returns from the function. Read it as “take the happy path, or get out”. Here it guards the counter that numbers plans:

crates/keyrill-core/src/session.rs:350-357

#![allow(unused)]
fn main() {
        // Exhaustion is permanent: reset keeps the counter, so every later proposal fails too
        let Some(id) = self.serial.checked_add(1) else {
            self.state = State::Invalidated;
            self.pending = None;
            self.history.clear();
            self.mode = None;
            return Err(Error::Invalidated);
        };
}

A plain self.serial += 1 would panic, stop with an error, in a debug build, the unoptimized build made for development, and wrap around to zero in a release build, the optimized one that ships. Python integers never overflow and JavaScript numbers silently lose precision, so neither prepares you for this. checked_add returns an Option instead, which makes overflow a case the code must handle. It is reached only after 2^64 plans. The rule it protects is that an expired plan id can never match a later plan, and the type system doesn’t let the code skip the case because it is unlikely.

An error type with nothing to leak

Goal: read an error type and its traits.

crates/keyrill-core/src/session.rs:143-162

#![allow(unused)]
fn main() {
/// Session protocol errors; no raw text is included.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
    /// The id is not the pending plan: a later proposal superseded it, it was already
    /// acknowledged, or a reset expired it.
    Stale,
    /// Session invalidated or token counter exhausted.
    Invalidated,
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::Stale => "plan is not the latest proposal",
            Self::Invalidated => "session is invalidated",
        })
    }
}

impl std::error::Error for Error {}
}

An error type is an ordinary enum. Implementing Display gives it human text, as __str__ does in Python and toString in JavaScript, and the empty impl std::error::Error admits it to the standard family of errors. The comment says “no raw text is included”, and the enum has no field that could hold any: an error from this crate can be logged without the risk of writing down what the user typed.

Tip

Remember. Failure is a value of type Result or Option, and ? passes it up. A panic is for bugs, not for expected failures.

Iterators and closures

Goal: read a chain of iterator methods and a function that takes a closure.

An iterator produces values one at a time, and its methods (map, zip, chain, filter) build a pipeline that does nothing until something asks for the values. Python’s generators and itertools work the same way, as do JavaScript’s iterator helpers; JavaScript’s Array.prototype.map is different, since it builds a whole new array at once. Rust’s compiler turns such a pipeline into a plain loop. The whole layout conversion is one:

crates/keyrill-core/src/mapping.rs:60-88

#![allow(unused)]
fn main() {
pub fn convert(text: &[u16], keyboard: Keyboard, mapping: Mapping) -> Vec<u16> {
    text.iter()
        .map(|&unit| convert_unit(unit, keyboard, mapping))
        .collect()
}

fn convert_unit(unit: u16, keyboard: Keyboard, mapping: Mapping) -> u16 {
    if mapping == Mapping::Manual && !is_letter(unit) {
        return unit;
    }
    let extra = match keyboard {
        Keyboard::Apple => ('\\', '|'),
        Keyboard::Pc => ('`', '~'),
    };
    for (en, ru) in EN
        .chars()
        .zip(RU.chars())
        .chain(EN_SHIFT.chars().zip(RU_SHIFT.chars()))
        .chain([(extra.0, 'ё'), (extra.1, 'Ё')])
    {
        if mapping != Mapping::RuToEn && unit == en as u16 {
            return ru as u16;
        }
        if mapping != Mapping::EnToRu && unit == ru as u16 {
            return en as u16;
        }
    }
    unit
}
}

|&unit| is a closure whose parameter pattern reads the u16 behind the reference the iterator yields. collect() builds whatever collection the return type names, here a Vec<u16>. In convert_unit, zip walks two strings of key labels side by side and chain appends the shifted row and the ё key, so the loop visits 66 pairs without an index or a table. The linear search is deliberate: 66 comparisons per key are nothing next to a round trip to the application, and the pairs stay readable as the rows of a keyboard.

Iterator methods replace index arithmetic in places where an off-by-one error would hurt. The word history keeps at most 256 units and must start at a whole word:

crates/keyrill-core/src/session.rs:414-426

#![allow(unused)]
fn main() {
                HistoryEffect::Append(text) => {
                    self.history.extend(text);
                    // Trim at a Space so the window starts at a whole word; this can drop one
                    // word more than the bound requires
                    if self.history.len() > MAX_HISTORY {
                        let minimum = self.history.len() - MAX_HISTORY;
                        let remove = self.history[minimum..]
                            .iter()
                            .position(|&unit| unit == 32)
                            .map_or(self.history.len(), |at| minimum + at + 1);
                        self.history.drain(..remove);
                    }
                }
}

position finds the first Space at or after the cut; map_or turns that into the removal point, or the whole history when there is no Space; and drain(..remove) deletes the prefix in place. The pattern HistoryEffect::Append(text) moves the appended text out of the enum, so extend consumes it without a copy.

A closure as a parameter

Goal: see dependency injection with a closure, and a value computed once per process.

A function may take a closure as a parameter, as a Python function may take a callable. impl FnOnce() -> ... in a parameter list means “any function or closure that can be called once and returns this”:

crates/keyrill-ffi/src/lib.rs:271-282

#![allow(unused)]
fn main() {
// Validated once per process; every engine that selects MODEL shares the result, a failure too
fn embedded_model() -> Result<Model<'static>, ModelError> {
    static MODEL: OnceLock<Result<Model<'static>, ModelError>> = OnceLock::new();
    *MODEL.get_or_init(Model::embedded)
}

// The model loader is a parameter so a test can inject an asset failure
fn set_policy(
    engine: &mut Engine,
    policy: u32,
    model: impl FnOnce() -> Result<Model<'static>, ModelError>,
) -> u32 {
}

Production passes embedded_model; a test passes a closure that returns an error, and so proves that a broken asset leaves the policy off. This is dependency injection, handing a function its collaborators instead of letting it reach for them, here with no interface and no virtual call. impl FnOnce is generic: the compiler produces a separate copy of set_policy for each closure type it is called with, as a C++ template does, so the call costs nothing at run time. The Objective-C side does the same with blocks, as the Objective-C chapter shows.

OnceLock is a cell that is filled at most once, safely even when several threads ask at the same moment. Python’s functools.cache on a function without arguments is the nearest relative, except that it may run the function twice under contention, while OnceLock runs a successful initializer only once (one that panics leaves the cell empty for the next caller). Here it validates the 5.6 MB model once per process, however many engines ask for it.

Tip

Remember. Iterator chains are lazy and compile to loops. A closure parameter is how Rust code lets a test swap a dependency.

Modules, documentation and lints

Goal: read a crate root, and know which checks the build enforces.

The crate root, lib.rs, is short, and its last lines are a promise the compiler keeps:

crates/keyrill-core/src/lib.rs:55-61

#![allow(unused)]
#![forbid(unsafe_code)]

fn main() {
pub mod inference;
pub mod mapping;
pub mod model;
pub mod session;
pub mod vocabulary;
}

#![...], with the !, applies an attribute to the whole crate. A lint is a check for a suspicious pattern that the compiler reports, and each has a level: allow, warn, deny or forbid (lint levels). forbid is the strictest: unlike deny, nothing further down can relax it, the way # noqa relaxes a Python linter or eslint-disable relaxes ESLint. So there is no unsafe code in this crate and no way to add any quietly (exercises 3 and 4); the next chapter explains what unsafe is.

pub mod declares a module, a namespace whose source is the file of that name, and makes it public. Items inside are private unless marked pub, and the compiler enforces it; Python’s leading underscore is only a convention. That is why State and Pending above are invisible to every other crate while Session and Plan are not.

The lints for the whole workspace live in one place:

Cargo.toml:12-18

[workspace.lints.rust]
unsafe_op_in_unsafe_fn = "deny"
missing_docs = "warn"

[workspace.lints.clippy]
missing_errors_doc = "warn"
missing_panics_doc = "warn"

./tools/verify runs Clippy, Rust’s extra linter, with warnings treated as errors, so these warnings fail the build too. missing_errors_doc is the reason every public function that returns a Result has an # Errors section, as Snapshot::replace above does. Documentation comments (///) may contain examples, and cargo test compiles and runs them as tests, like Python’s doctest. The example at the top of lib.rs types ghbdtn and Space through a whole session; it is the shortest complete use of the engine in the repository.

Tip

Remember. forbid can’t be relaxed below it. Private is the default, and examples in documentation run as tests.

The C boundary

Rust and Objective-C++ can’t call each other directly. They meet at the one interface both understand: C. This chapter is about that meeting point, what the compiler stops proving there, and what the code does in its place.

Why C, and what an ABI is

Goal: know what an ABI and an FFI are, and which files form Keyrill’s.

When a compiled program calls a function in another compiled library, both sides must agree on details no source code shows: which machine registers carry the arguments (the calling convention), the exact name the function has in the compiled file (its symbol, which the linker, the tool that joins compiled files into one program, matches between them), and the byte layout of every struct passed across. That agreement is an application binary interface (ABI). Every language can speak C’s ABI, which is why it serves as the common language here.

A foreign function interface (FFI) is the part of a language that calls, or is called by, code written in another one. Python has ctypes and cffi for it, Node.js has Node-API, and Rust has extern "C" functions, described in the Rustonomicon. Keyrill’s FFI has two halves:

  • the crate keyrill-ffi, compiled into a static library, a file of compiled code that the linker copies into the macOS program;
  • the C header include/keyrill.h, a file of declarations that C, C++ and Objective-C++ code includes so the compiler knows the names, types and struct layouts on the other side.

Tip

Remember. An ABI is the machine-level agreement between compiled code. Keyrill’s is C’s: keyrill-ffi on the Rust side, include/keyrill.h on the C side.

Where unsafe lives

Goal: read an unsafe block and the comment that must justify it.

The core crate forbids unsafe outright (Rust in the core), so every unsafe block in the project is in keyrill-ffi. The word is easy to misread. unsafe switches no check off: the borrow checker and the type checker run inside an unsafe block as everywhere else. It permits five extra operations, of which this crate uses two: reading through a raw pointer (*mut T or *const T, a plain C address with no lifetime and no guarantee that it points anywhere valid) and calling an unsafe fn.

Getting either wrong is undefined behavior: the program may crash, corrupt memory or seem to work, and nothing promises which. Python reaches the same territory when ctypes is handed a bad address and the interpreter crashes. So an unsafe block records that a person, not the compiler, now carries a proof, and every block here has a // SAFETY: comment that states the argument, as the Rust reference and the Book’s chapter on unsafe Rust describe.

An unsafe fn is a function with a precondition, a condition the caller must make true, that the compiler can’t check; calling it requires an unsafe block. Since the 2024 edition the compiler warns about an unsafe operation in the body of an unsafe fn that sits outside its own unsafe block, so each one gets its own block with its own justification (unsafe_op_in_unsafe_fn), and the workspace raises that lint from a warning to an error.

Tip

Remember. unsafe turns off no check; it lets a person vouch for what the compiler can’t prove, and the SAFETY comment is the written proof.

Step 1: agree on memory layout

Goal: see how two declarations of one struct, in two languages, are kept identical.

Rust may reorder the fields of a struct to save padding, the unused bytes the compiler inserts so that each field starts at a suitable address. #[repr(C)] forbids that and lays the fields out by C’s rules, in declaration order. Python’s ctypes.Structure, with its _fields_ list, does the same job from the Python side:

crates/keyrill-ffi/src/lib.rs:139-161

#![allow(unused)]
fn main() {
/// `kr_event`: one key or command, read by value; `len` counts the UTF-16 units in use.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct NativeEvent {
    role: u32,
    mode: u32,
    context: u32,
    len: u32,
    units: [u16; 8],
}

/// `kr_plan`: a proposal copied into caller-owned arrays; no Rust allocation crosses the
/// interface.
#[repr(C)]
pub struct NativePlan {
    plan_id: u64,
    action: u32,
    disposition: u32,
    expected_len: u32,
    mark_len: u32,
    expected: [u16; 128],
    mark: [u16; 128],
}
}

The same structs are declared a second time in C, and nothing ties the two declarations together except agreement. So the layout is pinned from both sides. In Rust, a const item is evaluated by the compiler, and an assert! in it that fails is a compile error:

crates/keyrill-ffi/src/lib.rs:260-269

#![allow(unused)]
fn main() {
// The same layouts the header's static assertions pin
const _: () = assert!(size_of::<CompatibilityPlan>() == 280);

const _: () = assert!(size_of::<NativeEvent>() == 32);
const _: () = assert!(size_of::<NativePlan>() == 536);
const _: () = assert!(std::mem::offset_of!(NativePlan, expected) == 24);
// A word plus its Space fits the 128-unit plan arrays
const _: () = assert!(keyrill_core::session::MAX_WORD < 128);
// KR_MAX_DICTIONARY_BYTES
const _: () = assert!(MAX_SOURCE_BYTES == 1_048_576);
}

In C, the header documents each offset and asserts the same numbers:

include/keyrill.h:174-193

/* A copied plan. expected is the exact text the owned composition must hold before the write,
 * empty when no word is owned; mark is the text to write. Units past each length are zero.
 *
 *   offset   0  plan_id       token for kr_commit; only the latest plan is accepted
 *            8  action        KR_PASS, KR_MARK, KR_FINISH or KR_UNAVAILABLE
 *           12  disposition   KR_KEY_PASS, KR_KEY_CONSUMED or KR_KEY_REPLAN
 *           16  expected_len
 *           20  mark_len
 *           24  expected      uint16_t[128]
 *          280  mark          uint16_t[128]                          536 bytes in all
 */
typedef struct {
  uint64_t plan_id;
  uint32_t action;
  uint32_t disposition;
  uint32_t expected_len;
  uint32_t mark_len;
  uint16_t expected[KR_TEXT_CAPACITY];
  uint16_t mark[KR_TEXT_CAPACITY];
} kr_plan;

include/keyrill.h:466-477

#ifdef __cplusplus
}
static_assert(sizeof(kr_event) == 32);
static_assert(sizeof(kr_plan) == 536);
static_assert(offsetof(kr_plan, expected) == 24);
static_assert(sizeof(kr_compatibility_plan) == 280);
#else
_Static_assert(sizeof(kr_event) == 32, "kr_event ABI");
_Static_assert(sizeof(kr_plan) == 536, "kr_plan ABI");
_Static_assert(offsetof(kr_plan, expected) == 24, "kr_plan text offset");
_Static_assert(sizeof(kr_compatibility_plan) == 280, "kr_compatibility_plan ABI");
#endif

A changed size or a moved text array is now a compile error on whichever side changed, never a plan read at the wrong offset at run time. Why pin the offset of expected and not only the size? Without #[repr(C)] Rust may put the arrays first, and the struct is still 536 bytes; only the offset shows the move. Exercises 5 and 6 show which assertion fires in each case.

The assertions don’t pin every field, though: swapping action and disposition in one declaration passes them both. That remaining risk is what the C smoke test crates/keyrill-ffi/tests/abi_smoke.c covers, by driving real plans through the header’s struct. The #ifdef picks the spelling each language understands: C11’s _Static_assert or C++’s static_assert. The } at the top closes an extern "C" block, which the Objective-C++ chapter explains.

Tip

Remember. #[repr(C)] gives a struct C’s layout, and compile-time assertions on both sides pin its size and the offset that would move.

Step 2: hand ownership across, and take it back

Goal: follow one engine from its creation in Rust to its destruction, requested from C.

C needs a handle to an engine, a value that identifies it, but must not see inside it. Python programmers know the idea from file descriptors: os.open returns an integer that means a file, and the program must close it exactly once. The header declares an opaque type, a struct with a name and no definition:

include/keyrill.h:74

typedef struct kr_engine kr_engine;

C code can hold a kr_engine * and pass it back; it can’t allocate one, copy one or read a field, because the compiler doesn’t know the size. On the Rust side the pointer is a Box<Engine>, Rust’s owning pointer to a value on the heap, the counterpart of C++’s std::unique_ptr:

crates/keyrill-ffi/src/lib.rs:423-459

#![allow(unused)]
fn main() {
#[unsafe(no_mangle)]
pub unsafe extern "C" fn kr_engine_new(abi: u32, out: *mut *mut Engine) -> u32 {
    if out.is_null() {
        return NULL;
    }
    // SAFETY: `out` is non-null (checked above), and the caller guarantees it is aligned and
    // writable for one pointer
    unsafe {
        out.write(std::ptr::null_mut());
    }
    if !compatible_abi(abi) {
        return VERSION;
    }
    match catch_unwind(|| {
        Box::new(Engine {
            session: Session::default(),
            poisoned: false,
            automatic: Automatic::Off,
            dictionaries: [Snapshot::default(), Snapshot::default()],
            learned: Vec::new(),
            backend: Backend::Unselected,
            compatibility_boundary: false,
            compatibility_word_boundary: false,
            compatibility_collect: true,
            compatibility_pending: None,
        })
    }) {
        Ok(engine) => {
            // SAFETY: same output contract; allocation is transferred exactly once
            unsafe {
                out.write(Box::into_raw(engine));
            }
            OK
        }
        Err(_) => POISONED,
    }
}
}

Read the order of operations: the output pointer is checked, then set to null, then the ABI version is compared, and only then is anything allocated. A caller that ignores the status code still finds a null handle, never leftover garbage from its own stack. Box::into_raw gives up ownership and returns a raw pointer, so Rust will not drop the engine; from this moment C holds the only reference. The way back is Box::from_raw, which takes ownership back, after which drop destroys the engine and frees its memory:

crates/keyrill-ffi/src/lib.rs:461-475

#![allow(unused)]
fn main() {
/// Free once, after every call on the engine has returned and no callback can reach it. Null is
/// a no-op.
///
/// # Safety
/// A non-null pointer must be the live allocation returned by `kr_engine_new`, with no aliases.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn kr_engine_free(pointer: *mut Engine) {
    if !pointer.is_null() {
        // An unwind must not cross into C; a panic while dropping is discarded
        let _ = catch_unwind(AssertUnwindSafe(|| {
            // SAFETY: caller transfers the original unique allocation exactly once
            drop(unsafe { Box::from_raw(pointer) });
        }));
    }
}
}

The # Safety section of the doc comment is the precondition of this unsafe fn, written for the caller: a pointer freed twice, or freed while another call on it is running, is the caller’s bug.

Is that enforced? Not by the compiler, and not by this function, which can’t tell a live pointer from a freed one. Two tools catch it in testing, on the paths a test exercises: ./tools/verify sanitize runs the native tests under AddressSanitizer, which reports a double free or a use after free at the moment it happens, and ./tools/verify miri runs the Rust pointer tests under Miri, an interpreter that detects undefined behavior. In the shipped program the guarantee is ownership: each engine belongs to exactly one Objective-C object, a KRSession or, for the compatibility backend, a KRCompatibilitySession, which frees it once in its destructor, as the next chapter shows. The only other frees are of engines that never left the function that created them: a failed configuration in KRController.mm and a validation probe in KRRuntime.mm.

Tip

Remember. Box::into_raw hands an allocation to C, and Box::from_raw takes it back for exactly one free. Freeing twice is the caller’s bug; tests catch it, the compiler can’t.

Step 3: stop panics at the boundary

Goal: see why a Rust panic must never reach C, and how one function prevents it.

A panic unwinds the stack: it leaves each function in turn, running the destructors of its local values, until something catches it, much as an exception does in Python, JavaScript and C++. It must not unwind into C or Objective-C frames, which know nothing about Rust’s unwinding. Since Rust 1.81, a panic that reaches an extern "C" function aborts the process, the running program, ending it at once with no cleanup; before 1.81 it was undefined behavior. An aborted input method takes the user’s typing with it. So every exported function that touches an engine goes through one function, the most instructive twenty lines of the crate:

crates/keyrill-ffi/src/lib.rs:385-409

#![allow(unused)]
fn main() {
// Callers provide live, uniquely borrowed handles. No callback is made while this borrow
// exists; every export releases it before returning to native code. A panic in `f` poisons the
// handle, which also drops the word, history and pending plans it held. AssertUnwindSafe is
// acceptable because nothing relies on state a panic may have left inconsistent: the handle is
// only reset, and every later call returns POISONED before touching it.
unsafe fn with_engine(pointer: *mut Engine, f: impl FnOnce(&mut Engine) -> u32) -> u32 {
    if pointer.is_null() {
        return NULL;
    }
    // SAFETY: non-null was checked above; the caller contract requires a live aligned handle from
    // kr_engine_new, not yet freed, with no other reference to it alive during this call
    let engine = unsafe { &mut *pointer };
    if engine.poisoned {
        return POISONED;
    }
    match catch_unwind(AssertUnwindSafe(|| f(engine))) {
        Ok(result) => result,
        Err(_) => {
            engine.poisoned = true;
            engine.session.reset();
            engine.compatibility_pending = None;
            POISONED
        }
    }
}
}

Three things happen in order. A null check, because C may pass anything. The conversion of a raw pointer into &mut Engine, the one step that needs unsafe: from here on the borrow checker treats the engine as exclusively borrowed, and the SAFETY comment states why that is true. Then catch_unwind around the work, which turns a panic into an Err. In Python terms, every exported function is wrapped in try/except and turns any exception into an error code.

A caught panic poisons the handle permanently. The panic may have left the session half-updated, and no later call should reason from that state, so the handle is reset and every later call returns KR_POISONED before touching anything. AssertUnwindSafe is the explicit statement that this is acceptable: by default catch_unwind refuses a closure that holds a &mut across the panic, precisely because of the half-updated state, and the comment explains why nothing here relies on it.

Look again at the closure parameter f: impl FnOnce(&mut Engine) -> u32. with_engine lends the engine to f and gets it back; the borrow ends when f returns, and the function returns to native code right after. No Rust reference to the engine can be alive while native code runs, and since Rust never calls back into the adapter, there is no other way for one to be. That is how the rule “never hold Rust borrows across native callbacks” from AGENTS.md is kept by construction.

Catching depends on one build setting:

Cargo.toml:20-22

[profile.release]
# The C ABI catches a panic and poisons the handle; with abort the panic would end the input server
panic = "unwind"

With panic = "abort" there is no unwinding to catch, and catch_unwind would never get a chance.

Tip

Remember. A panic must not cross into C. with_engine catches it, poisons the handle, and returns an error code instead.

Step 4: the anatomy of an exported function

Goal: read an extern "C" function line by line.

crates/keyrill-ffi/src/lib.rs:695-720

#![allow(unused)]
fn main() {
/// Acknowledge the latest plan; refused and unknown outcomes invalidate the session until
/// [`kr_reset`]. A stale token changes nothing.
///
/// # Safety
/// `pointer` must meet the live unique serialized handle contract, or be null.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn kr_commit(pointer: *mut Engine, token: u64, outcome: u32) -> u32 {
    // SAFETY: forwarded handle contract
    unsafe {
        with_engine(pointer, |engine| {
            let outcome = match outcome {
                0 => Outcome::Verified,
                1 => Outcome::Refused,
                2 => Outcome::Unknown,
                _ => return BAD_TAG,
            };
            if engine.backend == Backend::Compatibility {
                return STATE;
            }
            engine
                .session
                .acknowledge(token, outcome)
                .map_or_else(status, |()| OK)
        })
    }
}
}
  • extern "C" selects C’s calling convention.
  • #[unsafe(no_mangle)] keeps the symbol name exactly kr_commit. Without it the compiler would mangle the name, encoding the crate, module and a hash into the symbol so that equal names in different places stay distinct (name mangling), and the linker would never match it to the header’s declaration. The 2024 edition marks the attribute itself unsafe, because an unmangled name can collide with another symbol in the final program.
  • An integer from C becomes an enum only through a match with a catch-all arm that returns BAD_TAG. Rust has no cast from an integer to an enum, and a transmute, a reinterpretation of the bits, of a stray 3 would create an Outcome with no variant, which is undefined behavior; the value must be rejected before it becomes an enum.
  • return BAD_TAG inside the closure returns from the closure, which is with_engine’s result.
  • map_or_else(status, |()| OK) turns the session’s Result<(), Error> into a status code: the function status, passed by name, converts the error, and the closure converts success.

Plans travel the other way by value. kr_plan_event decodes the C event into an owned Rust Event and writes a complete NativePlan into memory the caller owns:

crates/keyrill-ffi/src/lib.rs:321-348

#![allow(unused)]
fn main() {
fn decode_event(event: &NativeEvent) -> Result<(Event, Mode, Context), u32> {
    if event.len > 8 {
        return Err(BOUNDS);
    }
    let mode = match event.mode {
        1 => Mode::En,
        2 => Mode::Ru,
        _ => return Err(BAD_TAG),
    };
    let context = match event.context {
        0 => Context::Boundary,
        1 => Context::Ineligible,
        _ => return Err(BAD_TAG),
    };
    if event.role != 1 && event.len != 0 {
        return Err(BAD_TAG);
    }
    let input = match event.role {
        1 => Event::Text(event.units[..event.len as usize].to_vec()),
        2 => Event::Backspace,
        3 => Event::Escape,
        4 => Event::Manual,
        5 => Event::Reverse,
        6 => Event::Finish,
        _ => return Err(BAD_TAG),
    };
    Ok((input, mode, context))
}
}

crates/keyrill-ffi/src/lib.rs:686-690

#![allow(unused)]
fn main() {
            // Conversion maps unit for unit, so both texts are at most a MAX_WORD word plus Space
            copied.expected[..plan.expected.len()].copy_from_slice(&plan.expected);
            copied.mark[..plan.text.len()].copy_from_slice(&plan.text);
            out.write(copied);
            OK
}

The length is checked before the slice event.units[..event.len as usize] is taken, although an out-of-range slice would only panic and be caught: a status code is a better answer to bad input than a poisoned handle. to_vec() copies the units into a vector the session owns, so nothing in Rust keeps a pointer into the caller’s struct. On the way out, the plan’s vectors are copied into the fixed arrays of NativePlan, the rest stays zero, and out.write stores the whole struct at once. No Rust allocation crosses the interface in either direction, and the adapter frees nothing but handles.

Tip

Remember. An export uses C’s calling convention and an unmangled name, validates every integer before it becomes an enum, and copies data across instead of sharing it.

Threads and locks

Goal: read a Mutex, an atomic flag and a lock order, and know what each prevents.

The engine is used from one thread: the header requires calls on one engine to come one at a time from the thread that owns its input context, and &mut in with_engine encodes exactly that. Dictionary files are a different matter. Reading a file is slow and must not happen on the thread that handles keys, so a second handle, kr_vocabulary, is shared between a background queue that reads files and the main thread, the one on which macOS delivers input, that hands dictionaries to engines.

Two threads that touch the same memory, at least one of them writing, without coordination, form a data race: undefined behavior in Rust and C++. Python’s global interpreter lock hides some of this, though not all, and JavaScript avoids it by running one thread per event loop. The module documentation states the design:

crates/keyrill-ffi/src/vocabulary_host.rs:1-19

#![allow(unused)]
fn main() {
//! `kr_vocabulary`: dictionary sources that engines adopt, without scheduling or native editing
//! authority.
//!
//! A vocabulary handle holds six vocabulary sources, the English and Russian Vim spell files and
//! four learned-word slots, each with a configured path, flags, a generation and a current
//! snapshot. Two locks keep the slow path away from the controller thread:
//!
//! ```text
//!   acquisition  one Source per slot; held across file I/O by kr_vocabulary_observe
//!   published    path, flags, generation and snapshot per slot; held briefly by configure,
//!                adopt, and the start and end of observe
//! ```
//!
//! Observe takes `acquisition` before `published` and nothing takes them in the other order, so
//! configure and adopt never wait for a file read. A configuration change advances the slot's
//! generation; an observation that began under the old generation finds the change when it
//! locks `published` again and publishes nothing (`STALE_CONFIGURATION`). Adoption clones every
//! snapshot under one lock, so an engine never pairs a language from before a change with one
//! from after it.
}

A lock lets one thread at a time into the code it protects. Taking two locks in different orders on two threads can leave each thread waiting for the lock the other holds, forever: a deadlock. A fixed order, here acquisition before published, rules that out. The data structure puts each lock around exactly what it protects:

crates/keyrill-ffi/src/vocabulary_host.rs:72-79

#![allow(unused)]
fn main() {
/// `kr_vocabulary`: six vocabulary sources behind two locks, shared by the acquisition queue and
/// the controller thread. Free only after every operation has completed.
#[derive(Default)]
pub struct VocabularyHandle {
    poisoned: AtomicBool,
    acquisition: Mutex<Acquisition>,
    published: Mutex<[Language; SOURCES]>,
}
}

A Rust Mutex<T> contains the data it guards. The only way to reach the Acquisition is lock(), which returns a guard that gives access to the data and unlocks when it is dropped, so forgetting to lock is not an error you can make. Python’s threading.Lock in a with block unlocks the same way, but it protects nothing by itself: any code can touch the data without taking it.

Rust tracks which types may be used from several threads with two traits the compiler derives on its own, Send and Sync; Mutex and AtomicBool are what make a shared &VocabularyHandle safe to use from two threads at once. A raw pointer from C bypasses that check, so the function that turns it into a reference states the argument itself:

crates/keyrill-ffi/src/vocabulary_host.rs:212-234

#![allow(unused)]
fn main() {
// Shared references are synchronized internally; no native calls occur under either lock.
// Any POISONED result, a caught panic or a lock poisoned by one, poisons the handle for good.
unsafe fn with_vocabulary(
    pointer: *const VocabularyHandle,
    operation: impl FnOnce(&VocabularyHandle) -> u32,
) -> u32 {
    if pointer.is_null() {
        return NULL;
    }
    // SAFETY: non-null was checked above; the caller contract requires the live aligned
    // allocation from kr_vocabulary_new, not yet freed and kept alive for this call. Only shared
    // references are made, and every mutation goes through a Mutex or the atomic flag, so
    // concurrent calls on the handle are allowed.
    let vocabulary = unsafe { &*pointer };
    if vocabulary.poisoned.load(Ordering::Acquire) {
        return POISONED;
    }
    let status = catch_unwind(AssertUnwindSafe(|| operation(vocabulary))).unwrap_or(POISONED);
    if status == POISONED {
        vocabulary.poisoned.store(true, Ordering::Release);
    }
    status
}
}

Compare it with with_engine. This one makes &*pointer, a shared reference, where with_engine made &mut *pointer; two threads may hold shared references at once, and the type allows nothing through them but locking and atomic operations. An atomic variable is one whose reads and writes are indivisible even across threads, and the poison flag is one, with Acquire and Release ordering: the rules that decide which other writes a thread is guaranteed to see. They are the same as C++’s std::memory_order. JavaScript also has atomic operations on memory shared between workers, Atomics, but they are all sequentially consistent and expose no ordering to choose.

A Rust mutex, short for mutual exclusion and the name of its lock type, has poisoning of its own: if a thread panics while it holds the guard, later calls to lock() return an error rather than hand out data that may be inconsistent (poisoning). The code turns that error into KR_POISONED as well:

crates/keyrill-ffi/src/vocabulary_host.rs:133-160

#![allow(unused)]
fn main() {
        let Ok(mut languages) = self.published.lock() else {
            return POISONED;
        };
        let language = &mut languages[index];
        if language.path == path
            && language.missing_is_empty == missing_is_empty
            && language.excluded == excluded
        {
            return OK;
        }
        let Some(generation) = language.generation.checked_add(1) else {
            return STATE;
        };
        let retired = std::mem::replace(
            language,
            Language {
                generation,
                path,
                missing_is_empty,
                excluded,
                current: None,
            },
        );
        // Free the old snapshot after unlocking, so a large vocabulary never holds the lock
        drop(languages);
        drop(retired);
        OK
    }
}

std::mem::replace puts a new value in place and hands back the old one, which keeps the old snapshot alive past the assignment. Then the order of the two drop calls does the work the comment describes: the guard first, which unlocks, and the retired value second, so freeing a large word list happens outside the lock. In C++ the same intent needs a carefully placed scope; here destruction is a function call you can put where you want it.

The generation is the same device the Objective-C++ side uses against reentrancy, applied to threads: an observation remembers the generation it started under and publishes nothing if the configuration changed while it read the file. You will meet it again, as _generation, in Reentrancy and tests.

Tip

Remember. A Rust Mutex owns its data, so it can’t be bypassed. Take locks in one fixed order, and free large values after unlocking.

Objective-C

Objective-C is C with one new expression, the message send, borrowed from Smalltalk, and an object model built on it. Everything C allows is still allowed, which is why the adapter can keep a raw kr_engine * inside an object and pass a kr_event by pointer. This chapter covers the Objective-C half of the adapter: the syntax, the objects, how their memory is managed and how work moves between threads. The C++ half is the next chapter.

Apple’s Programming with Objective-C is the reference for the language. It is archived, and the language hasn’t changed in the parts this code uses.

Messages

Goal: read a bracketed message send and name the method it calls.

The brackets look strange for about an hour. [receiver message] sends a message to an object, and the method that runs is looked up by name at run time (dynamic dispatch). If you come from Python or JavaScript, this is the familiar part: obj.method() there is also a lookup by name when the line runs. C++ is the odd one out, with a table of virtual functions fixed at compile time.

Arguments are written between the parts of the method’s name. [session handleEvent:&input client:client] calls one method whose full name, its selector, is handleEvent:client:, with one colon per argument. A method declared with - is an instance method, called on an object; a method declared with + is a class method, called on the class itself, like a Python @classmethod or a C++ static member function.

Objective-CC++PythonJavaScript
[client markedRange]client->markedRange()client.markedRange()client.markedRange()
[s handleEvent:e client:c]s->handleEvent(e, c)s.handleEvent(e, client=c)s.handleEvent(e, c)
@interface A : NSObject <P>class A : public NSObject, public Pclass A(NSObject, P)class A extends NSObject, plus an interface in TypeScript
@property(nonatomic) uint32_t mode;getter, setter and a field@property with a setterget mode() and set mode(v)
^BOOL { return YES; }a lambdaa lambda or nested defan arrow function
@"text", @[a, b], @{k : v}, @(n)library types"text", [a, b], {k: v}, n"text", [a, b], {k: v}, n
nil, and [nil anything] does nothing and gives zero for objects and numbersnullptr, but a call on it crashesNone, and a call on it raisesnull, closest to obj?.method()
YES, NO, BOOLtrue, false, boolTrue, Falsetrue, false

Tip

Remember. [object part1:a part2:b] calls the method part1:part2:, looked up by name at run time.

A class in two files

Goal: read a class’s public declaration and its private implementation.

A class has a public face, the @interface in a header, and a body, the @implementation in the source file. Here is the session’s interface, with its class methods and its one initializer:

native/macos/src/KRSession.h:76-92

@interface KRSession : NSObject <KRVocabularyAdopting>

/// Process-wide depth of host input callbacks on the main thread. While it is nonzero,
/// vocabulary adoption waits and runtime replacement and deferred mode requests are refused,
/// because a nested run loop inside one controller's callback can run work queued for another.
/// Begin and end off main are no-ops, and the query returns YES off main. End at zero is a no-op.
/// Overflow saturates and defers adoption until process exit.
+ (void)beginInputCallback;
+ (void)endInputCallback;
+ (BOOL)inputCallbackActive;

/// Takes ownership of `engine` and frees it in dealloc. `allowedClients` lists the bundle
/// identifiers in which a composition may start; a nonempty client bundle identifier and every
/// secure-input, ownership and readback check remain required.
- (instancetype)initWithEngine:(kr_engine *)engine
                allowedClients:(NSSet<NSString *> *)allowedClients NS_DESIGNATED_INITIALIZER;
- (instancetype)init NS_UNAVAILABLE;

NSObject is the root class, the ancestor of every object here. instancetype means “an instance of the class this was called on”, so a subclass’s initializer returns the subclass. The two macros at the end are checked by the compiler: NS_DESIGNATED_INITIALIZER marks the one initializer every other must call, and NS_UNAVAILABLE removes the inherited init, so [[KRSession alloc] init], a session with no engine, is a compile error rather than a crash later. NSSet<NSString *> * is a lightweight generic: a hint the compiler checks where the method is called, and forgets at run time, like a Python type annotation checked by mypy.

The private fields, instance variables, go in braces after @implementation, in the source file, so they never appear in the header at all. A C++ header shows every private member to whoever includes it; here the header says nothing about the representation:

native/macos/src/KRSession.mm:26-40

@implementation KRSession {
  kr_engine *_engine;
  NSSet<NSString *> *_allowedClients;
  // Bumped by every invalidation; each client call is followed by a comparison with the value
  // taken before it
  uint64_t _generation;
  // A plan is in flight; a callback that finds it set came through a nested run loop
  BOOL _busy;
  BOOL _poisoned;
  BOOL _finishVerified;
  // Local authority: the client, document start and exact text of the verified mark; the caret
  // is at its end
  id<IMKTextInput> _owner;
  NSUInteger _start;
  NSString *_text;

These comments are design notes, and the rest of the walkthrough leans on them; _generation and _busy are the subject of Reentrancy and tests. Note that the handle from Rust is an ordinary C pointer field, side by side with pointers to objects.

Creating and destroying an object

Goal: read the standard initializer and know what dealloc is for.

Creation is two messages, [[KRSession alloc] initWithEngine:... allowedClients:...]: alloc reserves memory filled with zeros, and the initializer, the counterpart of a constructor or Python’s __init__, fills it. Initialization is a convention rather than a language feature, and this is its standard shape:

native/macos/src/KRSession.mm:75-91

- (instancetype)initWithEngine:(kr_engine *)engine
                allowedClients:(NSSet<NSString *> *)allowedClients {
  if ((self = [super init])) {
    _engine = engine;
    _allowedClients = [allowedClients copy];
    _mode = KR_EN;
    _contextLocation = NSNotFound;
    _secureInputEnabled = ^BOOL {
      return IsSecureEventInputEnabled();
    };
  }
  return self;
}

- (void)dealloc {
  kr_engine_free(_engine);
}

self = [super init] lets the parent class initialize its part. The parent may return nil, or even a different object, so the result is assigned and checked. The double parentheses tell the compiler that the assignment inside if is intended. [allowedClients copy] keeps a private copy that can’t change, because the caller might have passed a mutable set and changed it later. The block assigned at the end is dependency injection, which the section on blocks returns to.

dealloc is the destructor, run when the object’s last owner lets go. Under ARC, described below, you don’t release fields and don’t call [super dealloc]; the compiler does both. You write dealloc only for what ARC can’t see, and a C handle is exactly that. This line is the other end of Box::from_raw from the C boundary: when the last reference to the session goes, the Rust engine goes with it.

Tip

Remember. The header shows the interface and hides the fields. dealloc exists here only to free what ARC doesn’t manage, the Rust engine.

Properties

Goal: read property attributes and know what they generate.

A property declares a pair of accessors, a getter and a setter; the compiler writes the methods and a field named with a leading underscore, as Python’s @property and JavaScript’s getters do by hand. The attributes in parentheses say how:

native/macos/src/KRSession.h:94-104

/// Input mode (KR_EN or KR_RU) of a finish the session plans on its own; the controller keeps
/// it equal to its current mode. A key carries its mode in its event.
@property(nonatomic) uint32_t mode;
/// True after an unknown write outcome, a contract violation or a poisoned engine. Ordinary
/// keys then pass with zero client calls until `activate` (never again once poisoned). After a
/// verified write, the first unknown outcome in an activation stops only that word: the next
/// text key re-arms the session and starts from fresh client checks.
@property(nonatomic, readonly) BOOL stopped;
/// YES while the session holds local authority over a verified mark.
@property(nonatomic, readonly) BOOL owned;
@property(nonatomic, readonly) KRInputStatus inputStatus;

native/macos/src/KRSession.h:112-114

/// Replaceable for controlled tests; defaults to `IsSecureEventInputEnabled`. Checked at entry
/// and again after each client query that precedes a text read or a write.
@property(nonatomic, copy) BOOL (^secureInputEnabled)(void);

nonatomic drops the default guarantee that a getter racing a setter on another thread still sees a whole value; everything here runs on the main thread, the one thread on which macOS delivers every input event, so the guarantee would buy nothing. readonly publishes only the getter: the class writes _stopped directly, and nobody outside can. copy makes the setter copy its argument, which a block requires, since a block written in a function may live on the stack until it is copied to the heap. self.mode = KR_RU and [self setMode:KR_RU] are the same message; the dot is notation, not direct field access.

A property may also be computed. owned has no field behind it; the implementation supplies the getter:

native/macos/src/KRSession.mm:93-99

- (BOOL)owned {
  return _owner != nil;
}

- (BOOL)boundaryRetained {
  return _owner && [_text hasSuffix:@" "];
}

When a class writes its own setter, it must say which field the property uses, with @synthesize; the controller does that to pass a new Secure Input block on to the sessions it owns:

native/macos/src/KRController.mm:175

@synthesize secureInputEnabled = _secureInputEnabled;

native/macos/src/KRController.mm:204-208

- (void)setSecureInputEnabled:(BOOL (^)(void))block {
  _secureInputEnabled = [block copy];
  _session.secureInputEnabled = _secureInputEnabled;
  _compatibility.secureInputEnabled = _secureInputEnabled;
}

The last line may run while _compatibility is nil, and that is fine: a message to nil does nothing, and a method returning an object, a number or a pointer gives nil or zero (a structure result is not always zeroed, so don’t rely on it there). The language guarantees it, and Cocoa code, written against Apple’s Objective-C frameworks for macOS applications, relies on it constantly, much as JavaScript code relies on optional chaining, obj?.method(), except that Objective-C does it for every message without being asked. It cuts both ways: a wrong assumption that an object exists produces no crash and no error, only zeros, which is one reason the adapter checks the objects an application hands it before using them, as below.

The type of the block property needs a reading aid. BOOL (^secureInputEnabled)(void) declares a block named secureInputEnabled that takes nothing and returns BOOL. It is built like the C function pointer BOOL (*f)(void), with ^ in place of *.

Tip

Remember. A property is a getter and a setter, written by the compiler. A message to nil is legal and does nothing; an object or number result is nil or zero.

Protocols and forward declarations

Goal: read a protocol and a type that requires it.

A protocol is a named list of methods that any class may adopt: a C++ class with only pure virtual functions, a Python typing.Protocol, a TypeScript interface, a Rust trait. Both editing backends adopt this one, so the dictionary loader can hand dictionaries to whichever is active without knowing its class:

native/macos/src/KRSession.h:8-14

/// A session that can take the runtime's published vocabulary snapshots into its engine. Both
/// backends implement it, so `KRRuntime` adopts into whichever session the active controller
/// routed to. Returns the `kr_adopt_vocabulary` status; STATE means "not now", and the runtime
/// retries after a later observation.
@protocol KRVocabularyAdopting <NSObject>
- (uint32_t)adoptVocabulary:(kr_vocabulary *)vocabulary;
@end

id<KRVocabularyAdopting> then means “any object that adopts it”. The most important protocol in the adapter is not Keyrill’s own. IMKTextInput, from Apple’s InputMethodKit (IMK), is how an input method talks to the application it types into: markedRange, selectedRange, stringFromRange:actualRange:, setMarkedText:selectionRange:replacementRange: and insertText:replacementRange: are messages of that protocol. Each one is inter-process communication (IPC): a request to another running program, the application, which answers when it is ready.

A header that only names a class or protocol, without calling it, declares it in advance, as C++ does with class X;:

native/macos/src/KRRuntime.h:9-10

@class KRSession;
@protocol KRVocabularyAdopting;

Tip

Remember. A protocol is an interface; id<P> is any object that adopts it. Every message to the application is IPC to another process.

Nullability and enums

Goal: read the annotations that open Keyrill’s headers.

Headers here open with NS_ASSUME_NONNULL_BEGIN, which makes every object pointer in the region non-null unless it is marked nullable. The compiler checks the annotations where it can, and they document the contract where it can’t (nullability).

NS_ENUM declares a C enum with a fixed underlying type, which makes its size part of the declaration rather than a choice the compiler makes:

native/macos/src/KRSession.h:16-30

/// Most recent input-boundary observation, shown in the input menu as the reason the last word
/// was left alone. It contains no text, offsets or client identity.
typedef NS_ENUM(uint8_t, KRInputStatus) {
  KRInputNotObserved,
  KRInputReady,
  /// The client's bundle identifier is not in the composition set.
  KRInputExcluded,
  KRInputSecure,
  /// The selection was not a collapsed caret, the client already had a mark, or the unit before
  /// the caret came back with another length or range.
  KRInputContextUnavailable,
  /// The UTF-16 unit before the caret is not whitespace: the word continues other text.
  KRInputNotAtBoundary,
  KRInputMarkMismatch,
  KRInputCaretMismatch,

The same privacy rule as on the Rust side shows in the doc comment: a status says why a word was left alone and carries nothing of what was typed.

Tip

Remember. Pointers are non-null unless marked nullable. A status names a reason, never the text.

Values from outside are checked

Goal: see how the adapter treats every answer from the application as untrusted.

The declared type of an application’s answer is a promise made by a header, and the application is someone else’s code in someone else’s process. The adapter checks the answer’s real type before it uses it, and it is ready for the call itself to fail:

native/macos/src/KRSession.mm:340-352

- (BOOL)clientAllowed:(id<IMKTextInput>)client generation:(uint64_t)generation {
  @try {
    NSString *bundle = [client bundleIdentifier];
    BOOL allowed = [bundle isKindOfClass:NSString.class] && bundle.length != 0 &&
                   [_allowedClients containsObject:bundle];
    if (generation == _generation)
      _inputStatus = allowed ? KRInputReady : KRInputExcluded;
    return generation == _generation && allowed && ![self secureAfterQuery];
  } @catch (NSException *) {
    _inputStatus = KRInputClientException;
    return NO;
  }
}

isKindOfClass: asks the object for its class at run time, as Python’s isinstance and JavaScript’s instanceof do. NSString.class is the class object itself, sent the class message through dot syntax. If the application returned nil, the first test is a message to nil and yields NO, so the same expression handles a missing answer and an answer of the wrong kind. Why the method compares generation with _generation after the call is the subject of Reentrancy and tests.

Tip

Remember. Check the class of anything an application returns, and expect any call to it to raise.

Literals and collections

Goal: read Foundation’s collection literals and their mutable variants.

Foundation, Apple’s base library, has collections that hold objects only, and the literal syntax makes them short to write. A per-application setting is updated like this:

native/macos/src/KRController.mm:520-525

  NSMutableDictionary *tiers = [runtime.tierOverrides mutableCopy];
  if (name)
    tiers[bundle] = name;
  else
    [tiers removeObjectForKey:bundle];
  NSDictionary *changes = @{@"ApplicationTiers" : tiers.count ? [tiers copy] : NSNull.null};

Each collection comes in two classes, mutable and immutable, and mutableCopy and copy convert between them; Python’s list and tuple are the nearest pair. Subscripting, tiers[bundle] = name, is notation for the message setObject:forKey:. A dictionary can’t store nil, so “remove this key” travels as the singleton NSNull.null, and the code that applies the change tests for it. Iterating a collection uses fast enumeration, for (NSString *key in changes), the counterpart of Python’s for key in changes:.

Tip

Remember. @[] and @{} make immutable collections; mutableCopy makes a version you can change. nil can’t go into a collection, so NSNull stands for it.

Memory: ARC

Goal: know what ARC does for you, and the one thing it doesn’t.

Every object carries a retain count, the number of owners it has; it is freed when the count reaches zero. Under Automatic Reference Counting (ARC), the compiler inserts the calls that raise and lower the count, called retain and release, so you never write them. A pointer is __strong by default and keeps its object alive; a __weak pointer doesn’t, and becomes nil when the object goes away, like Python’s weakref and JavaScript’s WeakRef.

CPython also counts references, and C++’s std::shared_ptr works the same way. The difference from CPython and JavaScript is that ARC has no garbage collector behind it: two objects that hold strong pointers to each other keep each other alive forever, a retain cycle. The controller keeps a weak pointer to the most recently activated controller, so this global never keeps alive a controller that InputMethodKit has discarded:

native/macos/src/KRController.mm:10-13

// Process-wide, main thread only
static __weak KeyrillAlphaController *activeController;
static KRRuntime *runtime;
static BOOL (^preferencesUpdater)(NSDictionary *);

ARC has no borrow checker, and one consequence matters here. A method is a function with a hidden self parameter, and ARC does not retain self for the duration of a call: the ARC specification treats it as kept alive by the caller, and calls deallocating an object during a message to it “undefined behavior, or at least dangerous”. In most programs nothing can release an object while one of its methods runs. In an input method something can: a call to the application can let other events run, including one that makes InputMethodKit drop its last reference to this session. Hence a line that looks peculiar until you know why it is there:

native/macos/src/KRSession.mm:191-195

- (BOOL)handleEvent:(const kr_event *)input client:(id<IMKTextInput>)client {
  __attribute__((objc_precise_lifetime)) KRSession *lifetime = self;
  (void)lifetime;
  if (!NSThread.isMainThread || !input)
    return NO;

The local strong reference retains self for the call. Without the attribute, ARC may release a local at its last use, and a local that is never read has no use at all. objc_precise_lifetime tells ARC to keep it until the end of its scope, and (void)lifetime; silences the warning about an unused variable. The other session and controller entry points that can reach the application start the same way.

Tip

Remember. ARC counts references for you but collects no cycles. It doesn’t keep self alive during a call, so methods that call the application retain self themselves.

Blocks

Goal: read a block, its captures, and the weak-strong pattern.

A block is Objective-C’s closure: a literal ^{ ... } that captures the variables it uses and can be stored, copied and called later (language specification). One difference from Python and JavaScript closures matters: a block captures the value a local variable had when the block was created, and can’t assign to it, unless the variable is declared __block; a Python or JavaScript closure always sees the variable itself (closures in JavaScript).

The session’s secureInputEnabled property, set in the initializer above, holds a block. Production code leaves the default, which asks macOS whether Secure Input, the mode in which keys go only to a password field, is on; a test replaces the block and turns Secure Input on at a chosen moment. This is the same dependency injection the Rust side does with a closure parameter in set_policy.

A block keeps the objects it captures alive, which makes retain cycles easy: an object that stores a block that captures the object keeps itself alive. Work put off until later is where this matters most, and the adapter answers it with the weak-strong pattern:

native/macos/src/KRController.mm:311-317

  // Permissions granted after launch take effect here; tap creation can't run in a callback
  __weak KeyrillAlphaController *weakController = self;
  dispatch_async(dispatch_get_main_queue(), ^{
    KeyrillAlphaController *controller = weakController;
    if (controller && activeController == controller && usesCompatibility(controller->_tier))
      controller->_startGuard();
  });

The block captures only a weak pointer, so a queued block doesn’t keep a closed controller alive. When it runs, it takes a strong local copy, which is either nil (the controller is gone, and the block does nothing) or a controller that now stays alive until the block ends. Inside the block, controller->_tier reads a field through a pointer, exactly as in C; that is how a block reaches the private fields of an object it holds in a local variable.

The opposite choice is also made on purpose. Work the dictionary loader puts on its own queue captures self strongly, and writes self-> explicitly, so the capture is visible on the page:

native/macos/src/KRRuntime.mm:296-303

  dispatch_async(_queue, ^{
    if (self->_stopped)
      return;
    NSString *home = self->_homeResolver();
    self->_mainExecutor(^{
      [self configureDefaultsInHome:home];
    });
  });

A one-shot block that keeps the loader alive until it has run is harmless: the cycle ends when the queue releases the block. A repeating timer is different, because the timer lives as long as the loader and would keep it alive forever, so its handler captures self weakly:

native/macos/src/KRRuntime.mm:331-338

  _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, _queue);
  __weak KRRuntime *weakSelf = self;
  dispatch_source_set_event_handler(_timer, ^{
    [weakSelf observe];
  });
  dispatch_source_set_timer(_timer, dispatch_time(DISPATCH_TIME_NOW, (int64_t)_interval), _interval,
                            _interval / 2);
  dispatch_resume(_timer);

[weakSelf observe] is a message to nil once the loader is gone, which does nothing, so no explicit check is needed.

Tip

Remember. A block captures values and keeps captured objects alive. Code that runs later captures self weakly and takes a strong copy when it starts.

Queues instead of threads

Goal: read dispatch_async and know which queue runs what.

The adapter never creates a thread. It uses Grand Central Dispatch (GCD), Apple’s library of work queues: dispatch_async(queue, block) puts a block on a queue and returns at once. The main queue runs its blocks on the main thread, where every input callback arrives, one after another, as JavaScript’s event loop runs callbacks (execution model). A serial queue runs its blocks one at a time, in order, on some thread from a shared pool, much as a Python ThreadPoolExecutor(max_workers=1) would. The process creates one serial queue for dictionary files, at low priority:

native/macos/src/main.mm:26-38

static KRRuntime *runtimeForPreferences(NSDictionary *preferences) {
  return [[KRRuntime alloc] initWithPreferences:preferences
      homeResolver:^NSString * {
        return accountHome();
      }
      workQueue:dispatch_queue_create("org.keyrill.vocabulary",
                                      dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL,
                                                                              QOS_CLASS_UTILITY, 0))
      mainExecutor:^(dispatch_block_t block) {
        dispatch_async(dispatch_get_main_queue(), block);
      }
      observationInterval:2 * NSEC_PER_SEC];
}

This is the “serialized acquisition queue” the header’s dictionary contract asks for (the C boundary): kr_vocabulary_observe runs only on this queue, and adoption only on the main thread. mainExecutor is the step back: “run this on the main queue”, as Python’s call_soon_threadsafe hands work from a worker thread to the event loop. Even that is injected: native/macos/tests/runtime_tests.mm passes an executor that queues blocks until the test drains them, which turns the interleaving of the two queues into a fixed schedule instead of a race.

Tip

Remember. Work moves between threads as blocks on queues. Input happens on the main queue, file reading on one serial queue.

Exceptions

Goal: know why an input method must catch exceptions that Cocoa programs usually don’t.

In Python and JavaScript, exceptions report ordinary failures. In Cocoa, exceptions signal programmer errors and are rarely caught; expected failures return nil, NO or an NSError object. An application, however, is foreign code that may raise anything from inside a protocol method, and an exception that escapes an input method’s callback can take the input method down. So the adapter is compiled with -fobjc-exceptions and wraps every call to the application:

native/macos/build.sh:31-33

  "$cxx" -std=c++20 -fobjc-arc -fobjc-exceptions -isysroot "$sdk" \
    -mmacosx-version-min=13.0 -g -Wall -Wextra -Wpedantic -Werror \
    -Wno-gnu-zero-variadic-macro-arguments -DKR_BUNDLE_IDENTIFIER="\"$bundle_id\"" \

@catch appears in clientAllowed: above. @finally runs however the block ends, by return or by exception, as finally does in Python and JavaScript; that is how the session makes sure its in-flight flag clears:

native/macos/src/KRSession.mm:221-226

  _busy = YES;
  @try {
    return [self runEvent:*input client:client generation:_generation];
  } @finally {
    _busy = NO;
  }

Whether the objects held by local variables are released when an exception passes through a function depends on a compiler setting, and the default differs between Objective-C and Objective-C++; the next chapter explains why that matters for this file.

Tip

Remember. Cocoa reserves exceptions for bugs, but an application’s bug must not crash the input method, so every call to the application is wrapped.

Selectors and target-action

Goal: read @selector and know what connects a menu item to a method.

A selector can be a value: @selector(name:) has the type SEL, like a method name stored in a string for Python’s getattr(obj, name). Menus in AppKit, the part of Cocoa for windows, menus and events, use selectors for target-action: a menu item stores a selector and, when chosen, sends that message to its target. The input menu’s “Correction in This App” items each name a one-line method:

native/macos/src/KRController.mm:540-543

- (void)useDefaultTier:(id)sender {
  (void)sender;
  [self overrideTier:nil];
}

The colon in useDefaultTier: is part of the name: an action method takes the sender as its one argument. Since dispatch is by name, nothing but the selector connects the menu item to the method, and a typo in @selector(...) compiles without a word under -Wall -Wextra; clang warns about a selector no visible class declares only with -Wundeclared-selector, which this build doesn’t enable.

Tip

Remember. A selector is a method name as a value, and only the name connects a menu item to its method.

Where the process starts

Goal: read main of a program that runs until the user logs out.

An input method is an ordinary application without a document window; Keyrill opens a window only for its settings, on request. main sets up AppKit, registers the controller class, creates an IMKServer and runs the run loop, the main thread’s event loop, forever:

native/macos/src/main.mm:100-128

int main() {
  @autoreleasepool {
    [NSApplication sharedApplication];
    // Registers the controller class before IMK resolves it by name from Info.plist
    (void)KeyrillAlphaController.class;
    __attribute__((objc_precise_lifetime)) KRApplicationDelegate *delegate =
        [KRApplicationDelegate new];
    NSApp.delegate = delegate;
    NSBundle *bundle = NSBundle.mainBundle;
    NSString *connection = [bundle objectForInfoDictionaryKey:@"InputMethodConnectionName"];
    if (!connection || ![bundle.bundleIdentifier isEqualToString:@KR_BUNDLE_IDENTIFIER])
      return 2;
    KRRuntime *runtime = runtimeForPreferences(
        [NSUserDefaults.standardUserDefaults persistentDomainForName:bundle.bundleIdentifier]);
    if (!runtime || ![KeyrillAlphaController setRuntime:runtime])
      return 2;
    KeyrillAlphaController.preferencesUpdater = ^BOOL(NSDictionary *changes) {
      return applyPreferences(changes);
    };
    [runtime start];
    // The server must outlive the run loop
    __attribute__((objc_precise_lifetime)) IMKServer *server =
        [[IMKServer alloc] initWithName:connection bundleIdentifier:bundle.bundleIdentifier];
    if (!server)
      return 2;
    [NSApp run];
  }
  return 0;
}

@autoreleasepool is a scope for objects whose release has been postponed, a leftover of manual reference counting that ARC still uses at the edges of Apple’s APIs. InputMethodKit finds the controller class by its name in Info.plist and then creates one IMKInputController per client input session; nothing in the program refers to the class directly, so main sends it the class message to make sure the runtime has registered it before InputMethodKit looks.

The two objc_precise_lifetime locals are the same device as in handleEvent:. NSApp doesn’t retain its delegate, and nothing else refers to the server, so each local is the only strong reference to its object; neither is read again, and without the attribute ARC could release both before [NSApp run], which returns only when the process ends.

Tip

Remember. main builds the server and enters the run loop for good. Objects only main holds are kept alive with objc_precise_lifetime.

Objective-C++

Objective-C++ is what clang compiles when a file ends in .mm: C++ and Objective-C in the same translation unit, the one source file plus every header it includes, which the compiler turns into one compiled object file. So a C++ class may hold an Objective-C object, an Objective-C method may take a C++ reference, and a block may capture a C++ value. Apple’s description of the mixture was in a guide that is no longer published; Wikipedia summarizes the rules, and clang’s ARC specification is the reference where memory is involved.

The previous chapter showed the Objective-C in the adapter. This one shows what C++ adds and, for each construct, why the adapter uses it. If you don’t know C++, read each section for the problem it solves; the C++ syntax is explained where it appears.

Which language is which

Goal: tell C, Objective-C and C++ apart in one file.

The build line from native/macos/build.sh names all three: clang++ -std=c++20 -fobjc-arc -fobjc-exceptions.

ConstructLanguageWhere
[client markedRange], @interface, @property, ^{ }, @tryObjective-CEvery adapter file
kr_event, kr_plan, NSRange, #include "keyrill.h"CThe ABI and Apple’s C types
namespace { }, constexpr, nullptr, static_cast, enum classC++Helpers and constants
struct CallbackScope with a destructorC++KRController.mm
- (uint32_t)apply:(const kr_plan &)plan ...Objective-C with a C++ referenceKRSession.mm
std::atomic<bool> _stopped; as an instance variableC++ inside Objective-CKRRuntime.mm
struct Choice { NSString *title; SEL action; ... }Objective-C inside C++KRController.mm
std::vector, std::copy, std::memcmp, std::string, std::arrayC++ standard librarymain.mm, KRKeys.mm, KRSession.mm, KRRuntime.mm

Tip

Remember. Brackets and @ are Objective-C; std::, namespace and & in a parameter are C++; the structs from the header are C.

C linkage

Goal: see why the header wraps its declarations in extern "C".

C++ allows two functions with the same name and different parameters, so it encodes the parameter types into each symbol name; this is the name mangling the C boundary chapter turned off on the Rust side. C doesn’t mangle, and Rust exports kr_commit under exactly that name. The adapter’s .mm files are C++, so when they include the header, every declaration in it must be marked as having C language linkage; otherwise the compiler asks the linker for a mangled name the Rust library never defined:

include/keyrill.h:54-62

#ifndef KEYRILL_H
#define KEYRILL_H

#include <stddef.h>
#include <stdint.h>

#ifdef __cplusplus
extern "C" {
#endif

__cplusplus is defined only when the compiler is compiling C++, so a C compiler sees plain declarations and a C++ compiler sees them inside extern "C" { ... }, closed near the end of the file just before the C++ static_assert block shown in the C boundary. The same header serves the C smoke test, which ./tools/verify compiles as C11, and the adapter, which compiles it as C++20. Exercise 7 removes the block and shows the linker’s complaint.

The adapter’s own functions don’t need this. KREventForKey is declared in KRKeys.h and defined in KRKeys.mm, and every file that calls it is C++, so its mangled name agrees on both sides:

native/macos/src/KRKeys.h:10-11

kr_event KREventForKey(unsigned short keyCode, NSEventModifierFlags flags, NSString *characters,
                       uint32_t mode);

Tip

Remember. C++ mangles names and C doesn’t. extern "C" makes C++ code look for the plain names that Rust exports.

Hidden helpers and compile-time constants

Goal: read an unnamed namespace and constexpr.

A helper used by one file only should be invisible to the linker, so that another file can’t call it or collide with its name; C++ calls that internal linkage. C gets it with static, and C++ adds the unnamed namespace, which hides everything inside it, types included. A Python module gets the same effect only by the convention of a leading underscore:

native/macos/src/KRSession.mm:6-24

namespace {

constexpr NSRange kCurrentSelection = {NSNotFound, 0};
// Keeps start + KR_TEXT_CAPACITY far from overflow without a check at every addition
constexpr NSUInteger kMaxStart = NSUIntegerMax - 4 * KR_TEXT_CAPACITY;
NSUInteger callbackDepth = 0;
bool callbackDepthSaturated = false;

bool hasMark(NSRange range) { return range.location != NSNotFound && range.length != 0; }

bool isWhitespace(unichar unit) {
  return unit == u' ' || unit == u'\t' || unit == u'\n' || unit == u'\r' || unit == 0x00A0;
}

NSString *string(const uint16_t *units, uint32_t length) {
  return [[NSString alloc] initWithCharacters:units length:length];
}

} // namespace

constexpr asks for a value computed at compile time, so kCurrentSelection, an NSRange (a plain C struct from Foundation), is built by the compiler. u' ' is a char16_t literal, one UTF-16 code unit, which compares directly with Foundation’s unichar. The last helper shows that a C++ function may contain Objective-C: it returns a new NSString, and ARC manages the result exactly as it would in a method.

The two counters in the namespace are process-wide state that the class methods +beginInputCallback and +endInputCallback update. Objective-C has no class variables, so file-level variables play that part, and the namespace keeps them out of reach of every other file.

Tip

Remember. An unnamed namespace hides a file’s helpers from every other file. constexpr values are computed by the compiler.

RAII across Objective-C exceptions

Goal: see why one small C++ struct is the main reason these files are Objective-C++.

RAII, “resource acquisition is initialization”, ties an action to the lifetime of a local object: its constructor does the action, its destructor undoes it, and the destructor runs on every way out of the scope, by return or by exception. Python’s with statement does the same job explicitly, and JavaScript code writes try/finally by hand. The controller uses RAII to count how deep the process is inside callbacks from the application:

native/macos/src/KRController.mm:15-24

namespace {

// Marks a host callback for the whole entry, including exception unwinding, so vocabulary
// adoption never runs inside one, even from a nested run loop serving another controller
struct CallbackScope {
  CallbackScope() { [KRSession beginInputCallback]; }
  ~CallbackScope() { [KRSession endInputCallback]; }
  CallbackScope(const CallbackScope &) = delete;
  CallbackScope &operator=(const CallbackScope &) = delete;
};

native/macos/src/KRController.mm:614-618

- (BOOL)handleEvent:(NSEvent *)event client:(id)sender {
  if (!NSThread.isMainThread || !_session)
    return NO;
  CallbackScope scope;
  __attribute__((objc_precise_lifetime)) KeyrillAlphaController *retained = self;

A C++ constructor and destructor send Objective-C messages, and the object lives inside an Objective-C method. The deleted copy constructor and copy assignment (= delete) make it impossible to duplicate a scope by accident, which would end the callback twice. handleEvent: has a dozen return statements; a matching endInputCallback call before each of them would be a dozen chances to forget one.

The comment’s phrase “including exception unwinding” is the reason this file is Objective-C++ and not Objective-C. In the 64-bit runtime, Objective-C exceptions are implemented on the same unwinding machinery as C++ exceptions, and Apple’s documentation states that C++ destructors and @finally blocks both run while an Objective-C exception unwinds (Exceptions in 64-Bit Executables). So an application’s exception that escapes handleEvent: still ends the callback scope. Plain Objective-C has @finally for that, but nothing that cleans up by itself.

The same holds for ARC. By default in Objective-C, ARC is not exception-safe: a strong local variable in a function that an exception passes through is never released. The ARC specification explains that Cocoa treats exceptions as fatal, so the cleanup code would cost size for nothing, and then adds: “In Objective-C++, -fobjc-arc-exceptions is enabled by default.” An input method that catches an application’s exceptions and keeps running is exactly the program that needs the cleanup, and the .mm extension gives it without a flag.

Tip

Remember. A C++ destructor runs even when an Objective-C exception passes through, and in Objective-C++ ARC releases objects on that path too.

C++ references in Objective-C methods

Goal: read const T & in a method signature.

A C++ reference is another name for an existing object; a const reference may be read and not written through, and unlike a pointer it can’t be null or be pointed somewhere else (references). Python and JavaScript pass every object this way already, so the novelty is only that C++ makes you ask for it. The plan is a 536-byte struct, and apply: takes it by const reference instead of copying it:

native/macos/src/KRSession.mm:445-447

- (uint32_t)apply:(const kr_plan &)plan
           client:(id<IMKTextInput>)client
       generation:(uint64_t)generation {

A function can also return a reference, which lets a helper choose which field of a C struct the caller assigns to:

native/macos/src/KRRuntime.mm:24-26

KRSourceStatus &source(KRRuntimeStatus &status, int index) {
  return index == kLearned ? status.learned : index ? status.russian : status.english;
}

native/macos/src/KRRuntime.mm:207-208

      source(_status, i) =
          _paths[i] == PathSetting::Unusable ? KRSourceStatusMissing : KRSourceStatusPending;

KRRuntimeStatus is a C struct declared in KRRuntime.h with three status fields. Without the reference, choosing a field by number would need a pointer, or a switch at every assignment.

Tip

Remember. A C++ reference is a name for an existing object that can’t be null. Objective-C++ methods may take and return them.

C++ objects inside Objective-C objects

Goal: see C++ fields in an Objective-C class, and why two of them are atomic.

An Objective-C class may have instance variables of C++ class type. The compiler generates hidden methods that run their constructors when the object is allocated and their destructors before its memory is freed, so a std::string field starts empty and is destroyed with its object, like a member of a C++ class. The dictionary loader’s fields show several kinds:

native/macos/src/KRRuntime.mm:107-130

@implementation KRRuntime {
  KRRuntimeStatus _status;
  uint32_t _enginePolicy;
  kr_vocabulary *_vocabulary;
  PathSetting _paths[2];
  std::string _explicitPaths[2];
  NSString *_Nullable (^_homeResolver)(void);
  dispatch_queue_t _queue;
  void (^_mainExecutor)(dispatch_block_t);
  uint64_t _interval;
  dispatch_source_t _timer;
  bool _configured[kSources];
  bool _learnedWordsEnabled;
  bool _started;
  __weak id<KRVocabularyAdopting> _target;
  // Written on main; read by observation rounds to keep retrying a refused adoption
  std::atomic<bool> _needsAdoption;
  std::atomic<bool> _stopped;
  NSDictionary<NSString *, NSNumber *> *_builtIn;
  // Work-queue confined once observation begins
  bool _observing;
  Sources _sources;
  bool _active[kSources];
}

Five kinds of member sit side by side: C structs and a C handle; an array of a C++ enum class (PathSetting, a scoped enumeration whose values must be written with their type’s name, declared in the file’s unnamed namespace); C++ library objects; blocks; and strong and weak pointers to objects. Under ARC even dispatch_queue_t is an object pointer, retained and released like any other.

The two std::atomic<bool> fields are the reason for C++ here. The loader is used from two queues: _stopped is written on the main thread and read in blocks on the dictionary queue, and an ordinary bool shared that way is a data race, undefined behavior in C++ as in Rust (the C boundary). Objective-C has no atomic type of its own; C11’s _Atomic would do in a .m file, and in a .mm file std::atomic is the idiom. The comment on _observing names the other discipline, confinement: that field is touched only on the work queue, so it needs no atomic.

A block that captures a C++ object copies it with the object’s copy constructor. That is how the loader hands its configured state to the work queue: by value, so the two queues share nothing that changes:

native/macos/src/KRRuntime.mm:318-328

// Hands the configured state to the work queue, then observes immediately and periodically
- (void)beginObserving {
  Sources sources = {{_status.english, _status.russian, _status.learned}, {}};
  std::array<bool, kSources> configured = {_configured[0], _configured[1], _configured[kLearned]};
  dispatch_async(_queue, ^{
    self->_observing = true;
    self->_sources = sources;
    for (int i = 0; i < kSources; ++i)
      self->_active[i] = configured[i];
    [self observe];
  });

The std::array is there for the capture: a block can’t capture a plain C array, but it can capture a C++ object that contains one.

Tip

Remember. C++ fields in an Objective-C object are constructed and destroyed with it. Share a flag between queues as std::atomic, or confine it to one queue.

Objective-C objects inside C++ objects

Goal: see ARC manage object pointers stored in a C++ struct.

The reverse also works. A C++ struct may hold pointers to Objective-C objects, and ARC retains and releases them as the struct is created, copied and destroyed. The input menu describes its items as a local table:

native/macos/src/KRController.mm:450-469

  struct Choice {
    NSString *title;
    SEL action;
    NSString *name;
  };
  const Choice items[] = {
      {[NSString stringWithFormat:@"Default (%@)", tierName(fallback)], @selector(useDefaultTier:),
       nil},
      {@"Direct Editing", @selector(useCompositionTier:), @"composition"},
      {@"Compatibility, Automatic and Manual", @selector(useAutomaticTier:), @"automatic"},
      {@"Compatibility, Manual Only", @selector(useManualTier:), @"manual"},
      {@"Off", @selector(useOffTier:), @"off"},
  };
  for (const Choice &choice : items) {
    NSMenuItem *item = [choices addItemWithTitle:choice.title
                                          action:choice.action
                                   keyEquivalent:@""];
    bool selected = choice.name ? [chosen isEqualToString:choice.name] : !chosen;
    item.state = selected ? NSControlStateValueOn : NSControlStateValueOff;
  }

A struct declared inside a function; an array initialized from a list in braces; and a range-based for, C++’s counterpart of Python’s for choice in items:, here by const reference. The first title is built when the code runs and has no other owner; the array holds it, strongly, until the function returns.

Tip

Remember. ARC manages object pointers inside C++ structs as it does anywhere else.

The standard library at the edges

Goal: read the places where C++’s standard library meets C and Objective-C.

A C function that fills a buffer the caller provides takes the buffer of a std::vector, C++’s growable array, directly. The home directory comes from the account database, with a buffer sized by sysconf:

native/macos/src/main.mm:13-24

// The account database, not $HOME, names the directory holding the default personal sources
static NSString *accountHome() {
  long size = sysconf(_SC_GETPW_R_SIZE_MAX);
  std::vector<char> buffer(size > 0 ? static_cast<size_t>(size) : 16384);
  passwd entry;
  passwd *result = nullptr;
  if (getpwuid_r(getuid(), &entry, buffer.data(), buffer.size(), &result) != 0 || !result ||
      !result->pw_dir)
    return nil;
  return [NSFileManager.defaultManager stringWithFileSystemRepresentation:result->pw_dir
                                                                   length:strlen(result->pw_dir)];
}

Note the two kinds of null side by side: nullptr for a C pointer, nil for an object. Both are zero; the spelling says which world the value belongs to. static_cast replaces the C cast where the conversion changes a value’s type in an ordinary way, so a reader searching for dangerous casts finds the one reinterpret_cast in the adapter, in KRRuntime.mm, which turns std::string bytes into the const uint8_t * the C ABI wants.

The key mapper is the plainest mixture in the adapter, and a good place to read Objective-C++ for the first time:

native/macos/src/KRKeys.mm:7-17

kr_event KREventForKey(unsigned short keyCode, NSEventModifierFlags flags, NSString *characters,
                       uint32_t mode) {
  kr_event event = {KR_FINISH_REQUEST, mode, KR_CTX_INELIGIBLE, 0, {}};
  NSEventModifierFlags modifiers =
      flags & (NSEventModifierFlagCommand | NSEventModifierFlagControl | NSEventModifierFlagOption |
               NSEventModifierFlagShift);
  constexpr NSEventModifierFlags chord = NSEventModifierFlagControl | NSEventModifierFlagOption;
  if (modifiers == chord && keyCode == kVK_ANSI_K) {
    event.role = KR_MANUAL;
    return event;
  }

native/macos/src/KRKeys.mm:32-47

  NSUInteger length = characters.length;
  if (length == 0 || length > KR_EVENT_CAPACITY)
    return event;
  uint16_t units[KR_EVENT_CAPACITY];
  [characters getCharacters:units range:NSMakeRange(0, length)];
  for (NSUInteger i = 0; i < length; ++i) {
    uint16_t unit = units[i];
    // Control characters (Return, Tab, Backspace with Shift) and AppKit function-key units
    if (unit < 0x20 || unit == 0x7F || (unit >= 0xF700 && unit <= 0xF8FF))
      return event;
  }
  event.role = KR_TEXT;
  event.len = static_cast<uint32_t>(length);
  std::copy(units, units + length, event.units);
  return event;
}

A C struct from the header, initialized from a list in braces in which {} zeroes the units; a constexpr mask; a message to an NSString; std::copy into the struct’s array. The first line is also the function’s policy: the event starts as KR_FINISH_REQUEST, so a key this function can’t classify ends the word and goes to the application, and every early return inherits that cautious answer. The length check comes before getCharacters:, which writes into a fixed array on the stack.

Tip

Remember. nullptr is a null C pointer and nil a null object. Start from the cautious answer and let every early return inherit it.

BOOL and bool

Goal: know why the code never compares with YES.

The adapter uses both, and whether they are the same type depends on the target. BOOL is Objective-C’s: a real bool on Apple silicon, but a signed char on Intel Macs, where any nonzero byte counts as true and comparing a BOOL with YES can fail. The code follows one rule: BOOL where an Objective-C API says BOOL, in method signatures and properties, and C++ bool in C++ helpers and local variables. It never compares with YES.

Tip

Remember. Use BOOL at Objective-C interfaces and bool inside C++, and test a BOOL for truth, not for equality with YES.

Reentrancy and tests

The previous chapters taught the languages. This one is about the hardest idea in the adapter, which no language feature solves: a call that waits for an answer and lets the world change underneath it. Then it follows one word through all the code shown so far, and ends with the two testing techniques that keep this design honest.

A call that runs your code

Goal: explain how a single-threaded program can be interrupted by itself.

A single-threaded program feels safe: nothing else runs while your function runs. In Keyrill’s adapter all input handling runs on the main thread, with only dictionary loading on a background queue, and that path is still not safe in this sense.

A message such as [client markedRange] is IPC to the application, and while the main thread waits for the answer, it may run a nested run loop: the event loop is entered again from inside the waiting call, and it delivers other events. A deactivation, a mode change or another key can arrive inside the call, and its callback runs on your thread, on your object, while your function is still waiting on the stack. This is reentrancy: your code entered again before its first run finished.

JavaScript and Python programmers know the shape from asynchronous code. Across an await, other callbacks run and may change any state you read before it; the difference here is that the call looks synchronous, so nothing in the code marks the place. No lock helps: a lock held by the outer call would block the inner call on the same thread forever. Rust’s borrow rules don’t help either, because the call to the application happens outside Rust altogether.

The session’s header documents the complete schedule for one correction, with the place of every check. Read it slowly; each line marked “recheck generation” guards one point where the application could have run the adapter’s code again:

native/macos/src/KRSession.h:48-75

/// Main thread only. A client call is synchronous IPC and can spin a nested run loop, so any of
/// them can reenter the controller with a deactivation, a mode change or another key. A
/// reentrant callback bumps the generation, resets Rust and drops local authority; the
/// interrupted operation sees the new generation at its next recheck and refuses before the
/// write or reports an unknown outcome after it, and never writes again. Automatic correction
/// of "ghbdtn" at Space, with the mark at [s, s+6) and the caret at s+6:
///
///   kr_plan_event          MARK, expected "ghbdtn", mark "привет " a proposal only
///   markedRange            == [s, s+6)                             recheck generation
///   selectedRange          == {s+6, 0}                             recheck generation
///   Secure Input           off
///   stringFromRange        == "ghbdtn", actual range == [s, s+6)   recheck generation
///   Secure Input           off
///   -- local authority dropped: from here the outcome is verified or unknown --
///   setMarkedText          "привет ", selection at its end         the plan's one write
///   markedRange            == [s, s+7)                             recheck generation
///   selectedRange          == {s+7, 0}                             recheck generation
///   Secure Input           off
///   stringFromRange        == "привет ", actual range == [s, s+7)  readback
///   kr_commit              APPLIED_VERIFIED: Rust advances, the new mark is owned
///
/// A failed check before the write acknowledges REFUSED_BEFORE_WRITE: nothing was written and
/// the key passes. A failed check after it acknowledges ATTEMPTED_UNKNOWN: correction stops,
/// and a key the write carried is consumed, never replayed. When that check failed on the
/// client's answer rather than on reentrancy, an exception or Secure Input, the session commits
/// the client's own exact readback of its marked range once, if both are still available, so
/// that the next key can't replace it; that is the one write allowed after an unknown outcome,
/// and it repairs nothing.

Tip

Remember. A call to the application can run your own callbacks before it returns. After such a call, everything you knew before it may be stale.

Generation and busy

Goal: read the two devices that detect a reentrant call.

The defense has two parts. The first is a counter, the generation. Every event that invalidates what the session knows adds one to _generation, drops the session’s authority over its text and resets the Rust engine:

native/macos/src/KRSession.mm:120-132

- (void)invalidate {
  if (!NSThread.isMainThread)
    return;
  ++_generation;
  _owner = nil;
  _text = nil;
  _ownerMode = 0;
  _contextLocation = NSNotFound;
  _automaticSwitchMode = 0;
  _finishVerified = NO;
  if (_engine)
    [self noteStatus:kr_reset(_engine)];
}

The operation in progress captured the generation when it started and carries it as an argument; after every call to the application it compares the two. A difference means some callback ran inside the call, and everything the operation knew before it is void. Front-end code uses the same pattern against stale network responses: number each request, and ignore a response whose number is no longer the latest.

native/macos/src/KRSession.mm:401-408

  NSRange expected = NSMakeRange(start, text.length);
  NSRange marked = [client markedRange];
  if (generation != _generation)
    return NO;
  if (!NSEqualRanges(marked, expected)) {
    _inputStatus = KRInputMarkMismatch;
    return NO;
  }

The order of the two tests matters. The generation comes first: after a reentrant callback, marked describes a document the session no longer has authority over, and comparing it with the expected range would answer a question that has expired.

The second part is a flag that lets the reentrant callback recognize itself. _busy is set while a plan is in flight, and a key that arrives while it is set came through a nested run loop:

native/macos/src/KRSession.mm:199-205

  // A key arriving while a plan is in flight came through a nested run loop inside a client
  // call. Invalidating here is what makes the outer operation's next recheck fail
  if (_busy) {
    _inputStatus = KRInputInterrupted;
    [self invalidate];
    return reserved;
  }

The nested call doesn’t try to finish the outer one’s work, or to do its own. It invalidates and returns, and the outer operation, when the call to the application returns to it, finds a new generation and stops. Work in flight is cancelled, never merged.

The _generation comparison is the same device as the slot generation in the dictionary handle. There it guards against another thread; here it guards against the same thread arriving a second time.

Tip

Remember. Capture the generation before a call, compare after it, and stop on any difference. A callback that finds _busy set invalidates and returns.

Two kinds of failure

Goal: tell “refused before the write” from “unknown after it”, and see where the code draws the line.

A failed check means different things before and after the write. Before it, nothing has happened to the document: the outcome is “refused before write”, the engine is told so, and the key goes to the application as if Keyrill weren’t there. After the write begins, the honest answer can only be “verified” or “unknown”. The application may have applied the text, part of it, or nothing, and a failed readback, reading the text back to compare it with what was written, doesn’t say which.

The adapter draws the line in the code by dropping its authority before the write, so that no path after it can reuse that authority:

native/macos/src/KRSession.mm:495-524

  // From here on the outcome is either verified or unknown; local authority is dropped first so
  // that no path can reuse it after the write
  _owner = nil;
  _text = nil;
  @try {
    if (plan.action == KR_MARK)
      [client setMarkedText:[[NSAttributedString alloc] initWithString:mark]
             selectionRange:NSMakeRange(plan.mark_len, 0)
           replacementRange:kCurrentSelection];
    else
      [client insertText:mark
          replacementRange:unchanged ? NSMakeRange(start, mark.length) : kCurrentSelection];
    if (generation != _generation)
      return KR_ATTEMPTED_UNKNOWN;

    if (plan.action == KR_MARK && mark.length) {
      if (![self verifyMark:mark
                         at:start
                      caret:start + plan.mark_len
                   readText:YES
                     client:client
                 generation:generation]) {
        _checkFailed = generation == _generation && _inputStatus != KRInputSecure;
        return KR_ATTEMPTED_UNKNOWN;
      }
      _owner = client;
      _start = start;
      _text = mark;
      return KR_APPLIED_VERIFIED;
    }

Authority comes back in exactly one place: after the readback matched, _owner, _start and _text are set to what was verified. Every other path out of this block leaves them nil. The method’s return value plays no part; setMarkedText: returns nothing, and if it returned YES, that would still be a claim by the application rather than evidence about the document. Only reading the document back is evidence.

Tip

Remember. Before the write, a failure is a refusal; after it, a failure is unknown. Only a readback that matches restores authority.

Plan, apply, acknowledge

Goal: read the adapter’s main loop for one key.

The core of the adapter’s loop is short enough to learn by heart. It runs once per key, twice when a finished word must be acknowledged before the same key starts the next one:

native/macos/src/KRSession.mm:257-288

    kr_plan plan;
    uint32_t status = kr_plan_event(_engine, &event, &plan);
    if (status != KR_OK) {
      _inputStatus = KRInputEngineUnavailable;
      [self invalidate];
      [self noteStatus:status];
      return NO;
    }

    uint32_t outcome = KR_APPLIED_VERIFIED;
    if (plan.action == KR_MARK || plan.action == KR_FINISH)
      outcome = [self apply:plan client:client generation:generation];
    else if (plan.action != KR_PASS && plan.action != KR_UNAVAILABLE)
      outcome = KR_REFUSED_BEFORE_WRITE;

    status = kr_commit(_engine, plan.plan_id, outcome);
    if (outcome == KR_ATTEMPTED_UNKNOWN) {
      // Only a check after the write that failed on the client's answer, with the generation
      // unchanged, earns the one readback commit; after reentrancy, a client exception or Secure
      // Input the client gets no further call
      BOOL commit = _checkFailed && generation == _generation;
      [self invalidate];
      _stopped = YES;
      ++_unknownOutcomes;
      _rearmable = _verifiedWrite && _unknownOutcomes < 2;
      [self noteStatus:status];
      if (commit)
        [self commitReadbackIn:client generation:_generation];
      // A write that carried this key may already be in the document: consume it, never replay
      // it. A FINISH that passes or replans carried only the previous mark, so the key passes.
      return plan.disposition == KR_KEY_CONSUMED;
    }

kr_plan plan; is a 536-byte struct on the stack, written by Rust; &plan passes its address, and apply: receives it by reference. An action the header doesn’t define is refused rather than guessed at. An unknown outcome stops correction: the session invalidates, marks itself stopped and doesn’t retry, because a retry would be a second write on top of an effect nobody can see. The one exception is spelled out in the comment and in the header above: if the readback failed on the application’s own answer, the session commits exactly what the application reports as its marked text, once, so that the next key the user types can’t replace it.

Tip

Remember. Plan, apply, acknowledge, once per plan: one plan per key, two when a finished word must be acknowledged first. An unknown outcome stops correction and is never retried.

One word, end to end

Goal: follow ghbdtn and Space through every layer.

Here are all the pieces in order, for ghbdtn and Space typed in TextEdit in English mode.

  1. Controller. -[KeyrillAlphaController handleEvent:client:] checks Secure Input, the runtime and the application’s tier, opens a CallbackScope, and builds a kr_event with KREventForKey.
  2. Session entry. -[KRSession handleEvent:client:] retains itself, checks _busy, sets it, and for a word not yet started asks the application what precedes the caret.
  3. ABI. kr_plan_event decodes the C struct into an Event inside with_engine, under catch_unwind.
  4. Decision. propose_using runs transition on the confirmed state; at Space, inference may convert the word. The proposed state waits in pending.
  5. Check and write. apply: verifies the mark, the caret and the text, comparing the generation after each call, drops authority, makes the one write and reads it back.
  6. Acknowledge. kr_commit reaches acknowledge, take() moves the proposal out, and the proposed state becomes the confirmed one.
KeyActionExpected in markWritten to markKey afterwards
gMARKemptygconsumed
h … nMARKg … ghbdtgh … ghbdtnconsumed
SpaceMARKghbdtnпривет consumed
next letterFINISH, then MARKпривет commits, then starts the new wordreplanned
Control-Option-Z before thatMARKпривет ghbdtn consumed

The word stays marked, underlined as text an input method is still composing, after Space, and that is the whole trick behind undo: as long as the text is a composition Keyrill owns, replacing it is an ordinary edit of its own mark. Keyrill never rewrites committed text on this path (ADR 005).

With layout switching on, the default, a converted word also makes the controller request the other input mode, Russian here. -[KeyrillAlphaController requestInputMode:client:] sends the request from a block queued with dispatch_async, after the key has returned to the application; the block holds the controller weakly, as in the Objective-C chapter, and gives up if the input-mode request generation (_selectionGeneration) changed in the meantime.

Tip

Remember. The word stays Keyrill’s own mark after Space, which is why undo is an ordinary edit and committed text is never touched.

Property tests in Rust

Goal: read a property test and know what makes it reproducible.

An example test checks the cases someone thought of. A property test states a law that must hold for every input and checks it against many generated inputs; when one fails, the tool shrinks it to a small failing input before reporting. Python has Hypothesis for this, JavaScript has fast-check, and Rust has proptest, all descended from Haskell’s QuickCheck. This test states that a plan id never comes back, whatever happens:

crates/keyrill-core/tests/contracts.rs:199-232

#![allow(unused)]
fn main() {
    // Ids grow strictly across resets and invalidation, so a late acknowledgement of an expired
    // plan can never match a later one; plans stay within one word and its Space. Codes divisible
    // by 3 reset before acknowledging, code 7 reports Unknown, and a failed proposal resets
    #[test]
    fn arbitrary_event_schedules_never_resurrect_a_reset_token(events in proptest::collection::vec(0u8..12, 0..=256)) {
        let mut session = Session::default();
        session.set_fixtures(true).unwrap();
        let mut previous = 0;
        for code in events {
            let event = match code {
                0 => Event::Manual, 1 => Event::Reverse, 2 => Event::Backspace,
                3 => Event::Escape, 4 => Event::Finish, 5 => Event::Text(vec![32]),
                6 => Event::Text(vec![0xd800]), 7 => Event::Text(vec![0x301]),
                _ => Event::Text(vec![97]),
            };
            if let Ok(plan) = session.propose(&event, Mode::En, Context::Boundary) {
                prop_assert!(plan.id > previous);
                prop_assert!(plan.text.len() <= MAX_WORD + 1);
                prop_assert!(plan.expected.len() <= MAX_WORD + 1);
                if plan.action == Action::Mark {
                    prop_assert!(plan.text.iter().all(|&u| mapping::is_letter(u) || u == 32 || b"[];',./`\\{}:\"<>~|".contains(&(u as u8))), "owned units remain in the defined map");
                }
                previous = plan.id;
                if code % 3 == 0 {
                    session.reset();
                    prop_assert!(session.acknowledge(plan.id, Outcome::Verified).is_err());
                } else {
                    session.acknowledge(plan.id, if code == 7 { Outcome::Unknown } else { Outcome::Verified }).unwrap();
                }
            } else {
                session.reset();
            }
        }
    }
}

The generator, vec(0u8..12, 0..=256), produces up to 256 codes; the match turns them into events, with letters weighted heavily, since four codes of twelve type a. The schedule mixes in the hostile cases on purpose: a lone surrogate (0xd800, half of a two-unit character with its other half missing), a combining accent (0x301), resets in the middle of a plan, unknown outcomes. The configuration a few lines above the test fixes the random seed, the starting value of the random generator, so every run tries the same 512 schedules and a failure reproduces on any machine.

Tip

Remember. A property test checks a law over generated inputs. A fixed seed makes it repeat exactly.

A hostile fake client

Goal: read a test that injects a fault at one exact step of a protocol.

The adapter is tested against FakeClient, a class in native/macos/tests/session_tests.mm that implements IMKTextInput over an NSMutableString and misbehaves on demand. It is a fake, a working stand-in written by hand, rather than a mock that only records calls, such as Python’s unittest.mock. Its documentation is the best description of what such a test can and can’t prove:

native/macos/tests/session_tests.mm:43-59

/// A scripted IMKTextInput client: one document string, a selection and a marked range, all in
/// UTF-16 units. setMarkedText ignores its replacement range and writes over the mark, or over
/// the selection when there is none, then places the caret by the mark-relative selection.
/// insertText writes to the same place for an NSNotFound range, or to exactly the explicit range
/// it is given, and puts the caret after the text.
/// stringFromRange clamps the range to the document and reports the clamped actual range.
///
/// A test plays the hostile host through `hook`, which runs at the entry of each call Keyrill
/// makes: it can move the caret, plant a foreign mark, switch Secure Input on, reenter the
/// session or throw, at exactly the call where a real host could. The flags below script what a
/// host does with a write. `calls` and `writes` let a test assert zero client contact or zero
/// writes after a refusal.
///
/// The client does nothing on its own: no focus, layout, undo, attributes or IMK reentrancy, and
/// it never moves the caret or commits the mark unless a test tells it to. That keeps every
/// schedule deterministic. A pass shows that the session refuses or verifies the scripted
/// schedule; it shows nothing about what a real application does.

The hook is a block property, called at the entry of every client method and once more after each write has taken effect:

native/macos/tests/session_tests.mm:138-157

- (void)setMarkedText:(id)string
       selectionRange:(NSRange)selectionRange
     replacementRange:(NSRange)r {
  (void)r;
  // A write counts as attempted from its entry, before any effect is visible
  ++_writes;
  ++_markWrites;
  NSString *text = [string isKindOfClass:NSAttributedString.class] ? [string string] : string;
  if (!text.length)
    ++_emptyMarks;
  [self enter:@"setMarkedText"];
  if (!_ignoreWrites) {
    NSRange target = [self target];
    [_document replaceCharactersInRange:target withString:text];
    _marked = text.length ? NSMakeRange(target.location, text.length) : NSMakeRange(NSNotFound, 0);
    _selection =
        NSMakeRange(_misplaceCaretOnMark ? 0 : target.location + selectionRange.location, 0);
  }
  [self enter:@"setMarkedText+after"];
}

This is fault injection at every step of a protocol: the hook is the injection point, and the test chooses the step and the fault. Here is a whole test that reenters the session from inside its own write:

native/macos/tests/session_tests.mm:1786-1810

// IMK asks for a commit from inside the first mark write, after its effect. The nested finish
// makes zero client calls and reports an interruption; the outer write is then unknown, its key
// stays consumed, and the session stops with the client's document as the write left it (S3, S4)
void testLifecycleInterruptionStatus() {
  currentTest = "lifecycle_interruption_status";
  KRSession *session = makeSession(true);
  FakeClient *client = fixtureClient();
  __block NSUInteger callsAtInterruption = 0;
  __weak FakeClient *weakClient = client;
  client.hook = ^(NSString *call) {
    if ([call isEqualToString:@"setMarkedText+after"]) {
      FakeClient *strong = weakClient;
      callsAtInterruption = strong.calls;
      [session finishInClient:strong];
    }
  };
  kr_event input = textEvent(@"g", KR_EN);
  CHECK([session handleEvent:&input client:client]);
  CHECK(callsAtInterruption > 0 && client.calls == callsAtInterruption);
  CHECK(client.writes == 1 && session.stopped && !session.owned);
  CHECK(session.inputStatus == KRInputInterrupted);
  NSString *expected = [kPrefix stringByAppendingFormat:@"g%@", kSuffix];
  CHECK([client.document isEqualToString:expected]);
  client.hook = nil;
}

Two details from the Objective-C chapter appear here in their natural place. __block lets the block assign to a local variable of the enclosing function; without it, a captured local is a read-only copy. __weak breaks a cycle: the client stores the hook, and a hook that captured the client strongly would keep both alive forever.

The checks then state the whole contract of the schedule. After the interruption the session made no further client call (client.calls == callsAtInterruption), made one write and no second, stopped, holds no authority, says why, and the document is exactly what the one write produced. S3, S4 refer to the safety invariants in ARCHITECTURE.md.

Know the limit of this evidence. The fake proves the adapter’s logic, not the behavior of real applications: TextEdit, Safari and Firefox each answer these calls in their own way, and some answers are wrong. The project treats controlled tests and physical application tests as different evidence and never substitutes one for the other; Testing describes both.

Tip

Remember. A fake with a hook can put a fault at any single step. Its pass says nothing about real applications.

Exercises

Goal: break each guarantee from the earlier chapters on purpose, and predict how it fails.

Each exercise is one small change that breaks a guarantee the earlier chapters described. Write down your prediction first: which tool complains, with which error, and why. Then run the command and compare. Predicting an error teaches more than reading about one, and a wrong prediction is the most useful result you can get, because it shows exactly which idea to reread. Every answer below was reproduced on this code, and the error texts are quoted from the compiler or the test runner.

A worktree is a second checkout of the same Git repository in another directory. Work in one, so that nothing touches your own checkout. Only exercises 7 and 9 need macOS, and they use the fake client; none of the exercises installs or selects the input method.

git worktree add --detach ../keyrill-lesson HEAD
cd ../keyrill-lesson
git checkout .                     # after each exercise
cd - && git worktree remove ../keyrill-lesson   # when finished

Each exercise starts from a clean checkout. Run git checkout . after each one and confirm that git status --short prints nothing before you start the next; the one exception is exercise 4, which keeps the change from exercise 3. When you are done, remove the worktree with the last line above.

#ChangeRunQuestion
1Add self.serial += 1; as the first line of transition in crates/keyrill-core/src/session.rscargo check -p keyrill-coreCan a method that takes &self be made to write?
2Add a variant Teleport to enum Action in session.rscargo check -p keyrill-ffiWhich crate complains, and where?
3Append fn sneak() { unsafe {} } to crates/keyrill-core/src/mapping.rscargo check -p keyrill-coreDoes an empty unsafe block count?
4Put #[allow(unsafe_code)] on the line above sneakcargo check -p keyrill-coreCan one function opt out of forbid?
5In NativeEvent in crates/keyrill-ffi/src/lib.rs, change units: [u16; 8] to [u16; 9]cargo check -p keyrill-ffiWho notices the ABI change?
6Delete #[repr(C)] above NativePlancargo check -p keyrill-ffiDoes anything notice, given that the size may stay the same?
7In include/keyrill.h, delete the three lines that open extern "C" { and the } that closes itnative/macos/build.sh checkThe header still compiles as C; what does the adapter see?
8In acknowledge, change outcome == Outcome::Verified to outcome != Outcome::Unknowncargo test -p keyrill-coreWhat goes wrong if a refusal advances the state?
9In apply: in native/macos/src/KRSession.mm, delete the generation check right after the write (lines 507 and 508)native/macos/build.sh checkIs one missing recheck observable?

Answers

Read these only after you have written down a prediction for every exercise.

  1. error[E0594]: cannot assign to `self.serial`, which is behind a `&` reference. It can’t, without changing the signature to &mut self, and then every caller that relies on the transition being pure would have to change too. See ownership and borrowing.
  2. error[E0004]: non-exhaustive patterns: `keyrill_core::session::Action::Teleport` not covered, in keyrill-ffi, at the match that turns an action into its C number; the core itself still compiles. The new case can’t cross the ABI silently. See match keeps count.
  3. error: usage of an `unsafe` block. The lint looks at the block, not at what is inside it, and the compiler also warns that the block is unnecessary.
  4. error[E0453]: allow(unsafe_code) incompatible with previous forbid, followed by the same error as in exercise 3. That is the difference between forbid and deny: a deny could be relaxed for one item, a forbid can’t.
  5. error[E0080], with assertion failed: size_of::<NativeEvent>() == 32. The check runs inside the compiler, before anything links. See Step 1.
  6. error[E0080], with assertion failed: std::mem::offset_of!(NativePlan, expected) == 24. Without repr(C) the compiler reorders the fields; the size assertion alone would not catch it, which is why the offset is pinned as well.
  7. The adapter compiles, then fails to link: Undefined symbols for architecture arm64: followed by names such as "kr_engine_new(unsigned int, kr_engine**)". Those are C++ signatures, demangled by the linker; the Rust library exports _kr_engine_new, without parameter types. See C linkage.
  8. Two tests fail: unknown_refused_and_reset_expire_pending_and_receipt and history_is_acknowledged_bounded_and_expires_with_authority. A refused plan then installs its proposed state although nothing was written, and Rust believes in a mark the document doesn’t have.
  9. session_tests: 1 failure(s), in the case lifecycle_interruption_status, the test shown in Reentrancy and tests. It reenters from inside the write and then requires that the adapter make no further client call. Without the check the adapter goes on to read the mark back from a client it no longer has authority over.

Reading order for the source

ReadFor
crates/keyrill-core/src/mapping.rs125 lines of idiomatic Rust with tests. Start here.
crates/keyrill-core/src/lib.rsA complete word in one doc example, which cargo test --doc runs.
crates/keyrill-core/src/session.rsThe state machine, with its diagrams in the module header.
include/keyrill.hThe contract as C sees it. The opening comment is the best summary in the repository.
crates/keyrill-ffi/src/lib.rswith_engine, then kr_plan_event and kr_commit.
native/macos/src/KRKeys.mm47 lines of Objective-C++ in its gentlest form.
native/macos/src/KRSession.h, KRSession.mmThe header’s schedule first, then runEvent: and apply:.
native/macos/tests/session_tests.mmFakeClient, then one reentrancy test.

Decisions

Each record is one decision that shapes Keyrill and its status. Most are a few paragraphs long.

ADR 001: Rust core, native adapters

Tip

Status: accepted.

Conversion, segmentation, vocabulary, scoring, policy and the word/reversal state live in one Rust 2024 crate that forbids unsafe and has no OS dependency. Each platform gets its own native adapter: Objective-C++ with ARC for macOS InputMethodKit, and whatever the platform’s input framework needs on Windows and Linux. They meet at a narrow, versioned C ABI with opaque handles, fixed-width tags, explicit lengths and copied buffers; raw pointers and panic containment stay in keyrill-ffi.

The alternatives were a C++ core, logic duplicated per platform, and a pure-Rust IMK adapter through objc2, which adds interop and lifetime work without a benefit over native Objective-C++.

No document-editing abstraction is shared across platforms. IMK, TSF and Linux frameworks differ in locks, callbacks, focus, source selection and composition identity, and a common facade would hide those differences instead of proving each one. Native code is still unsafe in the broader sense even though the core is not.

Revisit the boundary only with concrete evidence it doesn’t hold up, and a shared editing abstraction only after two working adapters expose the same contract.

ADR 002: a selected input method that owns its composition

Tip

Status: accepted. The default build admits composition only in TextEdit, Safari and Firefox, the clients whose composition behavior has been tested.

The user selects Keyrill’s EN or RU mode instead of the stock layouts. Keyrill composes the current word as marked text it owns and changes only that mark, after checking client, generation, exact UTF-16 text, range and caret. After Space the word and Space stay marked until the next input, so reversal can update the same mark.

The alternatives were a transparent global observer, post-Space editing through Accessibility, synthetic deletion and retyping, and absolute IMK ranges over committed text. An observer still needs a safe way to rewrite committed text, and none of the others supplied one (ADR 005).

The costs are visible: installing and selecting an input method, explaining source switching, and a marked word that changes underline and Undo behavior per host. Ownership checks are mandatory; a mark is not a document lock, and a client that ignores or rewrites a marked update can’t be admitted. On this path, committed-text and selection conversion are not supported; ADR 006 adds a separate backend that rewrites the tracked word.

Revisit if ordinary bilingual typing, completion or Undo proves unacceptable in applications that matter, or if a platform offers a stronger editing transaction with adversarial evidence.

ADR 003: precision before recall

Important

Status: accepted principle; scoring parameters are provisional.

Mapping is deterministic; the decision to change a word automatically is probabilistic and must be conservative. The engine protects general and personal vocabulary and abstains on technical, mixed-case, mixed-script, unknown and weakly supported tokens. Manual conversion is always available. Dictionary membership alone never justifies a change. The one place frequencies are compared across languages is the known-word gate: a typed string that is a rare word in its own layout (below Zipf 3) yields only to a reading at least 2.5 Zipf more frequent, and a 2-letter word needs 3.5 without context. That opens junk entries such as yf for на while leaving alone every word in the pinned negative set.

Replaying the pinned test split typed in the wrong layout, the model fixes 46.1% of Russian and 60.5% of English tokens, with no false corrections among 33,899 tokens typed correctly. That doesn’t measure precision on real typing: errors are synthetic, typos and transliterations are generated, tokens are correlated, and correctly typed corpus words never reach the scoring step, so only the typo and transliteration strata bound the thresholds. No cloud or LLM dependency is justified.

Change scoring only with versioned calibration data, held-out real and technical text, measured false-change cost and length, direction and context strata. Don’t trade protection for recall because an aggregate synthetic metric improved.

ADR 004: read existing Vim spelling files

Tip

Status: accepted.

Personal vocabulary comes from the user’s existing UTF-8 Vim .add files, read in place, read-only, with last-good snapshots on reload. They are parsed the way Vim reads them: a line whose first byte is # is a comment (Vim’s zw, zug and zuw overwrite that byte, which can leave invalid UTF-8 after it), and a line Keyrill can’t use is skipped and counted rather than rejecting the file. The alternatives were an app-specific dictionary, syncing from a remote repository, parsing binary .spl files and running Vim per correction; each adds ownership, licensing, privacy or maintenance cost with no demonstrated need.

Recognized, rare, forbidden and case distinctions are preserved. Personal membership protects a word but doesn’t give a candidate a frequency. A missing file never blocks typing or manual conversion. Automatic correction needs a source for both languages; an empty file is a valid source, and so is a missing file at the default path, since Vim creates it only on the first zg. The default path is where zg creates it while 'spellfile' is empty: ~/.vim/spell/{en,ru}.utf-8.add, or ~/vimfiles/spell on Windows. A missing file at a path the user chose keeps that language missing. Keyrill never modifies the files.

The OS spell checker’s learned lists are read the same way, read-only and in place, so a word taught with Learn Spelling on macOS or Add to dictionary on Windows is protected without a second list. They are plain word lists, not Vim syntax, and never required: correction waits only for the two Vim sources. Excluded words on Windows are forbidden, as with Vim’s zw.

Revisit if the user’s vocabulary workflow changes or a required semantic can’t be expressed in this format.

ADR 005: no committed-text rewrite on the composition path

Tip

Status: accepted. ADR 006 makes one explicit, separate exception.

The composition path never falls back to a temporary Accessibility selection, a whole-value write from a snapshot, counted Backspaces and retyping, clipboard paste, or a remembered absolute range. Controlled schedules show each of these overwriting an exposed selection, losing concurrent input or applying a stale range; verification can detect some of that damage but can’t undo it. Event tags, worker queues, focus rechecks and pacing don’t make a host atomic, and read access through UI Automation or Accessibility is not write authority.

So on the composition path converting committed words and selections remains unsupported. A failed or unknown composition write stops correction; it never triggers another transport.

Revisit only for a specific control and native API with a serialized or conditional editing contract and adversarial whole-document evidence, not because ordinary positive tests pass.

ADR 006: compatibility backend on macOS

Important

Status: accepted for the alpha.

Owned composition only works where the client reflects and reads back marked text, which leaves most applications without correction. Every identified application outside the composition list gets a tier instead. Manual only covers the built-in terminals, editors with completion and Microsoft Office, and every unlisted application by default: Keyrill tracks the input it passes through and rewrites a word by posting Backspace and Unicode key events, but only on the manual conversion and reversal shortcuts. Automatic adds correction at Space, for unlisted applications when the user turns it on. Off passes everything through: password managers, remote desktops, virtual machines and Keyrill itself. The built-in lists ship in the bundle, and the user can override any application’s tier. A user who enables this backend accepts that it can corrupt text; keeping automatic rewrites opt-in limits that to moments the user chose.

The backend is chosen at activation, before any edit, and is never used to repair a failed composition write. Automatic correction needs a Space observed since reset before the word, so focus or a click is not treated as a word boundary. Mouse, navigation, shortcuts and source changes expire tracking; a non-space separator blocks acquiring the identifier after it. Secure Input, foreground identity and generations are rechecked before each post, but a synchronous loop can’t see a focus change queued ahead of its events. Synthetic events are tagged, an expected-key sequence catches stripped tags, and an automatic rewrite needs real keys to have advanced since the last one. None of this is hardware provenance.

The ABI keeps this separate from composition. KR_COMPAT_OBSERVED and KR_COMPAT_DISPATCHED mean submission, never KR_APPLIED_VERIFIED; a handle can’t mix the two families; a proposal is a bounded batch rather than one write; and a dispatch that posted anything without completing, or that the engine refused to acknowledge, stops correction until the next activation, with no replay. A rewrite refused before its first post changed nothing, so it only drops the tracked word. Reversal is a best-effort rewrite to a predicted original, not a receipt.

What it gives up: counted deletion is unverifiable, so typing during a rewrite, application edits and focus changes can delete the wrong characters (the controlled test compatibility_known_interleaving_hazard keeps such a case). Terminals, TUIs and remote sessions may treat Backspace or keycodes as commands, and raw-key terminals also see the command chords. Hidden prompts without Secure Input are tracked in memory. It needs Accessibility and Input Monitoring permissions. For this backend only, this decision overrides S1, S4 and S6 in architecture and ADR 005. Don’t describe it as safe, transactional or supported, and don’t carry it to another platform without a separate decision.

ADR 007: Windows Text Services Framework

Status is accepted for the bounded native editor and Notepad proof. Completion-candidate application qualification remains pending.

A native TSF text service owns Windows editing authority. Granted edit sessions, explicit contexts, and owned compositions implement the architecture. The adapter, registrar, settings, installer, and proof tools use Rust with windows-rs. The shared core and C ABI retain their portable behavior. UI Automation supplies independent test and diagnostic observations.

Microsoft documents separate request and session outcomes for edit sessions, and composition creation that an owner can reject while still returning success with a null composition. The reference sample doesn’t handle either correctly. Locks are not rollback or a focus guarantee, and an in-process DLL failure can take down the host editor.

The recorded Windows proof includes native editor and Notepad document/caret observations, controlled denied sessions, and separate physical keyboard results. Those results support the bounded TSF choice. The completion plan requires renewed application, physical, and installation validation against one final candidate.

Broader admission requires the native control contract. Unsupported controls pass input through. Terminal functional acceptance remains open until ordinary input can be distinguished from secret input and owned readback and child-byte order are observed. A hook-and-SendInput backend requires a separate architectural decision.

Glossary

The documentation uses abbreviations, language terms and a set of terms with exact meanings in this project. An abbreviation links to the reference that defines it, and a language term to the section of the walkthrough that introduces it. A project term has no outside reference, so it is defined here, with a pointer to the page that treats it in full.

Abbreviations

AbbreviationMeaning
ABIApplication binary interface: names, calling convention and struct layouts at the machine level; Keyrill’s is include/keyrill.h
ADRArchitecture decision record; Keyrill’s are in docs/adr
APIApplication programming interface
ARCAutomatic Reference Counting: retain and release inserted by the Objective-C compiler
ASanAddressSanitizer, clang’s memory-error detector
BOMByte order mark, U+FEFF at the start of a text file
CC BY-SACreative Commons Attribution-ShareAlike 4.0, the license of the model’s word data
CIContinuous integration; here, the GitHub Actions workflows in .github/workflows
COMComponent Object Model, the Windows object system TSF is built on
DLLDynamic-link library, a Windows shared library
EWTEnglish Web Treebank, one of the evaluation corpora
FFIForeign function interface: calling between Rust and another language; here, the crate keyrill-ffi
GCDGrand Central Dispatch, Apple’s queue library
GTKGTK, a toolkit for Linux desktop applications
HRESULTA Windows status code returned by COM methods
IMKInputMethodKit, the macOS framework for input methods
IPCInter-process communication; every IMK client call is one
MSVCMicrosoft’s C and C++ toolchain, and the Rust Windows target that uses it
RAIIResource acquisition is initialization: a C++ object whose destructor undoes what its constructor did
SHA-256A cryptographic hash; used to pin the model source and the corpora, for consistency rather than authenticity
TISText Input Sources, the Carbon API that lists and selects keyboard layouts and input methods; see Terms
TSFText Services Framework, the Windows counterpart of IMK
TUIText-based user interface, such as a program running in a terminal
UBSanUndefinedBehaviorSanitizer, clang’s undefined-behavior detector
UDUniversal Dependencies, the treebank project the evaluation corpora come from
UTF-8, UTF-16UTF-8 and UTF-16, Unicode encodings; every length in the ABI counts UTF-16 code units
X11The X Window System, the older Linux display protocol

Language terms

The terms the walkthrough sets in bold, with the section that introduces each.

TermMeaning
AccessorA getter or setter method; an Objective-C property declares a pair
AppKitThe part of Cocoa for windows, menus and events
ARCAutomatic Reference Counting: the Objective-C compiler inserts the retain and release calls
AtomicA variable whose reads and writes are indivisible even across threads
AttributeAn annotation for the Rust compiler, written #[...], or #![...] for a whole crate
BlockObjective-C’s closure, written ^{ ... }
Borrow checkerThe part of the Rust compiler that enforces the rules for references
CallbackA function handed to other code for it to call later
Calling conventionWhich registers and stack slots carry a function’s arguments and result
CaptureA closure or block keeping a variable from the code around it
Class methodAn Objective-C method called on the class itself, declared with +
ClosureAn anonymous function that can use variables from where it was written
CocoaApple’s Objective-C frameworks for macOS applications
Compile time, run timeWhile the compiler translates the program, and while the program runs
Constructor, destructorThe C++ functions that run when an object is created and when it is destroyed
CrateRust’s unit of compilation: one library or one program, compiled as a whole
Data raceTwo threads touching the same memory, at least one writing, without coordination; undefined behavior
Debug build, release buildThe unoptimized build for development, and the optimized one that ships
Dependency injectionHanding a function its collaborators instead of letting it reach for them
DropDestroying a Rust value when its owner goes out of scope
EditionA per-crate dialect of Rust: 2015, 2018, 2021 or 2024
Enum, variantA Rust type that is one of several variants, each with its own fields
FakeA working stand-in for a real dependency, written by hand for tests
FuzzerA tool that feeds a program generated and damaged inputs
Garbage collectorThe part of Python’s or JavaScript’s runtime that frees objects nobody refers to
GenericCode written once for many types; the Rust compiler makes a copy per type
GuardIn a match, a condition after if; for a mutex, the value that holds the lock and releases it when dropped
HandleA value that identifies an object to code that can’t see inside it
HeaderA C file of declarations that other files include
Heap, stackMemory for data of unknown size or lifetime, and memory for a function’s local variables
InitializerAn Objective-C method that sets up a new object, the counterpart of a constructor
Input methodA program between the keyboard and applications that decides what text a key produces
Input sourceThe macOS name for a keyboard layout or input method chosen from the menu bar
Instance variableA private field of an Objective-C object, declared in @implementation
Internal linkageA name visible only inside its own source file
IteratorA source of values produced one at a time, on demand
LifetimeThe name, written 'a, for how long a borrowed reference stays valid
LinkerThe tool that joins compiled files into one program by matching symbols
LintA check for a suspicious pattern, at level allow, warn, deny or forbid
Lock, mutexLets one thread at a time into the code or data it protects; a Rust Mutex contains its data
MacroCode the compiler expands into more code; in Rust its name ends in !
Main thread, main queueThe thread on which macOS delivers every input event, and the queue that runs blocks on it
ManglingEncoding a function’s context or parameter types into its symbol name
Message, selectorA method call looked up by name at run time, and that name, such as handleEvent:client:
ModuleA Rust namespace, usually one file
MoveHanding a Rust value to a new owner; the old variable can’t be used afterwards
Nested run loopThe event loop entered again from inside a call that is waiting
Opaque typeA struct with a name and no definition, which code can point to but not look inside
OwnerThe variable or field that a Rust value belongs to
PanicRust stopping on a bug; it unwinds the stack unless the build aborts instead
Pattern, armA shape a value is compared against, and one branch of a match
ProcessA running program
PropertyAn Objective-C declaration of a getter and setter, written by the compiler
Property testA test that checks a law over many generated inputs
ProtocolA named list of methods any Objective-C class may adopt
Queue, serial queueA GCD list of blocks to run; a serial queue runs them one at a time, in order
RAIITying an action to a C++ object’s lifetime, so its destructor undoes it on every exit
Raw pointerA plain memory address with no lifetime and no guarantee it is valid
ReentrancyCode entered again before its first run has finished
ReferenceAccess to a value without owning it: &T shared, &mut T exclusive; in C++, another name for an object
Retain count, retain cycleThe number of owners of an Objective-C object, and two objects that own each other and so are never freed
Run loopThe main thread’s event loop in a macOS program
SeedThe starting value of a random generator; fixing it makes a test repeat exactly
ShrinkingA property-test tool reducing a failing input to a small one
SliceA view of part of an array: a pointer and a length
Standard libraryThe library every Rust program gets with the compiler
Static libraryA file of compiled code the linker copies into a program
Struct, fieldA record of named fields
SymbolThe name a function or variable has in compiled code
Tagged unionA value that is one of several variants and records which
ThreadAn independent sequence of execution inside one process
TraitA named set of methods a Rust type can provide
Translation unitOne source file with every header it includes, compiled as one unit
Undefined behaviorAn operation the language gives no meaning to; the program may crash, corrupt memory or seem to work
UnsafeRust code in which a person vouches for what the compiler can’t prove
UnwindingLeaving each function in turn and cleaning up, as an exception or panic propagates
UTF-16 code unitOne 16-bit value of UTF-16 text; most characters take one, some take two
WorkspaceThe set of Rust crates built together from one root Cargo.toml
WorktreeA second checkout of the same Git repository in another directory

Terms

Acknowledgement. The adapter’s report of what happened to a plan, through kr_commit: verified, refused before the write, or unknown. Only a verified acknowledgement advances the Rust session. See Rust in the core.

Adapter. The platform code that owns the native objects and the editing: on macOS, the Objective-C++ under native/macos. It calls the engine through the C ABI and never the other way round. See macOS adapter.

Boundary. The context in which a letter may start a word: the caret at the start of the document or after whitespace, read back from the client. Anything else, including a prefix that couldn’t be read, is ineligible, and the letter goes to the application untouched.

Boundary mark. A word and its Space, still marked after Space so that a correction can be undone by replacing Keyrill’s own mark. It ends with the next key. ARCHITECTURE.md calls the state BoundaryRetained.

Compatibility backend. The macOS backend for applications that can’t hold an owned composition, such as terminals: it posts synthetic key events and treats them as dispatched, never as verified edits. It is the one exception to owned-composition-only editing; see ADR 006.

Controlled-native evidence. A result from the native tests, which run the real adapter and the real Rust engine against a scripted fake client. It shows what the adapter does on a schedule; it shows nothing about a real application, which only a physical test can. See Testing.

Explicit intent. A manual conversion or a reversal by the user. It stops automatic inference for the rest of that word, so inference never undoes a choice the user made.

Fixture policy. A test policy that converts exactly ghbdtn and руддщ and nothing else, so that session tests don’t depend on the model.

Generation. A counter that grows on every event invalidating what the adapter knows. An operation remembers the generation it started under and compares after each native call; a difference means a callback ran in between, and the operation stops. See Reentrancy and tests.

Guard. The compatibility backend’s listen-only event tap. It observes mouse, navigation, shortcut and source changes without reading characters; each one ends tracking and advances the process-wide guard generation, which every rewrite rechecks before it posts. See macOS.

Inference. The engine’s decision, at a word boundary, whether a finished word was typed in the wrong layout. It uses the frozen model, the user’s dictionaries and recent context, and leaves the word alone whenever it is unsure. See Engine.

Input mode. Keyrill EN or Keyrill RU, the two input sources Keyrill installs; the mode decides which layout the keys type in.

Learned words. Words the user taught the OS spell checker. They protect and forbid words like the Vim dictionaries, but automatic correction never waits for them.

Local authority. The adapter’s record of the mark it verified last: the client, the start offset and the exact text. A write needs it, and the adapter drops it before every write and regains it only when the write’s checks pass, which for a mark update means a matching readback.

Mark, owned composition. Marked text, the underlined composition of an input method, that Keyrill itself placed with setMarkedText and still owns. It is the only text the composition path may change; the compatibility backend is the one exception. See How Keyrill works.

Plan. Rust’s answer to one key: an id, one permitted action (pass, mark, finish or unavailable), the text the mark must hold before the write, the text to write, and what to do with the key afterwards. A plan is a proposal, never editing authority.

Poisoned handle. An engine or vocabulary handle in which a Rust panic was caught. Every later call on it returns KR_POISONED; only freeing it remains. See The C boundary.

Provisional key. A key such as [ or ; that types punctuation in English but a Russian letter in Russian. In English mode it may start or continue a word, because the word may turn out to be Russian typed in the wrong layout.

Readback. Reading the composition back from the client after a write, over exactly the range written. It is the only evidence of a write’s effect that the adapter accepts; an API’s success return is not. The one write verified without it is an unchanged commit that IMK or the controller requests, which writes back the text last verified in the mark; see the edit contract.

Receipt. The text a word had before Keyrill first converted it, kept while the same word is owned so that Control-Option-Z or Escape can restore it. An edit or finishing the word expires it.

Secure Input. The macOS mode in which keyboard input goes only to the focused application, used for password fields (TN2150). While it is on, Keyrill passes every key and inspects nothing.

Snapshot. An immutable, fully parsed copy of a dictionary, published whole as an Arc and never edited in place. A failed parse leaves the last good snapshot in force.

Tier. How Keyrill handles one application, chosen by its bundle identifier: composition, compatibility (automatic and manual, or manual only) or off. See macOS adapter.

TIS. Text Input Sources, the Carbon interface in HIToolbox/TextInputSources.h (functions named TIS...) that lists, enables and selects input sources. Apple documents it only in that header. Keyrill uses it to list input sources and read their properties and to observe source changes, and avoids it where its answers are unreliable inside the input method’s own process (Input-source switching).

Unknown outcome. The acknowledgement for a write that was attempted but whose effect couldn’t be verified. It invalidates the session and stops correction; nothing is repaired or replayed. The edit contract lists the one write still allowed afterwards and when correction resumes.

Rust API

The rustdoc of the two library crates, built from the same commit as this site.

  • keyrill_core: the portable engine, with no unsafe code
  • keyrill_ffi: the versioned C ABI that native adapters call