cskk 3.1.4

C ABIから使う事を目的とした SKK(Simple Kana Kanji henkan)方式のかな漢字変換ライブラリ
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
//!
//! BNF風に表現
//!
//! <entry> ::= <midashi> " "+ <candidates>
//! <midashi> ::= (<char> except ' ')+
//! <candidates> ::= "/" (<candidate>"/")+
//! <candidate> ::= <no-strict-okuri-candidate> | <strict-okuri-candidates>
//! <no-strict-okuri-candidate> ::= <kouho> (";"<annotation>)?
//! <strict-okuri-candidates> ::= "[" <okuri> "/" (<no-strict-okuri-candidate> "/")+ "]"
//! <kouho> ::= (<char> except '/',';','[',']' )+
//! <annotation> ::= (<char> except '/',';')+
//! <okuri> ::= <hiragana>+
//! <hiragana> ::= U+3041..U+3096
//!

// 現在は見出しを空白文字以外としているが、ひらがなと末尾アルファベット以外は利用できないため制限するべきか?

use nom::branch::{alt, permutation};
use nom::bytes::complete::{take_till1, take_while1};
use nom::character::complete::char;
use nom::combinator::{all_consuming, map, opt};
use nom::multi::many1;
use nom::IResult;
use std::collections::BTreeMap;

#[derive(PartialEq, Debug, Clone)]
pub(in crate::dictionary) struct CandidatePrototype<'a> {
    pub(in crate::dictionary) kouho: &'a str,
    pub(in crate::dictionary) annotation: Option<&'a str>,
}

#[derive(PartialEq, Debug, Clone)]
pub(in crate::dictionary) struct DictEntryPrototype<'a> {
    pub(in crate::dictionary) midashi: &'a str,
    pub(in crate::dictionary) candidates: BTreeMap<&'a str, Vec<CandidatePrototype<'a>>>,
}

/// 辞書のエントリを読む
pub(in crate::dictionary) fn entry(input: &str) -> IResult<&str, DictEntryPrototype> {
    let (rest, (midashi, _, candidates)) = all_consuming(permutation((
        midashi,
        take_while1(|c| c == ' '),
        candidates,
    )))(input)?;

    Ok((
        rest,
        DictEntryPrototype {
            midashi,
            candidates,
        },
    ))
}

fn midashi(input: &str) -> IResult<&str, &str> {
    let (i, midashi) = take_till1(|c: char| c == ' ')(input)?;
    Ok((i, midashi))
}

/// 先頭の'/'を含む'/'で囲われた候補リスト全体からcandidate全部
fn candidates(input: &str) -> IResult<&str, BTreeMap<&str, Vec<CandidatePrototype>>> {
    // Make sure starts with '/'
    let (_, (_, parsed_cands)) = all_consuming(permutation((char('/'), many1(candidate))))(input)?;

    let mut result = BTreeMap::<&str, Vec<CandidatePrototype>>::new();
    for mut cand_map in parsed_cands {
        for (okuri, value) in cand_map.iter_mut() {
            if let Some(candidates) = result.get_mut(*okuri) {
                candidates.append(value);
            } else {
                let mut new_candidates = vec![];
                new_candidates.append(value);
                result.insert(okuri, new_candidates);
            }
        }
    }
    Ok(("", result))
}

/// 先頭の'/'を含まない部分から、Vec<CandidatePrototype>の厳密な送り仮名からのマップを返す。
/// 通常のcandidateだと空文字列からのマップで1要素のもの、厳密送りだと再帰的に含まれるので複数要素。
fn candidate(input: &str) -> IResult<&str, BTreeMap<&str, Vec<CandidatePrototype>>> {
    let (i, (result, _)) = permutation((
        alt((
            strict_okuri_candidates,
            map(no_strict_okuri_candidate, |cand: CandidatePrototype| {
                let mut map = BTreeMap::new();
                map.insert("", vec![cand]);
                map
            }),
        )),
        char('/'),
    ))(input)?;
    Ok((i, result))
}

/// 先頭の\[と末尾の\]を含む厳密な送り仮名候補列('かな文字列/候補/候補/')を受けてその文字列からの候補マップを返す
fn strict_okuri_candidates(input: &str) -> IResult<&str, BTreeMap<&str, Vec<CandidatePrototype>>> {
    let (i, (_, okuri_kana, _, cands, _)) = permutation((
        char('['),
        take_while1(|c: char| (''..'').contains(&c)),
        char('/'),
        many1(map(
            permutation((no_strict_okuri_candidate, char('/'))),
            |(cand, _)| cand,
        )),
        char(']'),
    ))(input)?;
    let mut result = BTreeMap::new();

    result.insert(okuri_kana, cands);
    Ok((i, result))
}

/// 先頭の'/'を含まない候補部分から候補と存在するならばアノテーションを解釈する。厳密な送り仮名の候補は解釈できない。
/// 候補と次の'/'から始まる残りの部分を返す。
fn no_strict_okuri_candidate(input: &str) -> IResult<&str, CandidatePrototype> {
    let (i, cand) = take_till1(|c: char| is_no_strict_okuri_candidate_illegal_char(&c))(input)?;

    let (i, annotation_opt) = opt(permutation((
        char(';'),
        take_till1(|c: char| is_annotation_illegal_char(&c)),
    )))(i)?;

    if let Some((_, a)) = annotation_opt {
        Ok((
            i,
            CandidatePrototype {
                kouho: cand,
                annotation: Some(a),
            },
        ))
    } else {
        Ok((
            i,
            CandidatePrototype {
                kouho: cand,
                annotation: None,
            },
        ))
    }
}

