Skip to main content

lindera_dependency/
schema.rs

1//! The schema of a dictionary: which feature column holds what, and which
2//! morphemes of a bunsetsu are its head and its function word.
3//!
4//! The feature columns of a morpheme differ from one dictionary to another,
5//! and so do the parts of speech that make a function word or a symbol.
6//! What needs them (the chunker, the parser, the output) takes them from a
7//! [`Schema`], and holds none of its own. A schema is data: a second
8//! dictionary is a second value, not a second code path.
9//!
10//! # The head and the function word
11//!
12//! The head (主辞) of a bunsetsu is its last content word, and the function
13//! word (機能語) its last particle or auxiliary. [`Schema::positions`] finds
14//! them as `findHead` of CaboCha does:
15//!
16//! 1. Both start at the first morpheme of the bunsetsu. A space
17//!    ([`is_space`]) is passed over everywhere: it is no word.
18//! 2. From the left, a morpheme that matches one of
19//!    [`Schema::function_words`] becomes the function word; a morpheme that
20//!    matches none of them, none of [`Schema::not_heads`], and is not a
21//!    symbol becomes the head.
22//! 3. A head after the function word becomes the function word too.
23//!
24//! That is [`HeadRule::FunctionWordsApart`], the rule of the schemas of this
25//! crate and of CaboCha for IPA. A model converted from CaboCha's for JUMAN
26//! has [`HeadRule::LastWords`] in [`Schema::head_rule`]: the function word
27//! is the last morpheme that is not a symbol, and the head the last one
28//! that is neither a symbol nor one of [`Schema::not_heads`]. One morpheme
29//! can be both, and nothing is moved afterwards.
30//!
31//! # Examples
32//!
33//! ```
34//! use lindera_dependency::Schema;
35//! use lindera_dependency::lattice::LatticeMorpheme;
36//!
37//! let schema = Schema::ipadic();
38//! // 読ん / で / いる / 。
39//! let bunsetsu = [
40//!     LatticeMorpheme::new("読ん", "動詞,自立,*,*,五段・マ行,連用タ接続,読む,ヨン,ヨン"),
41//!     LatticeMorpheme::new("で", "助詞,接続助詞,*,*,*,*,で,デ,デ"),
42//!     LatticeMorpheme::new("いる", "動詞,非自立,*,*,一段,基本形,いる,イル,イル"),
43//!     LatticeMorpheme::new("。", "記号,句点,*,*,*,*,。,。,。"),
44//! ];
45//! assert_eq!(schema.positions(&bunsetsu), Some((0, 2)));
46//! assert!(schema.is_period(&bunsetsu[3]));
47//! ```
48
49mod normalization;
50mod pattern;
51mod symbols;
52
53use std::borrow::Cow;
54use std::ops::Range;
55
56pub use normalization::Normalization;
57pub use pattern::Pattern;
58pub use symbols::{Marks, SurfaceRule, Symbols};
59
60use crate::bytes::{Reader, push_u32};
61use crate::error::{Error, Result};
62use crate::morpheme::{Morpheme, is_sentence_end, is_space};
63
64/// The value that stands for a column the schema does not have, in its
65/// bytes.
66const NO_COLUMN: u32 = u32::MAX;
67
68/// The first version of the model file whose schema holds
69/// [`Schema::head_fallback`] and [`Schema::sentence_split`]. In an older
70/// file the schema ends with the rule of the head: the head word of a
71/// bunsetsu without one is its first morpheme, and a text is not cut into
72/// sentences.
73const HEAD_FALLBACK_VERSION: u32 = 4;
74
75/// The value of a feature column that holds nothing.
76const EMPTY: &str = "*";
77
78/// The characters of the commas, in full width and half width.
79/// The formal nouns of the schema of UniDic, by their 語彙素: こと, ため,
80/// もの, 際, うえ and ところ.
81const FORMAL_NOUNS: [&str; 6] = ["事", "為", "物", "際", "上", "所"];
82
83const COMMAS: &str = "、,,";
84
85/// The characters of the periods, in full width and half width.
86const PERIODS: &str = "。..";
87
88/// The opening brackets: those CaboCha knows, and the other ones of the
89/// same blocks.
90const OPEN_BRACKETS: &str = "(([[{{「『【〔〈《〘〚‘“";
91
92/// The closing brackets, in the order of [`OPEN_BRACKETS`].
93const CLOSE_BRACKETS: &str = "))]]}}」』】〕〉》〙〛’”";
94
95/// The other characters of symbols: the punctuation of ASCII with its
96/// full-width forms, and marks of Japanese text. `%` and `°` are not here:
97/// they are units, which UD Japanese-GSD has as the content head (50 / %).
98const OTHER_SYMBOLS: &str = concat!(
99    "!\"#$&'*+-/:;<=>?@\\^_`|~",
100    "!"#$&'*+-/:;<=>?@\^_`|~",
101    "・…‥―—–‐〜※♪★☆○●◎◇◆□■△▲▽▼→←↑↓≠",
102);
103
104/// How [`Schema::positions`] finds the head word and the function word of
105/// a bunsetsu: the two forms `findHead` of CaboCha has.
106#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
107pub enum HeadRule {
108    /// A morpheme that matches one of [`Schema::function_words`] is the
109    /// function word, and is not the head; a morpheme that matches none of
110    /// them, none of [`Schema::not_heads`], and is not a symbol is the
111    /// head. The last of each is taken, and a head after the function word
112    /// becomes the function word too. The rule of the schemas of this
113    /// crate, and CaboCha's for IPA and for UniDic.
114    #[default]
115    FunctionWordsApart,
116    /// The function word is the last morpheme that is not a symbol, and the
117    /// head the last morpheme that is neither a symbol nor one of
118    /// [`Schema::not_heads`]. The two are found apart: one morpheme can be
119    /// both, as the noun of a bunsetsu of one noun, and nothing is moved
120    /// afterwards. [`Schema::function_words`] is not read. CaboCha's rule
121    /// for JUMAN, whose function word is the last morpheme that is not a
122    /// 特殊, and whose head is the last that is not a 特殊, a 助詞 or a
123    /// 接尾辞.
124    LastWords,
125}
126
127impl HeadRule {
128    /// The two rules with their codes in a model file.
129    const ALL: [(HeadRule, u8); 2] = [(HeadRule::FunctionWordsApart, 0), (HeadRule::LastWords, 1)];
130
131    /// The code of the rule in the bytes of a model.
132    fn code(self) -> u8 {
133        Self::ALL
134            .iter()
135            .find(|(rule, _)| *rule == self)
136            .map_or(0, |(_, code)| *code)
137    }
138
139    /// The rule of a code, or the error of a code that is not one.
140    fn from_code(code: u8) -> Result<Self> {
141        Self::ALL
142            .iter()
143            .find(|(_, one)| *one == code)
144            .map(|(rule, _)| *rule)
145            .ok_or_else(|| Error::Schema(format!("{code} is not the code of a rule of the head")))
146    }
147}
148
149/// What [`Schema::positions`] takes as the head word of a bunsetsu in which
150/// no morpheme can be one: a bunsetsu of function words, of what is not a
151/// head, and of symbols, such as 「 / する / 」 / と.
152#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
153pub enum HeadFallback {
154    /// The first morpheme, whatever it is: the bracket of 「 / する / 」 / と.
155    /// What CaboCha does, so the schema of a model converted from CaboCha
156    /// has it, and so does the schema of a model file older than the
157    /// version 4, which has no such setting. A space is passed over, as
158    /// everywhere: CaboCha is never given one.
159    #[default]
160    FirstMorpheme,
161    /// The first morpheme that is a word: not a comma, a period or a
162    /// bracket, not a space, and not a particle. する in 「 / する / 」 / と,
163    /// and the first letter of a word that a dictionary cuts into letters
164    /// it calls symbols (S / i / r / i / の). The first morpheme when the
165    /// bunsetsu has no such word. The schemas of this crate have it.
166    FirstWord,
167}
168
169impl HeadFallback {
170    /// The two settings with their codes in a model file.
171    const ALL: [(HeadFallback, u8); 2] = [
172        (HeadFallback::FirstMorpheme, 0),
173        (HeadFallback::FirstWord, 1),
174    ];
175
176    /// The code of the setting in the bytes of a model.
177    fn code(self) -> u8 {
178        Self::ALL
179            .iter()
180            .find(|(fallback, _)| *fallback == self)
181            .map_or(0, |(_, code)| *code)
182    }
183
184    /// The setting of a code, or the error of a code that is not one.
185    fn from_code(code: u8) -> Result<Self> {
186        Self::ALL
187            .iter()
188            .find(|(_, one)| *one == code)
189            .map(|(fallback, _)| *fallback)
190            .ok_or_else(|| {
191                Error::Schema(format!(
192                    "{code} is not the code of a head word for a bunsetsu without one"
193                ))
194            })
195    }
196}
197
198/// Whether a chunker cuts a text into sentences before it gives it to its
199/// model.
200///
201/// A chunker is trained on sentences, and no sentence of its training data
202/// goes on after its period: what a model does with the word after a `。` in
203/// the middle of a text is not learned. With [`SentenceSplit::AfterEnds`]
204/// the chunker cuts the text there and gives each part to the model on its
205/// own ([`Schema::sentence_starts`]).
206#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
207pub enum SentenceSplit {
208    /// The text is one sentence for the model. What CaboCha does, so the
209    /// schema of a model converted from CaboCha has it, and so does the
210    /// schema of a model file older than the version 4, which has no such
211    /// setting.
212    #[default]
213    None,
214    /// The text is cut after each sentence end
215    /// ([`is_sentence_end`]). The schemas
216    /// of this crate have it.
217    AfterEnds,
218}
219
220impl SentenceSplit {
221    /// The two settings with their codes in a model file.
222    const ALL: [(SentenceSplit, u8); 2] = [(SentenceSplit::None, 0), (SentenceSplit::AfterEnds, 1)];
223
224    /// The code of the setting in the bytes of a model.
225    fn code(self) -> u8 {
226        Self::ALL
227            .iter()
228            .find(|(split, _)| *split == self)
229            .map_or(0, |(_, code)| *code)
230    }
231
232    /// The setting of a code, or the error of a code that is not one.
233    fn from_code(code: u8) -> Result<Self> {
234        Self::ALL
235            .iter()
236            .find(|(_, one)| *one == code)
237            .map(|(split, _)| *split)
238            .ok_or_else(|| {
239                Error::Schema(format!(
240                    "{code} is not the code of a way to cut a text into sentences"
241                ))
242            })
243    }
244}
245
246/// What is known about a dictionary: which feature columns hold the part of
247/// speech, the conjugation and the base form, which morphemes are function
248/// words, which are not heads, and which are symbols.
249///
250/// Columns are counted from 0, as [`Morpheme::feature`]
251/// does.
252#[derive(Debug, Clone, PartialEq, Eq, Default)]
253pub struct Schema {
254    /// The columns of the part of speech, from the coarsest level to the
255    /// finest.
256    pub part_of_speech: Range<usize>,
257    /// The column of the conjugation type, when the dictionary has one.
258    pub conjugation_type: Option<usize>,
259    /// The column of the conjugation form, when the dictionary has one.
260    pub conjugation_form: Option<usize>,
261    /// The column of the base form, when the dictionary has one.
262    pub base_form: Option<usize>,
263    /// The function words: a morpheme that matches one of these patterns.
264    pub function_words: Vec<Pattern>,
265    /// What is neither a function word nor a head, besides the symbols: a
266    /// morpheme that matches one of these patterns.
267    pub not_heads: Vec<Pattern>,
268    /// The particles: a morpheme that matches one of these patterns. The
269    /// parser names the particles of a bunsetsu in its features.
270    pub particles: Vec<Pattern>,
271    /// The function words that tell by their surface how a bunsetsu
272    /// modifies another: a morpheme that matches one of these patterns. For
273    /// a bunsetsu that ends in any other word, the parser takes the
274    /// conjugation form or the part of speech in its place.
275    pub lexicalized: Vec<Pattern>,
276    /// How symbols, punctuation and brackets are recognized.
277    pub symbols: Symbols,
278    /// What a surface is replaced by before it becomes a feature or is
279    /// matched as a mark: empty for the schemas of this crate, the table
280    /// of CaboCha for a model converted from CaboCha.
281    pub normalization: Normalization,
282    /// How the head word and the function word of a bunsetsu are found.
283    pub head_rule: HeadRule,
284    /// The head word of a bunsetsu in which the rule finds none.
285    pub head_fallback: HeadFallback,
286    /// Whether a chunker cuts a text into sentences before it gives it to
287    /// its model.
288    pub sentence_split: SentenceSplit,
289}
290
291impl Schema {
292    /// The names of the dictionaries [`Schema::for_dictionary`] has a schema
293    /// for.
294    pub const DICTIONARIES: [&'static str; 4] = ["ipadic", "unidic", "unidic-cwj", "unidic-csj"];
295
296    /// The schema of IPADIC.
297    ///
298    /// The columns are four levels of part of speech, then the conjugation
299    /// type, the conjugation form and the base form.
300    ///
301    /// The function words are those of CaboCha for IPA (助詞, 助動詞,
302    /// 動詞,非自立, 動詞,接尾, 形容詞,非自立, 形容詞,接尾), and する and
303    /// できる (動詞,自立): in 利用 / し / た the head is 利用. At the start
304    /// of a bunsetsu する is still the head, since the head starts there
305    /// and only a head moves it.
306    ///
307    /// Besides the symbols, these are not heads: 名詞,非自立 (こと, の,
308    /// よう); the suffixes 的 (名詞,接尾,形容動詞語幹) and さ
309    /// (名詞,接尾,特殊), so that in 基本 / 的 / に the head is 基本; and a
310    /// 動詞,自立 right after a 助詞, which is part of a compound function
311    /// word (こと / に / なっ / た, かも / しれ / ない).
312    ///
313    /// With CaboCha's rule alone the head is the content head of UD
314    /// Japanese-GSD in 85% of the bunsetsu; with these additions, in 97%.
315    /// The README of the crate has the measurement.
316    ///
317    /// A symbol is a morpheme of the part of speech 記号, or one whose
318    /// surface is made of symbol characters only: IPADIC has no half-width
319    /// symbols, and gives `,` as 名詞,サ変接続.
320    ///
321    /// The particles are 助詞, and the function words taken by their
322    /// surface are 助詞, 副詞, 連体詞 and 接続詞, as in CaboCha.
323    ///
324    /// # Returns
325    ///
326    /// The schema.
327    pub fn ipadic() -> Self {
328        Self {
329            part_of_speech: 0..4,
330            conjugation_type: Some(4),
331            conjugation_form: Some(5),
332            base_form: Some(6),
333            function_words: vec![
334                Pattern::new(&["助詞"]),
335                Pattern::new(&["助動詞"]),
336                Pattern::new(&["動詞", "非自立"]),
337                Pattern::new(&["動詞", "接尾"]),
338                Pattern::new(&["形容詞", "非自立"]),
339                Pattern::new(&["形容詞", "接尾"]),
340                Pattern::new(&["動詞", "自立"]).with_base_forms(&["する", "できる", "出来る"]),
341            ],
342            not_heads: vec![
343                Pattern::new(&["名詞", "非自立"]),
344                Pattern::new(&["名詞", "接尾", "形容動詞語幹"]),
345                Pattern::new(&["名詞", "接尾", "特殊"]),
346                Pattern::new(&["動詞", "自立"]).after(Pattern::new(&["助詞"])),
347            ],
348            particles: vec![Pattern::new(&["助詞"])],
349            lexicalized: vec![
350                Pattern::new(&["助詞"]),
351                Pattern::new(&["副詞"]),
352                Pattern::new(&["連体詞"]),
353                Pattern::new(&["接続詞"]),
354            ],
355            symbols: Symbols {
356                others: Marks::new(&[&["記号"]], OTHER_SYMBOLS),
357                commas: Marks::new(&[&["記号", "読点"]], COMMAS),
358                periods: Marks::new(&[&["記号", "句点"]], PERIODS),
359                open_brackets: Marks::new(&[&["記号", "括弧開"]], OPEN_BRACKETS),
360                close_brackets: Marks::new(&[&["記号", "括弧閉"]], CLOSE_BRACKETS),
361                surface: SurfaceRule::EveryCharacter,
362            },
363            normalization: Normalization::default(),
364            head_rule: HeadRule::FunctionWordsApart,
365            head_fallback: HeadFallback::FirstWord,
366            sentence_split: SentenceSplit::AfterEnds,
367        }
368    }
369
370    /// The schema of UniDic: of `unidic` (unidic-mecab 2.1.2), `unidic-cwj`
371    /// and `unidic-csj`, whose first columns are the same.
372    ///
373    /// The columns are 品詞大分類, 中分類, 小分類, 細分類, 活用型, 活用形,
374    /// 語彙素読み and 語彙素; the base form is the 語彙素, so that of こと
375    /// is 事.
376    ///
377    /// The function words are the ones of the pattern CaboCha has for
378    /// UniDic (a particle, an auxiliary, and a suffix that is not nominal),
379    /// and a verb or an adjective that is 非自立可能. What is not a head
380    /// was measured on UD Japanese-GSD, as for IPADIC:
381    ///
382    /// * a verb right after に, と or を (に / よっ / て, と / し / て),
383    /// * a 助動詞語幹 (よう, そう, みたい),
384    /// * a formal noun (こと, ため, もの, 際, うえ, ところ) right after a
385    ///   verb, an auxiliary or an adjective,
386    /// * a nominal suffix right after an adjective (大き / さ).
387    ///
388    /// UniDic tags a letter of the Latin alphabet 記号,文字, and it is a
389    /// symbol here as any 記号 is.
390    ///
391    /// # Returns
392    ///
393    /// The schema.
394    ///
395    /// # Examples
396    ///
397    /// ```
398    /// use lindera_dependency::Schema;
399    /// use lindera_dependency::lattice::LatticeMorpheme;
400    ///
401    /// let schema = Schema::unidic();
402    /// // 利用 / する / こと / が
403    /// let bunsetsu = [
404    ///     LatticeMorpheme::new("利用", "名詞,普通名詞,サ変可能,*,*,*,リヨウ,利用"),
405    ///     LatticeMorpheme::new("する", "動詞,非自立可能,*,*,サ行変格,連体形-一般,スル,為る"),
406    ///     LatticeMorpheme::new("こと", "名詞,普通名詞,一般,*,*,*,コト,事"),
407    ///     LatticeMorpheme::new("が", "助詞,格助詞,*,*,*,*,ガ,が"),
408    /// ];
409    /// // The head word is 利用 and the function word が: する is 非自立可能,
410    /// // and こと is a formal noun after a verb.
411    /// assert_eq!(schema.positions(&bunsetsu), Some((0, 3)));
412    /// ```
413    pub fn unidic() -> Self {
414        Self {
415            part_of_speech: 0..4,
416            conjugation_type: Some(4),
417            conjugation_form: Some(5),
418            base_form: Some(7),
419            function_words: vec![
420                Pattern::new(&["助詞"]),
421                Pattern::new(&["助動詞"]),
422                Pattern::new(&["接尾辞", "形容詞的"]),
423                Pattern::new(&["接尾辞", "形状詞的"]),
424                Pattern::new(&["接尾辞", "動詞的"]),
425                Pattern::new(&["動詞", "非自立可能"]),
426                Pattern::new(&["形容詞", "非自立可能"]),
427            ],
428            not_heads: vec![
429                Pattern::new(&["動詞"])
430                    .after(Pattern::new(&["助詞"]).with_base_forms(&["に", "と", "を"])),
431                Pattern::new(&["形状詞", "助動詞語幹"]),
432                Pattern::new(&["名詞", "助動詞語幹"]),
433                Pattern::new(&["名詞", "普通名詞"])
434                    .with_base_forms(&FORMAL_NOUNS)
435                    .after(Pattern::new(&["動詞"])),
436                Pattern::new(&["名詞", "普通名詞"])
437                    .with_base_forms(&FORMAL_NOUNS)
438                    .after(Pattern::new(&["助動詞"])),
439                Pattern::new(&["名詞", "普通名詞"])
440                    .with_base_forms(&FORMAL_NOUNS)
441                    .after(Pattern::new(&["形容詞"])),
442                Pattern::new(&["接尾辞", "名詞的"]).after(Pattern::new(&["形容詞"])),
443            ],
444            particles: vec![Pattern::new(&["助詞"])],
445            lexicalized: vec![
446                Pattern::new(&["助詞"]),
447                Pattern::new(&["副詞"]),
448                Pattern::new(&["連体詞"]),
449                Pattern::new(&["接続詞"]),
450            ],
451            symbols: Symbols {
452                others: Marks::new(&[&["空白"], &["補助記号"], &["記号"]], ""),
453                commas: Marks::new(&[&["補助記号", "読点"]], COMMAS),
454                periods: Marks::new(&[&["補助記号", "句点"]], PERIODS),
455                open_brackets: Marks::new(&[&["補助記号", "括弧開"]], OPEN_BRACKETS),
456                close_brackets: Marks::new(&[&["補助記号", "括弧閉"]], CLOSE_BRACKETS),
457                surface: SurfaceRule::EveryCharacter,
458            },
459            normalization: Normalization::default(),
460            head_rule: HeadRule::FunctionWordsApart,
461            head_fallback: HeadFallback::FirstWord,
462            sentence_split: SentenceSplit::AfterEnds,
463        }
464    }
465
466    /// The schema of a dictionary of Lindera, by the name of the dictionary.
467    ///
468    /// # Arguments
469    ///
470    /// * `dictionary` - The name of the dictionary, as its metadata has it:
471    ///   `ipadic`, `unidic`, `unidic-cwj` or `unidic-csj`.
472    ///
473    /// # Returns
474    ///
475    /// The schema, or `None` for a dictionary this crate has no schema for.
476    ///
477    /// # Examples
478    ///
479    /// ```
480    /// use lindera_dependency::Schema;
481    ///
482    /// assert_eq!(Schema::for_dictionary("ipadic"), Some(Schema::ipadic()));
483    /// // The three UniDic dictionaries have one schema.
484    /// assert_eq!(Schema::for_dictionary("unidic-cwj"), Some(Schema::unidic()));
485    /// assert_eq!(Schema::for_dictionary("ko-dic"), None);
486    /// assert_eq!(
487    ///     Schema::DICTIONARIES,
488    ///     ["ipadic", "unidic", "unidic-cwj", "unidic-csj"]
489    /// );
490    /// ```
491    pub fn for_dictionary(dictionary: &str) -> Option<Self> {
492        match dictionary {
493            "ipadic" => Some(Self::ipadic()),
494            "unidic" | "unidic-cwj" | "unidic-csj" => Some(Self::unidic()),
495            _ => None,
496        }
497    }
498
499    /// The positions of the head word and of the function word of a
500    /// bunsetsu: what [`Bunsetsu::positions`](crate::Bunsetsu::positions)
501    /// holds.
502    ///
503    /// See the [module documentation](self) for the rule. A bunsetsu
504    /// without a function word has the function word at its head. A
505    /// bunsetsu in which the rule finds no head word has the one
506    /// [`Schema::head_fallback`] names, and both at its first morpheme when
507    /// it is of symbols only. A space is neither of the two, unless the
508    /// bunsetsu is of spaces alone.
509    ///
510    /// # Arguments
511    ///
512    /// * `bunsetsu` - The morphemes of the bunsetsu.
513    ///
514    /// # Returns
515    ///
516    /// The positions of the head word and of the function word, counted
517    /// from the first morpheme of the bunsetsu; `None` for no morpheme.
518    pub fn positions<M: Morpheme>(&self, bunsetsu: &[M]) -> Option<(usize, usize)> {
519        if bunsetsu.is_empty() {
520            return None;
521        }
522        let mut head = None;
523        let mut function = 0;
524        for (index, morpheme) in bunsetsu.iter().enumerate() {
525            // A space is no word: it is neither of the two.
526            if is_space(morpheme) {
527                continue;
528            }
529            let matches = |patterns: &[Pattern]| {
530                patterns
531                    .iter()
532                    .any(|one| one.matches(self, bunsetsu, index))
533            };
534            match self.head_rule {
535                HeadRule::FunctionWordsApart => {
536                    if matches(&self.function_words) {
537                        function = index;
538                    } else if !matches(&self.not_heads) && !self.is_symbol(morpheme) {
539                        head = Some(index);
540                    }
541                }
542                HeadRule::LastWords => {
543                    if !self.is_symbol(morpheme) {
544                        function = index;
545                        if !matches(&self.not_heads) {
546                            head = Some(index);
547                        }
548                    }
549                }
550            }
551        }
552        // No morpheme can be the head word: the setting of the schema says
553        // which one is taken.
554        let head = head.unwrap_or_else(|| {
555            let word = match self.head_fallback {
556                HeadFallback::FirstMorpheme => None,
557                HeadFallback::FirstWord => self.first_word(bunsetsu),
558            };
559            // Without a word, the first morpheme that is not a space.
560            word.or_else(|| bunsetsu.iter().position(|morpheme| !is_space(morpheme)))
561                .unwrap_or(0)
562        });
563        // With `LastWords` a head is never after the function word: the
564        // morpheme that becomes the head has just become the function word.
565        if head > function {
566            function = head;
567        }
568        Some((head, function))
569    }
570
571    /// Where the sentences of a text start, for a chunker: the words at
572    /// which it cuts the text, so that its model is given one sentence at a
573    /// time.
574    ///
575    /// With [`SentenceSplit::AfterEnds`], a sentence end
576    /// ([`is_sentence_end`]) takes the
577    /// ends and the closing brackets that follow it, and the word after
578    /// them starts a sentence: 読んだ / 。 / 面白かっ / た is cut before
579    /// 面白かっ. Two cases are left whole, where the word after the end
580    /// belongs to the bunsetsu of a quotation:
581    ///
582    /// - a function word after a closing bracket, as と in
583    ///   …。 / 」 / と / 言っ / た;
584    /// - the particle of a quotation, と or って, also without a bracket, as
585    ///   in …な / の / か / ? / と / 、.
586    ///
587    /// Another function word without a closing bracket starts a sentence as
588    /// any word does: …。 / だ / が, and …。 / で / も, which UniDic gives as
589    /// two particles.
590    ///
591    /// # Arguments
592    ///
593    /// * `words` - The words of the text: its morphemes without the spaces.
594    ///
595    /// # Returns
596    ///
597    /// The indices of the words that start a sentence, in order, each
598    /// larger than 0: the first word starts one in any case and is not
599    /// listed. Empty with [`SentenceSplit::None`], and for a text of one
600    /// sentence.
601    pub fn sentence_starts<M: Morpheme>(&self, words: &[M]) -> Vec<usize> {
602        let mut starts = Vec::new();
603        if self.sentence_split == SentenceSplit::None {
604            return starts;
605        }
606        let mut index = 0;
607        while index < words.len() {
608            if !is_sentence_end(&words[index], words.get(index + 1)) {
609                index += 1;
610                continue;
611            }
612            index += 1;
613            // What follows and still belongs to the sentence.
614            let mut closed = false;
615            while index < words.len()
616                && (is_sentence_end(&words[index], words.get(index + 1))
617                    || self.is_close_bracket(&words[index]))
618            {
619                closed |= self.is_close_bracket(&words[index]);
620                index += 1;
621            }
622            if index < words.len()
623                && !self.is_quotation_particle(words, index)
624                && !(closed && self.is_function_word(words, index))
625            {
626                starts.push(index);
627            }
628        }
629        starts
630    }
631
632    /// Whether a morpheme is a particle that closes a quotation: と or って.
633    ///
634    /// # Arguments
635    ///
636    /// * `morphemes` - The morphemes around it.
637    /// * `index` - Its index among them.
638    ///
639    /// # Returns
640    ///
641    /// Whether it is a particle of the schema with one of the two surfaces.
642    fn is_quotation_particle<M: Morpheme>(&self, morphemes: &[M], index: usize) -> bool {
643        matches!(morphemes[index].surface(), "と" | "って") && self.is_particle(morphemes, index)
644    }
645
646    /// Whether a morpheme matches a function word pattern of the schema.
647    ///
648    /// # Arguments
649    ///
650    /// * `morphemes` - The morphemes around it.
651    /// * `index` - Its index among them.
652    ///
653    /// # Returns
654    ///
655    /// Whether one of [`Schema::function_words`] matches it.
656    fn is_function_word<M: Morpheme>(&self, morphemes: &[M], index: usize) -> bool {
657        self.function_words
658            .iter()
659            .any(|one| one.matches(self, morphemes, index))
660    }
661
662    /// The first morpheme of a bunsetsu that is a word, for
663    /// [`HeadFallback::FirstWord`].
664    ///
665    /// # Arguments
666    ///
667    /// * `bunsetsu` - The morphemes of the bunsetsu.
668    ///
669    /// # Returns
670    ///
671    /// The index of the first morpheme that is not a comma, a period or a
672    /// bracket, not a space, and not a particle; `None` when there is none.
673    fn first_word<M: Morpheme>(&self, bunsetsu: &[M]) -> Option<usize> {
674        bunsetsu.iter().enumerate().position(|(index, morpheme)| {
675            !(is_space(morpheme)
676                || self.is_comma(morpheme)
677                || self.is_period(morpheme)
678                || self.is_open_bracket(morpheme)
679                || self.is_close_bracket(morpheme)
680                || self.is_particle(bunsetsu, index))
681        })
682    }
683
684    /// The surface of a morpheme as the chunker and the parser use it:
685    /// with [`Schema::normalization`] applied.
686    ///
687    /// # Arguments
688    ///
689    /// * `morpheme` - The morpheme.
690    ///
691    /// # Returns
692    ///
693    /// The normalized surface; the surface itself when the schema does not
694    /// normalize, or when no rule matches in it.
695    pub fn surface_of<'a, M: Morpheme>(&self, morpheme: &'a M) -> Cow<'a, str> {
696        self.normalization.apply(morpheme.surface())
697    }
698
699    /// Whether a morpheme of a bunsetsu is a particle: it matches one of
700    /// [`Schema::particles`].
701    ///
702    /// # Arguments
703    ///
704    /// * `bunsetsu` - The morphemes of the bunsetsu.
705    /// * `index` - The index of the morpheme in the bunsetsu.
706    ///
707    /// # Returns
708    ///
709    /// Whether it is a particle; `false` for an index past the bunsetsu.
710    pub fn is_particle<M: Morpheme>(&self, bunsetsu: &[M], index: usize) -> bool {
711        self.particles
712            .iter()
713            .any(|one| one.matches(self, bunsetsu, index))
714    }
715
716    /// Whether a morpheme of a bunsetsu tells by its surface how the
717    /// bunsetsu modifies another: it matches one of
718    /// [`Schema::lexicalized`].
719    ///
720    /// # Arguments
721    ///
722    /// * `bunsetsu` - The morphemes of the bunsetsu.
723    /// * `index` - The index of the morpheme in the bunsetsu.
724    ///
725    /// # Returns
726    ///
727    /// Whether it is such a word; `false` for an index past the bunsetsu.
728    pub fn is_lexicalized<M: Morpheme>(&self, bunsetsu: &[M], index: usize) -> bool {
729        self.lexicalized
730            .iter()
731            .any(|one| one.matches(self, bunsetsu, index))
732    }
733
734    /// Whether a morpheme is a symbol: a comma, a period, a bracket or any
735    /// other one. A symbol is neither the head nor the function word of a
736    /// bunsetsu.
737    ///
738    /// # Arguments
739    ///
740    /// * `morpheme` - The morpheme.
741    ///
742    /// # Returns
743    ///
744    /// Whether its part of speech is one of a symbol, or its surface is
745    /// made of symbol characters only.
746    pub fn is_symbol<M: Morpheme>(&self, morpheme: &M) -> bool {
747        self.symbols.matches(self, morpheme)
748    }
749
750    /// Whether a morpheme is a comma (読点): `、`, or `,` and `,`.
751    ///
752    /// # Arguments
753    ///
754    /// * `morpheme` - The morpheme.
755    ///
756    /// # Returns
757    ///
758    /// Whether its part of speech or its surface is the one of a comma.
759    pub fn is_comma<M: Morpheme>(&self, morpheme: &M) -> bool {
760        self.symbols.commas.matches(self, morpheme)
761    }
762
763    /// Whether a morpheme is a period (句点): `。`, or `.` and `.`.
764    ///
765    /// # Arguments
766    ///
767    /// * `morpheme` - The morpheme.
768    ///
769    /// # Returns
770    ///
771    /// Whether its part of speech or its surface is the one of a period.
772    pub fn is_period<M: Morpheme>(&self, morpheme: &M) -> bool {
773        self.symbols.periods.matches(self, morpheme)
774    }
775
776    /// Whether a morpheme is an opening bracket.
777    ///
778    /// # Arguments
779    ///
780    /// * `morpheme` - The morpheme.
781    ///
782    /// # Returns
783    ///
784    /// Whether its part of speech or its surface is the one of an opening
785    /// bracket.
786    pub fn is_open_bracket<M: Morpheme>(&self, morpheme: &M) -> bool {
787        self.symbols.open_brackets.matches(self, morpheme)
788    }
789
790    /// Whether a morpheme is a closing bracket.
791    ///
792    /// # Arguments
793    ///
794    /// * `morpheme` - The morpheme.
795    ///
796    /// # Returns
797    ///
798    /// Whether its part of speech or its surface is the one of a closing
799    /// bracket.
800    pub fn is_close_bracket<M: Morpheme>(&self, morpheme: &M) -> bool {
801        self.symbols.close_brackets.matches(self, morpheme)
802    }
803
804    /// The part of speech of a morpheme as one string: its levels joined by
805    /// `-`, up to the first one that is `*` or missing, as `名詞-サ変接続`.
806    ///
807    /// # Arguments
808    ///
809    /// * `morpheme` - The morpheme.
810    ///
811    /// # Returns
812    ///
813    /// The part of speech; an empty string without a first level.
814    pub fn part_of_speech_of<M: Morpheme>(&self, morpheme: &M) -> String {
815        self.levels_of(morpheme, self.part_of_speech.clone())
816    }
817
818    /// Some levels of the part of speech of a morpheme as one string.
819    ///
820    /// # Arguments
821    ///
822    /// * `morpheme` - The morpheme.
823    /// * `levels` - The columns of the levels to join.
824    ///
825    /// # Returns
826    ///
827    /// The levels joined by `-`, up to the first one that is `*` or
828    /// missing; an empty string without a first level.
829    pub(crate) fn levels_of<M: Morpheme>(&self, morpheme: &M, levels: Range<usize>) -> String {
830        let mut value = String::new();
831        for index in levels {
832            match morpheme.feature(index) {
833                Some(level) if level != EMPTY => {
834                    if !value.is_empty() {
835                        value.push('-');
836                    }
837                    value.push_str(level);
838                }
839                _ => break,
840            }
841        }
842        value
843    }
844
845    /// The number of feature columns the schema reads.
846    ///
847    /// # Returns
848    ///
849    /// One more than the largest index among the columns of the part of
850    /// speech, of the conjugation and of the base form: a morpheme of the
851    /// dictionary has at least this many columns.
852    pub fn width(&self) -> usize {
853        [
854            Some(self.part_of_speech.end),
855            self.conjugation_type.map(|index| index + 1),
856            self.conjugation_form.map(|index| index + 1),
857            self.base_form.map(|index| index + 1),
858        ]
859        .into_iter()
860        .flatten()
861        .max()
862        .unwrap_or(0)
863    }
864
865    /// Checks that morphemes can be of the dictionary of the schema.
866    ///
867    /// A morpheme with fewer feature columns than the schema reads comes
868    /// from another dictionary, or from a tokenizer that drops columns:
869    /// analyzing it would give an answer from columns that are not there.
870    /// Morphemes of another dictionary that are wide enough pass; the name
871    /// of the dictionary in a model file is for those
872    /// ([`Model::check_dictionary`](crate::model::Model::check_dictionary)).
873    ///
874    /// # Arguments
875    ///
876    /// * `morphemes` - The morphemes.
877    ///
878    /// # Returns
879    ///
880    /// `Ok(())`, or [`Error::Dictionary`] for the first morpheme that has
881    /// fewer columns than [`Schema::width`].
882    pub fn check<M: Morpheme>(&self, morphemes: &[M]) -> Result<()> {
883        let width = self.width();
884        let Some(last) = width.checked_sub(1) else {
885            return Ok(());
886        };
887        for (index, morpheme) in morphemes.iter().enumerate() {
888            if morpheme.feature(last).is_none() {
889                return Err(Error::Dictionary(format!(
890                    "the morpheme {} ({:?}) has fewer than the {width} feature columns the schema reads: it is not of the dictionary of the model",
891                    index + 1,
892                    morpheme.surface()
893                )));
894            }
895        }
896        Ok(())
897    }
898
899    /// Appends the schema to the bytes of a model.
900    ///
901    /// The columns, then the function word patterns, the patterns of what
902    /// is not a head, the particles, the function words taken by their
903    /// surface, the symbols, the normalization, the rule of the head, and
904    /// the head word of a bunsetsu without one.
905    ///
906    /// # Arguments
907    ///
908    /// * `bytes` - The bytes to append to.
909    pub(crate) fn write(&self, bytes: &mut Vec<u8>) {
910        let column = |index: Option<usize>| index.map_or(NO_COLUMN, |index| index as u32);
911        push_u32(bytes, self.part_of_speech.start as u32);
912        push_u32(bytes, self.part_of_speech.end as u32);
913        push_u32(bytes, column(self.conjugation_type));
914        push_u32(bytes, column(self.conjugation_form));
915        push_u32(bytes, column(self.base_form));
916        for patterns in [
917            &self.function_words,
918            &self.not_heads,
919            &self.particles,
920            &self.lexicalized,
921        ] {
922            push_u32(bytes, patterns.len() as u32);
923            for pattern in patterns {
924                pattern.write(bytes);
925            }
926        }
927        self.symbols.write(bytes);
928        self.normalization.write(bytes);
929        bytes.push(self.head_rule.code());
930        bytes.push(self.head_fallback.code());
931        bytes.push(self.sentence_split.code());
932    }
933
934    /// Reads a schema from the bytes of a model.
935    ///
936    /// # Arguments
937    ///
938    /// * `reader` - The bytes, at the schema.
939    ///
940    /// # Returns
941    ///
942    /// The schema, or the error of bytes that are not one.
943    pub(crate) fn read(reader: &mut Reader, version: u32) -> Result<Self> {
944        let start = reader.u32()? as usize;
945        let end = reader.u32()? as usize;
946        let mut column = || -> Result<Option<usize>> {
947            let value = reader.u32()?;
948            Ok((value != NO_COLUMN).then_some(value as usize))
949        };
950        let conjugation_type = column()?;
951        let conjugation_form = column()?;
952        let base_form = column()?;
953        let mut patterns = || -> Result<Vec<Pattern>> {
954            let count = reader.u32()?;
955            let mut patterns = Vec::new();
956            for _ in 0..count {
957                patterns.push(Pattern::read(reader, 0)?);
958            }
959            Ok(patterns)
960        };
961        let function_words = patterns()?;
962        let not_heads = patterns()?;
963        let particles = patterns()?;
964        let lexicalized = patterns()?;
965        let symbols = Symbols::read(reader)?;
966        let normalization = Normalization::read(reader)?;
967        let head_rule = HeadRule::from_code(reader.u8()?)?;
968        let (head_fallback, sentence_split) = if version >= HEAD_FALLBACK_VERSION {
969            (
970                HeadFallback::from_code(reader.u8()?)?,
971                SentenceSplit::from_code(reader.u8()?)?,
972            )
973        } else {
974            (HeadFallback::FirstMorpheme, SentenceSplit::None)
975        };
976        Ok(Self {
977            part_of_speech: start..end,
978            conjugation_type,
979            conjugation_form,
980            base_form,
981            function_words,
982            not_heads,
983            particles,
984            lexicalized,
985            symbols,
986            normalization,
987            head_rule,
988            head_fallback,
989            sentence_split,
990        })
991    }
992}
993
994#[cfg(test)]
995mod tests {
996    use super::*;
997    use crate::error::Error;
998    use crate::lattice::LatticeMorpheme;
999
1000    /// Morphemes of `(surface, features)`.
1001    fn morphemes(pairs: &[(&str, &str)]) -> Vec<LatticeMorpheme> {
1002        pairs
1003            .iter()
1004            .map(|(surface, features)| LatticeMorpheme::new(*surface, *features))
1005            .collect()
1006    }
1007
1008    /// The positions the schema of IPADIC gives for a bunsetsu.
1009    fn positions(pairs: &[(&str, &str)]) -> (usize, usize) {
1010        Schema::ipadic().positions(&morphemes(pairs)).unwrap()
1011    }
1012
1013    const HON: (&str, &str) = ("本", "名詞,一般,*,*,*,*,本,ホン,ホン");
1014    const WO: (&str, &str) = ("を", "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ");
1015    const NI: (&str, &str) = ("に", "助詞,格助詞,一般,*,*,*,に,ニ,ニ");
1016    const GA: (&str, &str) = ("が", "助詞,格助詞,一般,*,*,*,が,ガ,ガ");
1017    const YON: (&str, &str) = ("読ん", "動詞,自立,*,*,五段・マ行,連用タ接続,読む,ヨン,ヨン");
1018    const YOMU: (&str, &str) = ("読む", "動詞,自立,*,*,五段・マ行,基本形,読む,ヨム,ヨム");
1019    const DA: (&str, &str) = ("だ", "助動詞,*,*,*,特殊・タ,基本形,だ,ダ,ダ");
1020    const TA: (&str, &str) = ("た", "助動詞,*,*,*,特殊・タ,基本形,た,タ,タ");
1021    const DE: (&str, &str) = ("で", "助詞,接続助詞,*,*,*,*,で,デ,デ");
1022    const IRU: (&str, &str) = ("いる", "動詞,非自立,*,*,一段,基本形,いる,イル,イル");
1023    const MARU: (&str, &str) = ("。", "記号,句点,*,*,*,*,。,。,。");
1024    const TEN: (&str, &str) = ("、", "記号,読点,*,*,*,*,、,、,、");
1025    const KAGI: (&str, &str) = ("「", "記号,括弧開,*,*,*,*,「,「,「");
1026    const KAGI_TOJI: (&str, &str) = ("」", "記号,括弧閉,*,*,*,*,」,」,」");
1027    const RIYOU: (&str, &str) = ("利用", "名詞,サ変接続,*,*,*,*,利用,リヨウ,リヨー");
1028    const SHI: (&str, &str) = ("し", "動詞,自立,*,*,サ変・スル,連用形,する,シ,シ");
1029    const KOTO: (&str, &str) = ("こと", "名詞,非自立,一般,*,*,*,こと,コト,コト");
1030    const KIHON: (&str, &str) = ("基本", "名詞,一般,*,*,*,*,基本,キホン,キホン");
1031    const TEKI: (&str, &str) = ("的", "名詞,接尾,形容動詞語幹,*,*,*,的,テキ,テキ");
1032    /// The half-width comma, an unknown word of IPADIC.
1033    const COMMA: (&str, &str) = (",", "名詞,サ変接続,*,*,*,*,*,*,*");
1034
1035    #[test]
1036    fn ipadic_names_the_columns_of_mecab_ipadic() {
1037        // 読ん: 動詞,自立,*,*,五段・マ行,連用タ接続,読む,ヨン,ヨン
1038        let features = [
1039            "動詞",
1040            "自立",
1041            "*",
1042            "*",
1043            "五段・マ行",
1044            "連用タ接続",
1045            "読む",
1046            "ヨン",
1047            "ヨン",
1048        ];
1049        let schema = Schema::ipadic();
1050        assert_eq!(
1051            features[schema.part_of_speech.clone()],
1052            ["動詞", "自立", "*", "*"]
1053        );
1054        assert_eq!(features[schema.conjugation_type.unwrap()], "五段・マ行");
1055        assert_eq!(features[schema.conjugation_form.unwrap()], "連用タ接続");
1056        assert_eq!(features[schema.base_form.unwrap()], "読む");
1057    }
1058
1059    #[test]
1060    fn a_content_word_and_a_particle_are_the_head_and_the_function_word() {
1061        assert_eq!(positions(&[HON, WO]), (0, 1));
1062        // The last content word and the last function word.
1063        assert_eq!(positions(&[KIHON, HON, NI, WO]), (1, 3));
1064    }
1065
1066    #[test]
1067    fn a_content_word_alone_is_both() {
1068        assert_eq!(positions(&[HON]), (0, 0));
1069        assert_eq!(positions(&[KIHON, HON]), (1, 1));
1070    }
1071
1072    #[test]
1073    fn punctuation_at_the_end_is_neither() {
1074        assert_eq!(positions(&[YON, DA, MARU]), (0, 1));
1075        assert_eq!(positions(&[HON, WO, TEN]), (0, 1));
1076        // By the surface too: the half-width comma is 名詞,サ変接続.
1077        assert_eq!(positions(&[HON, WO, COMMA]), (0, 1));
1078        assert_eq!(positions(&[HON, COMMA]), (0, 0));
1079    }
1080
1081    #[test]
1082    fn a_bunsetsu_of_symbols_only_has_both_at_its_first_morpheme() {
1083        assert_eq!(positions(&[MARU]), (0, 0));
1084        assert_eq!(positions(&[KAGI_TOJI, MARU, COMMA]), (0, 0));
1085    }
1086
1087    #[test]
1088    fn a_bracket_before_the_head_is_skipped() {
1089        assert_eq!(positions(&[KAGI, HON, WO]), (1, 2));
1090    }
1091
1092    #[test]
1093    fn a_dependent_verb_is_the_function_word() {
1094        // 読ん / で / いる
1095        assert_eq!(positions(&[YON, DE, IRU]), (0, 2));
1096        assert_eq!(positions(&[YON, DE, IRU, MARU]), (0, 2));
1097    }
1098
1099    #[test]
1100    fn a_head_after_the_function_word_takes_the_function_word_with_it() {
1101        // に / 本: a particle, then the content word.
1102        assert_eq!(positions(&[NI, HON]), (1, 1));
1103        // The same with a symbol after it.
1104        assert_eq!(positions(&[NI, HON, MARU]), (1, 1));
1105        // A function word after the head is kept.
1106        assert_eq!(positions(&[NI, HON, DA]), (1, 2));
1107    }
1108
1109    #[test]
1110    fn the_function_words_of_cabocha_are_function_words() {
1111        // 読ま / れる (動詞,接尾)
1112        let yoma = ("読ま", "動詞,自立,*,*,五段・マ行,未然形,読む,ヨマ,ヨマ");
1113        let reru = ("れる", "動詞,接尾,*,*,一段,基本形,れる,レル,レル");
1114        assert_eq!(positions(&[yoma, reru]), (0, 1));
1115        // 読み / にくい (形容詞,非自立)
1116        let yomi = ("読み", "動詞,自立,*,*,五段・マ行,連用形,読む,ヨミ,ヨミ");
1117        let nikui = (
1118            "にくい",
1119            "形容詞,非自立,*,*,形容詞・アウオ段,基本形,にくい,ニクイ,ニクイ",
1120        );
1121        assert_eq!(positions(&[yomi, nikui]), (0, 1));
1122        // 本 / っぽい (形容詞,接尾)
1123        let ppoi = (
1124            "っぽい",
1125            "形容詞,接尾,*,*,形容詞・アウオ段,基本形,っぽい,ッポイ,ッポイ",
1126        );
1127        assert_eq!(positions(&[HON, ppoi]), (0, 1));
1128        // Each of the three after a particle: the last one wins.
1129        assert_eq!(positions(&[HON, WO, reru]), (0, 2));
1130        assert_eq!(positions(&[HON, WO, nikui]), (0, 2));
1131        assert_eq!(positions(&[HON, WO, ppoi]), (0, 2));
1132        // 助詞 and 助動詞 alone.
1133        assert_eq!(positions(&[HON, DA]), (0, 1));
1134        assert_eq!(positions(&[HON, WO]), (0, 1));
1135    }
1136
1137    #[test]
1138    fn suru_and_dekiru_are_function_words() {
1139        // 利用 / し / た
1140        assert_eq!(positions(&[RIYOU, SHI, TA]), (0, 2));
1141        assert_eq!(positions(&[RIYOU, SHI]), (0, 1));
1142        // する at the start of a bunsetsu is the head.
1143        assert_eq!(positions(&[SHI, TA]), (0, 1));
1144        assert_eq!(positions(&[SHI]), (0, 0));
1145        // Another verb after a verbal noun is the head.
1146        assert_eq!(positions(&[RIYOU, YON, DA]), (1, 2));
1147        // できる too, in either spelling of its base form.
1148        let dekiru = ("でき", "動詞,自立,*,*,一段,連用形,できる,デキ,デキ");
1149        assert_eq!(positions(&[RIYOU, dekiru, TA]), (0, 2));
1150        let dekiru = ("出来", "動詞,自立,*,*,一段,連用形,出来る,デキ,デキ");
1151        assert_eq!(positions(&[RIYOU, dekiru, TA]), (0, 2));
1152    }
1153
1154    #[test]
1155    fn a_dependent_noun_and_the_suffix_teki_are_not_heads() {
1156        // 読む / こと / が
1157        assert_eq!(positions(&[YOMU, KOTO, GA]), (0, 2));
1158        // At the start of a bunsetsu it stays the head, as nothing else is.
1159        assert_eq!(positions(&[KOTO, GA]), (0, 1));
1160        // 基本 / 的 / に
1161        assert_eq!(positions(&[KIHON, TEKI, NI]), (0, 2));
1162        // 長 / さ / は: the suffix さ (名詞,接尾,特殊).
1163        let naga = (
1164            "長",
1165            "形容詞,自立,*,*,形容詞・アウオ段,ガル接続,長い,ナガ,ナガ",
1166        );
1167        let sa = ("さ", "名詞,接尾,特殊,*,*,*,さ,サ,サ");
1168        assert_eq!(positions(&[naga, sa, GA]), (0, 2));
1169        // Another suffix is a head: 本 / 人 (名詞,接尾,助数詞).
1170        let nin = ("人", "名詞,接尾,助数詞,*,*,*,人,ニン,ニン");
1171        assert_eq!(positions(&[HON, nin, GA]), (1, 2));
1172    }
1173
1174    #[test]
1175    fn a_verb_after_a_particle_is_part_of_a_compound_function_word() {
1176        let naru = ("なっ", "動詞,自立,*,*,五段・ラ行,連用タ接続,なる,ナッ,ナッ");
1177        // 読む / こと / に / なっ / た
1178        assert_eq!(positions(&[YOMU, KOTO, NI, naru, TA]), (0, 4));
1179        // 本 / に / なっ / た: the same in a shorter bunsetsu.
1180        assert_eq!(positions(&[HON, NI, naru, TA]), (0, 3));
1181        // A verb after a noun is the head.
1182        assert_eq!(positions(&[HON, naru, TA]), (1, 2));
1183        // At the start of a bunsetsu too.
1184        assert_eq!(positions(&[naru, TA]), (0, 1));
1185    }
1186
1187    #[test]
1188    fn no_morpheme_has_no_positions() {
1189        let none: [LatticeMorpheme; 0] = [];
1190        assert_eq!(Schema::ipadic().positions(&none), None);
1191    }
1192
1193    #[test]
1194    fn morphemes_with_fewer_columns_do_not_panic() {
1195        // No column, one column, and the columns up to the part of speech.
1196        assert_eq!(positions(&[("x", ""), ("y", "")]), (1, 1));
1197        assert_eq!(positions(&[("本", "名詞"), ("を", "助詞")]), (0, 1));
1198        assert_eq!(
1199            positions(&[("利用", "名詞,サ変接続"), ("し", "動詞,自立")]),
1200            (1, 1)
1201        );
1202        let schema = Schema::ipadic();
1203        let bare = LatticeMorpheme::new("x", "");
1204        assert!(!schema.is_symbol(&bare));
1205        assert_eq!(schema.part_of_speech_of(&bare), "");
1206        // A symbol by its surface needs no column.
1207        assert!(schema.is_comma(&LatticeMorpheme::new(",", "")));
1208    }
1209
1210    #[test]
1211    fn a_schema_without_patterns_takes_the_last_morpheme() {
1212        // Every morpheme is a head, none a function word.
1213        let schema = Schema {
1214            part_of_speech: 0..4,
1215            ..Schema::default()
1216        };
1217        assert_eq!(schema.positions(&morphemes(&[HON, WO, MARU])), Some((2, 2)));
1218    }
1219
1220    #[test]
1221    fn punctuation_and_brackets_are_recognized_by_part_of_speech_and_by_surface() {
1222        let schema = Schema::ipadic();
1223        let unknown = |surface: &str| LatticeMorpheme::new(surface, "名詞,サ変接続,*,*,*,*,*,*,*");
1224        let known = |pair: (&str, &str)| LatticeMorpheme::new(pair.0, pair.1);
1225
1226        assert!(schema.is_comma(&known(TEN)));
1227        assert!(schema.is_period(&known(MARU)));
1228        assert!(schema.is_open_bracket(&known(KAGI)));
1229        assert!(schema.is_close_bracket(&known(KAGI_TOJI)));
1230        for surface in [",", ",", "、"] {
1231            assert!(schema.is_comma(&unknown(surface)), "{surface}");
1232            assert!(!schema.is_period(&unknown(surface)), "{surface}");
1233        }
1234        for surface in [".", ".", "。"] {
1235            assert!(schema.is_period(&unknown(surface)), "{surface}");
1236            assert!(!schema.is_comma(&unknown(surface)), "{surface}");
1237        }
1238        for surface in ["(", "(", "[", "「", "『", "“"] {
1239            assert!(schema.is_open_bracket(&unknown(surface)), "{surface}");
1240            assert!(!schema.is_close_bracket(&unknown(surface)), "{surface}");
1241        }
1242        for surface in [")", ")", "]", "」", "』", "”"] {
1243            assert!(schema.is_close_bracket(&unknown(surface)), "{surface}");
1244            assert!(!schema.is_open_bracket(&unknown(surface)), "{surface}");
1245        }
1246        // Each of them is a symbol, and so are the other marks.
1247        for surface in [
1248            ",", "。", "(", "」", "!", "?", "-", "/", "・", "…", ",“", "!?",
1249        ] {
1250            assert!(schema.is_symbol(&unknown(surface)), "{surface}");
1251        }
1252        // By the part of speech alone: the half-width forms of 、 。 「 」
1253        // are in no list of characters.
1254        let comma = LatticeMorpheme::new("、", "記号,読点,*,*,*,*,、,、,、");
1255        let period = LatticeMorpheme::new("。", "記号,句点,*,*,*,*,。,。,。");
1256        let open = LatticeMorpheme::new("「", "記号,括弧開,*,*,*,*,「,「,「");
1257        let close = LatticeMorpheme::new("」", "記号,括弧閉,*,*,*,*,」,」,」");
1258        assert!(schema.is_comma(&comma) && !schema.is_period(&comma));
1259        assert!(schema.is_period(&period) && !schema.is_comma(&period));
1260        assert!(schema.is_open_bracket(&open) && !schema.is_close_bracket(&open));
1261        assert!(schema.is_close_bracket(&close) && !schema.is_open_bracket(&close));
1262        assert!(!schema.is_comma(&unknown("、")));
1263        // The part of speech 記号 alone is a symbol of no finer kind.
1264        let alphabet = LatticeMorpheme::new("A", "記号,アルファベット,*,*,*,*,A,エイ,エイ");
1265        assert!(schema.is_symbol(&alphabet));
1266        assert!(!schema.is_comma(&alphabet) && !schema.is_period(&alphabet));
1267        // A unit, a word and a number are not symbols.
1268        for surface in ["%", "°", "%、", "本", "1", "a"] {
1269            assert!(!schema.is_symbol(&unknown(surface)), "{surface}");
1270        }
1271        assert!(!schema.is_comma(&known(HON)));
1272    }
1273
1274    #[test]
1275    fn the_brackets_come_in_pairs() {
1276        assert_eq!(
1277            OPEN_BRACKETS.chars().count(),
1278            CLOSE_BRACKETS.chars().count()
1279        );
1280        // No character is of two kinds.
1281        let all = [
1282            COMMAS,
1283            PERIODS,
1284            OPEN_BRACKETS,
1285            CLOSE_BRACKETS,
1286            OTHER_SYMBOLS,
1287        ]
1288        .concat();
1289        let mut characters: Vec<char> = all.chars().collect();
1290        let count = characters.len();
1291        characters.sort_unstable();
1292        characters.dedup();
1293        assert_eq!(characters.len(), count);
1294    }
1295
1296    #[test]
1297    fn the_part_of_speech_is_joined_up_to_the_first_empty_level() {
1298        let schema = Schema::ipadic();
1299        let of =
1300            |pair: (&str, &str)| schema.part_of_speech_of(&LatticeMorpheme::new(pair.0, pair.1));
1301        assert_eq!(of(HON), "名詞-一般");
1302        assert_eq!(of(TEKI), "名詞-接尾-形容動詞語幹");
1303        assert_eq!(of(DA), "助動詞");
1304        assert_eq!(of(("x", "*,名詞")), "");
1305    }
1306
1307    #[test]
1308    fn particles_and_words_taken_by_their_surface_follow_the_patterns() {
1309        let schema = Schema::ipadic();
1310        let bunsetsu = morphemes(&[
1311            (
1312                "ゆっくり",
1313                "副詞,助詞類接続,*,*,*,*,ゆっくり,ユックリ,ユックリ",
1314            ),
1315            ("と", "助詞,格助詞,一般,*,*,*,と,ト,ト"),
1316            ("この", "連体詞,*,*,*,*,*,この,コノ,コノ"),
1317            ("しかし", "接続詞,*,*,*,*,*,しかし,シカシ,シカシ"),
1318            ("本", "名詞,一般,*,*,*,*,本,ホン,ホン"),
1319        ]);
1320        // The last index is past the bunsetsu.
1321        let particles: Vec<bool> = (0..6)
1322            .map(|index| schema.is_particle(&bunsetsu, index))
1323            .collect();
1324        assert_eq!(particles, [false, true, false, false, false, false]);
1325        let lexicalized: Vec<bool> = (0..6)
1326            .map(|index| schema.is_lexicalized(&bunsetsu, index))
1327            .collect();
1328        assert_eq!(lexicalized, [true, true, true, true, false, false]);
1329    }
1330
1331    #[test]
1332    fn unidic_is_a_second_schema_of_data_only() {
1333        let schema = Schema::unidic();
1334        // 思っ / て / いる: いる (非自立可能) is a function word.
1335        let omotte_iru = morphemes(&[
1336            (
1337                "思っ",
1338                "動詞,一般,*,*,五段-ワア行,連用形-促音便,オモウ,思う",
1339            ),
1340            ("て", "助詞,接続助詞,*,*,*,*,テ,て"),
1341            (
1342                "いる",
1343                "動詞,非自立可能,*,*,上一段-ア行,終止形-一般,イル,居る",
1344            ),
1345        ]);
1346        assert_eq!(schema.positions(&omotte_iru), Some((0, 2)));
1347
1348        // 事故 / に / よっ / て: よっ after に is not the head.
1349        let ni_yotte = morphemes(&[
1350            ("事故", "名詞,普通名詞,一般,*,*,*,ジコ,事故"),
1351            ("に", "助詞,格助詞,*,*,*,*,ニ,に"),
1352            ("よっ", "動詞,一般,*,*,五段-ラ行,連用形-促音便,ヨル,因る"),
1353            ("て", "助詞,接続助詞,*,*,*,*,テ,て"),
1354        ]);
1355        assert_eq!(schema.positions(&ni_yotte), Some((0, 3)));
1356
1357        // 本 / が / 読む is not such a verb: が is not に, と or を.
1358        let ga_yomu = morphemes(&[
1359            ("本", "名詞,普通名詞,一般,*,*,*,ホン,本"),
1360            ("が", "助詞,格助詞,*,*,*,*,ガ,が"),
1361            ("読む", "動詞,一般,*,*,五段-マ行,終止形-一般,ヨム,読む"),
1362        ]);
1363        assert_eq!(schema.positions(&ga_yomu), Some((2, 2)));
1364
1365        // 。 is 補助記号,句点.
1366        let period = LatticeMorpheme::new("。", "補助記号,句点,*,*,*,*,,。");
1367        assert!(schema.is_period(&period) && schema.is_symbol(&period));
1368        // The schema of IPADIC does not know these parts of speech.
1369        assert_eq!(Schema::ipadic().positions(&omotte_iru), Some((2, 2)));
1370    }
1371
1372    const SURU_UNIDIC: (&str, &str) =
1373        ("する", "動詞,非自立可能,*,*,サ行変格,連体形-一般,スル,為る");
1374    const TA_UNIDIC: (&str, &str) = ("た", "助動詞,*,*,*,助動詞-タ,連体形-一般,タ,た");
1375    const NI_UNIDIC: (&str, &str) = ("に", "助詞,格助詞,*,*,*,*,ニ,に");
1376    const TSUKAU_UNIDIC: (&str, &str) =
1377        ("使う", "動詞,一般,*,*,五段-ワア行,連体形-一般,ツカウ,使う");
1378
1379    #[test]
1380    fn unidic_does_not_take_an_auxiliary_stem_as_the_head() {
1381        let schema = Schema::unidic();
1382        // 使う / よう / に: よう is 形状詞,助動詞語幹.
1383        let you = morphemes(&[
1384            TSUKAU_UNIDIC,
1385            ("よう", "形状詞,助動詞語幹,*,*,*,*,ヨウ,様"),
1386            ("に", "助動詞,*,*,*,助動詞-ダ,連用形-ニ,ダ,だ"),
1387        ]);
1388        assert_eq!(schema.positions(&you), Some((0, 2)));
1389        // 働い / た / そう / だ: そう of hearsay is 名詞,助動詞語幹.
1390        let sou = morphemes(&[
1391            (
1392                "働い",
1393                "動詞,一般,*,*,五段-カ行,連用形-イ音便,ハタラク,働く",
1394            ),
1395            TA_UNIDIC,
1396            ("そう", "名詞,助動詞語幹,*,*,*,*,ソウ,そう-伝聞"),
1397            ("だ", "助動詞,*,*,*,助動詞-ダ,終止形-一般,ダ,だ"),
1398        ]);
1399        assert_eq!(schema.positions(&sou), Some((0, 3)));
1400    }
1401
1402    #[test]
1403    fn unidic_does_not_take_a_formal_noun_after_a_predicate_as_the_head() {
1404        let schema = Schema::unidic();
1405        let koto = ("こと", "名詞,普通名詞,一般,*,*,*,コト,事");
1406        let tame = ("ため", "名詞,普通名詞,副詞可能,*,*,*,タメ,為");
1407        let kounyuu = ("購入", "名詞,普通名詞,サ変可能,*,*,*,コウニュウ,購入");
1408        // 購入 / する / こと / に: after a verb.
1409        let after_verb = morphemes(&[kounyuu, SURU_UNIDIC, koto, NI_UNIDIC]);
1410        assert_eq!(schema.positions(&after_verb), Some((0, 3)));
1411        // 購入 / する / た / ため / に: after an auxiliary.
1412        let after_auxiliary = morphemes(&[kounyuu, SURU_UNIDIC, TA_UNIDIC, tame, NI_UNIDIC]);
1413        assert_eq!(schema.positions(&after_auxiliary), Some((0, 4)));
1414        // 新しい / こと / に: after an adjective.
1415        let after_adjective = morphemes(&[
1416            (
1417                "新しい",
1418                "形容詞,一般,*,*,形容詞,連体形-一般,アタラシイ,新しい",
1419            ),
1420            koto,
1421            NI_UNIDIC,
1422        ]);
1423        assert_eq!(schema.positions(&after_adjective), Some((0, 2)));
1424        // こと / に, and 購入 / こと / に: not after one of them.
1425        assert_eq!(
1426            schema.positions(&morphemes(&[koto, NI_UNIDIC])),
1427            Some((0, 1))
1428        );
1429        assert_eq!(
1430            schema.positions(&morphemes(&[kounyuu, koto, NI_UNIDIC])),
1431            Some((1, 2))
1432        );
1433        // 使う / 人 / に: 人 is not a formal noun.
1434        let hito = morphemes(&[
1435            TSUKAU_UNIDIC,
1436            ("人", "名詞,普通名詞,一般,*,*,*,ヒト,人"),
1437            NI_UNIDIC,
1438        ]);
1439        assert_eq!(schema.positions(&hito), Some((1, 2)));
1440    }
1441
1442    #[test]
1443    fn unidic_does_not_take_a_nominal_suffix_after_an_adjective_as_the_head() {
1444        let schema = Schema::unidic();
1445        // 大き / さ / に.
1446        let ookisa = morphemes(&[
1447            ("大き", "形容詞,一般,*,*,形容詞,語幹-一般,オオキイ,大きい"),
1448            ("さ", "接尾辞,名詞的,一般,*,*,*,サ,さ"),
1449            NI_UNIDIC,
1450        ]);
1451        assert_eq!(schema.positions(&ookisa), Some((0, 2)));
1452        // 市 / 長 / に: after a noun the suffix is the head.
1453        let shichou = morphemes(&[
1454            ("市", "名詞,普通名詞,一般,*,*,*,シ,市"),
1455            ("長", "接尾辞,名詞的,一般,*,*,*,チョウ,長"),
1456            NI_UNIDIC,
1457        ]);
1458        assert_eq!(schema.positions(&shichou), Some((1, 2)));
1459    }
1460
1461    #[test]
1462    fn unidic_takes_a_letter_as_a_symbol() {
1463        let schema = Schema::unidic();
1464        // 5 / k / m: the letters are 記号,文字.
1465        let kilometers = morphemes(&[
1466            ("5", "名詞,数詞,*,*,*,*,ゴ,五"),
1467            ("k", "記号,文字,*,*,*,*,ケー,K"),
1468            ("m", "記号,文字,*,*,*,*,エム,M"),
1469        ]);
1470        assert!(schema.is_symbol(&kilometers[1]));
1471        assert_eq!(schema.positions(&kilometers), Some((0, 0)));
1472    }
1473
1474    #[test]
1475    fn a_schema_is_chosen_by_the_name_of_the_dictionary() {
1476        assert_eq!(Schema::for_dictionary("ipadic"), Some(Schema::ipadic()));
1477        for name in ["unidic", "unidic-cwj", "unidic-csj"] {
1478            assert_eq!(Schema::for_dictionary(name), Some(Schema::unidic()));
1479        }
1480        // Every name of the list has a schema, and no other name has.
1481        for name in Schema::DICTIONARIES {
1482            assert!(Schema::for_dictionary(name).is_some(), "{name}");
1483        }
1484        for name in ["", "IPADIC", "ipadic-neologd", "ko-dic", "unidic-"] {
1485            assert_eq!(Schema::for_dictionary(name), None, "{name}");
1486        }
1487    }
1488
1489    /// A schema with the rule of the last words: two levels of the part
1490    /// of speech, 特殊 as the symbols, and 助詞 and 接尾辞 as what is not a
1491    /// head. The rule CaboCha has for JUMAN.
1492    fn last_words() -> Schema {
1493        Schema {
1494            part_of_speech: 0..2,
1495            not_heads: vec![Pattern::new(&["助詞"]), Pattern::new(&["接尾辞"])],
1496            symbols: Symbols {
1497                others: Marks::new(&[&["特殊"]], ""),
1498                surface: SurfaceRule::OneCharacter,
1499                ..Symbols::default()
1500            },
1501            head_rule: HeadRule::LastWords,
1502            ..Schema::default()
1503        }
1504    }
1505
1506    #[test]
1507    fn with_the_rule_of_the_last_words_the_two_positions_are_found_apart() {
1508        const NOUN: (&str, &str) = ("本", "名詞,普通名詞,*,*,本,ほん,*");
1509        const PARTICLE: (&str, &str) = ("を", "助詞,格助詞,*,*,を,を,*");
1510        const VERB: (&str, &str) = ("読んで", "動詞,*,子音動詞マ行,タ系連用テ形,読む,よんで,*");
1511        const SUFFIX: (&str, &str) = ("いる", "接尾辞,動詞性接尾辞,母音動詞,基本形,いる,いる,*");
1512        const PERIOD: (&str, &str) = ("。", "特殊,句点,*,*,。,。,*");
1513        const BRACKET: (&str, &str) = ("「", "特殊,括弧始,*,*,「,「,*");
1514        let schema = last_words();
1515        let positions = |pairs: &[(&str, &str)]| schema.positions(&morphemes(pairs)).unwrap();
1516        // One word is the head and the function word.
1517        assert_eq!(positions(&[NOUN]), (0, 0));
1518        // A particle and a suffix are function words, and not heads.
1519        assert_eq!(positions(&[NOUN, PARTICLE]), (0, 1));
1520        assert_eq!(positions(&[VERB, SUFFIX]), (0, 1));
1521        assert_eq!(positions(&[VERB, SUFFIX, PARTICLE]), (0, 2));
1522        // The last word that is not a symbol is the function word, a head
1523        // or not: nothing is moved to it, and it is moved to nothing.
1524        assert_eq!(positions(&[NOUN, PARTICLE, NOUN]), (2, 2));
1525        assert_eq!(positions(&[SUFFIX, NOUN, PARTICLE, PARTICLE]), (1, 3));
1526        // A symbol is neither.
1527        assert_eq!(positions(&[VERB, SUFFIX, PERIOD]), (0, 1));
1528        assert_eq!(positions(&[BRACKET, NOUN, PERIOD]), (1, 1));
1529        // Without a word that can be one, each stays at the first morpheme.
1530        assert_eq!(positions(&[PERIOD]), (0, 0));
1531        assert_eq!(positions(&[BRACKET, PERIOD]), (0, 0));
1532        assert_eq!(positions(&[PARTICLE]), (0, 0));
1533        assert_eq!(positions(&[BRACKET, PARTICLE]), (0, 1));
1534        assert_eq!(schema.positions::<LatticeMorpheme>(&[]), None);
1535
1536        // The patterns of the function words are not read by this rule.
1537        let with_patterns = Schema {
1538            function_words: vec![Pattern::new(&["名詞"])],
1539            ..last_words()
1540        };
1541        assert_eq!(
1542            with_patterns.positions(&morphemes(&[NOUN, PARTICLE])),
1543            Some((0, 1))
1544        );
1545        // The other rule, with the same patterns, has no function word
1546        // here: both positions are at the head.
1547        let apart = Schema {
1548            head_rule: HeadRule::FunctionWordsApart,
1549            ..last_words()
1550        };
1551        assert_eq!(apart.positions(&morphemes(&[NOUN, PARTICLE])), Some((0, 0)));
1552        assert_eq!(apart.positions(&morphemes(&[VERB, SUFFIX])), Some((0, 0)));
1553    }
1554
1555    #[test]
1556    fn the_rule_of_the_head_comes_back_from_the_bytes() {
1557        assert_eq!(Schema::default().head_rule, HeadRule::FunctionWordsApart);
1558        assert_eq!(Schema::ipadic().head_rule, HeadRule::FunctionWordsApart);
1559        assert_eq!(Schema::unidic().head_rule, HeadRule::FunctionWordsApart);
1560        for (rule, code) in HeadRule::ALL {
1561            assert_eq!(rule.code(), code);
1562            assert_eq!(HeadRule::from_code(code).unwrap(), rule);
1563            let schema = Schema {
1564                head_rule: rule,
1565                ..last_words()
1566            };
1567            let mut bytes = Vec::new();
1568            schema.write(&mut bytes);
1569            // The rule is the third byte from the end of a schema.
1570            assert_eq!(bytes[bytes.len() - 3], code);
1571            let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
1572            assert_eq!(
1573                Schema::read(&mut reader, crate::model::VERSION).unwrap(),
1574                schema
1575            );
1576            assert_eq!(reader.remaining(), 0);
1577        }
1578        // A byte that is not a rule is refused.
1579        let mut bytes = Vec::new();
1580        last_words().write(&mut bytes);
1581        let rule = bytes.len() - 3;
1582        bytes[rule] = 2;
1583        let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
1584        assert_eq!(
1585            Schema::read(&mut reader, crate::model::VERSION)
1586                .unwrap_err()
1587                .to_string(),
1588            "2 is not the code of a rule of the head"
1589        );
1590    }
1591
1592    #[test]
1593    fn a_schema_comes_back_from_its_bytes() {
1594        for schema in [Schema::ipadic(), Schema::unidic(), Schema::default()] {
1595            let mut bytes = Vec::new();
1596            schema.write(&mut bytes);
1597            let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
1598            assert_eq!(
1599                Schema::read(&mut reader, crate::model::VERSION).unwrap(),
1600                schema
1601            );
1602            assert_eq!(reader.remaining(), 0);
1603        }
1604    }
1605
1606    #[test]
1607    fn the_two_lists_of_patterns_keep_their_places_in_the_bytes() {
1608        let schema = Schema {
1609            function_words: vec![Pattern::new(&["助詞"])],
1610            not_heads: vec![Pattern::new(&["名詞", "非自立"]), Pattern::default()],
1611            ..Schema::default()
1612        };
1613        let mut bytes = Vec::new();
1614        schema.write(&mut bytes);
1615        let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
1616        let read = Schema::read(&mut reader, crate::model::VERSION).unwrap();
1617        assert_eq!(read.function_words, [Pattern::new(&["助詞"])]);
1618        assert_eq!(read.not_heads.len(), 2);
1619    }
1620
1621    #[test]
1622    fn bytes_that_end_inside_a_schema_are_an_error() {
1623        let mut bytes = Vec::new();
1624        Schema::ipadic().write(&mut bytes);
1625        for length in [0, 4, 20, 24, bytes.len() / 2, bytes.len() - 1] {
1626            let mut reader = Reader::new(&bytes[..length], "test bytes", Error::Chunker);
1627            let message = Schema::read(&mut reader, crate::model::VERSION)
1628                .unwrap_err()
1629                .to_string();
1630            assert!(message.contains("ends early"), "{length}: {message}");
1631        }
1632    }
1633
1634    #[test]
1635    fn the_width_is_the_number_of_columns_the_schema_reads() {
1636        // IPADIC: four levels of part of speech, the conjugation type and
1637        // form, the base form.
1638        assert_eq!(Schema::ipadic().width(), 7);
1639        let mut schema = Schema::ipadic();
1640        schema.base_form = None;
1641        assert_eq!(schema.width(), 6);
1642        schema.conjugation_form = None;
1643        schema.conjugation_type = Some(9);
1644        assert_eq!(schema.width(), 10);
1645        schema.conjugation_type = None;
1646        assert_eq!(schema.width(), 4);
1647        schema.part_of_speech = 0..0;
1648        assert_eq!(schema.width(), 0);
1649    }
1650
1651    #[test]
1652    fn morphemes_with_fewer_columns_than_the_schema_reads_are_refused() {
1653        let schema = Schema::ipadic();
1654        let wide = LatticeMorpheme::new("彼", "名詞,代名詞,一般,*,*,*,彼,カレ,カレ");
1655        // An unknown word of MeCab has no reading: seven columns.
1656        let unknown = LatticeMorpheme::new("x", "名詞,一般,*,*,*,*,*");
1657        let narrow = LatticeMorpheme::new("彼", "名詞,代名詞,一般,*,*,*");
1658        let none: [LatticeMorpheme; 0] = [];
1659        assert!(schema.check(&none).is_ok());
1660        assert!(schema.check(&[wide.clone(), unknown.clone()]).is_ok());
1661
1662        let error = schema.check(&[wide.clone(), unknown, narrow]).unwrap_err();
1663        assert!(matches!(error, Error::Dictionary(_)), "{error:?}");
1664        assert_eq!(
1665            error.to_string(),
1666            "the morpheme 3 (\"彼\") has fewer than the 7 feature columns the schema reads: it is not of the dictionary of the model"
1667        );
1668
1669        // A schema that reads nothing refuses nothing.
1670        let mut schema = Schema::ipadic();
1671        schema.part_of_speech = 0..0;
1672        schema.conjugation_type = None;
1673        schema.conjugation_form = None;
1674        schema.base_form = None;
1675        assert!(schema.check(&[LatticeMorpheme::new("彼", "")]).is_ok());
1676    }
1677
1678    /// する, alone in brackets before a particle: a function word of the
1679    /// schema of IPADIC, so the bunsetsu has no morpheme that can be the
1680    /// head word.
1681    const SURU: (&str, &str) = ("する", "動詞,自立,*,*,サ変・スル,基本形,する,スル,スル");
1682    const TO: (&str, &str) = ("と", "助詞,格助詞,引用,*,*,*,と,ト,ト");
1683    /// A full-width space, as IPADIC gives it.
1684    const SPACE: (&str, &str) = ("\u{3000}", "記号,空白,*,*,*,*,\u{3000},\u{3000},\u{3000}");
1685
1686    /// A morpheme of UniDic, from its surface, the levels of its part of
1687    /// speech and its lemma.
1688    fn unidic(surface: &'static str, part_of_speech: &str, lemma: &str) -> LatticeMorpheme {
1689        let levels: Vec<&str> = part_of_speech.split(',').collect();
1690        let mut columns = vec!["*"; 17];
1691        columns[..levels.len()].copy_from_slice(&levels);
1692        columns[7] = lemma;
1693        LatticeMorpheme::new(surface, columns.join(","))
1694    }
1695
1696    #[test]
1697    fn the_schemas_of_this_crate_take_the_first_word() {
1698        assert_eq!(Schema::ipadic().head_fallback, HeadFallback::FirstWord);
1699        assert_eq!(Schema::unidic().head_fallback, HeadFallback::FirstWord);
1700        assert_eq!(Schema::default().head_fallback, HeadFallback::FirstMorpheme);
1701    }
1702
1703    /// The schema of a model converted from CaboCha's: the `cabocha` module
1704    /// is behind the `train` feature.
1705    #[cfg(feature = "train")]
1706    #[test]
1707    fn the_schemas_of_cabocha_take_the_first_morpheme() {
1708        use crate::cabocha::{self, PartOfSpeechSet};
1709
1710        for set in [
1711            PartOfSpeechSet::Ipa,
1712            PartOfSpeechSet::Juman,
1713            PartOfSpeechSet::Unidic,
1714        ] {
1715            assert_eq!(
1716                cabocha::schema(set).head_fallback,
1717                HeadFallback::FirstMorpheme,
1718                "{set:?}"
1719            );
1720        }
1721    }
1722
1723    #[test]
1724    fn a_bunsetsu_without_a_head_word_has_its_first_word_as_the_head() {
1725        // 「 / する / 」 / と: the bracket is no word.
1726        assert_eq!(positions(&[KAGI, SURU, KAGI_TOJI, TO]), (1, 3));
1727        // する at the start is the head as before: it is the first word.
1728        assert_eq!(positions(&[SURU, TO]), (0, 1));
1729        // Brackets and a particle alone: there is no word, and the first
1730        // morpheme is taken.
1731        assert_eq!(positions(&[KAGI, KAGI_TOJI, TO]), (0, 2));
1732        // A bunsetsu with a head word is as it was.
1733        assert_eq!(positions(&[KAGI, HON, KAGI_TOJI, WO]), (1, 3));
1734
1735        // With the first morpheme, as CaboCha: the bracket.
1736        let first_morpheme = Schema {
1737            head_fallback: HeadFallback::FirstMorpheme,
1738            ..Schema::ipadic()
1739        };
1740        assert_eq!(
1741            first_morpheme.positions(&morphemes(&[KAGI, SURU, KAGI_TOJI, TO])),
1742            Some((0, 3))
1743        );
1744    }
1745
1746    #[test]
1747    fn a_word_in_letters_keeps_its_first_letter_and_a_mark_before_a_verb_is_passed_over() {
1748        let schema = Schema::unidic();
1749        let open = unidic("「", "補助記号,括弧開", "「");
1750        let close = unidic("」", "補助記号,括弧閉", "」");
1751        let to = unidic("と", "助詞,格助詞", "と");
1752        let no = unidic("の", "助詞,格助詞", "の");
1753        // 治す is 動詞,非自立可能 in UniDic: a function word of the schema.
1754        let naosu = unidic("治す", "動詞,非自立可能", "直す");
1755        let letter = |surface| unidic(surface, "記号,文字", surface);
1756
1757        // 「 / 治す / 」 / と
1758        assert_eq!(
1759            schema.positions(&[open.clone(), naosu, close.clone(), to.clone()]),
1760            Some((1, 3))
1761        );
1762        // S / i / r / i / の: UniDic cuts the word into letters, which it
1763        // calls symbols, and the first one stays the head word.
1764        assert_eq!(
1765            schema.positions(&[
1766                letter("S"),
1767                letter("i"),
1768                letter("r"),
1769                letter("i"),
1770                no.clone()
1771            ]),
1772            Some((0, 4))
1773        );
1774        // 「 / S / M / T / 」 / と: the first letter, and not the bracket.
1775        assert_eq!(
1776            schema.positions(&[open, letter("S"), letter("M"), letter("T"), close, to]),
1777            Some((1, 5))
1778        );
1779        // ♂ / の: a mark and a particle. The particle is not taken.
1780        assert_eq!(
1781            schema.positions(&[unidic("♂", "補助記号,一般", "♂"), no]),
1782            Some((0, 1))
1783        );
1784    }
1785
1786    #[test]
1787    fn a_space_is_neither_the_head_word_nor_the_function_word() {
1788        // A space before する, which is a function word: する is the head.
1789        assert_eq!(positions(&[SPACE, SURU]), (1, 1));
1790        // Between a noun and its particle, and after them.
1791        assert_eq!(positions(&[HON, SPACE, WO]), (0, 2));
1792        assert_eq!(positions(&[HON, WO, SPACE]), (0, 1));
1793        // Spaces alone: there is no word.
1794        assert_eq!(positions(&[SPACE, SPACE]), (0, 0));
1795        // A space is told by its surface, whatever part of speech the
1796        // dictionary gives it: one that is a noun there is no head word.
1797        const NOUN_SPACE: (&str, &str) = (" ", "名詞,一般,*,*,*,*,*,*,*");
1798        assert_eq!(positions(&[NOUN_SPACE, HON, WO]), (1, 2));
1799        assert_eq!(positions(&[HON, NOUN_SPACE, WO]), (0, 2));
1800        assert_eq!(positions(&[HON, WO, NOUN_SPACE]), (0, 1));
1801        // A space and marks alone: the first mark, and not the space.
1802        assert_eq!(positions(&[SPACE, KAGI, KAGI_TOJI]), (1, 1));
1803
1804        // UniDic gives a space the part of speech 空白, and 治す is a
1805        // function word there.
1806        let space = unidic("\u{3000}", "空白", "\u{3000}");
1807        let naosu = unidic("治す", "動詞,非自立可能", "直す");
1808        assert_eq!(Schema::unidic().positions(&[space, naosu]), Some((1, 1)));
1809
1810        // With the first morpheme, the space is passed over too: by the
1811        // rule, and when the rule finds no head word.
1812        let first_morpheme = Schema {
1813            head_fallback: HeadFallback::FirstMorpheme,
1814            ..Schema::ipadic()
1815        };
1816        assert_eq!(
1817            first_morpheme.positions(&morphemes(&[SPACE, HON, WO])),
1818            Some((1, 2))
1819        );
1820        assert_eq!(
1821            first_morpheme.positions(&morphemes(&[SPACE, SURU])),
1822            Some((1, 1))
1823        );
1824        assert_eq!(
1825            first_morpheme.positions(&morphemes(&[SPACE, KAGI, SURU])),
1826            Some((1, 2))
1827        );
1828    }
1829
1830    #[test]
1831    fn the_head_word_of_a_bunsetsu_without_one_comes_back_from_the_bytes() {
1832        for (fallback, code) in HeadFallback::ALL {
1833            assert_eq!(fallback.code(), code);
1834            assert_eq!(HeadFallback::from_code(code).unwrap(), fallback);
1835            let schema = Schema {
1836                head_fallback: fallback,
1837                ..last_words()
1838            };
1839            let mut bytes = Vec::new();
1840            schema.write(&mut bytes);
1841            // It is the byte before the last of a schema.
1842            assert_eq!(bytes[bytes.len() - 2], code);
1843            let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
1844            assert_eq!(
1845                Schema::read(&mut reader, crate::model::VERSION).unwrap(),
1846                schema
1847            );
1848            assert_eq!(reader.remaining(), 0);
1849        }
1850        // A byte that is not one is refused.
1851        let mut bytes = Vec::new();
1852        last_words().write(&mut bytes);
1853        let fallback = bytes.len() - 2;
1854        bytes[fallback] = 2;
1855        let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
1856        assert_eq!(
1857            Schema::read(&mut reader, crate::model::VERSION)
1858                .unwrap_err()
1859                .to_string(),
1860            "2 is not the code of a head word for a bunsetsu without one"
1861        );
1862    }
1863
1864    #[test]
1865    fn the_schema_of_a_file_of_version_3_ends_with_the_rule_and_takes_the_first_morpheme() {
1866        // What the version 3 wrote: the bytes of today without the last
1867        // two.
1868        let schema = Schema {
1869            head_fallback: HeadFallback::FirstWord,
1870            sentence_split: SentenceSplit::AfterEnds,
1871            ..last_words()
1872        };
1873        let mut bytes = Vec::new();
1874        schema.write(&mut bytes);
1875        bytes.pop();
1876        bytes.pop();
1877        let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
1878        let read = Schema::read(&mut reader, 3).unwrap();
1879        assert_eq!(reader.remaining(), 0);
1880        assert_eq!(
1881            read,
1882            Schema {
1883                head_fallback: HeadFallback::FirstMorpheme,
1884                sentence_split: SentenceSplit::None,
1885                ..schema
1886            }
1887        );
1888        // Read as the version 4, the same bytes end early.
1889        let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
1890        assert!(Schema::read(&mut reader, 4).is_err());
1891    }
1892
1893    const HATENA: (&str, &str) = ("?", "記号,一般,*,*,*,*,?,?,?");
1894
1895    /// The words at which the schema of IPADIC cuts a text.
1896    fn starts(pairs: &[(&str, &str)]) -> Vec<usize> {
1897        Schema::ipadic().sentence_starts(&morphemes(pairs))
1898    }
1899
1900    #[test]
1901    fn the_schemas_of_this_crate_cut_a_text_into_sentences() {
1902        assert_eq!(Schema::ipadic().sentence_split, SentenceSplit::AfterEnds);
1903        assert_eq!(Schema::unidic().sentence_split, SentenceSplit::AfterEnds);
1904        assert_eq!(Schema::default().sentence_split, SentenceSplit::None);
1905    }
1906
1907    /// The schema of a model converted from CaboCha's: the `cabocha` module
1908    /// is behind the `train` feature.
1909    #[cfg(feature = "train")]
1910    #[test]
1911    fn the_schemas_of_cabocha_do_not_cut_a_text() {
1912        use crate::cabocha::{self, PartOfSpeechSet};
1913
1914        for set in [
1915            PartOfSpeechSet::Ipa,
1916            PartOfSpeechSet::Juman,
1917            PartOfSpeechSet::Unidic,
1918        ] {
1919            let schema = cabocha::schema(set);
1920            assert_eq!(schema.sentence_split, SentenceSplit::None, "{set:?}");
1921            assert!(
1922                schema
1923                    .sentence_starts(&morphemes(&[HON, MARU, HON, WO]))
1924                    .is_empty(),
1925                "{set:?}"
1926            );
1927        }
1928    }
1929
1930    #[test]
1931    fn a_text_is_cut_after_its_sentence_ends() {
1932        // 本 / 。 / 本 / を: the word after the period starts a sentence.
1933        assert_eq!(starts(&[HON, MARU, HON, WO]), [2]);
1934        // A sentence of its own has no start but its first word.
1935        assert!(starts(&[HON, WO, YOMU, MARU]).is_empty());
1936        assert!(starts(&[HON, WO, YOMU]).is_empty());
1937        assert!(starts(&[]).is_empty());
1938        // Three sentences, the second one a word alone.
1939        assert_eq!(starts(&[HON, MARU, YOMU, MARU, HON, MARU]), [2, 4]);
1940        // ? and ! end a sentence as 。 does, and ends in a row are one.
1941        assert_eq!(starts(&[HON, HATENA, HON]), [2]);
1942        assert_eq!(starts(&[HON, HATENA, HATENA, MARU, HON]), [4]);
1943        assert_eq!(
1944            starts(&[HON, ("!?", "記号,一般,*,*,*,*,*,*,*"), HON]),
1945            [2]
1946        );
1947        // A comma ends nothing.
1948        assert!(starts(&[HON, TEN, HON]).is_empty());
1949    }
1950
1951    #[test]
1952    fn a_closing_bracket_stays_with_the_sentence_it_closes() {
1953        // 「 / 本 / 。 / 」 / 本: the bracket is of the first sentence.
1954        assert_eq!(starts(&[KAGI, HON, MARU, KAGI_TOJI, HON]), [4]);
1955        // Nothing after the bracket: one sentence.
1956        assert!(starts(&[KAGI, HON, MARU, KAGI_TOJI]).is_empty());
1957        // An opening bracket starts the next sentence.
1958        assert_eq!(starts(&[HON, MARU, KAGI, HON, KAGI_TOJI]), [2]);
1959    }
1960
1961    #[test]
1962    fn a_function_word_after_a_closing_bracket_does_not_start_a_sentence() {
1963        // 「 / 本 / を / 読む / 。 / 」 / と / 読む: と is of the bunsetsu of
1964        // the quotation.
1965        assert!(starts(&[KAGI, HON, WO, YOMU, MARU, KAGI_TOJI, TO, YOMU]).is_empty());
1966        // An auxiliary too: …。 / 」 / だ.
1967        assert!(starts(&[KAGI, HON, MARU, KAGI_TOJI, DA]).is_empty());
1968        // The sentence in the quotation that is not the last one is cut,
1969        // and the function word after the bracket is not.
1970        assert_eq!(
1971            starts(&[KAGI, YOMU, MARU, HON, WO, YOMU, MARU, KAGI_TOJI, TO, YOMU]),
1972            [3]
1973        );
1974        // Without a closing bracket, a function word starts a sentence as
1975        // any word does: 読む / 。 / だ / が (だが).
1976        assert_eq!(starts(&[YOMU, MARU, DA, GA, HON]), [2]);
1977        assert_eq!(starts(&[YOMU, MARU, DE, HON]), [2]);
1978        assert_eq!(starts(&[YOMU, MARU, NI, HON]), [2]);
1979        // A word that is no function word starts one after a bracket.
1980        assert_eq!(starts(&[KAGI, YOMU, MARU, KAGI_TOJI, HON, WO]), [4]);
1981    }
1982
1983    #[test]
1984    fn the_particle_of_a_quotation_does_not_start_a_sentence() {
1985        // 読む / ? / と / 、 / 読む: a quotation without brackets.
1986        assert!(starts(&[YOMU, HATENA, TO, TEN, YOMU]).is_empty());
1987        assert!(starts(&[YOMU, MARU, TO, YOMU]).is_empty());
1988        let tte = ("って", "助詞,格助詞,連語,*,*,*,って,ッテ,ッテ");
1989        assert!(starts(&[YOMU, HATENA, tte, YOMU]).is_empty());
1990        // The sentence before it in the same text is cut.
1991        assert_eq!(starts(&[YOMU, HATENA, HON, HATENA, TO, YOMU]), [2]);
1992        // と that is no particle starts a sentence: by the part of speech,
1993        // and not by the surface alone.
1994        let noun = ("と", "名詞,一般,*,*,*,*,と,ト,ト");
1995        assert_eq!(starts(&[YOMU, MARU, noun, YOMU]), [2]);
1996        // The other particles do: UniDic gives でも as で / も, and
1997        // にもかかわらず as に / も / ….
1998        let schema = Schema::unidic();
1999        let text = [
2000            unidic("本", "名詞,普通名詞", "本"),
2001            unidic("。", "補助記号,句点", "。"),
2002            unidic("で", "助詞,格助詞", "で"),
2003            unidic("も", "助詞,係助詞", "も"),
2004            unidic("本", "名詞,普通名詞", "本"),
2005        ];
2006        assert_eq!(schema.sentence_starts(&text), [2]);
2007        let text = [
2008            unidic("本", "名詞,普通名詞", "本"),
2009            unidic("?", "補助記号,句点", "?"),
2010            unidic("と", "助詞,格助詞", "と"),
2011            unidic("本", "名詞,普通名詞", "本"),
2012        ];
2013        assert!(schema.sentence_starts(&text).is_empty());
2014    }
2015
2016    #[test]
2017    fn a_half_width_period_and_a_period_before_a_digit_end_nothing() {
2018        // IPADIC: 4 / . / 20.
2019        let digits = |surface: &'static str| (surface, "名詞,数,*,*,*,*,*");
2020        assert!(starts(&[digits("4"), (".", "記号,句点,*,*,*,*,.,.,."), digits("20")]).is_empty());
2021        // 3 / . / 14 is a number, and 本 / . / 本 two sentences.
2022        let wide = (".", "記号,句点,*,*,*,*,.,.,.");
2023        assert!(starts(&[digits("3"), wide, digits("14")]).is_empty());
2024        assert_eq!(starts(&[HON, wide, HON]), [2]);
2025        // UniDic calls the half-width period 補助記号,句点: 1 / . / 060 is
2026        // one number, and L / . / E / . / D one word.
2027        let schema = Schema::unidic();
2028        let dot = || unidic(".", "補助記号,句点", ".");
2029        let number = [
2030            unidic("1", "名詞,数詞", "1"),
2031            dot(),
2032            unidic("060", "名詞,数詞", "060"),
2033        ];
2034        assert!(schema.sentence_starts(&number).is_empty());
2035        let letters = [
2036            unidic("L", "記号,文字", "L"),
2037            dot(),
2038            unidic("E", "記号,文字", "E"),
2039            dot(),
2040            unidic("D", "記号,文字", "D"),
2041        ];
2042        assert!(schema.sentence_starts(&letters).is_empty());
2043        // And cuts after 。 as IPADIC does.
2044        let text = [
2045            unidic("本", "名詞,普通名詞", "本"),
2046            unidic("。", "補助記号,句点", "。"),
2047            unidic("本", "名詞,普通名詞", "本"),
2048        ];
2049        assert_eq!(schema.sentence_starts(&text), [2]);
2050    }
2051
2052    #[test]
2053    fn a_schema_that_does_not_cut_gives_no_start() {
2054        let whole = Schema {
2055            sentence_split: SentenceSplit::None,
2056            ..Schema::ipadic()
2057        };
2058        for text in [
2059            &[HON, MARU, HON, WO][..],
2060            &[HON, HATENA, HON],
2061            &[KAGI, HON, MARU, KAGI_TOJI, HON],
2062        ] {
2063            assert!(whole.sentence_starts(&morphemes(text)).is_empty());
2064            assert!(!starts(text).is_empty());
2065        }
2066    }
2067
2068    #[test]
2069    fn the_cut_into_sentences_comes_back_from_the_bytes() {
2070        for (split, code) in SentenceSplit::ALL {
2071            assert_eq!(split.code(), code);
2072            assert_eq!(SentenceSplit::from_code(code).unwrap(), split);
2073            let schema = Schema {
2074                sentence_split: split,
2075                ..last_words()
2076            };
2077            let mut bytes = Vec::new();
2078            schema.write(&mut bytes);
2079            // It is the last byte of a schema.
2080            assert_eq!(bytes.last(), Some(&code));
2081            let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
2082            assert_eq!(
2083                Schema::read(&mut reader, crate::model::VERSION).unwrap(),
2084                schema
2085            );
2086            assert_eq!(reader.remaining(), 0);
2087        }
2088        // A byte that is not one is refused.
2089        let mut bytes = Vec::new();
2090        last_words().write(&mut bytes);
2091        *bytes.last_mut().unwrap() = 2;
2092        let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
2093        assert_eq!(
2094            Schema::read(&mut reader, crate::model::VERSION)
2095                .unwrap_err()
2096                .to_string(),
2097            "2 is not the code of a way to cut a text into sentences"
2098        );
2099    }
2100}