1mod normalization;
50mod pattern;
51mod symbols;
52
53use std::borrow::Cow;
54use std::ops::Range;
55
56pub use normalization::Normalization;
57pub use pattern::Pattern;
58pub use symbols::{Marks, SurfaceRule, Symbols};
59
60use crate::bytes::{Reader, push_u32};
61use crate::error::{Error, Result};
62use crate::morpheme::{Morpheme, is_sentence_end, is_space};
63
64const NO_COLUMN: u32 = u32::MAX;
67
68const HEAD_FALLBACK_VERSION: u32 = 4;
74
75const EMPTY: &str = "*";
77
78const FORMAL_NOUNS: [&str; 6] = ["事", "為", "物", "際", "上", "所"];
82
83const COMMAS: &str = "、,,";
84
85const PERIODS: &str = "。..";
87
88const OPEN_BRACKETS: &str = "(([[{{「『【〔〈《〘〚‘“";
91
92const CLOSE_BRACKETS: &str = "))]]}}」』】〕〉》〙〛’”";
94
95const OTHER_SYMBOLS: &str = concat!(
99 "!\"#$&'*+-/:;<=>?@\\^_`|~",
100 "!"#$&'*+-/:;<=>?@\^_`|~",
101 "・…‥―—–‐〜※♪★☆○●◎◇◆□■△▲▽▼→←↑↓≠",
102);
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
107pub enum HeadRule {
108 #[default]
115 FunctionWordsApart,
116 LastWords,
125}
126
127impl HeadRule {
128 const ALL: [(HeadRule, u8); 2] = [(HeadRule::FunctionWordsApart, 0), (HeadRule::LastWords, 1)];
130
131 fn code(self) -> u8 {
133 Self::ALL
134 .iter()
135 .find(|(rule, _)| *rule == self)
136 .map_or(0, |(_, code)| *code)
137 }
138
139 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
153pub enum HeadFallback {
154 #[default]
160 FirstMorpheme,
161 FirstWord,
167}
168
169impl HeadFallback {
170 const ALL: [(HeadFallback, u8); 2] = [
172 (HeadFallback::FirstMorpheme, 0),
173 (HeadFallback::FirstWord, 1),
174 ];
175
176 fn code(self) -> u8 {
178 Self::ALL
179 .iter()
180 .find(|(fallback, _)| *fallback == self)
181 .map_or(0, |(_, code)| *code)
182 }
183
184 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
207pub enum SentenceSplit {
208 #[default]
213 None,
214 AfterEnds,
218}
219
220impl SentenceSplit {
221 const ALL: [(SentenceSplit, u8); 2] = [(SentenceSplit::None, 0), (SentenceSplit::AfterEnds, 1)];
223
224 fn code(self) -> u8 {
226 Self::ALL
227 .iter()
228 .find(|(split, _)| *split == self)
229 .map_or(0, |(_, code)| *code)
230 }
231
232 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#[derive(Debug, Clone, PartialEq, Eq, Default)]
253pub struct Schema {
254 pub part_of_speech: Range<usize>,
257 pub conjugation_type: Option<usize>,
259 pub conjugation_form: Option<usize>,
261 pub base_form: Option<usize>,
263 pub function_words: Vec<Pattern>,
265 pub not_heads: Vec<Pattern>,
268 pub particles: Vec<Pattern>,
271 pub lexicalized: Vec<Pattern>,
276 pub symbols: Symbols,
278 pub normalization: Normalization,
282 pub head_rule: HeadRule,
284 pub head_fallback: HeadFallback,
286 pub sentence_split: SentenceSplit,
289}
290
291impl Schema {
292 pub const DICTIONARIES: [&'static str; 4] = ["ipadic", "unidic", "unidic-cwj", "unidic-csj"];
295
296 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 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 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 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 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 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 word.or_else(|| bunsetsu.iter().position(|morpheme| !is_space(morpheme)))
561 .unwrap_or(0)
562 });
563 if head > function {
566 function = head;
567 }
568 Some((head, function))
569 }
570
571 pub fn sentence_starts<M: Morpheme>(&self, words: &[M]) -> Vec<usize> {
602 let mut starts = Vec::new();
603 if self.sentence_split == SentenceSplit::None {
604 return starts;
605 }
606 let mut index = 0;
607 while index < words.len() {
608 if !is_sentence_end(&words[index], words.get(index + 1)) {
609 index += 1;
610 continue;
611 }
612 index += 1;
613 let mut closed = false;
615 while index < words.len()
616 && (is_sentence_end(&words[index], words.get(index + 1))
617 || self.is_close_bracket(&words[index]))
618 {
619 closed |= self.is_close_bracket(&words[index]);
620 index += 1;
621 }
622 if index < words.len()
623 && !self.is_quotation_particle(words, index)
624 && !(closed && self.is_function_word(words, index))
625 {
626 starts.push(index);
627 }
628 }
629 starts
630 }
631
632 fn is_quotation_particle<M: Morpheme>(&self, morphemes: &[M], index: usize) -> bool {
643 matches!(morphemes[index].surface(), "と" | "って") && self.is_particle(morphemes, index)
644 }
645
646 fn is_function_word<M: Morpheme>(&self, morphemes: &[M], index: usize) -> bool {
657 self.function_words
658 .iter()
659 .any(|one| one.matches(self, morphemes, index))
660 }
661
662 fn first_word<M: Morpheme>(&self, bunsetsu: &[M]) -> Option<usize> {
674 bunsetsu.iter().enumerate().position(|(index, morpheme)| {
675 !(is_space(morpheme)
676 || self.is_comma(morpheme)
677 || self.is_period(morpheme)
678 || self.is_open_bracket(morpheme)
679 || self.is_close_bracket(morpheme)
680 || self.is_particle(bunsetsu, index))
681 })
682 }
683
684 pub fn surface_of<'a, M: Morpheme>(&self, morpheme: &'a M) -> Cow<'a, str> {
696 self.normalization.apply(morpheme.surface())
697 }
698
699 pub fn is_particle<M: Morpheme>(&self, bunsetsu: &[M], index: usize) -> bool {
711 self.particles
712 .iter()
713 .any(|one| one.matches(self, bunsetsu, index))
714 }
715
716 pub fn is_lexicalized<M: Morpheme>(&self, bunsetsu: &[M], index: usize) -> bool {
729 self.lexicalized
730 .iter()
731 .any(|one| one.matches(self, bunsetsu, index))
732 }
733
734 pub fn is_symbol<M: Morpheme>(&self, morpheme: &M) -> bool {
747 self.symbols.matches(self, morpheme)
748 }
749
750 pub fn is_comma<M: Morpheme>(&self, morpheme: &M) -> bool {
760 self.symbols.commas.matches(self, morpheme)
761 }
762
763 pub fn is_period<M: Morpheme>(&self, morpheme: &M) -> bool {
773 self.symbols.periods.matches(self, morpheme)
774 }
775
776 pub fn is_open_bracket<M: Morpheme>(&self, morpheme: &M) -> bool {
787 self.symbols.open_brackets.matches(self, morpheme)
788 }
789
790 pub fn is_close_bracket<M: Morpheme>(&self, morpheme: &M) -> bool {
801 self.symbols.close_brackets.matches(self, morpheme)
802 }
803
804 pub fn part_of_speech_of<M: Morpheme>(&self, morpheme: &M) -> String {
815 self.levels_of(morpheme, self.part_of_speech.clone())
816 }
817
818 pub(crate) fn levels_of<M: Morpheme>(&self, morpheme: &M, levels: Range<usize>) -> String {
830 let mut value = String::new();
831 for index in levels {
832 match morpheme.feature(index) {
833 Some(level) if level != EMPTY => {
834 if !value.is_empty() {
835 value.push('-');
836 }
837 value.push_str(level);
838 }
839 _ => break,
840 }
841 }
842 value
843 }
844
845 pub fn width(&self) -> usize {
853 [
854 Some(self.part_of_speech.end),
855 self.conjugation_type.map(|index| index + 1),
856 self.conjugation_form.map(|index| index + 1),
857 self.base_form.map(|index| index + 1),
858 ]
859 .into_iter()
860 .flatten()
861 .max()
862 .unwrap_or(0)
863 }
864
865 pub fn check<M: Morpheme>(&self, morphemes: &[M]) -> Result<()> {
883 let width = self.width();
884 let Some(last) = width.checked_sub(1) else {
885 return Ok(());
886 };
887 for (index, morpheme) in morphemes.iter().enumerate() {
888 if morpheme.feature(last).is_none() {
889 return Err(Error::Dictionary(format!(
890 "the morpheme {} ({:?}) has fewer than the {width} feature columns the schema reads: it is not of the dictionary of the model",
891 index + 1,
892 morpheme.surface()
893 )));
894 }
895 }
896 Ok(())
897 }
898
899 pub(crate) fn write(&self, bytes: &mut Vec<u8>) {
910 let column = |index: Option<usize>| index.map_or(NO_COLUMN, |index| index as u32);
911 push_u32(bytes, self.part_of_speech.start as u32);
912 push_u32(bytes, self.part_of_speech.end as u32);
913 push_u32(bytes, column(self.conjugation_type));
914 push_u32(bytes, column(self.conjugation_form));
915 push_u32(bytes, column(self.base_form));
916 for patterns in [
917 &self.function_words,
918 &self.not_heads,
919 &self.particles,
920 &self.lexicalized,
921 ] {
922 push_u32(bytes, patterns.len() as u32);
923 for pattern in patterns {
924 pattern.write(bytes);
925 }
926 }
927 self.symbols.write(bytes);
928 self.normalization.write(bytes);
929 bytes.push(self.head_rule.code());
930 bytes.push(self.head_fallback.code());
931 bytes.push(self.sentence_split.code());
932 }
933
934 pub(crate) fn read(reader: &mut Reader, version: u32) -> Result<Self> {
944 let start = reader.u32()? as usize;
945 let end = reader.u32()? as usize;
946 let mut column = || -> Result<Option<usize>> {
947 let value = reader.u32()?;
948 Ok((value != NO_COLUMN).then_some(value as usize))
949 };
950 let conjugation_type = column()?;
951 let conjugation_form = column()?;
952 let base_form = column()?;
953 let mut patterns = || -> Result<Vec<Pattern>> {
954 let count = reader.u32()?;
955 let mut patterns = Vec::new();
956 for _ in 0..count {
957 patterns.push(Pattern::read(reader, 0)?);
958 }
959 Ok(patterns)
960 };
961 let function_words = patterns()?;
962 let not_heads = patterns()?;
963 let particles = patterns()?;
964 let lexicalized = patterns()?;
965 let symbols = Symbols::read(reader)?;
966 let normalization = Normalization::read(reader)?;
967 let head_rule = HeadRule::from_code(reader.u8()?)?;
968 let (head_fallback, sentence_split) = if version >= HEAD_FALLBACK_VERSION {
969 (
970 HeadFallback::from_code(reader.u8()?)?,
971 SentenceSplit::from_code(reader.u8()?)?,
972 )
973 } else {
974 (HeadFallback::FirstMorpheme, SentenceSplit::None)
975 };
976 Ok(Self {
977 part_of_speech: start..end,
978 conjugation_type,
979 conjugation_form,
980 base_form,
981 function_words,
982 not_heads,
983 particles,
984 lexicalized,
985 symbols,
986 normalization,
987 head_rule,
988 head_fallback,
989 sentence_split,
990 })
991 }
992}
993
994#[cfg(test)]
995mod tests {
996 use super::*;
997 use crate::error::Error;
998 use crate::lattice::LatticeMorpheme;
999
1000 fn morphemes(pairs: &[(&str, &str)]) -> Vec<LatticeMorpheme> {
1002 pairs
1003 .iter()
1004 .map(|(surface, features)| LatticeMorpheme::new(*surface, *features))
1005 .collect()
1006 }
1007
1008 fn positions(pairs: &[(&str, &str)]) -> (usize, usize) {
1010 Schema::ipadic().positions(&morphemes(pairs)).unwrap()
1011 }
1012
1013 const HON: (&str, &str) = ("本", "名詞,一般,*,*,*,*,本,ホン,ホン");
1014 const WO: (&str, &str) = ("を", "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ");
1015 const NI: (&str, &str) = ("に", "助詞,格助詞,一般,*,*,*,に,ニ,ニ");
1016 const GA: (&str, &str) = ("が", "助詞,格助詞,一般,*,*,*,が,ガ,ガ");
1017 const YON: (&str, &str) = ("読ん", "動詞,自立,*,*,五段・マ行,連用タ接続,読む,ヨン,ヨン");
1018 const YOMU: (&str, &str) = ("読む", "動詞,自立,*,*,五段・マ行,基本形,読む,ヨム,ヨム");
1019 const DA: (&str, &str) = ("だ", "助動詞,*,*,*,特殊・タ,基本形,だ,ダ,ダ");
1020 const TA: (&str, &str) = ("た", "助動詞,*,*,*,特殊・タ,基本形,た,タ,タ");
1021 const DE: (&str, &str) = ("で", "助詞,接続助詞,*,*,*,*,で,デ,デ");
1022 const IRU: (&str, &str) = ("いる", "動詞,非自立,*,*,一段,基本形,いる,イル,イル");
1023 const MARU: (&str, &str) = ("。", "記号,句点,*,*,*,*,。,。,。");
1024 const TEN: (&str, &str) = ("、", "記号,読点,*,*,*,*,、,、,、");
1025 const KAGI: (&str, &str) = ("「", "記号,括弧開,*,*,*,*,「,「,「");
1026 const KAGI_TOJI: (&str, &str) = ("」", "記号,括弧閉,*,*,*,*,」,」,」");
1027 const RIYOU: (&str, &str) = ("利用", "名詞,サ変接続,*,*,*,*,利用,リヨウ,リヨー");
1028 const SHI: (&str, &str) = ("し", "動詞,自立,*,*,サ変・スル,連用形,する,シ,シ");
1029 const KOTO: (&str, &str) = ("こと", "名詞,非自立,一般,*,*,*,こと,コト,コト");
1030 const KIHON: (&str, &str) = ("基本", "名詞,一般,*,*,*,*,基本,キホン,キホン");
1031 const TEKI: (&str, &str) = ("的", "名詞,接尾,形容動詞語幹,*,*,*,的,テキ,テキ");
1032 const COMMA: (&str, &str) = (",", "名詞,サ変接続,*,*,*,*,*,*,*");
1034
1035 #[test]
1036 fn ipadic_names_the_columns_of_mecab_ipadic() {
1037 let features = [
1039 "動詞",
1040 "自立",
1041 "*",
1042 "*",
1043 "五段・マ行",
1044 "連用タ接続",
1045 "読む",
1046 "ヨン",
1047 "ヨン",
1048 ];
1049 let schema = Schema::ipadic();
1050 assert_eq!(
1051 features[schema.part_of_speech.clone()],
1052 ["動詞", "自立", "*", "*"]
1053 );
1054 assert_eq!(features[schema.conjugation_type.unwrap()], "五段・マ行");
1055 assert_eq!(features[schema.conjugation_form.unwrap()], "連用タ接続");
1056 assert_eq!(features[schema.base_form.unwrap()], "読む");
1057 }
1058
1059 #[test]
1060 fn a_content_word_and_a_particle_are_the_head_and_the_function_word() {
1061 assert_eq!(positions(&[HON, WO]), (0, 1));
1062 assert_eq!(positions(&[KIHON, HON, NI, WO]), (1, 3));
1064 }
1065
1066 #[test]
1067 fn a_content_word_alone_is_both() {
1068 assert_eq!(positions(&[HON]), (0, 0));
1069 assert_eq!(positions(&[KIHON, HON]), (1, 1));
1070 }
1071
1072 #[test]
1073 fn punctuation_at_the_end_is_neither() {
1074 assert_eq!(positions(&[YON, DA, MARU]), (0, 1));
1075 assert_eq!(positions(&[HON, WO, TEN]), (0, 1));
1076 assert_eq!(positions(&[HON, WO, COMMA]), (0, 1));
1078 assert_eq!(positions(&[HON, COMMA]), (0, 0));
1079 }
1080
1081 #[test]
1082 fn a_bunsetsu_of_symbols_only_has_both_at_its_first_morpheme() {
1083 assert_eq!(positions(&[MARU]), (0, 0));
1084 assert_eq!(positions(&[KAGI_TOJI, MARU, COMMA]), (0, 0));
1085 }
1086
1087 #[test]
1088 fn a_bracket_before_the_head_is_skipped() {
1089 assert_eq!(positions(&[KAGI, HON, WO]), (1, 2));
1090 }
1091
1092 #[test]
1093 fn a_dependent_verb_is_the_function_word() {
1094 assert_eq!(positions(&[YON, DE, IRU]), (0, 2));
1096 assert_eq!(positions(&[YON, DE, IRU, MARU]), (0, 2));
1097 }
1098
1099 #[test]
1100 fn a_head_after_the_function_word_takes_the_function_word_with_it() {
1101 assert_eq!(positions(&[NI, HON]), (1, 1));
1103 assert_eq!(positions(&[NI, HON, MARU]), (1, 1));
1105 assert_eq!(positions(&[NI, HON, DA]), (1, 2));
1107 }
1108
1109 #[test]
1110 fn the_function_words_of_cabocha_are_function_words() {
1111 let yoma = ("読ま", "動詞,自立,*,*,五段・マ行,未然形,読む,ヨマ,ヨマ");
1113 let reru = ("れる", "動詞,接尾,*,*,一段,基本形,れる,レル,レル");
1114 assert_eq!(positions(&[yoma, reru]), (0, 1));
1115 let yomi = ("読み", "動詞,自立,*,*,五段・マ行,連用形,読む,ヨミ,ヨミ");
1117 let nikui = (
1118 "にくい",
1119 "形容詞,非自立,*,*,形容詞・アウオ段,基本形,にくい,ニクイ,ニクイ",
1120 );
1121 assert_eq!(positions(&[yomi, nikui]), (0, 1));
1122 let ppoi = (
1124 "っぽい",
1125 "形容詞,接尾,*,*,形容詞・アウオ段,基本形,っぽい,ッポイ,ッポイ",
1126 );
1127 assert_eq!(positions(&[HON, ppoi]), (0, 1));
1128 assert_eq!(positions(&[HON, WO, reru]), (0, 2));
1130 assert_eq!(positions(&[HON, WO, nikui]), (0, 2));
1131 assert_eq!(positions(&[HON, WO, ppoi]), (0, 2));
1132 assert_eq!(positions(&[HON, DA]), (0, 1));
1134 assert_eq!(positions(&[HON, WO]), (0, 1));
1135 }
1136
1137 #[test]
1138 fn suru_and_dekiru_are_function_words() {
1139 assert_eq!(positions(&[RIYOU, SHI, TA]), (0, 2));
1141 assert_eq!(positions(&[RIYOU, SHI]), (0, 1));
1142 assert_eq!(positions(&[SHI, TA]), (0, 1));
1144 assert_eq!(positions(&[SHI]), (0, 0));
1145 assert_eq!(positions(&[RIYOU, YON, DA]), (1, 2));
1147 let dekiru = ("でき", "動詞,自立,*,*,一段,連用形,できる,デキ,デキ");
1149 assert_eq!(positions(&[RIYOU, dekiru, TA]), (0, 2));
1150 let dekiru = ("出来", "動詞,自立,*,*,一段,連用形,出来る,デキ,デキ");
1151 assert_eq!(positions(&[RIYOU, dekiru, TA]), (0, 2));
1152 }
1153
1154 #[test]
1155 fn a_dependent_noun_and_the_suffix_teki_are_not_heads() {
1156 assert_eq!(positions(&[YOMU, KOTO, GA]), (0, 2));
1158 assert_eq!(positions(&[KOTO, GA]), (0, 1));
1160 assert_eq!(positions(&[KIHON, TEKI, NI]), (0, 2));
1162 let naga = (
1164 "長",
1165 "形容詞,自立,*,*,形容詞・アウオ段,ガル接続,長い,ナガ,ナガ",
1166 );
1167 let sa = ("さ", "名詞,接尾,特殊,*,*,*,さ,サ,サ");
1168 assert_eq!(positions(&[naga, sa, GA]), (0, 2));
1169 let nin = ("人", "名詞,接尾,助数詞,*,*,*,人,ニン,ニン");
1171 assert_eq!(positions(&[HON, nin, GA]), (1, 2));
1172 }
1173
1174 #[test]
1175 fn a_verb_after_a_particle_is_part_of_a_compound_function_word() {
1176 let naru = ("なっ", "動詞,自立,*,*,五段・ラ行,連用タ接続,なる,ナッ,ナッ");
1177 assert_eq!(positions(&[YOMU, KOTO, NI, naru, TA]), (0, 4));
1179 assert_eq!(positions(&[HON, NI, naru, TA]), (0, 3));
1181 assert_eq!(positions(&[HON, naru, TA]), (1, 2));
1183 assert_eq!(positions(&[naru, TA]), (0, 1));
1185 }
1186
1187 #[test]
1188 fn no_morpheme_has_no_positions() {
1189 let none: [LatticeMorpheme; 0] = [];
1190 assert_eq!(Schema::ipadic().positions(&none), None);
1191 }
1192
1193 #[test]
1194 fn morphemes_with_fewer_columns_do_not_panic() {
1195 assert_eq!(positions(&[("x", ""), ("y", "")]), (1, 1));
1197 assert_eq!(positions(&[("本", "名詞"), ("を", "助詞")]), (0, 1));
1198 assert_eq!(
1199 positions(&[("利用", "名詞,サ変接続"), ("し", "動詞,自立")]),
1200 (1, 1)
1201 );
1202 let schema = Schema::ipadic();
1203 let bare = LatticeMorpheme::new("x", "");
1204 assert!(!schema.is_symbol(&bare));
1205 assert_eq!(schema.part_of_speech_of(&bare), "");
1206 assert!(schema.is_comma(&LatticeMorpheme::new(",", "")));
1208 }
1209
1210 #[test]
1211 fn a_schema_without_patterns_takes_the_last_morpheme() {
1212 let schema = Schema {
1214 part_of_speech: 0..4,
1215 ..Schema::default()
1216 };
1217 assert_eq!(schema.positions(&morphemes(&[HON, WO, MARU])), Some((2, 2)));
1218 }
1219
1220 #[test]
1221 fn punctuation_and_brackets_are_recognized_by_part_of_speech_and_by_surface() {
1222 let schema = Schema::ipadic();
1223 let unknown = |surface: &str| LatticeMorpheme::new(surface, "名詞,サ変接続,*,*,*,*,*,*,*");
1224 let known = |pair: (&str, &str)| LatticeMorpheme::new(pair.0, pair.1);
1225
1226 assert!(schema.is_comma(&known(TEN)));
1227 assert!(schema.is_period(&known(MARU)));
1228 assert!(schema.is_open_bracket(&known(KAGI)));
1229 assert!(schema.is_close_bracket(&known(KAGI_TOJI)));
1230 for surface in [",", ",", "、"] {
1231 assert!(schema.is_comma(&unknown(surface)), "{surface}");
1232 assert!(!schema.is_period(&unknown(surface)), "{surface}");
1233 }
1234 for surface in [".", ".", "。"] {
1235 assert!(schema.is_period(&unknown(surface)), "{surface}");
1236 assert!(!schema.is_comma(&unknown(surface)), "{surface}");
1237 }
1238 for surface in ["(", "(", "[", "「", "『", "“"] {
1239 assert!(schema.is_open_bracket(&unknown(surface)), "{surface}");
1240 assert!(!schema.is_close_bracket(&unknown(surface)), "{surface}");
1241 }
1242 for surface in [")", ")", "]", "」", "』", "”"] {
1243 assert!(schema.is_close_bracket(&unknown(surface)), "{surface}");
1244 assert!(!schema.is_open_bracket(&unknown(surface)), "{surface}");
1245 }
1246 for surface in [
1248 ",", "。", "(", "」", "!", "?", "-", "/", "・", "…", ",“", "!?",
1249 ] {
1250 assert!(schema.is_symbol(&unknown(surface)), "{surface}");
1251 }
1252 let comma = LatticeMorpheme::new("、", "記号,読点,*,*,*,*,、,、,、");
1255 let period = LatticeMorpheme::new("。", "記号,句点,*,*,*,*,。,。,。");
1256 let open = LatticeMorpheme::new("「", "記号,括弧開,*,*,*,*,「,「,「");
1257 let close = LatticeMorpheme::new("」", "記号,括弧閉,*,*,*,*,」,」,」");
1258 assert!(schema.is_comma(&comma) && !schema.is_period(&comma));
1259 assert!(schema.is_period(&period) && !schema.is_comma(&period));
1260 assert!(schema.is_open_bracket(&open) && !schema.is_close_bracket(&open));
1261 assert!(schema.is_close_bracket(&close) && !schema.is_open_bracket(&close));
1262 assert!(!schema.is_comma(&unknown("、")));
1263 let alphabet = LatticeMorpheme::new("A", "記号,アルファベット,*,*,*,*,A,エイ,エイ");
1265 assert!(schema.is_symbol(&alphabet));
1266 assert!(!schema.is_comma(&alphabet) && !schema.is_period(&alphabet));
1267 for surface in ["%", "°", "%、", "本", "1", "a"] {
1269 assert!(!schema.is_symbol(&unknown(surface)), "{surface}");
1270 }
1271 assert!(!schema.is_comma(&known(HON)));
1272 }
1273
1274 #[test]
1275 fn the_brackets_come_in_pairs() {
1276 assert_eq!(
1277 OPEN_BRACKETS.chars().count(),
1278 CLOSE_BRACKETS.chars().count()
1279 );
1280 let all = [
1282 COMMAS,
1283 PERIODS,
1284 OPEN_BRACKETS,
1285 CLOSE_BRACKETS,
1286 OTHER_SYMBOLS,
1287 ]
1288 .concat();
1289 let mut characters: Vec<char> = all.chars().collect();
1290 let count = characters.len();
1291 characters.sort_unstable();
1292 characters.dedup();
1293 assert_eq!(characters.len(), count);
1294 }
1295
1296 #[test]
1297 fn the_part_of_speech_is_joined_up_to_the_first_empty_level() {
1298 let schema = Schema::ipadic();
1299 let of =
1300 |pair: (&str, &str)| schema.part_of_speech_of(&LatticeMorpheme::new(pair.0, pair.1));
1301 assert_eq!(of(HON), "名詞-一般");
1302 assert_eq!(of(TEKI), "名詞-接尾-形容動詞語幹");
1303 assert_eq!(of(DA), "助動詞");
1304 assert_eq!(of(("x", "*,名詞")), "");
1305 }
1306
1307 #[test]
1308 fn particles_and_words_taken_by_their_surface_follow_the_patterns() {
1309 let schema = Schema::ipadic();
1310 let bunsetsu = morphemes(&[
1311 (
1312 "ゆっくり",
1313 "副詞,助詞類接続,*,*,*,*,ゆっくり,ユックリ,ユックリ",
1314 ),
1315 ("と", "助詞,格助詞,一般,*,*,*,と,ト,ト"),
1316 ("この", "連体詞,*,*,*,*,*,この,コノ,コノ"),
1317 ("しかし", "接続詞,*,*,*,*,*,しかし,シカシ,シカシ"),
1318 ("本", "名詞,一般,*,*,*,*,本,ホン,ホン"),
1319 ]);
1320 let particles: Vec<bool> = (0..6)
1322 .map(|index| schema.is_particle(&bunsetsu, index))
1323 .collect();
1324 assert_eq!(particles, [false, true, false, false, false, false]);
1325 let lexicalized: Vec<bool> = (0..6)
1326 .map(|index| schema.is_lexicalized(&bunsetsu, index))
1327 .collect();
1328 assert_eq!(lexicalized, [true, true, true, true, false, false]);
1329 }
1330
1331 #[test]
1332 fn unidic_is_a_second_schema_of_data_only() {
1333 let schema = Schema::unidic();
1334 let omotte_iru = morphemes(&[
1336 (
1337 "思っ",
1338 "動詞,一般,*,*,五段-ワア行,連用形-促音便,オモウ,思う",
1339 ),
1340 ("て", "助詞,接続助詞,*,*,*,*,テ,て"),
1341 (
1342 "いる",
1343 "動詞,非自立可能,*,*,上一段-ア行,終止形-一般,イル,居る",
1344 ),
1345 ]);
1346 assert_eq!(schema.positions(&omotte_iru), Some((0, 2)));
1347
1348 let ni_yotte = morphemes(&[
1350 ("事故", "名詞,普通名詞,一般,*,*,*,ジコ,事故"),
1351 ("に", "助詞,格助詞,*,*,*,*,ニ,に"),
1352 ("よっ", "動詞,一般,*,*,五段-ラ行,連用形-促音便,ヨル,因る"),
1353 ("て", "助詞,接続助詞,*,*,*,*,テ,て"),
1354 ]);
1355 assert_eq!(schema.positions(&ni_yotte), Some((0, 3)));
1356
1357 let ga_yomu = morphemes(&[
1359 ("本", "名詞,普通名詞,一般,*,*,*,ホン,本"),
1360 ("が", "助詞,格助詞,*,*,*,*,ガ,が"),
1361 ("読む", "動詞,一般,*,*,五段-マ行,終止形-一般,ヨム,読む"),
1362 ]);
1363 assert_eq!(schema.positions(&ga_yomu), Some((2, 2)));
1364
1365 let period = LatticeMorpheme::new("。", "補助記号,句点,*,*,*,*,,。");
1367 assert!(schema.is_period(&period) && schema.is_symbol(&period));
1368 assert_eq!(Schema::ipadic().positions(&omotte_iru), Some((2, 2)));
1370 }
1371
1372 const SURU_UNIDIC: (&str, &str) =
1373 ("する", "動詞,非自立可能,*,*,サ行変格,連体形-一般,スル,為る");
1374 const TA_UNIDIC: (&str, &str) = ("た", "助動詞,*,*,*,助動詞-タ,連体形-一般,タ,た");
1375 const NI_UNIDIC: (&str, &str) = ("に", "助詞,格助詞,*,*,*,*,ニ,に");
1376 const TSUKAU_UNIDIC: (&str, &str) =
1377 ("使う", "動詞,一般,*,*,五段-ワア行,連体形-一般,ツカウ,使う");
1378
1379 #[test]
1380 fn unidic_does_not_take_an_auxiliary_stem_as_the_head() {
1381 let schema = Schema::unidic();
1382 let you = morphemes(&[
1384 TSUKAU_UNIDIC,
1385 ("よう", "形状詞,助動詞語幹,*,*,*,*,ヨウ,様"),
1386 ("に", "助動詞,*,*,*,助動詞-ダ,連用形-ニ,ダ,だ"),
1387 ]);
1388 assert_eq!(schema.positions(&you), Some((0, 2)));
1389 let sou = morphemes(&[
1391 (
1392 "働い",
1393 "動詞,一般,*,*,五段-カ行,連用形-イ音便,ハタラク,働く",
1394 ),
1395 TA_UNIDIC,
1396 ("そう", "名詞,助動詞語幹,*,*,*,*,ソウ,そう-伝聞"),
1397 ("だ", "助動詞,*,*,*,助動詞-ダ,終止形-一般,ダ,だ"),
1398 ]);
1399 assert_eq!(schema.positions(&sou), Some((0, 3)));
1400 }
1401
1402 #[test]
1403 fn unidic_does_not_take_a_formal_noun_after_a_predicate_as_the_head() {
1404 let schema = Schema::unidic();
1405 let koto = ("こと", "名詞,普通名詞,一般,*,*,*,コト,事");
1406 let tame = ("ため", "名詞,普通名詞,副詞可能,*,*,*,タメ,為");
1407 let kounyuu = ("購入", "名詞,普通名詞,サ変可能,*,*,*,コウニュウ,購入");
1408 let after_verb = morphemes(&[kounyuu, SURU_UNIDIC, koto, NI_UNIDIC]);
1410 assert_eq!(schema.positions(&after_verb), Some((0, 3)));
1411 let after_auxiliary = morphemes(&[kounyuu, SURU_UNIDIC, TA_UNIDIC, tame, NI_UNIDIC]);
1413 assert_eq!(schema.positions(&after_auxiliary), Some((0, 4)));
1414 let after_adjective = morphemes(&[
1416 (
1417 "新しい",
1418 "形容詞,一般,*,*,形容詞,連体形-一般,アタラシイ,新しい",
1419 ),
1420 koto,
1421 NI_UNIDIC,
1422 ]);
1423 assert_eq!(schema.positions(&after_adjective), Some((0, 2)));
1424 assert_eq!(
1426 schema.positions(&morphemes(&[koto, NI_UNIDIC])),
1427 Some((0, 1))
1428 );
1429 assert_eq!(
1430 schema.positions(&morphemes(&[kounyuu, koto, NI_UNIDIC])),
1431 Some((1, 2))
1432 );
1433 let hito = morphemes(&[
1435 TSUKAU_UNIDIC,
1436 ("人", "名詞,普通名詞,一般,*,*,*,ヒト,人"),
1437 NI_UNIDIC,
1438 ]);
1439 assert_eq!(schema.positions(&hito), Some((1, 2)));
1440 }
1441
1442 #[test]
1443 fn unidic_does_not_take_a_nominal_suffix_after_an_adjective_as_the_head() {
1444 let schema = Schema::unidic();
1445 let ookisa = morphemes(&[
1447 ("大き", "形容詞,一般,*,*,形容詞,語幹-一般,オオキイ,大きい"),
1448 ("さ", "接尾辞,名詞的,一般,*,*,*,サ,さ"),
1449 NI_UNIDIC,
1450 ]);
1451 assert_eq!(schema.positions(&ookisa), Some((0, 2)));
1452 let shichou = morphemes(&[
1454 ("市", "名詞,普通名詞,一般,*,*,*,シ,市"),
1455 ("長", "接尾辞,名詞的,一般,*,*,*,チョウ,長"),
1456 NI_UNIDIC,
1457 ]);
1458 assert_eq!(schema.positions(&shichou), Some((1, 2)));
1459 }
1460
1461 #[test]
1462 fn unidic_takes_a_letter_as_a_symbol() {
1463 let schema = Schema::unidic();
1464 let kilometers = morphemes(&[
1466 ("5", "名詞,数詞,*,*,*,*,ゴ,五"),
1467 ("k", "記号,文字,*,*,*,*,ケー,K"),
1468 ("m", "記号,文字,*,*,*,*,エム,M"),
1469 ]);
1470 assert!(schema.is_symbol(&kilometers[1]));
1471 assert_eq!(schema.positions(&kilometers), Some((0, 0)));
1472 }
1473
1474 #[test]
1475 fn a_schema_is_chosen_by_the_name_of_the_dictionary() {
1476 assert_eq!(Schema::for_dictionary("ipadic"), Some(Schema::ipadic()));
1477 for name in ["unidic", "unidic-cwj", "unidic-csj"] {
1478 assert_eq!(Schema::for_dictionary(name), Some(Schema::unidic()));
1479 }
1480 for name in Schema::DICTIONARIES {
1482 assert!(Schema::for_dictionary(name).is_some(), "{name}");
1483 }
1484 for name in ["", "IPADIC", "ipadic-neologd", "ko-dic", "unidic-"] {
1485 assert_eq!(Schema::for_dictionary(name), None, "{name}");
1486 }
1487 }
1488
1489 fn last_words() -> Schema {
1493 Schema {
1494 part_of_speech: 0..2,
1495 not_heads: vec![Pattern::new(&["助詞"]), Pattern::new(&["接尾辞"])],
1496 symbols: Symbols {
1497 others: Marks::new(&[&["特殊"]], ""),
1498 surface: SurfaceRule::OneCharacter,
1499 ..Symbols::default()
1500 },
1501 head_rule: HeadRule::LastWords,
1502 ..Schema::default()
1503 }
1504 }
1505
1506 #[test]
1507 fn with_the_rule_of_the_last_words_the_two_positions_are_found_apart() {
1508 const NOUN: (&str, &str) = ("本", "名詞,普通名詞,*,*,本,ほん,*");
1509 const PARTICLE: (&str, &str) = ("を", "助詞,格助詞,*,*,を,を,*");
1510 const VERB: (&str, &str) = ("読んで", "動詞,*,子音動詞マ行,タ系連用テ形,読む,よんで,*");
1511 const SUFFIX: (&str, &str) = ("いる", "接尾辞,動詞性接尾辞,母音動詞,基本形,いる,いる,*");
1512 const PERIOD: (&str, &str) = ("。", "特殊,句点,*,*,。,。,*");
1513 const BRACKET: (&str, &str) = ("「", "特殊,括弧始,*,*,「,「,*");
1514 let schema = last_words();
1515 let positions = |pairs: &[(&str, &str)]| schema.positions(&morphemes(pairs)).unwrap();
1516 assert_eq!(positions(&[NOUN]), (0, 0));
1518 assert_eq!(positions(&[NOUN, PARTICLE]), (0, 1));
1520 assert_eq!(positions(&[VERB, SUFFIX]), (0, 1));
1521 assert_eq!(positions(&[VERB, SUFFIX, PARTICLE]), (0, 2));
1522 assert_eq!(positions(&[NOUN, PARTICLE, NOUN]), (2, 2));
1525 assert_eq!(positions(&[SUFFIX, NOUN, PARTICLE, PARTICLE]), (1, 3));
1526 assert_eq!(positions(&[VERB, SUFFIX, PERIOD]), (0, 1));
1528 assert_eq!(positions(&[BRACKET, NOUN, PERIOD]), (1, 1));
1529 assert_eq!(positions(&[PERIOD]), (0, 0));
1531 assert_eq!(positions(&[BRACKET, PERIOD]), (0, 0));
1532 assert_eq!(positions(&[PARTICLE]), (0, 0));
1533 assert_eq!(positions(&[BRACKET, PARTICLE]), (0, 1));
1534 assert_eq!(schema.positions::<LatticeMorpheme>(&[]), None);
1535
1536 let with_patterns = Schema {
1538 function_words: vec![Pattern::new(&["名詞"])],
1539 ..last_words()
1540 };
1541 assert_eq!(
1542 with_patterns.positions(&morphemes(&[NOUN, PARTICLE])),
1543 Some((0, 1))
1544 );
1545 let apart = Schema {
1548 head_rule: HeadRule::FunctionWordsApart,
1549 ..last_words()
1550 };
1551 assert_eq!(apart.positions(&morphemes(&[NOUN, PARTICLE])), Some((0, 0)));
1552 assert_eq!(apart.positions(&morphemes(&[VERB, SUFFIX])), Some((0, 0)));
1553 }
1554
1555 #[test]
1556 fn the_rule_of_the_head_comes_back_from_the_bytes() {
1557 assert_eq!(Schema::default().head_rule, HeadRule::FunctionWordsApart);
1558 assert_eq!(Schema::ipadic().head_rule, HeadRule::FunctionWordsApart);
1559 assert_eq!(Schema::unidic().head_rule, HeadRule::FunctionWordsApart);
1560 for (rule, code) in HeadRule::ALL {
1561 assert_eq!(rule.code(), code);
1562 assert_eq!(HeadRule::from_code(code).unwrap(), rule);
1563 let schema = Schema {
1564 head_rule: rule,
1565 ..last_words()
1566 };
1567 let mut bytes = Vec::new();
1568 schema.write(&mut bytes);
1569 assert_eq!(bytes[bytes.len() - 3], code);
1571 let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
1572 assert_eq!(
1573 Schema::read(&mut reader, crate::model::VERSION).unwrap(),
1574 schema
1575 );
1576 assert_eq!(reader.remaining(), 0);
1577 }
1578 let mut bytes = Vec::new();
1580 last_words().write(&mut bytes);
1581 let rule = bytes.len() - 3;
1582 bytes[rule] = 2;
1583 let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
1584 assert_eq!(
1585 Schema::read(&mut reader, crate::model::VERSION)
1586 .unwrap_err()
1587 .to_string(),
1588 "2 is not the code of a rule of the head"
1589 );
1590 }
1591
1592 #[test]
1593 fn a_schema_comes_back_from_its_bytes() {
1594 for schema in [Schema::ipadic(), Schema::unidic(), Schema::default()] {
1595 let mut bytes = Vec::new();
1596 schema.write(&mut bytes);
1597 let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
1598 assert_eq!(
1599 Schema::read(&mut reader, crate::model::VERSION).unwrap(),
1600 schema
1601 );
1602 assert_eq!(reader.remaining(), 0);
1603 }
1604 }
1605
1606 #[test]
1607 fn the_two_lists_of_patterns_keep_their_places_in_the_bytes() {
1608 let schema = Schema {
1609 function_words: vec![Pattern::new(&["助詞"])],
1610 not_heads: vec![Pattern::new(&["名詞", "非自立"]), Pattern::default()],
1611 ..Schema::default()
1612 };
1613 let mut bytes = Vec::new();
1614 schema.write(&mut bytes);
1615 let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
1616 let read = Schema::read(&mut reader, crate::model::VERSION).unwrap();
1617 assert_eq!(read.function_words, [Pattern::new(&["助詞"])]);
1618 assert_eq!(read.not_heads.len(), 2);
1619 }
1620
1621 #[test]
1622 fn bytes_that_end_inside_a_schema_are_an_error() {
1623 let mut bytes = Vec::new();
1624 Schema::ipadic().write(&mut bytes);
1625 for length in [0, 4, 20, 24, bytes.len() / 2, bytes.len() - 1] {
1626 let mut reader = Reader::new(&bytes[..length], "test bytes", Error::Chunker);
1627 let message = Schema::read(&mut reader, crate::model::VERSION)
1628 .unwrap_err()
1629 .to_string();
1630 assert!(message.contains("ends early"), "{length}: {message}");
1631 }
1632 }
1633
1634 #[test]
1635 fn the_width_is_the_number_of_columns_the_schema_reads() {
1636 assert_eq!(Schema::ipadic().width(), 7);
1639 let mut schema = Schema::ipadic();
1640 schema.base_form = None;
1641 assert_eq!(schema.width(), 6);
1642 schema.conjugation_form = None;
1643 schema.conjugation_type = Some(9);
1644 assert_eq!(schema.width(), 10);
1645 schema.conjugation_type = None;
1646 assert_eq!(schema.width(), 4);
1647 schema.part_of_speech = 0..0;
1648 assert_eq!(schema.width(), 0);
1649 }
1650
1651 #[test]
1652 fn morphemes_with_fewer_columns_than_the_schema_reads_are_refused() {
1653 let schema = Schema::ipadic();
1654 let wide = LatticeMorpheme::new("彼", "名詞,代名詞,一般,*,*,*,彼,カレ,カレ");
1655 let unknown = LatticeMorpheme::new("x", "名詞,一般,*,*,*,*,*");
1657 let narrow = LatticeMorpheme::new("彼", "名詞,代名詞,一般,*,*,*");
1658 let none: [LatticeMorpheme; 0] = [];
1659 assert!(schema.check(&none).is_ok());
1660 assert!(schema.check(&[wide.clone(), unknown.clone()]).is_ok());
1661
1662 let error = schema.check(&[wide.clone(), unknown, narrow]).unwrap_err();
1663 assert!(matches!(error, Error::Dictionary(_)), "{error:?}");
1664 assert_eq!(
1665 error.to_string(),
1666 "the morpheme 3 (\"彼\") has fewer than the 7 feature columns the schema reads: it is not of the dictionary of the model"
1667 );
1668
1669 let mut schema = Schema::ipadic();
1671 schema.part_of_speech = 0..0;
1672 schema.conjugation_type = None;
1673 schema.conjugation_form = None;
1674 schema.base_form = None;
1675 assert!(schema.check(&[LatticeMorpheme::new("彼", "")]).is_ok());
1676 }
1677
1678 const SURU: (&str, &str) = ("する", "動詞,自立,*,*,サ変・スル,基本形,する,スル,スル");
1682 const TO: (&str, &str) = ("と", "助詞,格助詞,引用,*,*,*,と,ト,ト");
1683 const SPACE: (&str, &str) = ("\u{3000}", "記号,空白,*,*,*,*,\u{3000},\u{3000},\u{3000}");
1685
1686 fn unidic(surface: &'static str, part_of_speech: &str, lemma: &str) -> LatticeMorpheme {
1689 let levels: Vec<&str> = part_of_speech.split(',').collect();
1690 let mut columns = vec!["*"; 17];
1691 columns[..levels.len()].copy_from_slice(&levels);
1692 columns[7] = lemma;
1693 LatticeMorpheme::new(surface, columns.join(","))
1694 }
1695
1696 #[test]
1697 fn the_schemas_of_this_crate_take_the_first_word() {
1698 assert_eq!(Schema::ipadic().head_fallback, HeadFallback::FirstWord);
1699 assert_eq!(Schema::unidic().head_fallback, HeadFallback::FirstWord);
1700 assert_eq!(Schema::default().head_fallback, HeadFallback::FirstMorpheme);
1701 }
1702
1703 #[cfg(feature = "train")]
1706 #[test]
1707 fn the_schemas_of_cabocha_take_the_first_morpheme() {
1708 use crate::cabocha::{self, PartOfSpeechSet};
1709
1710 for set in [
1711 PartOfSpeechSet::Ipa,
1712 PartOfSpeechSet::Juman,
1713 PartOfSpeechSet::Unidic,
1714 ] {
1715 assert_eq!(
1716 cabocha::schema(set).head_fallback,
1717 HeadFallback::FirstMorpheme,
1718 "{set:?}"
1719 );
1720 }
1721 }
1722
1723 #[test]
1724 fn a_bunsetsu_without_a_head_word_has_its_first_word_as_the_head() {
1725 assert_eq!(positions(&[KAGI, SURU, KAGI_TOJI, TO]), (1, 3));
1727 assert_eq!(positions(&[SURU, TO]), (0, 1));
1729 assert_eq!(positions(&[KAGI, KAGI_TOJI, TO]), (0, 2));
1732 assert_eq!(positions(&[KAGI, HON, KAGI_TOJI, WO]), (1, 3));
1734
1735 let first_morpheme = Schema {
1737 head_fallback: HeadFallback::FirstMorpheme,
1738 ..Schema::ipadic()
1739 };
1740 assert_eq!(
1741 first_morpheme.positions(&morphemes(&[KAGI, SURU, KAGI_TOJI, TO])),
1742 Some((0, 3))
1743 );
1744 }
1745
1746 #[test]
1747 fn a_word_in_letters_keeps_its_first_letter_and_a_mark_before_a_verb_is_passed_over() {
1748 let schema = Schema::unidic();
1749 let open = unidic("「", "補助記号,括弧開", "「");
1750 let close = unidic("」", "補助記号,括弧閉", "」");
1751 let to = unidic("と", "助詞,格助詞", "と");
1752 let no = unidic("の", "助詞,格助詞", "の");
1753 let naosu = unidic("治す", "動詞,非自立可能", "直す");
1755 let letter = |surface| unidic(surface, "記号,文字", surface);
1756
1757 assert_eq!(
1759 schema.positions(&[open.clone(), naosu, close.clone(), to.clone()]),
1760 Some((1, 3))
1761 );
1762 assert_eq!(
1765 schema.positions(&[
1766 letter("S"),
1767 letter("i"),
1768 letter("r"),
1769 letter("i"),
1770 no.clone()
1771 ]),
1772 Some((0, 4))
1773 );
1774 assert_eq!(
1776 schema.positions(&[open, letter("S"), letter("M"), letter("T"), close, to]),
1777 Some((1, 5))
1778 );
1779 assert_eq!(
1781 schema.positions(&[unidic("♂", "補助記号,一般", "♂"), no]),
1782 Some((0, 1))
1783 );
1784 }
1785
1786 #[test]
1787 fn a_space_is_neither_the_head_word_nor_the_function_word() {
1788 assert_eq!(positions(&[SPACE, SURU]), (1, 1));
1790 assert_eq!(positions(&[HON, SPACE, WO]), (0, 2));
1792 assert_eq!(positions(&[HON, WO, SPACE]), (0, 1));
1793 assert_eq!(positions(&[SPACE, SPACE]), (0, 0));
1795 const NOUN_SPACE: (&str, &str) = (" ", "名詞,一般,*,*,*,*,*,*,*");
1798 assert_eq!(positions(&[NOUN_SPACE, HON, WO]), (1, 2));
1799 assert_eq!(positions(&[HON, NOUN_SPACE, WO]), (0, 2));
1800 assert_eq!(positions(&[HON, WO, NOUN_SPACE]), (0, 1));
1801 assert_eq!(positions(&[SPACE, KAGI, KAGI_TOJI]), (1, 1));
1803
1804 let space = unidic("\u{3000}", "空白", "\u{3000}");
1807 let naosu = unidic("治す", "動詞,非自立可能", "直す");
1808 assert_eq!(Schema::unidic().positions(&[space, naosu]), Some((1, 1)));
1809
1810 let first_morpheme = Schema {
1813 head_fallback: HeadFallback::FirstMorpheme,
1814 ..Schema::ipadic()
1815 };
1816 assert_eq!(
1817 first_morpheme.positions(&morphemes(&[SPACE, HON, WO])),
1818 Some((1, 2))
1819 );
1820 assert_eq!(
1821 first_morpheme.positions(&morphemes(&[SPACE, SURU])),
1822 Some((1, 1))
1823 );
1824 assert_eq!(
1825 first_morpheme.positions(&morphemes(&[SPACE, KAGI, SURU])),
1826 Some((1, 2))
1827 );
1828 }
1829
1830 #[test]
1831 fn the_head_word_of_a_bunsetsu_without_one_comes_back_from_the_bytes() {
1832 for (fallback, code) in HeadFallback::ALL {
1833 assert_eq!(fallback.code(), code);
1834 assert_eq!(HeadFallback::from_code(code).unwrap(), fallback);
1835 let schema = Schema {
1836 head_fallback: fallback,
1837 ..last_words()
1838 };
1839 let mut bytes = Vec::new();
1840 schema.write(&mut bytes);
1841 assert_eq!(bytes[bytes.len() - 2], code);
1843 let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
1844 assert_eq!(
1845 Schema::read(&mut reader, crate::model::VERSION).unwrap(),
1846 schema
1847 );
1848 assert_eq!(reader.remaining(), 0);
1849 }
1850 let mut bytes = Vec::new();
1852 last_words().write(&mut bytes);
1853 let fallback = bytes.len() - 2;
1854 bytes[fallback] = 2;
1855 let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
1856 assert_eq!(
1857 Schema::read(&mut reader, crate::model::VERSION)
1858 .unwrap_err()
1859 .to_string(),
1860 "2 is not the code of a head word for a bunsetsu without one"
1861 );
1862 }
1863
1864 #[test]
1865 fn the_schema_of_a_file_of_version_3_ends_with_the_rule_and_takes_the_first_morpheme() {
1866 let schema = Schema {
1869 head_fallback: HeadFallback::FirstWord,
1870 sentence_split: SentenceSplit::AfterEnds,
1871 ..last_words()
1872 };
1873 let mut bytes = Vec::new();
1874 schema.write(&mut bytes);
1875 bytes.pop();
1876 bytes.pop();
1877 let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
1878 let read = Schema::read(&mut reader, 3).unwrap();
1879 assert_eq!(reader.remaining(), 0);
1880 assert_eq!(
1881 read,
1882 Schema {
1883 head_fallback: HeadFallback::FirstMorpheme,
1884 sentence_split: SentenceSplit::None,
1885 ..schema
1886 }
1887 );
1888 let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
1890 assert!(Schema::read(&mut reader, 4).is_err());
1891 }
1892
1893 const HATENA: (&str, &str) = ("?", "記号,一般,*,*,*,*,?,?,?");
1894
1895 fn starts(pairs: &[(&str, &str)]) -> Vec<usize> {
1897 Schema::ipadic().sentence_starts(&morphemes(pairs))
1898 }
1899
1900 #[test]
1901 fn the_schemas_of_this_crate_cut_a_text_into_sentences() {
1902 assert_eq!(Schema::ipadic().sentence_split, SentenceSplit::AfterEnds);
1903 assert_eq!(Schema::unidic().sentence_split, SentenceSplit::AfterEnds);
1904 assert_eq!(Schema::default().sentence_split, SentenceSplit::None);
1905 }
1906
1907 #[cfg(feature = "train")]
1910 #[test]
1911 fn the_schemas_of_cabocha_do_not_cut_a_text() {
1912 use crate::cabocha::{self, PartOfSpeechSet};
1913
1914 for set in [
1915 PartOfSpeechSet::Ipa,
1916 PartOfSpeechSet::Juman,
1917 PartOfSpeechSet::Unidic,
1918 ] {
1919 let schema = cabocha::schema(set);
1920 assert_eq!(schema.sentence_split, SentenceSplit::None, "{set:?}");
1921 assert!(
1922 schema
1923 .sentence_starts(&morphemes(&[HON, MARU, HON, WO]))
1924 .is_empty(),
1925 "{set:?}"
1926 );
1927 }
1928 }
1929
1930 #[test]
1931 fn a_text_is_cut_after_its_sentence_ends() {
1932 assert_eq!(starts(&[HON, MARU, HON, WO]), [2]);
1934 assert!(starts(&[HON, WO, YOMU, MARU]).is_empty());
1936 assert!(starts(&[HON, WO, YOMU]).is_empty());
1937 assert!(starts(&[]).is_empty());
1938 assert_eq!(starts(&[HON, MARU, YOMU, MARU, HON, MARU]), [2, 4]);
1940 assert_eq!(starts(&[HON, HATENA, HON]), [2]);
1942 assert_eq!(starts(&[HON, HATENA, HATENA, MARU, HON]), [4]);
1943 assert_eq!(
1944 starts(&[HON, ("!?", "記号,一般,*,*,*,*,*,*,*"), HON]),
1945 [2]
1946 );
1947 assert!(starts(&[HON, TEN, HON]).is_empty());
1949 }
1950
1951 #[test]
1952 fn a_closing_bracket_stays_with_the_sentence_it_closes() {
1953 assert_eq!(starts(&[KAGI, HON, MARU, KAGI_TOJI, HON]), [4]);
1955 assert!(starts(&[KAGI, HON, MARU, KAGI_TOJI]).is_empty());
1957 assert_eq!(starts(&[HON, MARU, KAGI, HON, KAGI_TOJI]), [2]);
1959 }
1960
1961 #[test]
1962 fn a_function_word_after_a_closing_bracket_does_not_start_a_sentence() {
1963 assert!(starts(&[KAGI, HON, WO, YOMU, MARU, KAGI_TOJI, TO, YOMU]).is_empty());
1966 assert!(starts(&[KAGI, HON, MARU, KAGI_TOJI, DA]).is_empty());
1968 assert_eq!(
1971 starts(&[KAGI, YOMU, MARU, HON, WO, YOMU, MARU, KAGI_TOJI, TO, YOMU]),
1972 [3]
1973 );
1974 assert_eq!(starts(&[YOMU, MARU, DA, GA, HON]), [2]);
1977 assert_eq!(starts(&[YOMU, MARU, DE, HON]), [2]);
1978 assert_eq!(starts(&[YOMU, MARU, NI, HON]), [2]);
1979 assert_eq!(starts(&[KAGI, YOMU, MARU, KAGI_TOJI, HON, WO]), [4]);
1981 }
1982
1983 #[test]
1984 fn the_particle_of_a_quotation_does_not_start_a_sentence() {
1985 assert!(starts(&[YOMU, HATENA, TO, TEN, YOMU]).is_empty());
1987 assert!(starts(&[YOMU, MARU, TO, YOMU]).is_empty());
1988 let tte = ("って", "助詞,格助詞,連語,*,*,*,って,ッテ,ッテ");
1989 assert!(starts(&[YOMU, HATENA, tte, YOMU]).is_empty());
1990 assert_eq!(starts(&[YOMU, HATENA, HON, HATENA, TO, YOMU]), [2]);
1992 let noun = ("と", "名詞,一般,*,*,*,*,と,ト,ト");
1995 assert_eq!(starts(&[YOMU, MARU, noun, YOMU]), [2]);
1996 let schema = Schema::unidic();
1999 let text = [
2000 unidic("本", "名詞,普通名詞", "本"),
2001 unidic("。", "補助記号,句点", "。"),
2002 unidic("で", "助詞,格助詞", "で"),
2003 unidic("も", "助詞,係助詞", "も"),
2004 unidic("本", "名詞,普通名詞", "本"),
2005 ];
2006 assert_eq!(schema.sentence_starts(&text), [2]);
2007 let text = [
2008 unidic("本", "名詞,普通名詞", "本"),
2009 unidic("?", "補助記号,句点", "?"),
2010 unidic("と", "助詞,格助詞", "と"),
2011 unidic("本", "名詞,普通名詞", "本"),
2012 ];
2013 assert!(schema.sentence_starts(&text).is_empty());
2014 }
2015
2016 #[test]
2017 fn a_half_width_period_and_a_period_before_a_digit_end_nothing() {
2018 let digits = |surface: &'static str| (surface, "名詞,数,*,*,*,*,*");
2020 assert!(starts(&[digits("4"), (".", "記号,句点,*,*,*,*,.,.,."), digits("20")]).is_empty());
2021 let wide = (".", "記号,句点,*,*,*,*,.,.,.");
2023 assert!(starts(&[digits("3"), wide, digits("14")]).is_empty());
2024 assert_eq!(starts(&[HON, wide, HON]), [2]);
2025 let schema = Schema::unidic();
2028 let dot = || unidic(".", "補助記号,句点", ".");
2029 let number = [
2030 unidic("1", "名詞,数詞", "1"),
2031 dot(),
2032 unidic("060", "名詞,数詞", "060"),
2033 ];
2034 assert!(schema.sentence_starts(&number).is_empty());
2035 let letters = [
2036 unidic("L", "記号,文字", "L"),
2037 dot(),
2038 unidic("E", "記号,文字", "E"),
2039 dot(),
2040 unidic("D", "記号,文字", "D"),
2041 ];
2042 assert!(schema.sentence_starts(&letters).is_empty());
2043 let text = [
2045 unidic("本", "名詞,普通名詞", "本"),
2046 unidic("。", "補助記号,句点", "。"),
2047 unidic("本", "名詞,普通名詞", "本"),
2048 ];
2049 assert_eq!(schema.sentence_starts(&text), [2]);
2050 }
2051
2052 #[test]
2053 fn a_schema_that_does_not_cut_gives_no_start() {
2054 let whole = Schema {
2055 sentence_split: SentenceSplit::None,
2056 ..Schema::ipadic()
2057 };
2058 for text in [
2059 &[HON, MARU, HON, WO][..],
2060 &[HON, HATENA, HON],
2061 &[KAGI, HON, MARU, KAGI_TOJI, HON],
2062 ] {
2063 assert!(whole.sentence_starts(&morphemes(text)).is_empty());
2064 assert!(!starts(text).is_empty());
2065 }
2066 }
2067
2068 #[test]
2069 fn the_cut_into_sentences_comes_back_from_the_bytes() {
2070 for (split, code) in SentenceSplit::ALL {
2071 assert_eq!(split.code(), code);
2072 assert_eq!(SentenceSplit::from_code(code).unwrap(), split);
2073 let schema = Schema {
2074 sentence_split: split,
2075 ..last_words()
2076 };
2077 let mut bytes = Vec::new();
2078 schema.write(&mut bytes);
2079 assert_eq!(bytes.last(), Some(&code));
2081 let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
2082 assert_eq!(
2083 Schema::read(&mut reader, crate::model::VERSION).unwrap(),
2084 schema
2085 );
2086 assert_eq!(reader.remaining(), 0);
2087 }
2088 let mut bytes = Vec::new();
2090 last_words().write(&mut bytes);
2091 *bytes.last_mut().unwrap() = 2;
2092 let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
2093 assert_eq!(
2094 Schema::read(&mut reader, crate::model::VERSION)
2095 .unwrap_err()
2096 .to_string(),
2097 "2 is not the code of a way to cut a text into sentences"
2098 );
2099 }
2100}