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::{Mark, Morpheme, is_sentence_end, is_space, marks, sentence_end};
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.
90pub(crate) const OPEN_BRACKETS: &str = "(([[{{「『【〔〈《〘〚‘“";
91
92/// The closing brackets, in the order of [`OPEN_BRACKETS`].
93pub(crate) const 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    /// A sentence end that a dictionary joined with other marks is one too,
592    /// and its closing bracket counts as one: IPADIC gives 本当 / ?」 / と,
593    /// and nothing is cut before と.
594    ///
595    /// # Arguments
596    ///
597    /// * `words` - The words of the text: its morphemes without the spaces.
598    ///
599    /// # Returns
600    ///
601    /// The indices of the words that start a sentence, in order, each
602    /// larger than 0: the first word starts one in any case and is not
603    /// listed. Empty with [`SentenceSplit::None`], and for a text of one
604    /// sentence.
605    pub fn sentence_starts<M: Morpheme>(&self, words: &[M]) -> Vec<usize> {
606        self.sentence_parts(words).0
607    }
608
609    /// Where the sentences of a text start ([`Schema::sentence_starts`]),
610    /// and the words that stay with the end of a sentence.
611    ///
612    /// # Arguments
613    ///
614    /// * `words` - The words of the text: its morphemes without the spaces.
615    ///
616    /// # Returns
617    ///
618    /// The indices of the words that start a sentence, and those of the
619    /// sentence ends with the ends and the closing brackets that follow
620    /// them, each in order. Both empty with [`SentenceSplit::None`].
621    pub(crate) fn sentence_parts<M: Morpheme>(&self, words: &[M]) -> (Vec<usize>, Vec<usize>) {
622        let mut starts = Vec::new();
623        let mut tails = Vec::new();
624        if self.sentence_split == SentenceSplit::None {
625            return (starts, tails);
626        }
627        let mut index = 0;
628        while index < words.len() {
629            let Some(mut closed) = sentence_end(&words[index], words.get(index + 1)) else {
630                index += 1;
631                continue;
632            };
633            tails.push(index);
634            index += 1;
635            // What follows and still belongs to the sentence.
636            while index < words.len() {
637                let end = sentence_end(&words[index], words.get(index + 1));
638                let bracket = self.is_close_bracket(&words[index]);
639                if end.is_none() && !bracket {
640                    break;
641                }
642                closed |= bracket || end == Some(true);
643                tails.push(index);
644                index += 1;
645            }
646            if index < words.len()
647                && !self.is_quotation_particle(words, index)
648                && !(closed && self.is_function_word(words, index))
649            {
650                starts.push(index);
651            }
652        }
653        (starts, tails)
654    }
655
656    /// Where the sentences of a text end, for a reader of text: what a
657    /// chunker and a parser are given one at a time.
658    ///
659    /// The models are trained on single sentences. A sentence ends after a
660    /// sentence end ([`is_sentence_end`])
661    /// that is outside brackets, and takes the ends, the closing brackets
662    /// and the spaces that follow it: a quotation is one sentence with the
663    /// sentence around it. A word of marks that a dictionary joined is read
664    /// one mark at a time ([`marks`]), and an
665    /// opening bracket that nothing in the text closes is no bracket.
666    ///
667    /// The token filter `japanese_dependency` and the layer of text of
668    /// `lindera dependency parse` cut their text with it, so that a text is
669    /// analyzed the same way through either. [`Schema::sentence_starts`] is
670    /// another cut, the one a chunker makes inside what it is given: it also
671    /// cuts inside brackets, where a bunsetsu starts after a sentence end
672    /// all the same.
673    ///
674    /// # Arguments
675    ///
676    /// * `morphemes` - The morphemes of the text, with its spaces.
677    ///
678    /// # Returns
679    ///
680    /// The end of each sentence, as the index after its last morpheme; the last
681    /// one is the number of morphemes. Nothing for no morpheme.
682    ///
683    /// # Examples
684    ///
685    /// ```
686    /// use lindera_dependency::Schema;
687    /// use lindera_dependency::lattice::LatticeMorpheme;
688    ///
689    /// let noun = |surface| LatticeMorpheme::new(surface, "名詞,一般,*,*,*,*,*,*,*");
690    /// let mark = |surface, kind| LatticeMorpheme::new(surface, format!("記号,{kind},*,*,*,*,*,*,*"));
691    /// // 本 。 「 本 。 」 本: the second 。 is inside the brackets.
692    /// let text = [
693    ///     noun("本"),
694    ///     mark("。", "句点"),
695    ///     mark("「", "括弧開"),
696    ///     noun("本"),
697    ///     mark("。", "句点"),
698    ///     mark("」", "括弧閉"),
699    ///     noun("本"),
700    /// ];
701    /// assert_eq!(Schema::ipadic().sentence_ends(&text), [2, 7]);
702    /// ```
703    pub fn sentence_ends<M: Morpheme>(&self, morphemes: &[M]) -> Vec<usize> {
704        let read: Vec<Vec<Mark>> = (0..morphemes.len())
705            .map(|index| self.sentence_marks(&morphemes[index], morphemes.get(index + 1)))
706            .collect();
707        // The opening brackets that nothing closes, in order: `:(` and `(泣`
708        // open no bracket, and a sentence ends after them as before them.
709        let mut open = Vec::new();
710        for (index, marks) in read.iter().enumerate() {
711            for (offset, mark) in marks.iter().enumerate() {
712                match mark {
713                    Mark::OpenBracket => open.push((index, offset)),
714                    Mark::CloseBracket => {
715                        open.pop();
716                    }
717                    Mark::SentenceEnd | Mark::Other => {}
718                }
719            }
720        }
721        let mut unclosed = open.into_iter().peekable();
722        let mut depth = 0usize;
723        // Reads the marks of a morpheme, for the brackets it opens and closes,
724        // and tells whether its last mark that is no closing bracket is a
725        // sentence end with no bracket open.
726        let mut step = |index: usize| {
727            let mut ended = false;
728            for (offset, mark) in read[index].iter().enumerate() {
729                match mark {
730                    Mark::SentenceEnd => ended = depth == 0,
731                    Mark::CloseBracket => depth = depth.saturating_sub(1),
732                    Mark::OpenBracket => {
733                        if unclosed.next_if_eq(&(index, offset)).is_none() {
734                            depth += 1;
735                        }
736                        ended = false;
737                    }
738                    Mark::Other => ended = false,
739                }
740            }
741            ended
742        };
743        let mut ends = Vec::new();
744        let mut index = 0;
745        while index < morphemes.len() {
746            let ended = step(index);
747            index += 1;
748            if ended {
749                // What follows and still belongs to the sentence: more ends,
750                // closing brackets, and spaces, which are no start of a
751                // sentence.
752                while morphemes.get(index).is_some_and(|next| {
753                    is_sentence_end(next, morphemes.get(index + 1))
754                        || self.is_close_bracket(next)
755                        || is_space(next)
756                }) {
757                    step(index);
758                    index += 1;
759                }
760                ends.push(index);
761            }
762        }
763        if ends.last().copied().unwrap_or(0) < morphemes.len() {
764            ends.push(morphemes.len());
765        }
766        ends
767    }
768
769    /// The marks of a morpheme, for the sentences of a text.
770    ///
771    /// A dictionary can join marks into one word, as IPADIC does with `)。`
772    /// and `?」`: such a morpheme is read one mark at a time ([`marks`]), so
773    /// that its brackets open and close, and its ends end, as they do when
774    /// they are words of their own.
775    ///
776    /// # Arguments
777    ///
778    /// * `morpheme` - The morpheme.
779    /// * `next` - The morpheme after it, when there is one.
780    ///
781    /// # Returns
782    ///
783    /// One bracket for a bracket of the schema; a sentence end or another mark
784    /// for `.` alone, by what follows it ([`is_sentence_end`]); the marks of
785    /// the surface for another morpheme of marks; nothing for a word.
786    fn sentence_marks<M: Morpheme>(&self, morpheme: &M, next: Option<&M>) -> Vec<Mark> {
787        if self.is_open_bracket(morpheme) {
788            return vec![Mark::OpenBracket];
789        }
790        if self.is_close_bracket(morpheme) {
791            return vec![Mark::CloseBracket];
792        }
793        let surface = morpheme.surface();
794        if surface == "." {
795            return if is_sentence_end(morpheme, next) {
796                vec![Mark::SentenceEnd]
797            } else {
798                vec![Mark::Other]
799            };
800        }
801        marks(surface).map(Iterator::collect).unwrap_or_default()
802    }
803
804    /// Whether a morpheme is a particle that closes a quotation: と or って.
805    ///
806    /// # Arguments
807    ///
808    /// * `morphemes` - The morphemes around it.
809    /// * `index` - Its index among them.
810    ///
811    /// # Returns
812    ///
813    /// Whether it is a particle of the schema with one of the two surfaces.
814    fn is_quotation_particle<M: Morpheme>(&self, morphemes: &[M], index: usize) -> bool {
815        matches!(morphemes[index].surface(), "と" | "って") && self.is_particle(morphemes, index)
816    }
817
818    /// Whether a morpheme matches a function word pattern of the schema.
819    ///
820    /// # Arguments
821    ///
822    /// * `morphemes` - The morphemes around it.
823    /// * `index` - Its index among them.
824    ///
825    /// # Returns
826    ///
827    /// Whether one of [`Schema::function_words`] matches it.
828    fn is_function_word<M: Morpheme>(&self, morphemes: &[M], index: usize) -> bool {
829        self.function_words
830            .iter()
831            .any(|one| one.matches(self, morphemes, index))
832    }
833
834    /// The first morpheme of a bunsetsu that is a word, for
835    /// [`HeadFallback::FirstWord`].
836    ///
837    /// # Arguments
838    ///
839    /// * `bunsetsu` - The morphemes of the bunsetsu.
840    ///
841    /// # Returns
842    ///
843    /// The index of the first morpheme that is not a comma, a period or a
844    /// bracket, not a space, and not a particle; `None` when there is none.
845    fn first_word<M: Morpheme>(&self, bunsetsu: &[M]) -> Option<usize> {
846        bunsetsu.iter().enumerate().position(|(index, morpheme)| {
847            !(is_space(morpheme)
848                || self.is_comma(morpheme)
849                || self.is_period(morpheme)
850                || self.is_open_bracket(morpheme)
851                || self.is_close_bracket(morpheme)
852                || self.is_particle(bunsetsu, index))
853        })
854    }
855
856    /// The surface of a morpheme as the chunker and the parser use it:
857    /// with [`Schema::normalization`] applied.
858    ///
859    /// # Arguments
860    ///
861    /// * `morpheme` - The morpheme.
862    ///
863    /// # Returns
864    ///
865    /// The normalized surface; the surface itself when the schema does not
866    /// normalize, or when no rule matches in it.
867    pub fn surface_of<'a, M: Morpheme>(&self, morpheme: &'a M) -> Cow<'a, str> {
868        self.normalization.apply(morpheme.surface())
869    }
870
871    /// Whether a morpheme of a bunsetsu is a particle: it matches one of
872    /// [`Schema::particles`].
873    ///
874    /// # Arguments
875    ///
876    /// * `bunsetsu` - The morphemes of the bunsetsu.
877    /// * `index` - The index of the morpheme in the bunsetsu.
878    ///
879    /// # Returns
880    ///
881    /// Whether it is a particle; `false` for an index past the bunsetsu.
882    pub fn is_particle<M: Morpheme>(&self, bunsetsu: &[M], index: usize) -> bool {
883        self.particles
884            .iter()
885            .any(|one| one.matches(self, bunsetsu, index))
886    }
887
888    /// Whether a morpheme of a bunsetsu tells by its surface how the
889    /// bunsetsu modifies another: it matches one of
890    /// [`Schema::lexicalized`].
891    ///
892    /// # Arguments
893    ///
894    /// * `bunsetsu` - The morphemes of the bunsetsu.
895    /// * `index` - The index of the morpheme in the bunsetsu.
896    ///
897    /// # Returns
898    ///
899    /// Whether it is such a word; `false` for an index past the bunsetsu.
900    pub fn is_lexicalized<M: Morpheme>(&self, bunsetsu: &[M], index: usize) -> bool {
901        self.lexicalized
902            .iter()
903            .any(|one| one.matches(self, bunsetsu, index))
904    }
905
906    /// Whether a morpheme is a symbol: a comma, a period, a bracket or any
907    /// other one. A symbol is neither the head nor the function word of a
908    /// bunsetsu.
909    ///
910    /// # Arguments
911    ///
912    /// * `morpheme` - The morpheme.
913    ///
914    /// # Returns
915    ///
916    /// Whether its part of speech is one of a symbol, or its surface is
917    /// made of symbol characters only.
918    pub fn is_symbol<M: Morpheme>(&self, morpheme: &M) -> bool {
919        self.symbols.matches(self, morpheme)
920    }
921
922    /// Whether a morpheme is a comma (読点): `、`, or `,` and `,`.
923    ///
924    /// # Arguments
925    ///
926    /// * `morpheme` - The morpheme.
927    ///
928    /// # Returns
929    ///
930    /// Whether its part of speech or its surface is the one of a comma.
931    pub fn is_comma<M: Morpheme>(&self, morpheme: &M) -> bool {
932        self.symbols.commas.matches(self, morpheme)
933    }
934
935    /// Whether a morpheme is a period (句点): `。`, or `.` and `.`.
936    ///
937    /// # Arguments
938    ///
939    /// * `morpheme` - The morpheme.
940    ///
941    /// # Returns
942    ///
943    /// Whether its part of speech or its surface is the one of a period.
944    pub fn is_period<M: Morpheme>(&self, morpheme: &M) -> bool {
945        self.symbols.periods.matches(self, morpheme)
946    }
947
948    /// Whether a morpheme is an opening bracket.
949    ///
950    /// # Arguments
951    ///
952    /// * `morpheme` - The morpheme.
953    ///
954    /// # Returns
955    ///
956    /// Whether its part of speech or its surface is the one of an opening
957    /// bracket.
958    pub fn is_open_bracket<M: Morpheme>(&self, morpheme: &M) -> bool {
959        self.symbols.open_brackets.matches(self, morpheme)
960    }
961
962    /// Whether a morpheme is a closing bracket.
963    ///
964    /// # Arguments
965    ///
966    /// * `morpheme` - The morpheme.
967    ///
968    /// # Returns
969    ///
970    /// Whether its part of speech or its surface is the one of a closing
971    /// bracket.
972    pub fn is_close_bracket<M: Morpheme>(&self, morpheme: &M) -> bool {
973        self.symbols.close_brackets.matches(self, morpheme)
974    }
975
976    /// The part of speech of a morpheme as one string: its levels joined by
977    /// `-`, up to the first one that is `*` or missing, as `名詞-サ変接続`.
978    ///
979    /// # Arguments
980    ///
981    /// * `morpheme` - The morpheme.
982    ///
983    /// # Returns
984    ///
985    /// The part of speech; an empty string without a first level.
986    pub fn part_of_speech_of<M: Morpheme>(&self, morpheme: &M) -> String {
987        self.levels_of(morpheme, self.part_of_speech.clone())
988    }
989
990    /// Some levels of the part of speech of a morpheme as one string.
991    ///
992    /// # Arguments
993    ///
994    /// * `morpheme` - The morpheme.
995    /// * `levels` - The columns of the levels to join.
996    ///
997    /// # Returns
998    ///
999    /// The levels joined by `-`, up to the first one that is `*` or
1000    /// missing; an empty string without a first level.
1001    pub(crate) fn levels_of<M: Morpheme>(&self, morpheme: &M, levels: Range<usize>) -> String {
1002        let mut value = String::new();
1003        for index in levels {
1004            match morpheme.feature(index) {
1005                Some(level) if level != EMPTY => {
1006                    if !value.is_empty() {
1007                        value.push('-');
1008                    }
1009                    value.push_str(level);
1010                }
1011                _ => break,
1012            }
1013        }
1014        value
1015    }
1016
1017    /// The number of feature columns the schema reads.
1018    ///
1019    /// # Returns
1020    ///
1021    /// One more than the largest index among the columns of the part of
1022    /// speech, of the conjugation and of the base form: a morpheme of the
1023    /// dictionary has at least this many columns.
1024    pub fn width(&self) -> usize {
1025        [
1026            Some(self.part_of_speech.end),
1027            self.conjugation_type.map(|index| index + 1),
1028            self.conjugation_form.map(|index| index + 1),
1029            self.base_form.map(|index| index + 1),
1030        ]
1031        .into_iter()
1032        .flatten()
1033        .max()
1034        .unwrap_or(0)
1035    }
1036
1037    /// Checks that morphemes can be of the dictionary of the schema.
1038    ///
1039    /// A morpheme with fewer feature columns than the schema reads comes
1040    /// from another dictionary, or from a tokenizer that drops columns:
1041    /// analyzing it would give an answer from columns that are not there.
1042    /// Morphemes of another dictionary that are wide enough pass; the name
1043    /// of the dictionary in a model file is for those
1044    /// ([`Model::check_dictionary`](crate::model::Model::check_dictionary)).
1045    ///
1046    /// # Arguments
1047    ///
1048    /// * `morphemes` - The morphemes.
1049    ///
1050    /// # Returns
1051    ///
1052    /// `Ok(())`, or [`Error::Dictionary`] for the first morpheme that has
1053    /// fewer columns than [`Schema::width`].
1054    pub fn check<M: Morpheme>(&self, morphemes: &[M]) -> Result<()> {
1055        let width = self.width();
1056        let Some(last) = width.checked_sub(1) else {
1057            return Ok(());
1058        };
1059        for (index, morpheme) in morphemes.iter().enumerate() {
1060            if morpheme.feature(last).is_none() {
1061                return Err(Error::Dictionary(format!(
1062                    "the morpheme {} ({:?}) has fewer than the {width} feature columns the schema reads: it is not of the dictionary of the model",
1063                    index + 1,
1064                    morpheme.surface()
1065                )));
1066            }
1067        }
1068        Ok(())
1069    }
1070
1071    /// Appends the schema to the bytes of a model.
1072    ///
1073    /// The columns, then the function word patterns, the patterns of what
1074    /// is not a head, the particles, the function words taken by their
1075    /// surface, the symbols, the normalization, the rule of the head, and
1076    /// the head word of a bunsetsu without one.
1077    ///
1078    /// # Arguments
1079    ///
1080    /// * `bytes` - The bytes to append to.
1081    pub(crate) fn write(&self, bytes: &mut Vec<u8>) {
1082        let column = |index: Option<usize>| index.map_or(NO_COLUMN, |index| index as u32);
1083        push_u32(bytes, self.part_of_speech.start as u32);
1084        push_u32(bytes, self.part_of_speech.end as u32);
1085        push_u32(bytes, column(self.conjugation_type));
1086        push_u32(bytes, column(self.conjugation_form));
1087        push_u32(bytes, column(self.base_form));
1088        for patterns in [
1089            &self.function_words,
1090            &self.not_heads,
1091            &self.particles,
1092            &self.lexicalized,
1093        ] {
1094            push_u32(bytes, patterns.len() as u32);
1095            for pattern in patterns {
1096                pattern.write(bytes);
1097            }
1098        }
1099        self.symbols.write(bytes);
1100        self.normalization.write(bytes);
1101        bytes.push(self.head_rule.code());
1102        bytes.push(self.head_fallback.code());
1103        bytes.push(self.sentence_split.code());
1104    }
1105
1106    /// Reads a schema from the bytes of a model.
1107    ///
1108    /// # Arguments
1109    ///
1110    /// * `reader` - The bytes, at the schema.
1111    ///
1112    /// # Returns
1113    ///
1114    /// The schema, or the error of bytes that are not one.
1115    pub(crate) fn read(reader: &mut Reader, version: u32) -> Result<Self> {
1116        let start = reader.u32()? as usize;
1117        let end = reader.u32()? as usize;
1118        let mut column = || -> Result<Option<usize>> {
1119            let value = reader.u32()?;
1120            Ok((value != NO_COLUMN).then_some(value as usize))
1121        };
1122        let conjugation_type = column()?;
1123        let conjugation_form = column()?;
1124        let base_form = column()?;
1125        let mut patterns = || -> Result<Vec<Pattern>> {
1126            let count = reader.u32()?;
1127            let mut patterns = Vec::new();
1128            for _ in 0..count {
1129                patterns.push(Pattern::read(reader, 0)?);
1130            }
1131            Ok(patterns)
1132        };
1133        let function_words = patterns()?;
1134        let not_heads = patterns()?;
1135        let particles = patterns()?;
1136        let lexicalized = patterns()?;
1137        let symbols = Symbols::read(reader)?;
1138        let normalization = Normalization::read(reader)?;
1139        let head_rule = HeadRule::from_code(reader.u8()?)?;
1140        let (head_fallback, sentence_split) = if version >= HEAD_FALLBACK_VERSION {
1141            (
1142                HeadFallback::from_code(reader.u8()?)?,
1143                SentenceSplit::from_code(reader.u8()?)?,
1144            )
1145        } else {
1146            (HeadFallback::FirstMorpheme, SentenceSplit::None)
1147        };
1148        Ok(Self {
1149            part_of_speech: start..end,
1150            conjugation_type,
1151            conjugation_form,
1152            base_form,
1153            function_words,
1154            not_heads,
1155            particles,
1156            lexicalized,
1157            symbols,
1158            normalization,
1159            head_rule,
1160            head_fallback,
1161            sentence_split,
1162        })
1163    }
1164}
1165
1166#[cfg(test)]
1167mod tests {
1168    use super::*;
1169    use crate::error::Error;
1170    use crate::lattice::LatticeMorpheme;
1171
1172    /// Morphemes of `(surface, features)`.
1173    fn morphemes(pairs: &[(&str, &str)]) -> Vec<LatticeMorpheme> {
1174        pairs
1175            .iter()
1176            .map(|(surface, features)| LatticeMorpheme::new(*surface, *features))
1177            .collect()
1178    }
1179
1180    /// The positions the schema of IPADIC gives for a bunsetsu.
1181    fn positions(pairs: &[(&str, &str)]) -> (usize, usize) {
1182        Schema::ipadic().positions(&morphemes(pairs)).unwrap()
1183    }
1184
1185    const HON: (&str, &str) = ("本", "名詞,一般,*,*,*,*,本,ホン,ホン");
1186    const WO: (&str, &str) = ("を", "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ");
1187    const NI: (&str, &str) = ("に", "助詞,格助詞,一般,*,*,*,に,ニ,ニ");
1188    const GA: (&str, &str) = ("が", "助詞,格助詞,一般,*,*,*,が,ガ,ガ");
1189    const YON: (&str, &str) = ("読ん", "動詞,自立,*,*,五段・マ行,連用タ接続,読む,ヨン,ヨン");
1190    const YOMU: (&str, &str) = ("読む", "動詞,自立,*,*,五段・マ行,基本形,読む,ヨム,ヨム");
1191    const DA: (&str, &str) = ("だ", "助動詞,*,*,*,特殊・タ,基本形,だ,ダ,ダ");
1192    const TA: (&str, &str) = ("た", "助動詞,*,*,*,特殊・タ,基本形,た,タ,タ");
1193    const DE: (&str, &str) = ("で", "助詞,接続助詞,*,*,*,*,で,デ,デ");
1194    const IRU: (&str, &str) = ("いる", "動詞,非自立,*,*,一段,基本形,いる,イル,イル");
1195    const MARU: (&str, &str) = ("。", "記号,句点,*,*,*,*,。,。,。");
1196    const TEN: (&str, &str) = ("、", "記号,読点,*,*,*,*,、,、,、");
1197    const KAGI: (&str, &str) = ("「", "記号,括弧開,*,*,*,*,「,「,「");
1198    const KAGI_TOJI: (&str, &str) = ("」", "記号,括弧閉,*,*,*,*,」,」,」");
1199    const RIYOU: (&str, &str) = ("利用", "名詞,サ変接続,*,*,*,*,利用,リヨウ,リヨー");
1200    const SHI: (&str, &str) = ("し", "動詞,自立,*,*,サ変・スル,連用形,する,シ,シ");
1201    const KOTO: (&str, &str) = ("こと", "名詞,非自立,一般,*,*,*,こと,コト,コト");
1202    const KIHON: (&str, &str) = ("基本", "名詞,一般,*,*,*,*,基本,キホン,キホン");
1203    const TEKI: (&str, &str) = ("的", "名詞,接尾,形容動詞語幹,*,*,*,的,テキ,テキ");
1204    /// The half-width comma, an unknown word of IPADIC.
1205    const COMMA: (&str, &str) = (",", "名詞,サ変接続,*,*,*,*,*,*,*");
1206
1207    #[test]
1208    fn ipadic_names_the_columns_of_mecab_ipadic() {
1209        // 読ん: 動詞,自立,*,*,五段・マ行,連用タ接続,読む,ヨン,ヨン
1210        let features = [
1211            "動詞",
1212            "自立",
1213            "*",
1214            "*",
1215            "五段・マ行",
1216            "連用タ接続",
1217            "読む",
1218            "ヨン",
1219            "ヨン",
1220        ];
1221        let schema = Schema::ipadic();
1222        assert_eq!(
1223            features[schema.part_of_speech.clone()],
1224            ["動詞", "自立", "*", "*"]
1225        );
1226        assert_eq!(features[schema.conjugation_type.unwrap()], "五段・マ行");
1227        assert_eq!(features[schema.conjugation_form.unwrap()], "連用タ接続");
1228        assert_eq!(features[schema.base_form.unwrap()], "読む");
1229    }
1230
1231    #[test]
1232    fn a_content_word_and_a_particle_are_the_head_and_the_function_word() {
1233        assert_eq!(positions(&[HON, WO]), (0, 1));
1234        // The last content word and the last function word.
1235        assert_eq!(positions(&[KIHON, HON, NI, WO]), (1, 3));
1236    }
1237
1238    #[test]
1239    fn a_content_word_alone_is_both() {
1240        assert_eq!(positions(&[HON]), (0, 0));
1241        assert_eq!(positions(&[KIHON, HON]), (1, 1));
1242    }
1243
1244    #[test]
1245    fn punctuation_at_the_end_is_neither() {
1246        assert_eq!(positions(&[YON, DA, MARU]), (0, 1));
1247        assert_eq!(positions(&[HON, WO, TEN]), (0, 1));
1248        // By the surface too: the half-width comma is 名詞,サ変接続.
1249        assert_eq!(positions(&[HON, WO, COMMA]), (0, 1));
1250        assert_eq!(positions(&[HON, COMMA]), (0, 0));
1251    }
1252
1253    #[test]
1254    fn a_bunsetsu_of_symbols_only_has_both_at_its_first_morpheme() {
1255        assert_eq!(positions(&[MARU]), (0, 0));
1256        assert_eq!(positions(&[KAGI_TOJI, MARU, COMMA]), (0, 0));
1257    }
1258
1259    #[test]
1260    fn a_bracket_before_the_head_is_skipped() {
1261        assert_eq!(positions(&[KAGI, HON, WO]), (1, 2));
1262    }
1263
1264    #[test]
1265    fn a_dependent_verb_is_the_function_word() {
1266        // 読ん / で / いる
1267        assert_eq!(positions(&[YON, DE, IRU]), (0, 2));
1268        assert_eq!(positions(&[YON, DE, IRU, MARU]), (0, 2));
1269    }
1270
1271    #[test]
1272    fn a_head_after_the_function_word_takes_the_function_word_with_it() {
1273        // に / 本: a particle, then the content word.
1274        assert_eq!(positions(&[NI, HON]), (1, 1));
1275        // The same with a symbol after it.
1276        assert_eq!(positions(&[NI, HON, MARU]), (1, 1));
1277        // A function word after the head is kept.
1278        assert_eq!(positions(&[NI, HON, DA]), (1, 2));
1279    }
1280
1281    #[test]
1282    fn the_function_words_of_cabocha_are_function_words() {
1283        // 読ま / れる (動詞,接尾)
1284        let yoma = ("読ま", "動詞,自立,*,*,五段・マ行,未然形,読む,ヨマ,ヨマ");
1285        let reru = ("れる", "動詞,接尾,*,*,一段,基本形,れる,レル,レル");
1286        assert_eq!(positions(&[yoma, reru]), (0, 1));
1287        // 読み / にくい (形容詞,非自立)
1288        let yomi = ("読み", "動詞,自立,*,*,五段・マ行,連用形,読む,ヨミ,ヨミ");
1289        let nikui = (
1290            "にくい",
1291            "形容詞,非自立,*,*,形容詞・アウオ段,基本形,にくい,ニクイ,ニクイ",
1292        );
1293        assert_eq!(positions(&[yomi, nikui]), (0, 1));
1294        // 本 / っぽい (形容詞,接尾)
1295        let ppoi = (
1296            "っぽい",
1297            "形容詞,接尾,*,*,形容詞・アウオ段,基本形,っぽい,ッポイ,ッポイ",
1298        );
1299        assert_eq!(positions(&[HON, ppoi]), (0, 1));
1300        // Each of the three after a particle: the last one wins.
1301        assert_eq!(positions(&[HON, WO, reru]), (0, 2));
1302        assert_eq!(positions(&[HON, WO, nikui]), (0, 2));
1303        assert_eq!(positions(&[HON, WO, ppoi]), (0, 2));
1304        // 助詞 and 助動詞 alone.
1305        assert_eq!(positions(&[HON, DA]), (0, 1));
1306        assert_eq!(positions(&[HON, WO]), (0, 1));
1307    }
1308
1309    #[test]
1310    fn suru_and_dekiru_are_function_words() {
1311        // 利用 / し / た
1312        assert_eq!(positions(&[RIYOU, SHI, TA]), (0, 2));
1313        assert_eq!(positions(&[RIYOU, SHI]), (0, 1));
1314        // する at the start of a bunsetsu is the head.
1315        assert_eq!(positions(&[SHI, TA]), (0, 1));
1316        assert_eq!(positions(&[SHI]), (0, 0));
1317        // Another verb after a verbal noun is the head.
1318        assert_eq!(positions(&[RIYOU, YON, DA]), (1, 2));
1319        // できる too, in either spelling of its base form.
1320        let dekiru = ("でき", "動詞,自立,*,*,一段,連用形,できる,デキ,デキ");
1321        assert_eq!(positions(&[RIYOU, dekiru, TA]), (0, 2));
1322        let dekiru = ("出来", "動詞,自立,*,*,一段,連用形,出来る,デキ,デキ");
1323        assert_eq!(positions(&[RIYOU, dekiru, TA]), (0, 2));
1324    }
1325
1326    #[test]
1327    fn a_dependent_noun_and_the_suffix_teki_are_not_heads() {
1328        // 読む / こと / が
1329        assert_eq!(positions(&[YOMU, KOTO, GA]), (0, 2));
1330        // At the start of a bunsetsu it stays the head, as nothing else is.
1331        assert_eq!(positions(&[KOTO, GA]), (0, 1));
1332        // 基本 / 的 / に
1333        assert_eq!(positions(&[KIHON, TEKI, NI]), (0, 2));
1334        // 長 / さ / は: the suffix さ (名詞,接尾,特殊).
1335        let naga = (
1336            "長",
1337            "形容詞,自立,*,*,形容詞・アウオ段,ガル接続,長い,ナガ,ナガ",
1338        );
1339        let sa = ("さ", "名詞,接尾,特殊,*,*,*,さ,サ,サ");
1340        assert_eq!(positions(&[naga, sa, GA]), (0, 2));
1341        // Another suffix is a head: 本 / 人 (名詞,接尾,助数詞).
1342        let nin = ("人", "名詞,接尾,助数詞,*,*,*,人,ニン,ニン");
1343        assert_eq!(positions(&[HON, nin, GA]), (1, 2));
1344    }
1345
1346    #[test]
1347    fn a_verb_after_a_particle_is_part_of_a_compound_function_word() {
1348        let naru = ("なっ", "動詞,自立,*,*,五段・ラ行,連用タ接続,なる,ナッ,ナッ");
1349        // 読む / こと / に / なっ / た
1350        assert_eq!(positions(&[YOMU, KOTO, NI, naru, TA]), (0, 4));
1351        // 本 / に / なっ / た: the same in a shorter bunsetsu.
1352        assert_eq!(positions(&[HON, NI, naru, TA]), (0, 3));
1353        // A verb after a noun is the head.
1354        assert_eq!(positions(&[HON, naru, TA]), (1, 2));
1355        // At the start of a bunsetsu too.
1356        assert_eq!(positions(&[naru, TA]), (0, 1));
1357    }
1358
1359    #[test]
1360    fn no_morpheme_has_no_positions() {
1361        let none: [LatticeMorpheme; 0] = [];
1362        assert_eq!(Schema::ipadic().positions(&none), None);
1363    }
1364
1365    #[test]
1366    fn morphemes_with_fewer_columns_do_not_panic() {
1367        // No column, one column, and the columns up to the part of speech.
1368        assert_eq!(positions(&[("x", ""), ("y", "")]), (1, 1));
1369        assert_eq!(positions(&[("本", "名詞"), ("を", "助詞")]), (0, 1));
1370        assert_eq!(
1371            positions(&[("利用", "名詞,サ変接続"), ("し", "動詞,自立")]),
1372            (1, 1)
1373        );
1374        let schema = Schema::ipadic();
1375        let bare = LatticeMorpheme::new("x", "");
1376        assert!(!schema.is_symbol(&bare));
1377        assert_eq!(schema.part_of_speech_of(&bare), "");
1378        // A symbol by its surface needs no column.
1379        assert!(schema.is_comma(&LatticeMorpheme::new(",", "")));
1380    }
1381
1382    #[test]
1383    fn a_schema_without_patterns_takes_the_last_morpheme() {
1384        // Every morpheme is a head, none a function word.
1385        let schema = Schema {
1386            part_of_speech: 0..4,
1387            ..Schema::default()
1388        };
1389        assert_eq!(schema.positions(&morphemes(&[HON, WO, MARU])), Some((2, 2)));
1390    }
1391
1392    #[test]
1393    fn punctuation_and_brackets_are_recognized_by_part_of_speech_and_by_surface() {
1394        let schema = Schema::ipadic();
1395        let unknown = |surface: &str| LatticeMorpheme::new(surface, "名詞,サ変接続,*,*,*,*,*,*,*");
1396        let known = |pair: (&str, &str)| LatticeMorpheme::new(pair.0, pair.1);
1397
1398        assert!(schema.is_comma(&known(TEN)));
1399        assert!(schema.is_period(&known(MARU)));
1400        assert!(schema.is_open_bracket(&known(KAGI)));
1401        assert!(schema.is_close_bracket(&known(KAGI_TOJI)));
1402        for surface in [",", ",", "、"] {
1403            assert!(schema.is_comma(&unknown(surface)), "{surface}");
1404            assert!(!schema.is_period(&unknown(surface)), "{surface}");
1405        }
1406        for surface in [".", ".", "。"] {
1407            assert!(schema.is_period(&unknown(surface)), "{surface}");
1408            assert!(!schema.is_comma(&unknown(surface)), "{surface}");
1409        }
1410        for surface in ["(", "(", "[", "「", "『", "“"] {
1411            assert!(schema.is_open_bracket(&unknown(surface)), "{surface}");
1412            assert!(!schema.is_close_bracket(&unknown(surface)), "{surface}");
1413        }
1414        for surface in [")", ")", "]", "」", "』", "”"] {
1415            assert!(schema.is_close_bracket(&unknown(surface)), "{surface}");
1416            assert!(!schema.is_open_bracket(&unknown(surface)), "{surface}");
1417        }
1418        // Each of them is a symbol, and so are the other marks.
1419        for surface in [
1420            ",", "。", "(", "」", "!", "?", "-", "/", "・", "…", ",“", "!?",
1421        ] {
1422            assert!(schema.is_symbol(&unknown(surface)), "{surface}");
1423        }
1424        // By the part of speech alone: the half-width forms of 、 。 「 」
1425        // are in no list of characters.
1426        let comma = LatticeMorpheme::new("、", "記号,読点,*,*,*,*,、,、,、");
1427        let period = LatticeMorpheme::new("。", "記号,句点,*,*,*,*,。,。,。");
1428        let open = LatticeMorpheme::new("「", "記号,括弧開,*,*,*,*,「,「,「");
1429        let close = LatticeMorpheme::new("」", "記号,括弧閉,*,*,*,*,」,」,」");
1430        assert!(schema.is_comma(&comma) && !schema.is_period(&comma));
1431        assert!(schema.is_period(&period) && !schema.is_comma(&period));
1432        assert!(schema.is_open_bracket(&open) && !schema.is_close_bracket(&open));
1433        assert!(schema.is_close_bracket(&close) && !schema.is_open_bracket(&close));
1434        assert!(!schema.is_comma(&unknown("、")));
1435        // The part of speech 記号 alone is a symbol of no finer kind.
1436        let alphabet = LatticeMorpheme::new("A", "記号,アルファベット,*,*,*,*,A,エイ,エイ");
1437        assert!(schema.is_symbol(&alphabet));
1438        assert!(!schema.is_comma(&alphabet) && !schema.is_period(&alphabet));
1439        // A unit, a word and a number are not symbols.
1440        for surface in ["%", "°", "%、", "本", "1", "a"] {
1441            assert!(!schema.is_symbol(&unknown(surface)), "{surface}");
1442        }
1443        assert!(!schema.is_comma(&known(HON)));
1444    }
1445
1446    #[test]
1447    fn the_brackets_come_in_pairs() {
1448        assert_eq!(
1449            OPEN_BRACKETS.chars().count(),
1450            CLOSE_BRACKETS.chars().count()
1451        );
1452        // No character is of two kinds.
1453        let all = [
1454            COMMAS,
1455            PERIODS,
1456            OPEN_BRACKETS,
1457            CLOSE_BRACKETS,
1458            OTHER_SYMBOLS,
1459        ]
1460        .concat();
1461        let mut characters: Vec<char> = all.chars().collect();
1462        let count = characters.len();
1463        characters.sort_unstable();
1464        characters.dedup();
1465        assert_eq!(characters.len(), count);
1466    }
1467
1468    #[test]
1469    fn the_part_of_speech_is_joined_up_to_the_first_empty_level() {
1470        let schema = Schema::ipadic();
1471        let of =
1472            |pair: (&str, &str)| schema.part_of_speech_of(&LatticeMorpheme::new(pair.0, pair.1));
1473        assert_eq!(of(HON), "名詞-一般");
1474        assert_eq!(of(TEKI), "名詞-接尾-形容動詞語幹");
1475        assert_eq!(of(DA), "助動詞");
1476        assert_eq!(of(("x", "*,名詞")), "");
1477    }
1478
1479    #[test]
1480    fn particles_and_words_taken_by_their_surface_follow_the_patterns() {
1481        let schema = Schema::ipadic();
1482        let bunsetsu = morphemes(&[
1483            (
1484                "ゆっくり",
1485                "副詞,助詞類接続,*,*,*,*,ゆっくり,ユックリ,ユックリ",
1486            ),
1487            ("と", "助詞,格助詞,一般,*,*,*,と,ト,ト"),
1488            ("この", "連体詞,*,*,*,*,*,この,コノ,コノ"),
1489            ("しかし", "接続詞,*,*,*,*,*,しかし,シカシ,シカシ"),
1490            ("本", "名詞,一般,*,*,*,*,本,ホン,ホン"),
1491        ]);
1492        // The last index is past the bunsetsu.
1493        let particles: Vec<bool> = (0..6)
1494            .map(|index| schema.is_particle(&bunsetsu, index))
1495            .collect();
1496        assert_eq!(particles, [false, true, false, false, false, false]);
1497        let lexicalized: Vec<bool> = (0..6)
1498            .map(|index| schema.is_lexicalized(&bunsetsu, index))
1499            .collect();
1500        assert_eq!(lexicalized, [true, true, true, true, false, false]);
1501    }
1502
1503    #[test]
1504    fn unidic_is_a_second_schema_of_data_only() {
1505        let schema = Schema::unidic();
1506        // 思っ / て / いる: いる (非自立可能) is a function word.
1507        let omotte_iru = morphemes(&[
1508            (
1509                "思っ",
1510                "動詞,一般,*,*,五段-ワア行,連用形-促音便,オモウ,思う",
1511            ),
1512            ("て", "助詞,接続助詞,*,*,*,*,テ,て"),
1513            (
1514                "いる",
1515                "動詞,非自立可能,*,*,上一段-ア行,終止形-一般,イル,居る",
1516            ),
1517        ]);
1518        assert_eq!(schema.positions(&omotte_iru), Some((0, 2)));
1519
1520        // 事故 / に / よっ / て: よっ after に is not the head.
1521        let ni_yotte = morphemes(&[
1522            ("事故", "名詞,普通名詞,一般,*,*,*,ジコ,事故"),
1523            ("に", "助詞,格助詞,*,*,*,*,ニ,に"),
1524            ("よっ", "動詞,一般,*,*,五段-ラ行,連用形-促音便,ヨル,因る"),
1525            ("て", "助詞,接続助詞,*,*,*,*,テ,て"),
1526        ]);
1527        assert_eq!(schema.positions(&ni_yotte), Some((0, 3)));
1528
1529        // 本 / が / 読む is not such a verb: が is not に, と or を.
1530        let ga_yomu = morphemes(&[
1531            ("本", "名詞,普通名詞,一般,*,*,*,ホン,本"),
1532            ("が", "助詞,格助詞,*,*,*,*,ガ,が"),
1533            ("読む", "動詞,一般,*,*,五段-マ行,終止形-一般,ヨム,読む"),
1534        ]);
1535        assert_eq!(schema.positions(&ga_yomu), Some((2, 2)));
1536
1537        // 。 is 補助記号,句点.
1538        let period = LatticeMorpheme::new("。", "補助記号,句点,*,*,*,*,,。");
1539        assert!(schema.is_period(&period) && schema.is_symbol(&period));
1540        // The schema of IPADIC does not know these parts of speech.
1541        assert_eq!(Schema::ipadic().positions(&omotte_iru), Some((2, 2)));
1542    }
1543
1544    const SURU_UNIDIC: (&str, &str) =
1545        ("する", "動詞,非自立可能,*,*,サ行変格,連体形-一般,スル,為る");
1546    const TA_UNIDIC: (&str, &str) = ("た", "助動詞,*,*,*,助動詞-タ,連体形-一般,タ,た");
1547    const NI_UNIDIC: (&str, &str) = ("に", "助詞,格助詞,*,*,*,*,ニ,に");
1548    const TSUKAU_UNIDIC: (&str, &str) =
1549        ("使う", "動詞,一般,*,*,五段-ワア行,連体形-一般,ツカウ,使う");
1550
1551    #[test]
1552    fn unidic_does_not_take_an_auxiliary_stem_as_the_head() {
1553        let schema = Schema::unidic();
1554        // 使う / よう / に: よう is 形状詞,助動詞語幹.
1555        let you = morphemes(&[
1556            TSUKAU_UNIDIC,
1557            ("よう", "形状詞,助動詞語幹,*,*,*,*,ヨウ,様"),
1558            ("に", "助動詞,*,*,*,助動詞-ダ,連用形-ニ,ダ,だ"),
1559        ]);
1560        assert_eq!(schema.positions(&you), Some((0, 2)));
1561        // 働い / た / そう / だ: そう of hearsay is 名詞,助動詞語幹.
1562        let sou = morphemes(&[
1563            (
1564                "働い",
1565                "動詞,一般,*,*,五段-カ行,連用形-イ音便,ハタラク,働く",
1566            ),
1567            TA_UNIDIC,
1568            ("そう", "名詞,助動詞語幹,*,*,*,*,ソウ,そう-伝聞"),
1569            ("だ", "助動詞,*,*,*,助動詞-ダ,終止形-一般,ダ,だ"),
1570        ]);
1571        assert_eq!(schema.positions(&sou), Some((0, 3)));
1572    }
1573
1574    #[test]
1575    fn unidic_does_not_take_a_formal_noun_after_a_predicate_as_the_head() {
1576        let schema = Schema::unidic();
1577        let koto = ("こと", "名詞,普通名詞,一般,*,*,*,コト,事");
1578        let tame = ("ため", "名詞,普通名詞,副詞可能,*,*,*,タメ,為");
1579        let kounyuu = ("購入", "名詞,普通名詞,サ変可能,*,*,*,コウニュウ,購入");
1580        // 購入 / する / こと / に: after a verb.
1581        let after_verb = morphemes(&[kounyuu, SURU_UNIDIC, koto, NI_UNIDIC]);
1582        assert_eq!(schema.positions(&after_verb), Some((0, 3)));
1583        // 購入 / する / た / ため / に: after an auxiliary.
1584        let after_auxiliary = morphemes(&[kounyuu, SURU_UNIDIC, TA_UNIDIC, tame, NI_UNIDIC]);
1585        assert_eq!(schema.positions(&after_auxiliary), Some((0, 4)));
1586        // 新しい / こと / に: after an adjective.
1587        let after_adjective = morphemes(&[
1588            (
1589                "新しい",
1590                "形容詞,一般,*,*,形容詞,連体形-一般,アタラシイ,新しい",
1591            ),
1592            koto,
1593            NI_UNIDIC,
1594        ]);
1595        assert_eq!(schema.positions(&after_adjective), Some((0, 2)));
1596        // こと / に, and 購入 / こと / に: not after one of them.
1597        assert_eq!(
1598            schema.positions(&morphemes(&[koto, NI_UNIDIC])),
1599            Some((0, 1))
1600        );
1601        assert_eq!(
1602            schema.positions(&morphemes(&[kounyuu, koto, NI_UNIDIC])),
1603            Some((1, 2))
1604        );
1605        // 使う / 人 / に: 人 is not a formal noun.
1606        let hito = morphemes(&[
1607            TSUKAU_UNIDIC,
1608            ("人", "名詞,普通名詞,一般,*,*,*,ヒト,人"),
1609            NI_UNIDIC,
1610        ]);
1611        assert_eq!(schema.positions(&hito), Some((1, 2)));
1612    }
1613
1614    #[test]
1615    fn unidic_does_not_take_a_nominal_suffix_after_an_adjective_as_the_head() {
1616        let schema = Schema::unidic();
1617        // 大き / さ / に.
1618        let ookisa = morphemes(&[
1619            ("大き", "形容詞,一般,*,*,形容詞,語幹-一般,オオキイ,大きい"),
1620            ("さ", "接尾辞,名詞的,一般,*,*,*,サ,さ"),
1621            NI_UNIDIC,
1622        ]);
1623        assert_eq!(schema.positions(&ookisa), Some((0, 2)));
1624        // 市 / 長 / に: after a noun the suffix is the head.
1625        let shichou = morphemes(&[
1626            ("市", "名詞,普通名詞,一般,*,*,*,シ,市"),
1627            ("長", "接尾辞,名詞的,一般,*,*,*,チョウ,長"),
1628            NI_UNIDIC,
1629        ]);
1630        assert_eq!(schema.positions(&shichou), Some((1, 2)));
1631    }
1632
1633    #[test]
1634    fn unidic_takes_a_letter_as_a_symbol() {
1635        let schema = Schema::unidic();
1636        // 5 / k / m: the letters are 記号,文字.
1637        let kilometers = morphemes(&[
1638            ("5", "名詞,数詞,*,*,*,*,ゴ,五"),
1639            ("k", "記号,文字,*,*,*,*,ケー,K"),
1640            ("m", "記号,文字,*,*,*,*,エム,M"),
1641        ]);
1642        assert!(schema.is_symbol(&kilometers[1]));
1643        assert_eq!(schema.positions(&kilometers), Some((0, 0)));
1644    }
1645
1646    #[test]
1647    fn a_schema_is_chosen_by_the_name_of_the_dictionary() {
1648        assert_eq!(Schema::for_dictionary("ipadic"), Some(Schema::ipadic()));
1649        for name in ["unidic", "unidic-cwj", "unidic-csj"] {
1650            assert_eq!(Schema::for_dictionary(name), Some(Schema::unidic()));
1651        }
1652        // Every name of the list has a schema, and no other name has.
1653        for name in Schema::DICTIONARIES {
1654            assert!(Schema::for_dictionary(name).is_some(), "{name}");
1655        }
1656        for name in ["", "IPADIC", "ipadic-neologd", "ko-dic", "unidic-"] {
1657            assert_eq!(Schema::for_dictionary(name), None, "{name}");
1658        }
1659    }
1660
1661    /// A schema with the rule of the last words: two levels of the part
1662    /// of speech, 特殊 as the symbols, and 助詞 and 接尾辞 as what is not a
1663    /// head. The rule CaboCha has for JUMAN.
1664    fn last_words() -> Schema {
1665        Schema {
1666            part_of_speech: 0..2,
1667            not_heads: vec![Pattern::new(&["助詞"]), Pattern::new(&["接尾辞"])],
1668            symbols: Symbols {
1669                others: Marks::new(&[&["特殊"]], ""),
1670                surface: SurfaceRule::OneCharacter,
1671                ..Symbols::default()
1672            },
1673            head_rule: HeadRule::LastWords,
1674            ..Schema::default()
1675        }
1676    }
1677
1678    #[test]
1679    fn with_the_rule_of_the_last_words_the_two_positions_are_found_apart() {
1680        const NOUN: (&str, &str) = ("本", "名詞,普通名詞,*,*,本,ほん,*");
1681        const PARTICLE: (&str, &str) = ("を", "助詞,格助詞,*,*,を,を,*");
1682        const VERB: (&str, &str) = ("読んで", "動詞,*,子音動詞マ行,タ系連用テ形,読む,よんで,*");
1683        const SUFFIX: (&str, &str) = ("いる", "接尾辞,動詞性接尾辞,母音動詞,基本形,いる,いる,*");
1684        const PERIOD: (&str, &str) = ("。", "特殊,句点,*,*,。,。,*");
1685        const BRACKET: (&str, &str) = ("「", "特殊,括弧始,*,*,「,「,*");
1686        let schema = last_words();
1687        let positions = |pairs: &[(&str, &str)]| schema.positions(&morphemes(pairs)).unwrap();
1688        // One word is the head and the function word.
1689        assert_eq!(positions(&[NOUN]), (0, 0));
1690        // A particle and a suffix are function words, and not heads.
1691        assert_eq!(positions(&[NOUN, PARTICLE]), (0, 1));
1692        assert_eq!(positions(&[VERB, SUFFIX]), (0, 1));
1693        assert_eq!(positions(&[VERB, SUFFIX, PARTICLE]), (0, 2));
1694        // The last word that is not a symbol is the function word, a head
1695        // or not: nothing is moved to it, and it is moved to nothing.
1696        assert_eq!(positions(&[NOUN, PARTICLE, NOUN]), (2, 2));
1697        assert_eq!(positions(&[SUFFIX, NOUN, PARTICLE, PARTICLE]), (1, 3));
1698        // A symbol is neither.
1699        assert_eq!(positions(&[VERB, SUFFIX, PERIOD]), (0, 1));
1700        assert_eq!(positions(&[BRACKET, NOUN, PERIOD]), (1, 1));
1701        // Without a word that can be one, each stays at the first morpheme.
1702        assert_eq!(positions(&[PERIOD]), (0, 0));
1703        assert_eq!(positions(&[BRACKET, PERIOD]), (0, 0));
1704        assert_eq!(positions(&[PARTICLE]), (0, 0));
1705        assert_eq!(positions(&[BRACKET, PARTICLE]), (0, 1));
1706        assert_eq!(schema.positions::<LatticeMorpheme>(&[]), None);
1707
1708        // The patterns of the function words are not read by this rule.
1709        let with_patterns = Schema {
1710            function_words: vec![Pattern::new(&["名詞"])],
1711            ..last_words()
1712        };
1713        assert_eq!(
1714            with_patterns.positions(&morphemes(&[NOUN, PARTICLE])),
1715            Some((0, 1))
1716        );
1717        // The other rule, with the same patterns, has no function word
1718        // here: both positions are at the head.
1719        let apart = Schema {
1720            head_rule: HeadRule::FunctionWordsApart,
1721            ..last_words()
1722        };
1723        assert_eq!(apart.positions(&morphemes(&[NOUN, PARTICLE])), Some((0, 0)));
1724        assert_eq!(apart.positions(&morphemes(&[VERB, SUFFIX])), Some((0, 0)));
1725    }
1726
1727    #[test]
1728    fn the_rule_of_the_head_comes_back_from_the_bytes() {
1729        assert_eq!(Schema::default().head_rule, HeadRule::FunctionWordsApart);
1730        assert_eq!(Schema::ipadic().head_rule, HeadRule::FunctionWordsApart);
1731        assert_eq!(Schema::unidic().head_rule, HeadRule::FunctionWordsApart);
1732        for (rule, code) in HeadRule::ALL {
1733            assert_eq!(rule.code(), code);
1734            assert_eq!(HeadRule::from_code(code).unwrap(), rule);
1735            let schema = Schema {
1736                head_rule: rule,
1737                ..last_words()
1738            };
1739            let mut bytes = Vec::new();
1740            schema.write(&mut bytes);
1741            // The rule is the third byte from the end of a schema.
1742            assert_eq!(bytes[bytes.len() - 3], code);
1743            let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
1744            assert_eq!(
1745                Schema::read(&mut reader, crate::model::VERSION).unwrap(),
1746                schema
1747            );
1748            assert_eq!(reader.remaining(), 0);
1749        }
1750        // A byte that is not a rule is refused.
1751        let mut bytes = Vec::new();
1752        last_words().write(&mut bytes);
1753        let rule = bytes.len() - 3;
1754        bytes[rule] = 2;
1755        let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
1756        assert_eq!(
1757            Schema::read(&mut reader, crate::model::VERSION)
1758                .unwrap_err()
1759                .to_string(),
1760            "2 is not the code of a rule of the head"
1761        );
1762    }
1763
1764    #[test]
1765    fn a_schema_comes_back_from_its_bytes() {
1766        for schema in [Schema::ipadic(), Schema::unidic(), Schema::default()] {
1767            let mut bytes = Vec::new();
1768            schema.write(&mut bytes);
1769            let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
1770            assert_eq!(
1771                Schema::read(&mut reader, crate::model::VERSION).unwrap(),
1772                schema
1773            );
1774            assert_eq!(reader.remaining(), 0);
1775        }
1776    }
1777
1778    #[test]
1779    fn the_two_lists_of_patterns_keep_their_places_in_the_bytes() {
1780        let schema = Schema {
1781            function_words: vec![Pattern::new(&["助詞"])],
1782            not_heads: vec![Pattern::new(&["名詞", "非自立"]), Pattern::default()],
1783            ..Schema::default()
1784        };
1785        let mut bytes = Vec::new();
1786        schema.write(&mut bytes);
1787        let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
1788        let read = Schema::read(&mut reader, crate::model::VERSION).unwrap();
1789        assert_eq!(read.function_words, [Pattern::new(&["助詞"])]);
1790        assert_eq!(read.not_heads.len(), 2);
1791    }
1792
1793    #[test]
1794    fn bytes_that_end_inside_a_schema_are_an_error() {
1795        let mut bytes = Vec::new();
1796        Schema::ipadic().write(&mut bytes);
1797        for length in [0, 4, 20, 24, bytes.len() / 2, bytes.len() - 1] {
1798            let mut reader = Reader::new(&bytes[..length], "test bytes", Error::Chunker);
1799            let message = Schema::read(&mut reader, crate::model::VERSION)
1800                .unwrap_err()
1801                .to_string();
1802            assert!(message.contains("ends early"), "{length}: {message}");
1803        }
1804    }
1805
1806    #[test]
1807    fn the_width_is_the_number_of_columns_the_schema_reads() {
1808        // IPADIC: four levels of part of speech, the conjugation type and
1809        // form, the base form.
1810        assert_eq!(Schema::ipadic().width(), 7);
1811        let mut schema = Schema::ipadic();
1812        schema.base_form = None;
1813        assert_eq!(schema.width(), 6);
1814        schema.conjugation_form = None;
1815        schema.conjugation_type = Some(9);
1816        assert_eq!(schema.width(), 10);
1817        schema.conjugation_type = None;
1818        assert_eq!(schema.width(), 4);
1819        schema.part_of_speech = 0..0;
1820        assert_eq!(schema.width(), 0);
1821    }
1822
1823    #[test]
1824    fn morphemes_with_fewer_columns_than_the_schema_reads_are_refused() {
1825        let schema = Schema::ipadic();
1826        let wide = LatticeMorpheme::new("彼", "名詞,代名詞,一般,*,*,*,彼,カレ,カレ");
1827        // An unknown word of MeCab has no reading: seven columns.
1828        let unknown = LatticeMorpheme::new("x", "名詞,一般,*,*,*,*,*");
1829        let narrow = LatticeMorpheme::new("彼", "名詞,代名詞,一般,*,*,*");
1830        let none: [LatticeMorpheme; 0] = [];
1831        assert!(schema.check(&none).is_ok());
1832        assert!(schema.check(&[wide.clone(), unknown.clone()]).is_ok());
1833
1834        let error = schema.check(&[wide.clone(), unknown, narrow]).unwrap_err();
1835        assert!(matches!(error, Error::Dictionary(_)), "{error:?}");
1836        assert_eq!(
1837            error.to_string(),
1838            "the morpheme 3 (\"彼\") has fewer than the 7 feature columns the schema reads: it is not of the dictionary of the model"
1839        );
1840
1841        // A schema that reads nothing refuses nothing.
1842        let mut schema = Schema::ipadic();
1843        schema.part_of_speech = 0..0;
1844        schema.conjugation_type = None;
1845        schema.conjugation_form = None;
1846        schema.base_form = None;
1847        assert!(schema.check(&[LatticeMorpheme::new("彼", "")]).is_ok());
1848    }
1849
1850    /// する, alone in brackets before a particle: a function word of the
1851    /// schema of IPADIC, so the bunsetsu has no morpheme that can be the
1852    /// head word.
1853    const SURU: (&str, &str) = ("する", "動詞,自立,*,*,サ変・スル,基本形,する,スル,スル");
1854    const TO: (&str, &str) = ("と", "助詞,格助詞,引用,*,*,*,と,ト,ト");
1855    /// A full-width space, as IPADIC gives it.
1856    const SPACE: (&str, &str) = ("\u{3000}", "記号,空白,*,*,*,*,\u{3000},\u{3000},\u{3000}");
1857
1858    /// A morpheme of UniDic, from its surface, the levels of its part of
1859    /// speech and its lemma.
1860    fn unidic(surface: &'static str, part_of_speech: &str, lemma: &str) -> LatticeMorpheme {
1861        let levels: Vec<&str> = part_of_speech.split(',').collect();
1862        let mut columns = vec!["*"; 17];
1863        columns[..levels.len()].copy_from_slice(&levels);
1864        columns[7] = lemma;
1865        LatticeMorpheme::new(surface, columns.join(","))
1866    }
1867
1868    #[test]
1869    fn the_schemas_of_this_crate_take_the_first_word() {
1870        assert_eq!(Schema::ipadic().head_fallback, HeadFallback::FirstWord);
1871        assert_eq!(Schema::unidic().head_fallback, HeadFallback::FirstWord);
1872        assert_eq!(Schema::default().head_fallback, HeadFallback::FirstMorpheme);
1873    }
1874
1875    /// The schema of a model converted from CaboCha's: the `cabocha` module
1876    /// is behind the `train` feature.
1877    #[cfg(feature = "train")]
1878    #[test]
1879    fn the_schemas_of_cabocha_take_the_first_morpheme() {
1880        use crate::cabocha::{self, PartOfSpeechSet};
1881
1882        for set in [
1883            PartOfSpeechSet::Ipa,
1884            PartOfSpeechSet::Juman,
1885            PartOfSpeechSet::Unidic,
1886        ] {
1887            assert_eq!(
1888                cabocha::schema(set).head_fallback,
1889                HeadFallback::FirstMorpheme,
1890                "{set:?}"
1891            );
1892        }
1893    }
1894
1895    #[test]
1896    fn a_bunsetsu_without_a_head_word_has_its_first_word_as_the_head() {
1897        // 「 / する / 」 / と: the bracket is no word.
1898        assert_eq!(positions(&[KAGI, SURU, KAGI_TOJI, TO]), (1, 3));
1899        // する at the start is the head as before: it is the first word.
1900        assert_eq!(positions(&[SURU, TO]), (0, 1));
1901        // Brackets and a particle alone: there is no word, and the first
1902        // morpheme is taken.
1903        assert_eq!(positions(&[KAGI, KAGI_TOJI, TO]), (0, 2));
1904        // A bunsetsu with a head word is as it was.
1905        assert_eq!(positions(&[KAGI, HON, KAGI_TOJI, WO]), (1, 3));
1906
1907        // With the first morpheme, as CaboCha: the bracket.
1908        let first_morpheme = Schema {
1909            head_fallback: HeadFallback::FirstMorpheme,
1910            ..Schema::ipadic()
1911        };
1912        assert_eq!(
1913            first_morpheme.positions(&morphemes(&[KAGI, SURU, KAGI_TOJI, TO])),
1914            Some((0, 3))
1915        );
1916    }
1917
1918    #[test]
1919    fn a_word_in_letters_keeps_its_first_letter_and_a_mark_before_a_verb_is_passed_over() {
1920        let schema = Schema::unidic();
1921        let open = unidic("「", "補助記号,括弧開", "「");
1922        let close = unidic("」", "補助記号,括弧閉", "」");
1923        let to = unidic("と", "助詞,格助詞", "と");
1924        let no = unidic("の", "助詞,格助詞", "の");
1925        // 治す is 動詞,非自立可能 in UniDic: a function word of the schema.
1926        let naosu = unidic("治す", "動詞,非自立可能", "直す");
1927        let letter = |surface| unidic(surface, "記号,文字", surface);
1928
1929        // 「 / 治す / 」 / と
1930        assert_eq!(
1931            schema.positions(&[open.clone(), naosu, close.clone(), to.clone()]),
1932            Some((1, 3))
1933        );
1934        // S / i / r / i / の: UniDic cuts the word into letters, which it
1935        // calls symbols, and the first one stays the head word.
1936        assert_eq!(
1937            schema.positions(&[
1938                letter("S"),
1939                letter("i"),
1940                letter("r"),
1941                letter("i"),
1942                no.clone()
1943            ]),
1944            Some((0, 4))
1945        );
1946        // 「 / S / M / T / 」 / と: the first letter, and not the bracket.
1947        assert_eq!(
1948            schema.positions(&[open, letter("S"), letter("M"), letter("T"), close, to]),
1949            Some((1, 5))
1950        );
1951        // ♂ / の: a mark and a particle. The particle is not taken.
1952        assert_eq!(
1953            schema.positions(&[unidic("♂", "補助記号,一般", "♂"), no]),
1954            Some((0, 1))
1955        );
1956    }
1957
1958    #[test]
1959    fn a_space_is_neither_the_head_word_nor_the_function_word() {
1960        // A space before する, which is a function word: する is the head.
1961        assert_eq!(positions(&[SPACE, SURU]), (1, 1));
1962        // Between a noun and its particle, and after them.
1963        assert_eq!(positions(&[HON, SPACE, WO]), (0, 2));
1964        assert_eq!(positions(&[HON, WO, SPACE]), (0, 1));
1965        // Spaces alone: there is no word.
1966        assert_eq!(positions(&[SPACE, SPACE]), (0, 0));
1967        // A space is told by its surface, whatever part of speech the
1968        // dictionary gives it: one that is a noun there is no head word.
1969        const NOUN_SPACE: (&str, &str) = (" ", "名詞,一般,*,*,*,*,*,*,*");
1970        assert_eq!(positions(&[NOUN_SPACE, HON, WO]), (1, 2));
1971        assert_eq!(positions(&[HON, NOUN_SPACE, WO]), (0, 2));
1972        assert_eq!(positions(&[HON, WO, NOUN_SPACE]), (0, 1));
1973        // A space and marks alone: the first mark, and not the space.
1974        assert_eq!(positions(&[SPACE, KAGI, KAGI_TOJI]), (1, 1));
1975
1976        // UniDic gives a space the part of speech 空白, and 治す is a
1977        // function word there.
1978        let space = unidic("\u{3000}", "空白", "\u{3000}");
1979        let naosu = unidic("治す", "動詞,非自立可能", "直す");
1980        assert_eq!(Schema::unidic().positions(&[space, naosu]), Some((1, 1)));
1981
1982        // With the first morpheme, the space is passed over too: by the
1983        // rule, and when the rule finds no head word.
1984        let first_morpheme = Schema {
1985            head_fallback: HeadFallback::FirstMorpheme,
1986            ..Schema::ipadic()
1987        };
1988        assert_eq!(
1989            first_morpheme.positions(&morphemes(&[SPACE, HON, WO])),
1990            Some((1, 2))
1991        );
1992        assert_eq!(
1993            first_morpheme.positions(&morphemes(&[SPACE, SURU])),
1994            Some((1, 1))
1995        );
1996        assert_eq!(
1997            first_morpheme.positions(&morphemes(&[SPACE, KAGI, SURU])),
1998            Some((1, 2))
1999        );
2000    }
2001
2002    #[test]
2003    fn the_head_word_of_a_bunsetsu_without_one_comes_back_from_the_bytes() {
2004        for (fallback, code) in HeadFallback::ALL {
2005            assert_eq!(fallback.code(), code);
2006            assert_eq!(HeadFallback::from_code(code).unwrap(), fallback);
2007            let schema = Schema {
2008                head_fallback: fallback,
2009                ..last_words()
2010            };
2011            let mut bytes = Vec::new();
2012            schema.write(&mut bytes);
2013            // It is the byte before the last of a schema.
2014            assert_eq!(bytes[bytes.len() - 2], code);
2015            let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
2016            assert_eq!(
2017                Schema::read(&mut reader, crate::model::VERSION).unwrap(),
2018                schema
2019            );
2020            assert_eq!(reader.remaining(), 0);
2021        }
2022        // A byte that is not one is refused.
2023        let mut bytes = Vec::new();
2024        last_words().write(&mut bytes);
2025        let fallback = bytes.len() - 2;
2026        bytes[fallback] = 2;
2027        let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
2028        assert_eq!(
2029            Schema::read(&mut reader, crate::model::VERSION)
2030                .unwrap_err()
2031                .to_string(),
2032            "2 is not the code of a head word for a bunsetsu without one"
2033        );
2034    }
2035
2036    #[test]
2037    fn the_schema_of_a_file_of_version_3_ends_with_the_rule_and_takes_the_first_morpheme() {
2038        // What the version 3 wrote: the bytes of today without the last
2039        // two.
2040        let schema = Schema {
2041            head_fallback: HeadFallback::FirstWord,
2042            sentence_split: SentenceSplit::AfterEnds,
2043            ..last_words()
2044        };
2045        let mut bytes = Vec::new();
2046        schema.write(&mut bytes);
2047        bytes.pop();
2048        bytes.pop();
2049        let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
2050        let read = Schema::read(&mut reader, 3).unwrap();
2051        assert_eq!(reader.remaining(), 0);
2052        assert_eq!(
2053            read,
2054            Schema {
2055                head_fallback: HeadFallback::FirstMorpheme,
2056                sentence_split: SentenceSplit::None,
2057                ..schema
2058            }
2059        );
2060        // Read as the version 4, the same bytes end early.
2061        let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
2062        assert!(Schema::read(&mut reader, 4).is_err());
2063    }
2064
2065    const HATENA: (&str, &str) = ("?", "記号,一般,*,*,*,*,?,?,?");
2066
2067    /// The words at which the schema of IPADIC cuts a text.
2068    fn starts(pairs: &[(&str, &str)]) -> Vec<usize> {
2069        Schema::ipadic().sentence_starts(&morphemes(pairs))
2070    }
2071
2072    #[test]
2073    fn the_schemas_of_this_crate_cut_a_text_into_sentences() {
2074        assert_eq!(Schema::ipadic().sentence_split, SentenceSplit::AfterEnds);
2075        assert_eq!(Schema::unidic().sentence_split, SentenceSplit::AfterEnds);
2076        assert_eq!(Schema::default().sentence_split, SentenceSplit::None);
2077    }
2078
2079    /// The schema of a model converted from CaboCha's: the `cabocha` module
2080    /// is behind the `train` feature.
2081    #[cfg(feature = "train")]
2082    #[test]
2083    fn the_schemas_of_cabocha_do_not_cut_a_text() {
2084        use crate::cabocha::{self, PartOfSpeechSet};
2085
2086        for set in [
2087            PartOfSpeechSet::Ipa,
2088            PartOfSpeechSet::Juman,
2089            PartOfSpeechSet::Unidic,
2090        ] {
2091            let schema = cabocha::schema(set);
2092            assert_eq!(schema.sentence_split, SentenceSplit::None, "{set:?}");
2093            assert!(
2094                schema
2095                    .sentence_starts(&morphemes(&[HON, MARU, HON, WO]))
2096                    .is_empty(),
2097                "{set:?}"
2098            );
2099        }
2100    }
2101
2102    #[test]
2103    fn a_text_is_cut_after_its_sentence_ends() {
2104        // 本 / 。 / 本 / を: the word after the period starts a sentence.
2105        assert_eq!(starts(&[HON, MARU, HON, WO]), [2]);
2106        // A sentence of its own has no start but its first word.
2107        assert!(starts(&[HON, WO, YOMU, MARU]).is_empty());
2108        assert!(starts(&[HON, WO, YOMU]).is_empty());
2109        assert!(starts(&[]).is_empty());
2110        // Three sentences, the second one a word alone.
2111        assert_eq!(starts(&[HON, MARU, YOMU, MARU, HON, MARU]), [2, 4]);
2112        // ? and ! end a sentence as 。 does, and ends in a row are one.
2113        assert_eq!(starts(&[HON, HATENA, HON]), [2]);
2114        assert_eq!(starts(&[HON, HATENA, HATENA, MARU, HON]), [4]);
2115        assert_eq!(
2116            starts(&[HON, ("!?", "記号,一般,*,*,*,*,*,*,*"), HON]),
2117            [2]
2118        );
2119        // A comma ends nothing.
2120        assert!(starts(&[HON, TEN, HON]).is_empty());
2121    }
2122
2123    #[test]
2124    fn a_closing_bracket_stays_with_the_sentence_it_closes() {
2125        // 「 / 本 / 。 / 」 / 本: the bracket is of the first sentence.
2126        assert_eq!(starts(&[KAGI, HON, MARU, KAGI_TOJI, HON]), [4]);
2127        // Nothing after the bracket: one sentence.
2128        assert!(starts(&[KAGI, HON, MARU, KAGI_TOJI]).is_empty());
2129        // An opening bracket starts the next sentence.
2130        assert_eq!(starts(&[HON, MARU, KAGI, HON, KAGI_TOJI]), [2]);
2131    }
2132
2133    /// A word of marks that IPADIC does not have: an unknown word, with
2134    /// the part of speech of a noun.
2135    fn joined(surface: &str) -> (&str, &str) {
2136        (surface, "名詞,サ変接続,*,*,*,*,*,*,*")
2137    }
2138
2139    #[test]
2140    fn a_sentence_end_joined_with_other_marks_cuts_the_text() {
2141        // 読む / ~。 / 本, 読む / )。 / 本 and 読む / %。 / 本.
2142        for end in ["~。", ")。", "%。", "!?"] {
2143            assert_eq!(starts(&[YOMU, joined(end), HON]), [2], "{end}");
2144        }
2145        // The ends and the closing brackets after it stay with it.
2146        assert_eq!(
2147            starts(&[YOMU, joined("~。"), KAGI_TOJI, joined(")。"), HON]),
2148            [4]
2149        );
2150        // Marks without an end.
2151        for other in [",“", "~」", "()"] {
2152            assert!(starts(&[YOMU, joined(other), HON]).is_empty(), "{other}");
2153        }
2154        // 本 / (?) / 本 is cut as 本 / ( / ? / ) / 本 is, and not before a
2155        // function word: its bracket is closed.
2156        assert_eq!(starts(&[HON, joined("(?)"), HON]), [2]);
2157        assert_eq!(starts(&[HON, joined("("), HATENA, joined(")"), HON]), [4]);
2158        assert!(starts(&[HON, joined("(?)"), GA, YOMU]).is_empty());
2159        assert!(starts(&[HON, joined("("), HATENA, joined(")"), GA, YOMU]).is_empty());
2160    }
2161
2162    #[test]
2163    fn the_closing_bracket_of_a_joined_sentence_end_is_one_of_the_exception() {
2164        // 「 / 本 / ?」 / で / 読む: で follows a closing bracket, the one of
2165        // ?」, and is of the bunsetsu of the quotation.
2166        assert!(starts(&[KAGI, HON, joined("?」"), DE, YOMU]).is_empty());
2167        assert!(starts(&[KAGI, HON, joined("?」"), DA]).is_empty());
2168        // Another word after it starts a sentence.
2169        assert_eq!(starts(&[KAGI, HON, joined("?」"), HON]), [3]);
2170        // The same when ?」 follows another end: 本 / 。 / ?」 / で.
2171        assert!(starts(&[HON, MARU, joined("?」"), DE, YOMU]).is_empty());
2172        // A closing bracket before the end closes nothing after it: で
2173        // starts a sentence, as after 。 alone.
2174        assert_eq!(starts(&[HON, joined(")。"), DE, YOMU]), [2]);
2175        assert_eq!(starts(&[HON, MARU, DE, YOMU]), [2]);
2176    }
2177
2178    #[test]
2179    fn the_words_that_stay_with_the_end_of_a_sentence() {
2180        let tails = |pairs: &[(&str, &str)]| Schema::ipadic().sentence_parts(&morphemes(pairs)).1;
2181        // 本 / 。 / 」 / 本 / ?: the period, the bracket after it, and the
2182        // last mark.
2183        assert_eq!(tails(&[HON, MARU, KAGI_TOJI, HON, HATENA]), [1, 2, 4]);
2184        // A closing bracket that follows no end is none of them, and an
2185        // end joined with marks is one.
2186        assert_eq!(tails(&[KAGI, HON, KAGI_TOJI, HON, joined(")。")]), [4]);
2187        // Before a word that starts no sentence too.
2188        assert_eq!(tails(&[KAGI, HON, joined("?」"), TO, YOMU]), [2]);
2189        // A text that starts with an end.
2190        assert_eq!(tails(&[MARU, HON]), [0]);
2191        assert!(tails(&[HON, WO, YOMU]).is_empty());
2192        // A schema that does not cut names none.
2193        let whole = Schema {
2194            sentence_split: SentenceSplit::None,
2195            ..Schema::ipadic()
2196        };
2197        assert_eq!(
2198            whole.sentence_parts(&morphemes(&[HON, MARU, HON])),
2199            (Vec::new(), Vec::new())
2200        );
2201    }
2202
2203    #[test]
2204    fn a_function_word_after_a_closing_bracket_does_not_start_a_sentence() {
2205        // 「 / 本 / を / 読む / 。 / 」 / と / 読む: と is of the bunsetsu of
2206        // the quotation.
2207        assert!(starts(&[KAGI, HON, WO, YOMU, MARU, KAGI_TOJI, TO, YOMU]).is_empty());
2208        // An auxiliary too: …。 / 」 / だ.
2209        assert!(starts(&[KAGI, HON, MARU, KAGI_TOJI, DA]).is_empty());
2210        // The sentence in the quotation that is not the last one is cut,
2211        // and the function word after the bracket is not.
2212        assert_eq!(
2213            starts(&[KAGI, YOMU, MARU, HON, WO, YOMU, MARU, KAGI_TOJI, TO, YOMU]),
2214            [3]
2215        );
2216        // Without a closing bracket, a function word starts a sentence as
2217        // any word does: 読む / 。 / だ / が (だが).
2218        assert_eq!(starts(&[YOMU, MARU, DA, GA, HON]), [2]);
2219        assert_eq!(starts(&[YOMU, MARU, DE, HON]), [2]);
2220        assert_eq!(starts(&[YOMU, MARU, NI, HON]), [2]);
2221        // A word that is no function word starts one after a bracket.
2222        assert_eq!(starts(&[KAGI, YOMU, MARU, KAGI_TOJI, HON, WO]), [4]);
2223    }
2224
2225    #[test]
2226    fn the_particle_of_a_quotation_does_not_start_a_sentence() {
2227        // 読む / ? / と / 、 / 読む: a quotation without brackets.
2228        assert!(starts(&[YOMU, HATENA, TO, TEN, YOMU]).is_empty());
2229        assert!(starts(&[YOMU, MARU, TO, YOMU]).is_empty());
2230        let tte = ("って", "助詞,格助詞,連語,*,*,*,って,ッテ,ッテ");
2231        assert!(starts(&[YOMU, HATENA, tte, YOMU]).is_empty());
2232        // The sentence before it in the same text is cut.
2233        assert_eq!(starts(&[YOMU, HATENA, HON, HATENA, TO, YOMU]), [2]);
2234        // と that is no particle starts a sentence: by the part of speech,
2235        // and not by the surface alone.
2236        let noun = ("と", "名詞,一般,*,*,*,*,と,ト,ト");
2237        assert_eq!(starts(&[YOMU, MARU, noun, YOMU]), [2]);
2238        // The other particles do: UniDic gives でも as で / も, and
2239        // にもかかわらず as に / も / ….
2240        let schema = Schema::unidic();
2241        let text = [
2242            unidic("本", "名詞,普通名詞", "本"),
2243            unidic("。", "補助記号,句点", "。"),
2244            unidic("で", "助詞,格助詞", "で"),
2245            unidic("も", "助詞,係助詞", "も"),
2246            unidic("本", "名詞,普通名詞", "本"),
2247        ];
2248        assert_eq!(schema.sentence_starts(&text), [2]);
2249        let text = [
2250            unidic("本", "名詞,普通名詞", "本"),
2251            unidic("?", "補助記号,句点", "?"),
2252            unidic("と", "助詞,格助詞", "と"),
2253            unidic("本", "名詞,普通名詞", "本"),
2254        ];
2255        assert!(schema.sentence_starts(&text).is_empty());
2256    }
2257
2258    #[test]
2259    fn a_half_width_period_and_a_period_before_a_digit_end_nothing() {
2260        // IPADIC: 4 / . / 20.
2261        let digits = |surface: &'static str| (surface, "名詞,数,*,*,*,*,*");
2262        assert!(starts(&[digits("4"), (".", "記号,句点,*,*,*,*,.,.,."), digits("20")]).is_empty());
2263        // 3 / . / 14 is a number, and 本 / . / 本 two sentences.
2264        let wide = (".", "記号,句点,*,*,*,*,.,.,.");
2265        assert!(starts(&[digits("3"), wide, digits("14")]).is_empty());
2266        assert_eq!(starts(&[HON, wide, HON]), [2]);
2267        // UniDic calls the half-width period 補助記号,句点: 1 / . / 060 is
2268        // one number, and L / . / E / . / D one word.
2269        let schema = Schema::unidic();
2270        let dot = || unidic(".", "補助記号,句点", ".");
2271        let number = [
2272            unidic("1", "名詞,数詞", "1"),
2273            dot(),
2274            unidic("060", "名詞,数詞", "060"),
2275        ];
2276        assert!(schema.sentence_starts(&number).is_empty());
2277        let letters = [
2278            unidic("L", "記号,文字", "L"),
2279            dot(),
2280            unidic("E", "記号,文字", "E"),
2281            dot(),
2282            unidic("D", "記号,文字", "D"),
2283        ];
2284        assert!(schema.sentence_starts(&letters).is_empty());
2285        // And cuts after 。 as IPADIC does.
2286        let text = [
2287            unidic("本", "名詞,普通名詞", "本"),
2288            unidic("。", "補助記号,句点", "。"),
2289            unidic("本", "名詞,普通名詞", "本"),
2290        ];
2291        assert_eq!(schema.sentence_starts(&text), [2]);
2292    }
2293
2294    #[test]
2295    fn a_schema_that_does_not_cut_gives_no_start() {
2296        let whole = Schema {
2297            sentence_split: SentenceSplit::None,
2298            ..Schema::ipadic()
2299        };
2300        for text in [
2301            &[HON, MARU, HON, WO][..],
2302            &[HON, HATENA, HON],
2303            &[KAGI, HON, MARU, KAGI_TOJI, HON],
2304        ] {
2305            assert!(whole.sentence_starts(&morphemes(text)).is_empty());
2306            assert!(!starts(text).is_empty());
2307        }
2308    }
2309
2310    #[test]
2311    fn the_cut_into_sentences_comes_back_from_the_bytes() {
2312        for (split, code) in SentenceSplit::ALL {
2313            assert_eq!(split.code(), code);
2314            assert_eq!(SentenceSplit::from_code(code).unwrap(), split);
2315            let schema = Schema {
2316                sentence_split: split,
2317                ..last_words()
2318            };
2319            let mut bytes = Vec::new();
2320            schema.write(&mut bytes);
2321            // It is the last byte of a schema.
2322            assert_eq!(bytes.last(), Some(&code));
2323            let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
2324            assert_eq!(
2325                Schema::read(&mut reader, crate::model::VERSION).unwrap(),
2326                schema
2327            );
2328            assert_eq!(reader.remaining(), 0);
2329        }
2330        // A byte that is not one is refused.
2331        let mut bytes = Vec::new();
2332        last_words().write(&mut bytes);
2333        *bytes.last_mut().unwrap() = 2;
2334        let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
2335        assert_eq!(
2336            Schema::read(&mut reader, crate::model::VERSION)
2337                .unwrap_err()
2338                .to_string(),
2339            "2 is not the code of a way to cut a text into sentences"
2340        );
2341    }
2342}
2343
2344#[cfg(test)]
2345mod sentence_ends_tests {
2346    use crate::Schema;
2347    use crate::lattice::LatticeMorpheme;
2348
2349    /// The morphemes of a text, from their surfaces: brackets and periods
2350    /// with the features of IPADIC, anything else as a noun.
2351    fn morphemes(surfaces: &[&str]) -> Vec<LatticeMorpheme> {
2352        surfaces
2353            .iter()
2354            .map(|surface| {
2355                let features = match *surface {
2356                    "。" | "." | "." => {
2357                        format!("記号,句点,*,*,*,*,{surface},{surface},{surface}")
2358                    }
2359                    "「" | "(" => format!("記号,括弧開,*,*,*,*,{surface},{surface},{surface}"),
2360                    "」" | ")" => format!("記号,括弧閉,*,*,*,*,{surface},{surface},{surface}"),
2361                    "!" | "?" | "!" | "?" | "!?" => {
2362                        format!("記号,一般,*,*,*,*,{surface},{surface},{surface}")
2363                    }
2364                    "\u{3000}" => format!("記号,空白,*,*,*,*,{surface},{surface},{surface}"),
2365                    _ => format!("名詞,一般,*,*,*,*,{surface},{surface},{surface}"),
2366                };
2367                LatticeMorpheme::new(*surface, features)
2368            })
2369            .collect()
2370    }
2371
2372    /// The ends of the sentences of a text.
2373    fn ends(surfaces: &[&str]) -> Vec<usize> {
2374        Schema::ipadic().sentence_ends(&morphemes(surfaces))
2375    }
2376
2377    #[test]
2378    fn no_morpheme_is_no_sentence() {
2379        assert_eq!(ends(&[]), Vec::<usize>::new());
2380    }
2381
2382    #[test]
2383    fn a_period_ends_a_sentence_and_the_rest_is_one() {
2384        assert_eq!(ends(&["本", "。"]), [2]);
2385        assert_eq!(ends(&["本", "。", "本", "。"]), [2, 4]);
2386        // Without a period at the end.
2387        assert_eq!(ends(&["本", ".", "本"]), [2, 3]);
2388        assert_eq!(ends(&["本", "。。", "本"]), [2, 3]);
2389        assert_eq!(ends(&["本", "本"]), [2]);
2390        // A period alone is a sentence.
2391        assert_eq!(ends(&["。"]), [1]);
2392    }
2393
2394    #[test]
2395    fn marks_joined_into_one_word_are_read_one_at_a_time() {
2396        // 本 ( 笑 )。 本 。: the bracket is closed in )。, whose 。 ends the
2397        // sentence, and the next sentence is cut too.
2398        assert_eq!(ends(&["本", "(", "笑", ")。", "本", "。"]), [4, 6]);
2399        // The same with the marks as words of their own.
2400        assert_eq!(ends(&["本", "(", "笑", ")", "。", "本", "。"]), [5, 7]);
2401        // 「 本 ?」 と 本 。 本 。: the ? is inside the bracket, which ?」
2402        // closes.
2403        assert_eq!(
2404            ends(&["「", "本", "?」", "と", "本", "。", "本", "。"]),
2405            [6, 8]
2406        );
2407        assert_eq!(
2408            ends(&["「", "本", "?", "」", "と", "本", "。", "本", "。"]),
2409            [7, 9]
2410        );
2411        // An end after other marks, outside brackets.
2412        assert_eq!(ends(&["本", "~。", "本"]), [2, 3]);
2413        assert_eq!(ends(&["本", "%。", "本", "!?"]), [2, 4]);
2414        // Inside a bracket it ends nothing.
2415        assert_eq!(ends(&["「", "本", "~。", "本", "」", "本"]), [6]);
2416        // A bracket that a word of marks opens: 本 ,“ 本 。 ” 本 。
2417        assert_eq!(ends(&["本", ",“", "本", "。", "”", "本", "。"]), [7]);
2418        // (?) opens and closes its bracket, and ends nothing.
2419        assert_eq!(ends(&["本", "(?)", "本", "。", "本"]), [4, 5]);
2420        // An end and a closing bracket without an opening one.
2421        assert_eq!(ends(&["本", "?」", "本"]), [2, 3]);
2422        // A word with a letter is no mark.
2423        assert_eq!(ends(&["本。", "本"]), [2]);
2424        // An end that another mark follows in its word is not its last
2425        // mark, and one that an opening bracket follows is before it.
2426        assert_eq!(ends(&["本", "。~", "本"]), [3]);
2427        assert_eq!(ends(&["本", "?「", "本", "」", "本"]), [5]);
2428        // . alone inside a bracket ends nothing, as outside before a digit.
2429        assert_eq!(ends(&["「", "本", ".", "本", "」"]), [5]);
2430        assert_eq!(ends(&["本", ".", "本"]), [2, 3]);
2431    }
2432
2433    #[test]
2434    fn an_opening_bracket_that_nothing_closes_is_no_bracket() {
2435        // 本 :(。 本 。 本 。 and 本 ( 泣 。 本 。 本 。: the sentences after
2436        // the bracket are cut.
2437        assert_eq!(ends(&["本", ":(。", "本", "。", "本", "。"]), [2, 4, 6]);
2438        assert_eq!(
2439            ends(&["本", "(", "泣", "。", "本", "。", "本", "。"]),
2440            [4, 6, 8]
2441        );
2442        // A bracket that is closed keeps what is inside it: only the one
2443        // nothing closes is left out. 本 ( 本 「 本 。 」 本 。
2444        assert_eq!(
2445            ends(&["本", "(", "本", "「", "本", "。", "」", "本", "。"]),
2446            [9]
2447        );
2448        // The closing bracket closes the last one that is open: 「 本 ( 本 。
2449        // 」 本 。 has ( … 」 as its bracket, and 「 open no more.
2450        assert_eq!(ends(&["「", "本", "(", "本", "。", "」", "本", "。"]), [8]);
2451        // A closing bracket that closes nothing changes nothing.
2452        assert_eq!(ends(&["本", ")", "本", "。", "本"]), [4, 5]);
2453        // Two that are open and one that is closed: the first is left out.
2454        assert_eq!(
2455            ends(&["(", "本", "。", "(", "本", "。", ")", "本", "。"]),
2456            [3, 9]
2457        );
2458    }
2459
2460    #[test]
2461    fn a_period_of_a_number_and_a_half_width_period_end_nothing() {
2462        // The half-width period: 4.20, an ellipsis, and at the end.
2463        assert_eq!(ends(&["4", ".", "20", "本", "。", "本"]), [5, 6]);
2464        assert_eq!(ends(&["本", ".", ".", ".", "本", "."]), [6]);
2465        // The full-width one before a digit, of either width.
2466        assert_eq!(ends(&["3", ".", "14", "本", ".", "本"]), [5, 6]);
2467        assert_eq!(ends(&["3", ".", "14", "."]), [4]);
2468    }
2469
2470    #[test]
2471    fn a_period_inside_brackets_ends_nothing() {
2472        assert_eq!(ends(&["「", "本", "。", "」", "本", "。", "本"]), [6, 7]);
2473        // Two levels.
2474        assert_eq!(
2475            ends(&["(", "「", "本", "。", "」", "本", "。", ")", "本", "。"]),
2476            [10]
2477        );
2478    }
2479
2480    #[test]
2481    fn exclamation_and_question_marks_end_a_sentence() {
2482        assert_eq!(
2483            ends(&["本", "!", "本", "?", "本", "!", "本", "?", "本"]),
2484            [2, 4, 6, 8, 9]
2485        );
2486        assert_eq!(ends(&["本", "!?", "本"]), [2, 3]);
2487        assert_eq!(ends(&["「", "本", "!", "」", "本"]), [5]);
2488    }
2489
2490    #[test]
2491    fn what_follows_an_end_and_belongs_to_it_stays_with_the_sentence() {
2492        // More ends, and a closing bracket that nothing opened.
2493        assert_eq!(ends(&["本", "。", "。", "本"]), [3, 4]);
2494        assert_eq!(ends(&["本", "!", "?", "本"]), [3, 4]);
2495        assert_eq!(ends(&["本", "。", "」", "本", "。"]), [3, 5]);
2496    }
2497
2498    #[test]
2499    fn the_spaces_after_an_end_stay_with_the_sentence() {
2500        // 本。␣本。␣␣: no sentence starts with a space, and none is of
2501        // spaces alone.
2502        assert_eq!(
2503            ends(&["本", "。", "\u{3000}", "本", "。", "\u{3000}", "\u{3000}"]),
2504            [3, 7]
2505        );
2506        // A space elsewhere ends nothing.
2507        assert_eq!(ends(&["本", "\u{3000}", "本", "。"]), [4]);
2508        assert_eq!(ends(&["\u{3000}", "本"]), [2]);
2509    }
2510
2511    #[test]
2512    fn a_bracket_by_the_part_of_speech_of_the_schema_is_a_bracket() {
2513        // < 本 。 > 本, with the part of speech of a bracket: the two
2514        // characters are no brackets of the crate.
2515        let bracket = |surface: &str, kind: &str| {
2516            LatticeMorpheme::new(
2517                surface,
2518                format!("記号,{kind},*,*,*,*,{surface},{surface},{surface}"),
2519            )
2520        };
2521        let mut text = morphemes(&["本", "。", "本"]);
2522        text.insert(0, bracket("<", "括弧開"));
2523        text.insert(3, bracket(">", "括弧閉"));
2524        assert_eq!(Schema::ipadic().sentence_ends(&text), [5]);
2525        // As nouns they are none.
2526        assert_eq!(ends(&["<", "本", "。", ">", "本"]), [3, 5]);
2527    }
2528
2529    #[test]
2530    fn the_brackets_of_what_follows_an_end_are_counted() {
2531        // 本 。 (。 本 。 ) 本 。: (。 stays with the sentence the first 。
2532        // ends, and its bracket is open until ).
2533        assert_eq!(
2534            ends(&["本", "。", "(。", "本", "。", ")", "本", "。"]),
2535            [3, 8]
2536        );
2537    }
2538
2539    #[test]
2540    fn a_bracket_that_is_never_closed_does_not_keep_the_rest_in_one_sentence() {
2541        // Lindera 7.2.0 gave one sentence.
2542        assert_eq!(ends(&["「", "本", "。", "本", "。"]), [3, 5]);
2543        // With its closing bracket, the sentence inside stays inside.
2544        assert_eq!(ends(&["「", "本", "。", "本", "。", "」"]), [6]);
2545    }
2546}