1use super::{
2 BOUNDS, DICTIONARY_DATA, Engine, MODEL_ASSET, NULL, OK, POISONED, STATE, VERSION,
3 compatible_abi, embedded_model, with_engine,
4};
5use keyrill_core::model::{Model, ModelError};
6use keyrill_core::vocabulary::{MAX_SOURCE_BYTES, ParseError, Snapshot, Vocabulary};
7use std::panic::{AssertUnwindSafe, catch_unwind};
8use std::sync::Arc;
9
10pub struct Dictionary {
12 vocabulary: Arc<Vocabulary>,
13}
14
15unsafe fn parse_with(
16 abi: u32,
17 bytes: *const u8,
18 len: u32,
19 out: *mut *mut Dictionary,
20 parse: impl FnOnce(&[u8]) -> Result<Vocabulary, ParseError>,
21) -> u32 {
22 if out.is_null() {
23 return NULL;
24 }
25 unsafe { out.write(std::ptr::null_mut()) };
27 if !compatible_abi(abi) {
28 return VERSION;
29 }
30 if len as usize > MAX_SOURCE_BYTES {
31 return BOUNDS;
32 }
33 if len != 0 && bytes.is_null() {
34 return NULL;
35 }
36 match catch_unwind(AssertUnwindSafe(|| {
37 let source = if len == 0 {
38 &[]
39 } else {
40 unsafe { std::slice::from_raw_parts(bytes, len as usize) }
42 };
43 parse(source).map(|vocabulary| {
44 Box::new(Dictionary {
45 vocabulary: Arc::new(vocabulary),
46 })
47 })
48 })) {
49 Ok(Ok(dictionary)) => {
50 unsafe { out.write(Box::into_raw(dictionary)) };
52 OK
53 }
54 Ok(Err(_)) => DICTIONARY_DATA,
55 Err(_) => POISONED,
56 }
57}
58
59#[unsafe(no_mangle)]
67pub unsafe extern "C" fn kr_dictionary_parse_utf8(
68 abi: u32,
69 bytes: *const u8,
70 len: u32,
71 out: *mut *mut Dictionary,
72) -> u32 {
73 unsafe { parse_with(abi, bytes, len, out, Vocabulary::parse) }
75}
76
77#[unsafe(no_mangle)]
83pub unsafe extern "C" fn kr_dictionary_free(pointer: *mut Dictionary) {
84 if !pointer.is_null() {
85 let _ = catch_unwind(AssertUnwindSafe(|| {
86 drop(unsafe { Box::from_raw(pointer) });
88 }));
89 }
90}
91
92#[unsafe(no_mangle)]
100pub unsafe extern "C" fn kr_adopt_dictionaries(
101 pointer: *mut Engine,
102 english: *const Dictionary,
103 russian: *const Dictionary,
104) -> u32 {
105 unsafe {
107 with_engine(pointer, |engine| {
108 if engine.session.has_pending() || engine.compatibility_pending.is_some() {
109 return STATE;
110 }
111 let dictionaries = [english, russian].map(|dictionary| {
112 Snapshot::from(
113 dictionary
114 .as_ref()
115 .map(|value| Arc::clone(&value.vocabulary)),
116 )
117 });
118 engine.dictionaries = dictionaries;
119 OK
120 })
121 }
122}
123
124fn prepare_with(abi: u32, model: impl FnOnce() -> Result<Model<'static>, ModelError>) -> u32 {
125 if !compatible_abi(abi) {
126 return VERSION;
127 }
128 match catch_unwind(AssertUnwindSafe(model)) {
129 Ok(Ok(_)) => OK,
130 Ok(Err(_)) => MODEL_ASSET,
131 Err(_) => POISONED,
132 }
133}
134
135#[unsafe(no_mangle)]
138pub extern "C" fn kr_prepare_model(abi: u32) -> u32 {
139 prepare_with(abi, embedded_model)
140}
141
142#[cfg(test)]
143mod tests {
144 use super::*;
145 use crate::tests::{apply_event, type_text};
146 use crate::{
147 ABI, NativeEvent, NativePlan, kr_commit, kr_dictionary_skipped_lines, kr_engine_free,
148 kr_engine_new, kr_plan_event, kr_reset, kr_set_automatic_policy, kr_set_keyboard,
149 };
150 use keyrill_core::vocabulary::Membership;
151 use std::ptr::{null, null_mut};
152
153 fn event(role: u32) -> NativeEvent {
154 NativeEvent {
155 role,
156 mode: 1,
157 context: 0,
158 len: 0,
159 units: [0; 8],
160 }
161 }
162
163 unsafe fn parse(source: &[u8]) -> *mut Dictionary {
164 let mut dictionary = null_mut();
165 unsafe {
167 assert_eq!(
168 kr_dictionary_parse_utf8(
169 ABI,
170 source.as_ptr(),
171 source.len() as u32,
172 &mut dictionary
173 ),
174 OK
175 );
176 }
177 assert!(!dictionary.is_null());
178 dictionary
179 }
180
181 fn units(text: &str) -> Vec<u16> {
182 text.encode_utf16().collect()
183 }
184
185 fn assert_mark(plan: &NativePlan, text: &str) {
186 assert_eq!(&plan.mark[..plan.mark_len as usize], units(text));
187 }
188
189 #[test]
190 fn parse_checks_arguments_before_bytes_and_never_publishes_failure() {
191 unsafe {
194 let unreadable = std::ptr::NonNull::<u8>::dangling().as_ptr();
195 let mut out = std::ptr::NonNull::<Dictionary>::dangling().as_ptr();
196 assert_eq!(kr_dictionary_parse_utf8(ABI, null(), 0, null_mut()), NULL);
197 for abi in [ABI - 1, ABI + 1, 0x0001_0000] {
198 assert_eq!(
199 kr_dictionary_parse_utf8(abi, unreadable, 1, &mut out),
200 VERSION
201 );
202 assert!(out.is_null());
203 }
204 assert_eq!(kr_dictionary_parse_utf8(ABI, null(), 1, &mut out), NULL);
205 assert!(out.is_null());
206 for source in [null(), unreadable] {
207 out = std::ptr::NonNull::<Dictionary>::dangling().as_ptr();
208 assert_eq!(
209 kr_dictionary_parse_utf8(ABI, source, MAX_SOURCE_BYTES as u32 + 1, &mut out),
210 BOUNDS
211 );
212 assert!(out.is_null());
213 }
214 for source in [b"word\0other".as_slice(), b"/encoding=latin1\nword"] {
215 assert_eq!(
216 kr_dictionary_parse_utf8(ABI, source.as_ptr(), source.len() as u32, &mut out),
217 DICTIONARY_DATA
218 );
219 assert!(out.is_null());
220 }
221 assert_eq!(kr_dictionary_parse_utf8(ABI, null(), 0, &mut out), OK);
222 assert!((*out).vocabulary.is_empty());
223 kr_dictionary_free(out);
224 kr_dictionary_free(null_mut());
225 }
226 }
227
228 #[test]
229 fn shared_parser_flags_skips_and_owned_bytes_survive_failed_candidate() {
230 unsafe {
233 let mut source = "\u{feff}/encoding=utf-8\r\n/regions=usgb\nkeep\nNeovim/=\nrare/?\nno/!\nno\nbad/*\n/future\n".as_bytes().to_vec();
234 source.extend_from_slice(b"\xff\n");
235 let dictionary = parse(&source);
236 source.fill(b'x');
237 let mut engine = null_mut();
238 assert_eq!(kr_engine_new(ABI, &mut engine), OK);
239 assert_eq!(kr_adopt_dictionaries(engine, dictionary, null()), OK);
240 let old = (*engine).dictionaries[0].current().unwrap();
241 for (word, membership) in [
242 ("KEEP", Membership::Recognized),
243 ("Neovim", Membership::Recognized),
244 ("neovim", Membership::Absent),
245 ("rare", Membership::Rare),
246 ("no", Membership::Forbidden),
247 ] {
248 assert_eq!(old.lookup(&units(word)), membership);
249 }
250 let mut skipped = 77;
251 assert_eq!(kr_dictionary_skipped_lines(engine, 1, &mut skipped), OK);
252 assert_eq!(skipped, 3);
253 let mut failed = null_mut();
254 assert_eq!(
255 kr_dictionary_parse_utf8(ABI, [0].as_ptr(), 1, &mut failed),
256 DICTIONARY_DATA
257 );
258 assert!(failed.is_null());
259 assert!(Arc::ptr_eq(
260 &old,
261 &(*engine).dictionaries[0].current().unwrap()
262 ));
263 kr_dictionary_free(dictionary);
264 assert_eq!(old.lookup(&units("keep")), Membership::Recognized);
265 kr_engine_free(engine);
266 assert_eq!(old.lookup(&units("keep")), Membership::Recognized);
267 }
268 }
269
270 #[test]
271 fn adoption_is_pairwise_missing_differs_from_empty_and_pending_token_survives() {
272 unsafe {
275 let empty = parse(b"");
276 let replacement = parse(b"replacement");
277 let mut engine = null_mut();
278 assert_eq!(kr_engine_new(ABI, &mut engine), OK);
279 assert_eq!(kr_adopt_dictionaries(null_mut(), empty, empty), NULL);
280 assert_eq!(kr_adopt_dictionaries(engine, empty, null()), OK);
281 let mut skipped = 77;
282 assert_eq!(kr_dictionary_skipped_lines(engine, 1, &mut skipped), OK);
283 assert_eq!(skipped, 0);
284 skipped = 77;
285 assert_eq!(kr_dictionary_skipped_lines(engine, 2, &mut skipped), STATE);
286 assert_eq!(skipped, 77);
287 let old = (*engine).dictionaries[0].current().unwrap();
288 let mut letter = event(1);
289 letter.len = 1;
290 letter.units[0] = b'a' as u16;
291 let mut out = std::mem::MaybeUninit::uninit();
292 assert_eq!(kr_plan_event(engine, &letter, out.as_mut_ptr()), OK);
293 let pending = out.assume_init();
294 assert_eq!(
295 kr_adopt_dictionaries(engine, replacement, replacement),
296 STATE
297 );
298 assert!(Arc::ptr_eq(
299 &old,
300 &(*engine).dictionaries[0].current().unwrap()
301 ));
302 assert!((*engine).dictionaries[1].current().is_none());
303 assert_eq!(kr_commit(engine, pending.plan_id, 0), OK);
304 assert_eq!(kr_adopt_dictionaries(engine, replacement, replacement), OK);
305 assert!(Arc::ptr_eq(
306 &(*engine).dictionaries[0].current().unwrap(),
307 &(*engine).dictionaries[1].current().unwrap()
308 ));
309 assert_mark(&apply_event(engine, &event(6)), "a");
310 assert_eq!(kr_adopt_dictionaries(engine, null(), null()), OK);
311 assert!(
312 (*engine)
313 .dictionaries
314 .iter()
315 .all(|source| source.current().is_none())
316 );
317 kr_dictionary_free(empty);
318 kr_dictionary_free(replacement);
319 kr_engine_free(engine);
320 }
321 }
322
323 #[test]
324 fn immutable_handoff_and_old_readers_outlive_independent_engines() {
325 unsafe {
328 let dictionary = parse(b"original");
329 let replacement = parse(b"replacement");
330 let retained = (*dictionary).vocabulary.clone();
331 let shared = &*dictionary;
332 std::thread::scope(|scope| {
333 for _ in 0..2 {
334 scope.spawn(move || {
335 let mut engine = null_mut();
336 assert_eq!(kr_engine_new(ABI, &mut engine), OK);
337 assert_eq!(kr_adopt_dictionaries(engine, shared, shared), OK);
338 let snapshot = (*engine).dictionaries[0].current().unwrap();
339 assert_eq!(snapshot.lookup(&units("original")), Membership::Recognized);
340 kr_engine_free(engine);
341 assert_eq!(snapshot.lookup(&units("original")), Membership::Recognized);
342 });
343 }
344 });
345 let mut first = null_mut();
346 let mut second = null_mut();
347 assert_eq!(kr_engine_new(ABI, &mut first), OK);
348 assert_eq!(kr_engine_new(ABI, &mut second), OK);
349 assert_eq!(kr_adopt_dictionaries(first, dictionary, dictionary), OK);
350 assert_eq!(kr_adopt_dictionaries(second, dictionary, dictionary), OK);
351 kr_dictionary_free(dictionary);
352 assert_eq!(kr_adopt_dictionaries(first, replacement, replacement), OK);
353 kr_dictionary_free(replacement);
354 kr_engine_free(first);
355 assert_eq!(
356 (*second).dictionaries[0]
357 .current()
358 .unwrap()
359 .lookup(&units("original")),
360 Membership::Recognized
361 );
362 kr_engine_free(second);
363 assert_eq!(retained.lookup(&units("original")), Membership::Recognized);
364 }
365 }
366
367 #[test]
368 fn compatibility_proposal_also_blocks_adoption_without_changing_its_token() {
369 unsafe {
372 let empty = parse(b"");
373 let mut engine = null_mut();
374 assert_eq!(kr_engine_new(ABI, &mut engine), OK);
375 let mut letter = event(1);
376 letter.len = 1;
377 letter.units[0] = b'a' as u16;
378 let mut out = std::mem::MaybeUninit::uninit();
379 assert_eq!(
380 crate::compatibility::kr_plan_compatibility_event(
381 engine,
382 &letter,
383 0,
384 out.as_mut_ptr()
385 ),
386 OK
387 );
388 let pending = out.assume_init();
389 assert_eq!(kr_adopt_dictionaries(engine, empty, empty), STATE);
390 assert!(
391 (*engine)
392 .dictionaries
393 .iter()
394 .all(|source| source.current().is_none())
395 );
396 assert_eq!(
397 crate::compatibility::kr_commit_compatibility(engine, pending.plan_id, 0),
398 OK
399 );
400 assert_eq!(kr_adopt_dictionaries(engine, empty, empty), OK);
401 kr_dictionary_free(empty);
402 kr_engine_free(engine);
403 }
404 }
405
406 #[test]
407 #[cfg_attr(miri, ignore)]
408 fn adoption_preserves_model_history_manual_intent_and_reversal_receipts() {
409 unsafe {
412 let empty = parse(b"");
413 let protected = parse(b"cgbcjr");
414 let mut engine = null_mut();
415 assert_eq!(kr_engine_new(ABI, &mut engine), OK);
416 assert_eq!(kr_prepare_model(ABI), OK);
417 assert_eq!(kr_set_automatic_policy(engine, 2), OK);
418 assert_eq!(kr_adopt_dictionaries(engine, empty, null()), OK);
419 assert_mark(&type_text(engine, 1, "cgbcjr "), "cgbcjr ");
420 assert_eq!(kr_reset(engine), OK);
421 assert_eq!(kr_adopt_dictionaries(engine, empty, empty), OK);
422 assert_mark(&type_text(engine, 1, "cgbcjr "), "список ");
423 assert_eq!(kr_adopt_dictionaries(engine, protected, empty), OK);
424 assert_mark(&apply_event(engine, &event(5)), "cgbcjr ");
425 assert_eq!(kr_reset(engine), OK);
426 assert_mark(&type_text(engine, 1, "cgbcjr "), "cgbcjr ");
427 assert_eq!(kr_reset(engine), OK);
428 assert_eq!(kr_adopt_dictionaries(engine, empty, empty), OK);
429 type_text(engine, 1, "hello world ");
430 let mut next = event(1);
431 next.len = 1;
432 next.units[0] = b'y' as u16;
433 let mut out = std::mem::MaybeUninit::uninit();
434 assert_eq!(kr_plan_event(engine, &next, out.as_mut_ptr()), OK);
435 let finish = out.assume_init();
436 assert_eq!((finish.action, finish.disposition), (2, 2));
437 assert_eq!(kr_commit(engine, finish.plan_id, 0), OK);
438 assert_eq!(kr_adopt_dictionaries(engine, empty, empty), OK);
439 assert_mark(&type_text(engine, 1, "yfv "), "yfv ");
440 assert_eq!(kr_reset(engine), OK);
441 assert_eq!(kr_set_automatic_policy(engine, 0), OK);
442 assert_eq!(kr_set_keyboard(engine, 1), OK);
443 type_text(engine, 1, "`krf");
444 assert_mark(&apply_event(engine, &event(4)), "ёлка");
445 assert_eq!(kr_adopt_dictionaries(engine, null(), null()), OK);
446 assert_mark(&type_text(engine, 1, " "), "ёлка ");
447 assert_mark(&apply_event(engine, &event(5)), "`krf ");
448 kr_dictionary_free(empty);
449 kr_dictionary_free(protected);
450 kr_engine_free(engine);
451 }
452 }
453
454 #[test]
455 fn panic_is_contained_without_publishing_or_reviving_engine_authority() {
456 unsafe {
459 let mut engine = null_mut();
460 assert_eq!(kr_engine_new(ABI, &mut engine), OK);
461 let mut dictionary = std::ptr::NonNull::<Dictionary>::dangling().as_ptr();
462 assert_eq!(
463 parse_with(ABI, null(), 0, &mut dictionary, |_| panic!(
464 "parser containment"
465 )),
466 POISONED
467 );
468 assert!(dictionary.is_null());
469 assert_eq!(kr_reset(engine), OK);
470 let empty = parse(b"");
471 let mut out = std::mem::MaybeUninit::uninit();
472 let reverse = event(5);
473 assert_eq!(kr_plan_event(engine, &reverse, out.as_mut_ptr()), OK);
474 let pending = out.assume_init_read();
475 assert_eq!(kr_commit(engine, pending.plan_id, 2), OK);
476 assert_eq!(kr_adopt_dictionaries(engine, empty, empty), OK);
477 assert_eq!(kr_plan_event(engine, &reverse, out.as_mut_ptr()), STATE);
478 assert_eq!(with_engine(engine, |_| panic!("adoption poison")), POISONED);
479 assert_eq!(kr_adopt_dictionaries(engine, empty, empty), POISONED);
480 kr_dictionary_free(empty);
481 kr_engine_free(engine);
482 }
483 }
484
485 #[test]
486 fn model_preparation_rejects_versions_and_contains_failures() {
487 assert_eq!(kr_prepare_model(ABI + 1), VERSION);
488 assert_eq!(
489 prepare_with(ABI + 1, || panic!("must not prepare")),
490 VERSION
491 );
492 assert_eq!(prepare_with(ABI, || Err(ModelError::Magic)), MODEL_ASSET);
493 assert_eq!(prepare_with(ABI, || panic!("model containment")), POISONED);
494 }
495
496 #[test]
497 #[cfg_attr(miri, ignore)]
498 fn model_preparation_is_idempotent() {
499 assert_eq!(kr_prepare_model(ABI), OK);
500 assert_eq!(
501 std::thread::spawn(|| kr_prepare_model(ABI)).join().unwrap(),
502 OK
503 );
504 assert_eq!(kr_prepare_model(ABI), OK);
505 }
506}