// true when contains chars not good for no strict okuri candidate: '[', ']', '/', ';'
fn is_no_strict_okuri_candidate_illegal_char(c: &char) -> bool {
    ['/', ';', '[', ']'].contains(c)
}

fn is_annotation_illegal_char(c: &char) -> bool {
    ['/', ';'].contains(c)
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn basic_midashi() {
        let (_i, result) = midashi("ほげr ////").unwrap();
        assert_eq!(result, "ほげr");
    }

    #[test]
    fn basic_candidates() {
        let (rest, result) = candidates("/愛;love/相/[す/愛/]/").unwrap();
        let mut expected = BTreeMap::new();
        expected.insert(
            "",
            vec![
                CandidatePrototype {
                    kouho: "",
                    annotation: Some("love"),
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
            ],
        );
        expected.insert(
            "",
            vec![CandidatePrototype {
                kouho: "",
                annotation: None,
            }],
        );

        assert_eq!(rest, "");
        assert_eq!(result, expected)
    }

    #[test]
    fn basic_candidate() {
        let (rest, result) = candidate("愛/相/").unwrap();
        assert_eq!(rest, "相/");
        let mut expected = BTreeMap::new();
        expected.insert(
            "",
            vec![CandidatePrototype {
                kouho: "",
                annotation: None,
            }],
        );
        assert_eq!(result, expected);
    }

    #[test]
    fn strict_okuri_candidate_in_candidates() {
        let (rest, result) = candidate("[つ/打;hit/討/]/打/").unwrap();
        assert_eq!(rest, "打/");
        let mut expected = BTreeMap::new();
        expected.insert(
            "",
            vec![
                CandidatePrototype {
                    kouho: "",
                    annotation: Some("hit"),
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
            ],
        );
        assert_eq!(result, expected);
    }

    #[test]
    fn basic_strict_okuri_candidate() {
        let mut expected = BTreeMap::new();
        expected.insert(
            "って",
            vec![
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
            ],
        );
        let (i, result) = strict_okuri_candidates("[って/送/贈/]").unwrap();
        assert_eq!(i, "");
        assert_eq!(result, expected);
    }

    #[test]
    fn no_strict_okuri_candidate_test() {
        let (rest, result) = no_strict_okuri_candidate("送/贈/").unwrap();
        assert_eq!(
            result,
            CandidatePrototype {
                kouho: "",
                annotation: None
            }
        );
        assert_eq!(rest, "/贈/");
    }

    #[test]
    fn no_strict_okuri_candidate_with_annotation() {
        let (rest, result) = no_strict_okuri_candidate("送;アノテーション/贈/").unwrap();
        assert_eq!(
            result,
            CandidatePrototype {
                kouho: "",
                annotation: Some("アノテーション")
            }
        );
        assert_eq!(rest, "/贈/");
    }

    #[test]
    fn strict_okuri_candidate_with_annotation() {
        let mut expected = BTreeMap::new();
        expected.insert(
            "",
            vec![
                CandidatePrototype {
                    kouho: "",
                    annotation: Some("[match]"),
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: Some("[meet]"),
                },
            ],
        );
        let (rest, result) = strict_okuri_candidates("[う/合;[match]/会;[meet]/]/").unwrap();
        assert_eq!(result, expected);
        assert_eq!(rest, "/");
    }

    #[test]
    fn annotation_with_bracket() {
        let (rest, result) = candidates("/愛;love/藍;color[004c71]/[す/愛;[love]/]/").unwrap();
        let mut expected = BTreeMap::new();
        expected.insert(
            "",
            vec![
                CandidatePrototype {
                    kouho: "",
                    annotation: Some("love"),
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: Some("color[004c71]"),
                },
            ],
        );
        expected.insert(
            "",
            vec![CandidatePrototype {
                kouho: "",
                annotation: Some("[love]"),
            }],
        );

        assert_eq!(rest, "");
        assert_eq!(result, expected)
    }

    #[test]
    fn github_issue244() {
        let (rest, result) = entry("よし /由/葦/葭/葭/余資/余矢;[数学]versed cosine/好/良/美/吉/純/義/喜/善/佳/圭/慶/祥/芳/嘉/克/宜/淑/禎/禧/譱/縦/").unwrap();
        let mut candidates = BTreeMap::new();
        candidates.insert(
            "",
            vec![
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
                CandidatePrototype {
                    kouho: "余資",
                    annotation: None,
                },
                CandidatePrototype {
                    kouho: "余矢",
                    annotation: Some("[数学]versed cosine"),
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
                CandidatePrototype {
                    kouho: "",
                    annotation: None,
                },
            ],
        );
        let expected = DictEntryPrototype {
            midashi: "よし",
            candidates,
        };

        assert_eq!(rest, "");
        assert_eq!(result, expected)
    }
}