mod normalization;
mod pattern;
mod symbols;
use std::borrow::Cow;
use std::ops::Range;
pub use normalization::Normalization;
pub use pattern::Pattern;
pub use symbols::{Marks, SurfaceRule, Symbols};
use crate::bytes::{Reader, push_u32};
use crate::error::{Error, Result};
use crate::morpheme::Morpheme;
const NO_COLUMN: u32 = u32::MAX;
const EMPTY: &str = "*";
const FORMAL_NOUNS: [&str; 6] = ["事", "為", "物", "際", "上", "所"];
const COMMAS: &str = "、,,";
const PERIODS: &str = "。..";
const OPEN_BRACKETS: &str = "(([[{{「『【〔〈《〘〚‘“";
const CLOSE_BRACKETS: &str = "))]]}}」』】〕〉》〙〛’”";
const OTHER_SYMBOLS: &str = concat!(
"!\"#$&'*+-/:;<=>?@\\^_`|~",
"!"#$&'*+-/:;<=>?@\^_`|~",
"・…‥―—–‐〜※♪★☆○●◎◇◆□■△▲▽▼→←↑↓≠",
);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum HeadRule {
#[default]
FunctionWordsApart,
LastWords,
}
impl HeadRule {
const ALL: [(HeadRule, u8); 2] = [(HeadRule::FunctionWordsApart, 0), (HeadRule::LastWords, 1)];
fn code(self) -> u8 {
Self::ALL
.iter()
.find(|(rule, _)| *rule == self)
.map_or(0, |(_, code)| *code)
}
fn from_code(code: u8) -> Result<Self> {
Self::ALL
.iter()
.find(|(_, one)| *one == code)
.map(|(rule, _)| *rule)
.ok_or_else(|| Error::Schema(format!("{code} is not the code of a rule of the head")))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Schema {
pub part_of_speech: Range<usize>,
pub conjugation_type: Option<usize>,
pub conjugation_form: Option<usize>,
pub base_form: Option<usize>,
pub function_words: Vec<Pattern>,
pub not_heads: Vec<Pattern>,
pub particles: Vec<Pattern>,
pub lexicalized: Vec<Pattern>,
pub symbols: Symbols,
pub normalization: Normalization,
pub head_rule: HeadRule,
}
impl Schema {
pub const DICTIONARIES: [&'static str; 4] = ["ipadic", "unidic", "unidic-cwj", "unidic-csj"];
pub fn ipadic() -> Self {
Self {
part_of_speech: 0..4,
conjugation_type: Some(4),
conjugation_form: Some(5),
base_form: Some(6),
function_words: vec![
Pattern::new(&["助詞"]),
Pattern::new(&["助動詞"]),
Pattern::new(&["動詞", "非自立"]),
Pattern::new(&["動詞", "接尾"]),
Pattern::new(&["形容詞", "非自立"]),
Pattern::new(&["形容詞", "接尾"]),
Pattern::new(&["動詞", "自立"]).with_base_forms(&["する", "できる", "出来る"]),
],
not_heads: vec![
Pattern::new(&["名詞", "非自立"]),
Pattern::new(&["名詞", "接尾", "形容動詞語幹"]),
Pattern::new(&["名詞", "接尾", "特殊"]),
Pattern::new(&["動詞", "自立"]).after(Pattern::new(&["助詞"])),
],
particles: vec![Pattern::new(&["助詞"])],
lexicalized: vec![
Pattern::new(&["助詞"]),
Pattern::new(&["副詞"]),
Pattern::new(&["連体詞"]),
Pattern::new(&["接続詞"]),
],
symbols: Symbols {
others: Marks::new(&[&["記号"]], OTHER_SYMBOLS),
commas: Marks::new(&[&["記号", "読点"]], COMMAS),
periods: Marks::new(&[&["記号", "句点"]], PERIODS),
open_brackets: Marks::new(&[&["記号", "括弧開"]], OPEN_BRACKETS),
close_brackets: Marks::new(&[&["記号", "括弧閉"]], CLOSE_BRACKETS),
surface: SurfaceRule::EveryCharacter,
},
normalization: Normalization::default(),
head_rule: HeadRule::FunctionWordsApart,
}
}
pub fn unidic() -> Self {
Self {
part_of_speech: 0..4,
conjugation_type: Some(4),
conjugation_form: Some(5),
base_form: Some(7),
function_words: vec![
Pattern::new(&["助詞"]),
Pattern::new(&["助動詞"]),
Pattern::new(&["接尾辞", "形容詞的"]),
Pattern::new(&["接尾辞", "形状詞的"]),
Pattern::new(&["接尾辞", "動詞的"]),
Pattern::new(&["動詞", "非自立可能"]),
Pattern::new(&["形容詞", "非自立可能"]),
],
not_heads: vec![
Pattern::new(&["動詞"])
.after(Pattern::new(&["助詞"]).with_base_forms(&["に", "と", "を"])),
Pattern::new(&["形状詞", "助動詞語幹"]),
Pattern::new(&["名詞", "助動詞語幹"]),
Pattern::new(&["名詞", "普通名詞"])
.with_base_forms(&FORMAL_NOUNS)
.after(Pattern::new(&["動詞"])),
Pattern::new(&["名詞", "普通名詞"])
.with_base_forms(&FORMAL_NOUNS)
.after(Pattern::new(&["助動詞"])),
Pattern::new(&["名詞", "普通名詞"])
.with_base_forms(&FORMAL_NOUNS)
.after(Pattern::new(&["形容詞"])),
Pattern::new(&["接尾辞", "名詞的"]).after(Pattern::new(&["形容詞"])),
],
particles: vec![Pattern::new(&["助詞"])],
lexicalized: vec![
Pattern::new(&["助詞"]),
Pattern::new(&["副詞"]),
Pattern::new(&["連体詞"]),
Pattern::new(&["接続詞"]),
],
symbols: Symbols {
others: Marks::new(&[&["空白"], &["補助記号"], &["記号"]], ""),
commas: Marks::new(&[&["補助記号", "読点"]], COMMAS),
periods: Marks::new(&[&["補助記号", "句点"]], PERIODS),
open_brackets: Marks::new(&[&["補助記号", "括弧開"]], OPEN_BRACKETS),
close_brackets: Marks::new(&[&["補助記号", "括弧閉"]], CLOSE_BRACKETS),
surface: SurfaceRule::EveryCharacter,
},
normalization: Normalization::default(),
head_rule: HeadRule::FunctionWordsApart,
}
}
pub fn for_dictionary(dictionary: &str) -> Option<Self> {
match dictionary {
"ipadic" => Some(Self::ipadic()),
"unidic" | "unidic-cwj" | "unidic-csj" => Some(Self::unidic()),
_ => None,
}
}
pub fn positions<M: Morpheme>(&self, bunsetsu: &[M]) -> Option<(usize, usize)> {
if bunsetsu.is_empty() {
return None;
}
let mut head = 0;
let mut function = 0;
for (index, morpheme) in bunsetsu.iter().enumerate() {
let matches = |patterns: &[Pattern]| {
patterns
.iter()
.any(|one| one.matches(self, bunsetsu, index))
};
match self.head_rule {
HeadRule::FunctionWordsApart => {
if matches(&self.function_words) {
function = index;
} else if !matches(&self.not_heads) && !self.is_symbol(morpheme) {
head = index;
}
}
HeadRule::LastWords => {
if !self.is_symbol(morpheme) {
function = index;
if !matches(&self.not_heads) {
head = index;
}
}
}
}
}
if head > function {
function = head;
}
Some((head, function))
}
pub fn surface_of<'a, M: Morpheme>(&self, morpheme: &'a M) -> Cow<'a, str> {
self.normalization.apply(morpheme.surface())
}
pub fn is_particle<M: Morpheme>(&self, bunsetsu: &[M], index: usize) -> bool {
self.particles
.iter()
.any(|one| one.matches(self, bunsetsu, index))
}
pub fn is_lexicalized<M: Morpheme>(&self, bunsetsu: &[M], index: usize) -> bool {
self.lexicalized
.iter()
.any(|one| one.matches(self, bunsetsu, index))
}
pub fn is_symbol<M: Morpheme>(&self, morpheme: &M) -> bool {
self.symbols.matches(self, morpheme)
}
pub fn is_comma<M: Morpheme>(&self, morpheme: &M) -> bool {
self.symbols.commas.matches(self, morpheme)
}
pub fn is_period<M: Morpheme>(&self, morpheme: &M) -> bool {
self.symbols.periods.matches(self, morpheme)
}
pub fn is_open_bracket<M: Morpheme>(&self, morpheme: &M) -> bool {
self.symbols.open_brackets.matches(self, morpheme)
}
pub fn is_close_bracket<M: Morpheme>(&self, morpheme: &M) -> bool {
self.symbols.close_brackets.matches(self, morpheme)
}
pub fn part_of_speech_of<M: Morpheme>(&self, morpheme: &M) -> String {
self.levels_of(morpheme, self.part_of_speech.clone())
}
pub(crate) fn levels_of<M: Morpheme>(&self, morpheme: &M, levels: Range<usize>) -> String {
let mut value = String::new();
for index in levels {
match morpheme.feature(index) {
Some(level) if level != EMPTY => {
if !value.is_empty() {
value.push('-');
}
value.push_str(level);
}
_ => break,
}
}
value
}
pub fn width(&self) -> usize {
[
Some(self.part_of_speech.end),
self.conjugation_type.map(|index| index + 1),
self.conjugation_form.map(|index| index + 1),
self.base_form.map(|index| index + 1),
]
.into_iter()
.flatten()
.max()
.unwrap_or(0)
}
pub fn check<M: Morpheme>(&self, morphemes: &[M]) -> Result<()> {
let width = self.width();
let Some(last) = width.checked_sub(1) else {
return Ok(());
};
for (index, morpheme) in morphemes.iter().enumerate() {
if morpheme.feature(last).is_none() {
return Err(Error::Dictionary(format!(
"the morpheme {} ({:?}) has fewer than the {width} feature columns the schema reads: it is not of the dictionary of the model",
index + 1,
morpheme.surface()
)));
}
}
Ok(())
}
pub(crate) fn write(&self, bytes: &mut Vec<u8>) {
let column = |index: Option<usize>| index.map_or(NO_COLUMN, |index| index as u32);
push_u32(bytes, self.part_of_speech.start as u32);
push_u32(bytes, self.part_of_speech.end as u32);
push_u32(bytes, column(self.conjugation_type));
push_u32(bytes, column(self.conjugation_form));
push_u32(bytes, column(self.base_form));
for patterns in [
&self.function_words,
&self.not_heads,
&self.particles,
&self.lexicalized,
] {
push_u32(bytes, patterns.len() as u32);
for pattern in patterns {
pattern.write(bytes);
}
}
self.symbols.write(bytes);
self.normalization.write(bytes);
bytes.push(self.head_rule.code());
}
pub(crate) fn read(reader: &mut Reader) -> Result<Self> {
let start = reader.u32()? as usize;
let end = reader.u32()? as usize;
let mut column = || -> Result<Option<usize>> {
let value = reader.u32()?;
Ok((value != NO_COLUMN).then_some(value as usize))
};
let conjugation_type = column()?;
let conjugation_form = column()?;
let base_form = column()?;
let mut patterns = || -> Result<Vec<Pattern>> {
let count = reader.u32()?;
let mut patterns = Vec::new();
for _ in 0..count {
patterns.push(Pattern::read(reader, 0)?);
}
Ok(patterns)
};
let function_words = patterns()?;
let not_heads = patterns()?;
let particles = patterns()?;
let lexicalized = patterns()?;
Ok(Self {
part_of_speech: start..end,
conjugation_type,
conjugation_form,
base_form,
function_words,
not_heads,
particles,
lexicalized,
symbols: Symbols::read(reader)?,
normalization: Normalization::read(reader)?,
head_rule: HeadRule::from_code(reader.u8()?)?,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::error::Error;
use crate::lattice::LatticeMorpheme;
fn morphemes(pairs: &[(&str, &str)]) -> Vec<LatticeMorpheme> {
pairs
.iter()
.map(|(surface, features)| LatticeMorpheme::new(*surface, *features))
.collect()
}
fn positions(pairs: &[(&str, &str)]) -> (usize, usize) {
Schema::ipadic().positions(&morphemes(pairs)).unwrap()
}
const HON: (&str, &str) = ("本", "名詞,一般,*,*,*,*,本,ホン,ホン");
const WO: (&str, &str) = ("を", "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ");
const NI: (&str, &str) = ("に", "助詞,格助詞,一般,*,*,*,に,ニ,ニ");
const GA: (&str, &str) = ("が", "助詞,格助詞,一般,*,*,*,が,ガ,ガ");
const YON: (&str, &str) = ("読ん", "動詞,自立,*,*,五段・マ行,連用タ接続,読む,ヨン,ヨン");
const YOMU: (&str, &str) = ("読む", "動詞,自立,*,*,五段・マ行,基本形,読む,ヨム,ヨム");
const DA: (&str, &str) = ("だ", "助動詞,*,*,*,特殊・タ,基本形,だ,ダ,ダ");
const TA: (&str, &str) = ("た", "助動詞,*,*,*,特殊・タ,基本形,た,タ,タ");
const DE: (&str, &str) = ("で", "助詞,接続助詞,*,*,*,*,で,デ,デ");
const IRU: (&str, &str) = ("いる", "動詞,非自立,*,*,一段,基本形,いる,イル,イル");
const MARU: (&str, &str) = ("。", "記号,句点,*,*,*,*,。,。,。");
const TEN: (&str, &str) = ("、", "記号,読点,*,*,*,*,、,、,、");
const KAGI: (&str, &str) = ("「", "記号,括弧開,*,*,*,*,「,「,「");
const KAGI_TOJI: (&str, &str) = ("」", "記号,括弧閉,*,*,*,*,」,」,」");
const RIYOU: (&str, &str) = ("利用", "名詞,サ変接続,*,*,*,*,利用,リヨウ,リヨー");
const SHI: (&str, &str) = ("し", "動詞,自立,*,*,サ変・スル,連用形,する,シ,シ");
const KOTO: (&str, &str) = ("こと", "名詞,非自立,一般,*,*,*,こと,コト,コト");
const KIHON: (&str, &str) = ("基本", "名詞,一般,*,*,*,*,基本,キホン,キホン");
const TEKI: (&str, &str) = ("的", "名詞,接尾,形容動詞語幹,*,*,*,的,テキ,テキ");
const COMMA: (&str, &str) = (",", "名詞,サ変接続,*,*,*,*,*,*,*");
#[test]
fn ipadic_names_the_columns_of_mecab_ipadic() {
let features = [
"動詞",
"自立",
"*",
"*",
"五段・マ行",
"連用タ接続",
"読む",
"ヨン",
"ヨン",
];
let schema = Schema::ipadic();
assert_eq!(
features[schema.part_of_speech.clone()],
["動詞", "自立", "*", "*"]
);
assert_eq!(features[schema.conjugation_type.unwrap()], "五段・マ行");
assert_eq!(features[schema.conjugation_form.unwrap()], "連用タ接続");
assert_eq!(features[schema.base_form.unwrap()], "読む");
}
#[test]
fn a_content_word_and_a_particle_are_the_head_and_the_function_word() {
assert_eq!(positions(&[HON, WO]), (0, 1));
assert_eq!(positions(&[KIHON, HON, NI, WO]), (1, 3));
}
#[test]
fn a_content_word_alone_is_both() {
assert_eq!(positions(&[HON]), (0, 0));
assert_eq!(positions(&[KIHON, HON]), (1, 1));
}
#[test]
fn punctuation_at_the_end_is_neither() {
assert_eq!(positions(&[YON, DA, MARU]), (0, 1));
assert_eq!(positions(&[HON, WO, TEN]), (0, 1));
assert_eq!(positions(&[HON, WO, COMMA]), (0, 1));
assert_eq!(positions(&[HON, COMMA]), (0, 0));
}
#[test]
fn a_bunsetsu_of_symbols_only_has_both_at_its_first_morpheme() {
assert_eq!(positions(&[MARU]), (0, 0));
assert_eq!(positions(&[KAGI_TOJI, MARU, COMMA]), (0, 0));
}
#[test]
fn a_bracket_before_the_head_is_skipped() {
assert_eq!(positions(&[KAGI, HON, WO]), (1, 2));
}
#[test]
fn a_dependent_verb_is_the_function_word() {
assert_eq!(positions(&[YON, DE, IRU]), (0, 2));
assert_eq!(positions(&[YON, DE, IRU, MARU]), (0, 2));
}
#[test]
fn a_head_after_the_function_word_takes_the_function_word_with_it() {
assert_eq!(positions(&[NI, HON]), (1, 1));
assert_eq!(positions(&[NI, HON, MARU]), (1, 1));
assert_eq!(positions(&[NI, HON, DA]), (1, 2));
}
#[test]
fn the_function_words_of_cabocha_are_function_words() {
let yoma = ("読ま", "動詞,自立,*,*,五段・マ行,未然形,読む,ヨマ,ヨマ");
let reru = ("れる", "動詞,接尾,*,*,一段,基本形,れる,レル,レル");
assert_eq!(positions(&[yoma, reru]), (0, 1));
let yomi = ("読み", "動詞,自立,*,*,五段・マ行,連用形,読む,ヨミ,ヨミ");
let nikui = (
"にくい",
"形容詞,非自立,*,*,形容詞・アウオ段,基本形,にくい,ニクイ,ニクイ",
);
assert_eq!(positions(&[yomi, nikui]), (0, 1));
let ppoi = (
"っぽい",
"形容詞,接尾,*,*,形容詞・アウオ段,基本形,っぽい,ッポイ,ッポイ",
);
assert_eq!(positions(&[HON, ppoi]), (0, 1));
assert_eq!(positions(&[HON, WO, reru]), (0, 2));
assert_eq!(positions(&[HON, WO, nikui]), (0, 2));
assert_eq!(positions(&[HON, WO, ppoi]), (0, 2));
assert_eq!(positions(&[HON, DA]), (0, 1));
assert_eq!(positions(&[HON, WO]), (0, 1));
}
#[test]
fn suru_and_dekiru_are_function_words() {
assert_eq!(positions(&[RIYOU, SHI, TA]), (0, 2));
assert_eq!(positions(&[RIYOU, SHI]), (0, 1));
assert_eq!(positions(&[SHI, TA]), (0, 1));
assert_eq!(positions(&[SHI]), (0, 0));
assert_eq!(positions(&[RIYOU, YON, DA]), (1, 2));
let dekiru = ("でき", "動詞,自立,*,*,一段,連用形,できる,デキ,デキ");
assert_eq!(positions(&[RIYOU, dekiru, TA]), (0, 2));
let dekiru = ("出来", "動詞,自立,*,*,一段,連用形,出来る,デキ,デキ");
assert_eq!(positions(&[RIYOU, dekiru, TA]), (0, 2));
}
#[test]
fn a_dependent_noun_and_the_suffix_teki_are_not_heads() {
assert_eq!(positions(&[YOMU, KOTO, GA]), (0, 2));
assert_eq!(positions(&[KOTO, GA]), (0, 1));
assert_eq!(positions(&[KIHON, TEKI, NI]), (0, 2));
let naga = (
"長",
"形容詞,自立,*,*,形容詞・アウオ段,ガル接続,長い,ナガ,ナガ",
);
let sa = ("さ", "名詞,接尾,特殊,*,*,*,さ,サ,サ");
assert_eq!(positions(&[naga, sa, GA]), (0, 2));
let nin = ("人", "名詞,接尾,助数詞,*,*,*,人,ニン,ニン");
assert_eq!(positions(&[HON, nin, GA]), (1, 2));
}
#[test]
fn a_verb_after_a_particle_is_part_of_a_compound_function_word() {
let naru = ("なっ", "動詞,自立,*,*,五段・ラ行,連用タ接続,なる,ナッ,ナッ");
assert_eq!(positions(&[YOMU, KOTO, NI, naru, TA]), (0, 4));
assert_eq!(positions(&[HON, NI, naru, TA]), (0, 3));
assert_eq!(positions(&[HON, naru, TA]), (1, 2));
assert_eq!(positions(&[naru, TA]), (0, 1));
}
#[test]
fn no_morpheme_has_no_positions() {
let none: [LatticeMorpheme; 0] = [];
assert_eq!(Schema::ipadic().positions(&none), None);
}
#[test]
fn morphemes_with_fewer_columns_do_not_panic() {
assert_eq!(positions(&[("x", ""), ("y", "")]), (1, 1));
assert_eq!(positions(&[("本", "名詞"), ("を", "助詞")]), (0, 1));
assert_eq!(
positions(&[("利用", "名詞,サ変接続"), ("し", "動詞,自立")]),
(1, 1)
);
let schema = Schema::ipadic();
let bare = LatticeMorpheme::new("x", "");
assert!(!schema.is_symbol(&bare));
assert_eq!(schema.part_of_speech_of(&bare), "");
assert!(schema.is_comma(&LatticeMorpheme::new(",", "")));
}
#[test]
fn a_schema_without_patterns_takes_the_last_morpheme() {
let schema = Schema {
part_of_speech: 0..4,
..Schema::default()
};
assert_eq!(schema.positions(&morphemes(&[HON, WO, MARU])), Some((2, 2)));
}
#[test]
fn punctuation_and_brackets_are_recognized_by_part_of_speech_and_by_surface() {
let schema = Schema::ipadic();
let unknown = |surface: &str| LatticeMorpheme::new(surface, "名詞,サ変接続,*,*,*,*,*,*,*");
let known = |pair: (&str, &str)| LatticeMorpheme::new(pair.0, pair.1);
assert!(schema.is_comma(&known(TEN)));
assert!(schema.is_period(&known(MARU)));
assert!(schema.is_open_bracket(&known(KAGI)));
assert!(schema.is_close_bracket(&known(KAGI_TOJI)));
for surface in [",", ",", "、"] {
assert!(schema.is_comma(&unknown(surface)), "{surface}");
assert!(!schema.is_period(&unknown(surface)), "{surface}");
}
for surface in [".", ".", "。"] {
assert!(schema.is_period(&unknown(surface)), "{surface}");
assert!(!schema.is_comma(&unknown(surface)), "{surface}");
}
for surface in ["(", "(", "[", "「", "『", "“"] {
assert!(schema.is_open_bracket(&unknown(surface)), "{surface}");
assert!(!schema.is_close_bracket(&unknown(surface)), "{surface}");
}
for surface in [")", ")", "]", "」", "』", "”"] {
assert!(schema.is_close_bracket(&unknown(surface)), "{surface}");
assert!(!schema.is_open_bracket(&unknown(surface)), "{surface}");
}
for surface in [
",", "。", "(", "」", "!", "?", "-", "/", "・", "…", ",“", "!?",
] {
assert!(schema.is_symbol(&unknown(surface)), "{surface}");
}
let comma = LatticeMorpheme::new("、", "記号,読点,*,*,*,*,、,、,、");
let period = LatticeMorpheme::new("。", "記号,句点,*,*,*,*,。,。,。");
let open = LatticeMorpheme::new("「", "記号,括弧開,*,*,*,*,「,「,「");
let close = LatticeMorpheme::new("」", "記号,括弧閉,*,*,*,*,」,」,」");
assert!(schema.is_comma(&comma) && !schema.is_period(&comma));
assert!(schema.is_period(&period) && !schema.is_comma(&period));
assert!(schema.is_open_bracket(&open) && !schema.is_close_bracket(&open));
assert!(schema.is_close_bracket(&close) && !schema.is_open_bracket(&close));
assert!(!schema.is_comma(&unknown("、")));
let alphabet = LatticeMorpheme::new("A", "記号,アルファベット,*,*,*,*,A,エイ,エイ");
assert!(schema.is_symbol(&alphabet));
assert!(!schema.is_comma(&alphabet) && !schema.is_period(&alphabet));
for surface in ["%", "°", "%、", "本", "1", "a"] {
assert!(!schema.is_symbol(&unknown(surface)), "{surface}");
}
assert!(!schema.is_comma(&known(HON)));
}
#[test]
fn the_brackets_come_in_pairs() {
assert_eq!(
OPEN_BRACKETS.chars().count(),
CLOSE_BRACKETS.chars().count()
);
let all = [
COMMAS,
PERIODS,
OPEN_BRACKETS,
CLOSE_BRACKETS,
OTHER_SYMBOLS,
]
.concat();
let mut characters: Vec<char> = all.chars().collect();
let count = characters.len();
characters.sort_unstable();
characters.dedup();
assert_eq!(characters.len(), count);
}
#[test]
fn the_part_of_speech_is_joined_up_to_the_first_empty_level() {
let schema = Schema::ipadic();
let of =
|pair: (&str, &str)| schema.part_of_speech_of(&LatticeMorpheme::new(pair.0, pair.1));
assert_eq!(of(HON), "名詞-一般");
assert_eq!(of(TEKI), "名詞-接尾-形容動詞語幹");
assert_eq!(of(DA), "助動詞");
assert_eq!(of(("x", "*,名詞")), "");
}
#[test]
fn particles_and_words_taken_by_their_surface_follow_the_patterns() {
let schema = Schema::ipadic();
let bunsetsu = morphemes(&[
(
"ゆっくり",
"副詞,助詞類接続,*,*,*,*,ゆっくり,ユックリ,ユックリ",
),
("と", "助詞,格助詞,一般,*,*,*,と,ト,ト"),
("この", "連体詞,*,*,*,*,*,この,コノ,コノ"),
("しかし", "接続詞,*,*,*,*,*,しかし,シカシ,シカシ"),
("本", "名詞,一般,*,*,*,*,本,ホン,ホン"),
]);
let particles: Vec<bool> = (0..6)
.map(|index| schema.is_particle(&bunsetsu, index))
.collect();
assert_eq!(particles, [false, true, false, false, false, false]);
let lexicalized: Vec<bool> = (0..6)
.map(|index| schema.is_lexicalized(&bunsetsu, index))
.collect();
assert_eq!(lexicalized, [true, true, true, true, false, false]);
}
#[test]
fn unidic_is_a_second_schema_of_data_only() {
let schema = Schema::unidic();
let omotte_iru = morphemes(&[
(
"思っ",
"動詞,一般,*,*,五段-ワア行,連用形-促音便,オモウ,思う",
),
("て", "助詞,接続助詞,*,*,*,*,テ,て"),
(
"いる",
"動詞,非自立可能,*,*,上一段-ア行,終止形-一般,イル,居る",
),
]);
assert_eq!(schema.positions(&omotte_iru), Some((0, 2)));
let ni_yotte = morphemes(&[
("事故", "名詞,普通名詞,一般,*,*,*,ジコ,事故"),
("に", "助詞,格助詞,*,*,*,*,ニ,に"),
("よっ", "動詞,一般,*,*,五段-ラ行,連用形-促音便,ヨル,因る"),
("て", "助詞,接続助詞,*,*,*,*,テ,て"),
]);
assert_eq!(schema.positions(&ni_yotte), Some((0, 3)));
let ga_yomu = morphemes(&[
("本", "名詞,普通名詞,一般,*,*,*,ホン,本"),
("が", "助詞,格助詞,*,*,*,*,ガ,が"),
("読む", "動詞,一般,*,*,五段-マ行,終止形-一般,ヨム,読む"),
]);
assert_eq!(schema.positions(&ga_yomu), Some((2, 2)));
let period = LatticeMorpheme::new("。", "補助記号,句点,*,*,*,*,,。");
assert!(schema.is_period(&period) && schema.is_symbol(&period));
assert_eq!(Schema::ipadic().positions(&omotte_iru), Some((2, 2)));
}
const SURU_UNIDIC: (&str, &str) =
("する", "動詞,非自立可能,*,*,サ行変格,連体形-一般,スル,為る");
const TA_UNIDIC: (&str, &str) = ("た", "助動詞,*,*,*,助動詞-タ,連体形-一般,タ,た");
const NI_UNIDIC: (&str, &str) = ("に", "助詞,格助詞,*,*,*,*,ニ,に");
const TSUKAU_UNIDIC: (&str, &str) =
("使う", "動詞,一般,*,*,五段-ワア行,連体形-一般,ツカウ,使う");
#[test]
fn unidic_does_not_take_an_auxiliary_stem_as_the_head() {
let schema = Schema::unidic();
let you = morphemes(&[
TSUKAU_UNIDIC,
("よう", "形状詞,助動詞語幹,*,*,*,*,ヨウ,様"),
("に", "助動詞,*,*,*,助動詞-ダ,連用形-ニ,ダ,だ"),
]);
assert_eq!(schema.positions(&you), Some((0, 2)));
let sou = morphemes(&[
(
"働い",
"動詞,一般,*,*,五段-カ行,連用形-イ音便,ハタラク,働く",
),
TA_UNIDIC,
("そう", "名詞,助動詞語幹,*,*,*,*,ソウ,そう-伝聞"),
("だ", "助動詞,*,*,*,助動詞-ダ,終止形-一般,ダ,だ"),
]);
assert_eq!(schema.positions(&sou), Some((0, 3)));
}
#[test]
fn unidic_does_not_take_a_formal_noun_after_a_predicate_as_the_head() {
let schema = Schema::unidic();
let koto = ("こと", "名詞,普通名詞,一般,*,*,*,コト,事");
let tame = ("ため", "名詞,普通名詞,副詞可能,*,*,*,タメ,為");
let kounyuu = ("購入", "名詞,普通名詞,サ変可能,*,*,*,コウニュウ,購入");
let after_verb = morphemes(&[kounyuu, SURU_UNIDIC, koto, NI_UNIDIC]);
assert_eq!(schema.positions(&after_verb), Some((0, 3)));
let after_auxiliary = morphemes(&[kounyuu, SURU_UNIDIC, TA_UNIDIC, tame, NI_UNIDIC]);
assert_eq!(schema.positions(&after_auxiliary), Some((0, 4)));
let after_adjective = morphemes(&[
(
"新しい",
"形容詞,一般,*,*,形容詞,連体形-一般,アタラシイ,新しい",
),
koto,
NI_UNIDIC,
]);
assert_eq!(schema.positions(&after_adjective), Some((0, 2)));
assert_eq!(
schema.positions(&morphemes(&[koto, NI_UNIDIC])),
Some((0, 1))
);
assert_eq!(
schema.positions(&morphemes(&[kounyuu, koto, NI_UNIDIC])),
Some((1, 2))
);
let hito = morphemes(&[
TSUKAU_UNIDIC,
("人", "名詞,普通名詞,一般,*,*,*,ヒト,人"),
NI_UNIDIC,
]);
assert_eq!(schema.positions(&hito), Some((1, 2)));
}
#[test]
fn unidic_does_not_take_a_nominal_suffix_after_an_adjective_as_the_head() {
let schema = Schema::unidic();
let ookisa = morphemes(&[
("大き", "形容詞,一般,*,*,形容詞,語幹-一般,オオキイ,大きい"),
("さ", "接尾辞,名詞的,一般,*,*,*,サ,さ"),
NI_UNIDIC,
]);
assert_eq!(schema.positions(&ookisa), Some((0, 2)));
let shichou = morphemes(&[
("市", "名詞,普通名詞,一般,*,*,*,シ,市"),
("長", "接尾辞,名詞的,一般,*,*,*,チョウ,長"),
NI_UNIDIC,
]);
assert_eq!(schema.positions(&shichou), Some((1, 2)));
}
#[test]
fn unidic_takes_a_letter_as_a_symbol() {
let schema = Schema::unidic();
let kilometers = morphemes(&[
("5", "名詞,数詞,*,*,*,*,ゴ,五"),
("k", "記号,文字,*,*,*,*,ケー,K"),
("m", "記号,文字,*,*,*,*,エム,M"),
]);
assert!(schema.is_symbol(&kilometers[1]));
assert_eq!(schema.positions(&kilometers), Some((0, 0)));
}
#[test]
fn a_schema_is_chosen_by_the_name_of_the_dictionary() {
assert_eq!(Schema::for_dictionary("ipadic"), Some(Schema::ipadic()));
for name in ["unidic", "unidic-cwj", "unidic-csj"] {
assert_eq!(Schema::for_dictionary(name), Some(Schema::unidic()));
}
for name in Schema::DICTIONARIES {
assert!(Schema::for_dictionary(name).is_some(), "{name}");
}
for name in ["", "IPADIC", "ipadic-neologd", "ko-dic", "unidic-"] {
assert_eq!(Schema::for_dictionary(name), None, "{name}");
}
}
fn last_words() -> Schema {
Schema {
part_of_speech: 0..2,
not_heads: vec![Pattern::new(&["助詞"]), Pattern::new(&["接尾辞"])],
symbols: Symbols {
others: Marks::new(&[&["特殊"]], ""),
surface: SurfaceRule::OneCharacter,
..Symbols::default()
},
head_rule: HeadRule::LastWords,
..Schema::default()
}
}
#[test]
fn with_the_rule_of_the_last_words_the_two_positions_are_found_apart() {
const NOUN: (&str, &str) = ("本", "名詞,普通名詞,*,*,本,ほん,*");
const PARTICLE: (&str, &str) = ("を", "助詞,格助詞,*,*,を,を,*");
const VERB: (&str, &str) = ("読んで", "動詞,*,子音動詞マ行,タ系連用テ形,読む,よんで,*");
const SUFFIX: (&str, &str) = ("いる", "接尾辞,動詞性接尾辞,母音動詞,基本形,いる,いる,*");
const PERIOD: (&str, &str) = ("。", "特殊,句点,*,*,。,。,*");
const BRACKET: (&str, &str) = ("「", "特殊,括弧始,*,*,「,「,*");
let schema = last_words();
let positions = |pairs: &[(&str, &str)]| schema.positions(&morphemes(pairs)).unwrap();
assert_eq!(positions(&[NOUN]), (0, 0));
assert_eq!(positions(&[NOUN, PARTICLE]), (0, 1));
assert_eq!(positions(&[VERB, SUFFIX]), (0, 1));
assert_eq!(positions(&[VERB, SUFFIX, PARTICLE]), (0, 2));
assert_eq!(positions(&[NOUN, PARTICLE, NOUN]), (2, 2));
assert_eq!(positions(&[SUFFIX, NOUN, PARTICLE, PARTICLE]), (1, 3));
assert_eq!(positions(&[VERB, SUFFIX, PERIOD]), (0, 1));
assert_eq!(positions(&[BRACKET, NOUN, PERIOD]), (1, 1));
assert_eq!(positions(&[PERIOD]), (0, 0));
assert_eq!(positions(&[BRACKET, PERIOD]), (0, 0));
assert_eq!(positions(&[PARTICLE]), (0, 0));
assert_eq!(positions(&[BRACKET, PARTICLE]), (0, 1));
assert_eq!(schema.positions::<LatticeMorpheme>(&[]), None);
let with_patterns = Schema {
function_words: vec![Pattern::new(&["名詞"])],
..last_words()
};
assert_eq!(
with_patterns.positions(&morphemes(&[NOUN, PARTICLE])),
Some((0, 1))
);
let apart = Schema {
head_rule: HeadRule::FunctionWordsApart,
..last_words()
};
assert_eq!(apart.positions(&morphemes(&[NOUN, PARTICLE])), Some((0, 0)));
assert_eq!(apart.positions(&morphemes(&[VERB, SUFFIX])), Some((0, 0)));
}
#[test]
fn the_rule_of_the_head_comes_back_from_the_bytes() {
assert_eq!(Schema::default().head_rule, HeadRule::FunctionWordsApart);
assert_eq!(Schema::ipadic().head_rule, HeadRule::FunctionWordsApart);
assert_eq!(Schema::unidic().head_rule, HeadRule::FunctionWordsApart);
for (rule, code) in HeadRule::ALL {
assert_eq!(rule.code(), code);
assert_eq!(HeadRule::from_code(code).unwrap(), rule);
let schema = Schema {
head_rule: rule,
..last_words()
};
let mut bytes = Vec::new();
schema.write(&mut bytes);
assert_eq!(bytes.last(), Some(&code));
let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
assert_eq!(Schema::read(&mut reader).unwrap(), schema);
assert_eq!(reader.remaining(), 0);
}
let mut bytes = Vec::new();
last_words().write(&mut bytes);
*bytes.last_mut().unwrap() = 2;
let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
assert_eq!(
Schema::read(&mut reader).unwrap_err().to_string(),
"2 is not the code of a rule of the head"
);
}
#[test]
fn a_schema_comes_back_from_its_bytes() {
for schema in [Schema::ipadic(), Schema::unidic(), Schema::default()] {
let mut bytes = Vec::new();
schema.write(&mut bytes);
let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
assert_eq!(Schema::read(&mut reader).unwrap(), schema);
assert_eq!(reader.remaining(), 0);
}
}
#[test]
fn the_two_lists_of_patterns_keep_their_places_in_the_bytes() {
let schema = Schema {
function_words: vec![Pattern::new(&["助詞"])],
not_heads: vec![Pattern::new(&["名詞", "非自立"]), Pattern::default()],
..Schema::default()
};
let mut bytes = Vec::new();
schema.write(&mut bytes);
let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
let read = Schema::read(&mut reader).unwrap();
assert_eq!(read.function_words, [Pattern::new(&["助詞"])]);
assert_eq!(read.not_heads.len(), 2);
}
#[test]
fn bytes_that_end_inside_a_schema_are_an_error() {
let mut bytes = Vec::new();
Schema::ipadic().write(&mut bytes);
for length in [0, 4, 20, 24, bytes.len() / 2, bytes.len() - 1] {
let mut reader = Reader::new(&bytes[..length], "test bytes", Error::Chunker);
let message = Schema::read(&mut reader).unwrap_err().to_string();
assert!(message.contains("ends early"), "{length}: {message}");
}
}
#[test]
fn the_width_is_the_number_of_columns_the_schema_reads() {
assert_eq!(Schema::ipadic().width(), 7);
let mut schema = Schema::ipadic();
schema.base_form = None;
assert_eq!(schema.width(), 6);
schema.conjugation_form = None;
schema.conjugation_type = Some(9);
assert_eq!(schema.width(), 10);
schema.conjugation_type = None;
assert_eq!(schema.width(), 4);
schema.part_of_speech = 0..0;
assert_eq!(schema.width(), 0);
}
#[test]
fn morphemes_with_fewer_columns_than_the_schema_reads_are_refused() {
let schema = Schema::ipadic();
let wide = LatticeMorpheme::new("彼", "名詞,代名詞,一般,*,*,*,彼,カレ,カレ");
let unknown = LatticeMorpheme::new("x", "名詞,一般,*,*,*,*,*");
let narrow = LatticeMorpheme::new("彼", "名詞,代名詞,一般,*,*,*");
let none: [LatticeMorpheme; 0] = [];
assert!(schema.check(&none).is_ok());
assert!(schema.check(&[wide.clone(), unknown.clone()]).is_ok());
let error = schema.check(&[wide.clone(), unknown, narrow]).unwrap_err();
assert!(matches!(error, Error::Dictionary(_)), "{error:?}");
assert_eq!(
error.to_string(),
"the morpheme 3 (\"彼\") has fewer than the 7 feature columns the schema reads: it is not of the dictionary of the model"
);
let mut schema = Schema::ipadic();
schema.part_of_speech = 0..0;
schema.conjugation_type = None;
schema.conjugation_form = None;
schema.base_form = None;
assert!(schema.check(&[LatticeMorpheme::new("彼", "")]).is_ok());
}
}