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::{Mark, Morpheme, is_sentence_end, is_space, marks, sentence_end};
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
88pub(crate) const OPEN_BRACKETS: &str = "(([[{{「『【〔〈《〘〚‘“";
91
92pub(crate) const 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> {
606 self.sentence_parts(words).0
607 }
608
609 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 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 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 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 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 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 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 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 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 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 pub fn surface_of<'a, M: Morpheme>(&self, morpheme: &'a M) -> Cow<'a, str> {
868 self.normalization.apply(morpheme.surface())
869 }
870
871 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 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 pub fn is_symbol<M: Morpheme>(&self, morpheme: &M) -> bool {
919 self.symbols.matches(self, morpheme)
920 }
921
922 pub fn is_comma<M: Morpheme>(&self, morpheme: &M) -> bool {
932 self.symbols.commas.matches(self, morpheme)
933 }
934
935 pub fn is_period<M: Morpheme>(&self, morpheme: &M) -> bool {
945 self.symbols.periods.matches(self, morpheme)
946 }
947
948 pub fn is_open_bracket<M: Morpheme>(&self, morpheme: &M) -> bool {
959 self.symbols.open_brackets.matches(self, morpheme)
960 }
961
962 pub fn is_close_bracket<M: Morpheme>(&self, morpheme: &M) -> bool {
973 self.symbols.close_brackets.matches(self, morpheme)
974 }
975
976 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 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 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 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 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 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 fn morphemes(pairs: &[(&str, &str)]) -> Vec<LatticeMorpheme> {
1174 pairs
1175 .iter()
1176 .map(|(surface, features)| LatticeMorpheme::new(*surface, *features))
1177 .collect()
1178 }
1179
1180 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 const COMMA: (&str, &str) = (",", "名詞,サ変接続,*,*,*,*,*,*,*");
1206
1207 #[test]
1208 fn ipadic_names_the_columns_of_mecab_ipadic() {
1209 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 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 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 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 assert_eq!(positions(&[NI, HON]), (1, 1));
1275 assert_eq!(positions(&[NI, HON, MARU]), (1, 1));
1277 assert_eq!(positions(&[NI, HON, DA]), (1, 2));
1279 }
1280
1281 #[test]
1282 fn the_function_words_of_cabocha_are_function_words() {
1283 let yoma = ("読ま", "動詞,自立,*,*,五段・マ行,未然形,読む,ヨマ,ヨマ");
1285 let reru = ("れる", "動詞,接尾,*,*,一段,基本形,れる,レル,レル");
1286 assert_eq!(positions(&[yoma, reru]), (0, 1));
1287 let yomi = ("読み", "動詞,自立,*,*,五段・マ行,連用形,読む,ヨミ,ヨミ");
1289 let nikui = (
1290 "にくい",
1291 "形容詞,非自立,*,*,形容詞・アウオ段,基本形,にくい,ニクイ,ニクイ",
1292 );
1293 assert_eq!(positions(&[yomi, nikui]), (0, 1));
1294 let ppoi = (
1296 "っぽい",
1297 "形容詞,接尾,*,*,形容詞・アウオ段,基本形,っぽい,ッポイ,ッポイ",
1298 );
1299 assert_eq!(positions(&[HON, ppoi]), (0, 1));
1300 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 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 assert_eq!(positions(&[RIYOU, SHI, TA]), (0, 2));
1313 assert_eq!(positions(&[RIYOU, SHI]), (0, 1));
1314 assert_eq!(positions(&[SHI, TA]), (0, 1));
1316 assert_eq!(positions(&[SHI]), (0, 0));
1317 assert_eq!(positions(&[RIYOU, YON, DA]), (1, 2));
1319 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 assert_eq!(positions(&[YOMU, KOTO, GA]), (0, 2));
1330 assert_eq!(positions(&[KOTO, GA]), (0, 1));
1332 assert_eq!(positions(&[KIHON, TEKI, NI]), (0, 2));
1334 let naga = (
1336 "長",
1337 "形容詞,自立,*,*,形容詞・アウオ段,ガル接続,長い,ナガ,ナガ",
1338 );
1339 let sa = ("さ", "名詞,接尾,特殊,*,*,*,さ,サ,サ");
1340 assert_eq!(positions(&[naga, sa, GA]), (0, 2));
1341 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 assert_eq!(positions(&[YOMU, KOTO, NI, naru, TA]), (0, 4));
1351 assert_eq!(positions(&[HON, NI, naru, TA]), (0, 3));
1353 assert_eq!(positions(&[HON, naru, TA]), (1, 2));
1355 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 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 assert!(schema.is_comma(&LatticeMorpheme::new(",", "")));
1380 }
1381
1382 #[test]
1383 fn a_schema_without_patterns_takes_the_last_morpheme() {
1384 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 for surface in [
1420 ",", "。", "(", "」", "!", "?", "-", "/", "・", "…", ",“", "!?",
1421 ] {
1422 assert!(schema.is_symbol(&unknown(surface)), "{surface}");
1423 }
1424 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 let alphabet = LatticeMorpheme::new("A", "記号,アルファベット,*,*,*,*,A,エイ,エイ");
1437 assert!(schema.is_symbol(&alphabet));
1438 assert!(!schema.is_comma(&alphabet) && !schema.is_period(&alphabet));
1439 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 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 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 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 let ni_yotte = morphemes(&[
1522 ("事故", "名詞,普通名詞,一般,*,*,*,ジコ,事故"),
1523 ("に", "助詞,格助詞,*,*,*,*,ニ,に"),
1524 ("よっ", "動詞,一般,*,*,五段-ラ行,連用形-促音便,ヨル,因る"),
1525 ("て", "助詞,接続助詞,*,*,*,*,テ,て"),
1526 ]);
1527 assert_eq!(schema.positions(&ni_yotte), Some((0, 3)));
1528
1529 let ga_yomu = morphemes(&[
1531 ("本", "名詞,普通名詞,一般,*,*,*,ホン,本"),
1532 ("が", "助詞,格助詞,*,*,*,*,ガ,が"),
1533 ("読む", "動詞,一般,*,*,五段-マ行,終止形-一般,ヨム,読む"),
1534 ]);
1535 assert_eq!(schema.positions(&ga_yomu), Some((2, 2)));
1536
1537 let period = LatticeMorpheme::new("。", "補助記号,句点,*,*,*,*,,。");
1539 assert!(schema.is_period(&period) && schema.is_symbol(&period));
1540 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 let you = morphemes(&[
1556 TSUKAU_UNIDIC,
1557 ("よう", "形状詞,助動詞語幹,*,*,*,*,ヨウ,様"),
1558 ("に", "助動詞,*,*,*,助動詞-ダ,連用形-ニ,ダ,だ"),
1559 ]);
1560 assert_eq!(schema.positions(&you), Some((0, 2)));
1561 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 let after_verb = morphemes(&[kounyuu, SURU_UNIDIC, koto, NI_UNIDIC]);
1582 assert_eq!(schema.positions(&after_verb), Some((0, 3)));
1583 let after_auxiliary = morphemes(&[kounyuu, SURU_UNIDIC, TA_UNIDIC, tame, NI_UNIDIC]);
1585 assert_eq!(schema.positions(&after_auxiliary), Some((0, 4)));
1586 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 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 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 let ookisa = morphemes(&[
1619 ("大き", "形容詞,一般,*,*,形容詞,語幹-一般,オオキイ,大きい"),
1620 ("さ", "接尾辞,名詞的,一般,*,*,*,サ,さ"),
1621 NI_UNIDIC,
1622 ]);
1623 assert_eq!(schema.positions(&ookisa), Some((0, 2)));
1624 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 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 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 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 assert_eq!(positions(&[NOUN]), (0, 0));
1690 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 assert_eq!(positions(&[NOUN, PARTICLE, NOUN]), (2, 2));
1697 assert_eq!(positions(&[SUFFIX, NOUN, PARTICLE, PARTICLE]), (1, 3));
1698 assert_eq!(positions(&[VERB, SUFFIX, PERIOD]), (0, 1));
1700 assert_eq!(positions(&[BRACKET, NOUN, PERIOD]), (1, 1));
1701 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 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 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 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 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 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 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 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 const SURU: (&str, &str) = ("する", "動詞,自立,*,*,サ変・スル,基本形,する,スル,スル");
1854 const TO: (&str, &str) = ("と", "助詞,格助詞,引用,*,*,*,と,ト,ト");
1855 const SPACE: (&str, &str) = ("\u{3000}", "記号,空白,*,*,*,*,\u{3000},\u{3000},\u{3000}");
1857
1858 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 #[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 assert_eq!(positions(&[KAGI, SURU, KAGI_TOJI, TO]), (1, 3));
1899 assert_eq!(positions(&[SURU, TO]), (0, 1));
1901 assert_eq!(positions(&[KAGI, KAGI_TOJI, TO]), (0, 2));
1904 assert_eq!(positions(&[KAGI, HON, KAGI_TOJI, WO]), (1, 3));
1906
1907 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 let naosu = unidic("治す", "動詞,非自立可能", "直す");
1927 let letter = |surface| unidic(surface, "記号,文字", surface);
1928
1929 assert_eq!(
1931 schema.positions(&[open.clone(), naosu, close.clone(), to.clone()]),
1932 Some((1, 3))
1933 );
1934 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 assert_eq!(
1948 schema.positions(&[open, letter("S"), letter("M"), letter("T"), close, to]),
1949 Some((1, 5))
1950 );
1951 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 assert_eq!(positions(&[SPACE, SURU]), (1, 1));
1962 assert_eq!(positions(&[HON, SPACE, WO]), (0, 2));
1964 assert_eq!(positions(&[HON, WO, SPACE]), (0, 1));
1965 assert_eq!(positions(&[SPACE, SPACE]), (0, 0));
1967 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 assert_eq!(positions(&[SPACE, KAGI, KAGI_TOJI]), (1, 1));
1975
1976 let space = unidic("\u{3000}", "空白", "\u{3000}");
1979 let naosu = unidic("治す", "動詞,非自立可能", "直す");
1980 assert_eq!(Schema::unidic().positions(&[space, naosu]), Some((1, 1)));
1981
1982 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 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 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 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 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 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 #[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 assert_eq!(starts(&[HON, MARU, HON, WO]), [2]);
2106 assert!(starts(&[HON, WO, YOMU, MARU]).is_empty());
2108 assert!(starts(&[HON, WO, YOMU]).is_empty());
2109 assert!(starts(&[]).is_empty());
2110 assert_eq!(starts(&[HON, MARU, YOMU, MARU, HON, MARU]), [2, 4]);
2112 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 assert!(starts(&[HON, TEN, HON]).is_empty());
2121 }
2122
2123 #[test]
2124 fn a_closing_bracket_stays_with_the_sentence_it_closes() {
2125 assert_eq!(starts(&[KAGI, HON, MARU, KAGI_TOJI, HON]), [4]);
2127 assert!(starts(&[KAGI, HON, MARU, KAGI_TOJI]).is_empty());
2129 assert_eq!(starts(&[HON, MARU, KAGI, HON, KAGI_TOJI]), [2]);
2131 }
2132
2133 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 for end in ["~。", ")。", "%。", "!?"] {
2143 assert_eq!(starts(&[YOMU, joined(end), HON]), [2], "{end}");
2144 }
2145 assert_eq!(
2147 starts(&[YOMU, joined("~。"), KAGI_TOJI, joined(")。"), HON]),
2148 [4]
2149 );
2150 for other in [",“", "~」", "()"] {
2152 assert!(starts(&[YOMU, joined(other), HON]).is_empty(), "{other}");
2153 }
2154 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 assert!(starts(&[KAGI, HON, joined("?」"), DE, YOMU]).is_empty());
2167 assert!(starts(&[KAGI, HON, joined("?」"), DA]).is_empty());
2168 assert_eq!(starts(&[KAGI, HON, joined("?」"), HON]), [3]);
2170 assert!(starts(&[HON, MARU, joined("?」"), DE, YOMU]).is_empty());
2172 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 assert_eq!(tails(&[HON, MARU, KAGI_TOJI, HON, HATENA]), [1, 2, 4]);
2184 assert_eq!(tails(&[KAGI, HON, KAGI_TOJI, HON, joined(")。")]), [4]);
2187 assert_eq!(tails(&[KAGI, HON, joined("?」"), TO, YOMU]), [2]);
2189 assert_eq!(tails(&[MARU, HON]), [0]);
2191 assert!(tails(&[HON, WO, YOMU]).is_empty());
2192 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 assert!(starts(&[KAGI, HON, WO, YOMU, MARU, KAGI_TOJI, TO, YOMU]).is_empty());
2208 assert!(starts(&[KAGI, HON, MARU, KAGI_TOJI, DA]).is_empty());
2210 assert_eq!(
2213 starts(&[KAGI, YOMU, MARU, HON, WO, YOMU, MARU, KAGI_TOJI, TO, YOMU]),
2214 [3]
2215 );
2216 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 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 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 assert_eq!(starts(&[YOMU, HATENA, HON, HATENA, TO, YOMU]), [2]);
2234 let noun = ("と", "名詞,一般,*,*,*,*,と,ト,ト");
2237 assert_eq!(starts(&[YOMU, MARU, noun, YOMU]), [2]);
2238 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 let digits = |surface: &'static str| (surface, "名詞,数,*,*,*,*,*");
2262 assert!(starts(&[digits("4"), (".", "記号,句点,*,*,*,*,.,.,."), digits("20")]).is_empty());
2263 let wide = (".", "記号,句点,*,*,*,*,.,.,.");
2265 assert!(starts(&[digits("3"), wide, digits("14")]).is_empty());
2266 assert_eq!(starts(&[HON, wide, HON]), [2]);
2267 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 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 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 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 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 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 assert_eq!(ends(&["本", ".", "本"]), [2, 3]);
2388 assert_eq!(ends(&["本", "。。", "本"]), [2, 3]);
2389 assert_eq!(ends(&["本", "本"]), [2]);
2390 assert_eq!(ends(&["。"]), [1]);
2392 }
2393
2394 #[test]
2395 fn marks_joined_into_one_word_are_read_one_at_a_time() {
2396 assert_eq!(ends(&["本", "(", "笑", ")。", "本", "。"]), [4, 6]);
2399 assert_eq!(ends(&["本", "(", "笑", ")", "。", "本", "。"]), [5, 7]);
2401 assert_eq!(
2404 ends(&["「", "本", "?」", "と", "本", "。", "本", "。"]),
2405 [6, 8]
2406 );
2407 assert_eq!(
2408 ends(&["「", "本", "?", "」", "と", "本", "。", "本", "。"]),
2409 [7, 9]
2410 );
2411 assert_eq!(ends(&["本", "~。", "本"]), [2, 3]);
2413 assert_eq!(ends(&["本", "%。", "本", "!?"]), [2, 4]);
2414 assert_eq!(ends(&["「", "本", "~。", "本", "」", "本"]), [6]);
2416 assert_eq!(ends(&["本", ",“", "本", "。", "”", "本", "。"]), [7]);
2418 assert_eq!(ends(&["本", "(?)", "本", "。", "本"]), [4, 5]);
2420 assert_eq!(ends(&["本", "?」", "本"]), [2, 3]);
2422 assert_eq!(ends(&["本。", "本"]), [2]);
2424 assert_eq!(ends(&["本", "。~", "本"]), [3]);
2427 assert_eq!(ends(&["本", "?「", "本", "」", "本"]), [5]);
2428 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 assert_eq!(ends(&["本", ":(。", "本", "。", "本", "。"]), [2, 4, 6]);
2438 assert_eq!(
2439 ends(&["本", "(", "泣", "。", "本", "。", "本", "。"]),
2440 [4, 6, 8]
2441 );
2442 assert_eq!(
2445 ends(&["本", "(", "本", "「", "本", "。", "」", "本", "。"]),
2446 [9]
2447 );
2448 assert_eq!(ends(&["「", "本", "(", "本", "。", "」", "本", "。"]), [8]);
2451 assert_eq!(ends(&["本", ")", "本", "。", "本"]), [4, 5]);
2453 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 assert_eq!(ends(&["4", ".", "20", "本", "。", "本"]), [5, 6]);
2464 assert_eq!(ends(&["本", ".", ".", ".", "本", "."]), [6]);
2465 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 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 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 assert_eq!(
2503 ends(&["本", "。", "\u{3000}", "本", "。", "\u{3000}", "\u{3000}"]),
2504 [3, 7]
2505 );
2506 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 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 assert_eq!(ends(&["<", "本", "。", ">", "本"]), [3, 5]);
2527 }
2528
2529 #[test]
2530 fn the_brackets_of_what_follows_an_end_are_counted() {
2531 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 assert_eq!(ends(&["「", "本", "。", "本", "。"]), [3, 5]);
2543 assert_eq!(ends(&["「", "本", "。", "本", "。", "」"]), [6]);
2545 }
2546}