lindera_dependency/morpheme.rs
1//! The morpheme trait, and the feature string of a morpheme.
2
3use std::borrow::Cow;
4
5use crate::schema::{CLOSE_BRACKETS, OPEN_BRACKETS};
6
7/// A morpheme: a surface and the feature columns of its dictionary.
8///
9/// The crate works on any sequence of morphemes, so a type outside Lindera
10/// can implement this trait. What a column means depends on the dictionary:
11/// in IPADIC, column 0 is the part of speech and column 6 the base form.
12///
13/// # Examples
14///
15/// ```
16/// use lindera_dependency::Morpheme;
17///
18/// struct Word {
19/// surface: &'static str,
20/// features: [&'static str; 2],
21/// }
22///
23/// impl Morpheme for Word {
24/// fn surface(&self) -> &str {
25/// self.surface
26/// }
27///
28/// fn feature(&self, index: usize) -> Option<&str> {
29/// self.features.get(index).copied()
30/// }
31/// }
32///
33/// let word = Word { surface: "本", features: ["名詞", "一般"] };
34/// assert_eq!(word.feature(1), Some("一般"));
35/// assert_eq!(word.features(), "名詞,一般");
36/// ```
37pub trait Morpheme {
38 /// The surface of the morpheme.
39 ///
40 /// # Returns
41 ///
42 /// The surface, as it stands in the text.
43 fn surface(&self) -> &str;
44
45 /// A feature column of the morpheme.
46 ///
47 /// # Arguments
48 ///
49 /// * `index` - The index of the column, from 0.
50 ///
51 /// # Returns
52 ///
53 /// The column, or `None` past the last one. The columns have no gap: when
54 /// an index gives `None`, so does every larger one.
55 fn feature(&self, index: usize) -> Option<&str>;
56
57 /// The feature columns as the one string that follows the surface in the
58 /// lattice format.
59 ///
60 /// The default joins the columns with commas, and quotes a column that
61 /// holds a comma or a double quote, as CSV does. An implementation that
62 /// has the string as it was read returns that instead, so that writing a
63 /// sentence gives back the bytes it was read from.
64 ///
65 /// # Returns
66 ///
67 /// The feature string.
68 fn features(&self) -> Cow<'_, str> {
69 let mut joined = String::new();
70 let mut index = 0;
71 while let Some(column) = self.feature(index) {
72 if index > 0 {
73 joined.push(',');
74 }
75 push_column(&mut joined, column);
76 index += 1;
77 }
78 Cow::Owned(joined)
79 }
80
81 /// The named entity tag of the morpheme: the third column of its line in
82 /// the lattice format.
83 ///
84 /// # Returns
85 ///
86 /// The tag, or `None` (the default) for a morpheme without one.
87 fn named_entity(&self) -> Option<&str> {
88 None
89 }
90}
91
92/// A reference to a morpheme is a morpheme: a selection of the morphemes of
93/// a sentence, such as those that are not spaces, is read as a sentence
94/// without a copy.
95impl<M: Morpheme + ?Sized> Morpheme for &M {
96 fn surface(&self) -> &str {
97 (**self).surface()
98 }
99
100 fn feature(&self, index: usize) -> Option<&str> {
101 (**self).feature(index)
102 }
103
104 fn features(&self) -> Cow<'_, str> {
105 (**self).features()
106 }
107
108 fn named_entity(&self) -> Option<&str> {
109 (**self).named_entity()
110 }
111}
112
113/// Whether a morpheme is a space: its surface is of white space alone.
114///
115/// A tokenizer gives a full-width space (U+3000) as a token, and a
116/// half-width one when it is told to keep white space. A space is no word:
117/// the chunker and the parser do not read it, and it is neither the head
118/// word nor the function word of a bunsetsu. It is told by its surface, so
119/// that it is the same for every dictionary, whatever part of speech the
120/// dictionary gives it.
121///
122/// # Arguments
123///
124/// * `morpheme` - The morpheme.
125///
126/// # Returns
127///
128/// Whether the surface has a character and every one is white space.
129///
130/// # Examples
131///
132/// ```
133/// use lindera_dependency::lattice::LatticeMorpheme;
134/// use lindera_dependency::morpheme::is_space;
135///
136/// assert!(is_space(&LatticeMorpheme::new("\u{3000}", "記号,空白")));
137/// assert!(!is_space(&LatticeMorpheme::new("本", "名詞,一般")));
138/// ```
139pub fn is_space<M: Morpheme>(morpheme: &M) -> bool {
140 let surface = morpheme.surface();
141 !surface.is_empty() && surface.chars().all(char::is_whitespace)
142}
143
144/// What a character of a morpheme made of marks is, for the sentences of a
145/// text: see [`marks`].
146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147pub enum Mark {
148 /// A mark that ends a sentence: `。`, `!`, `?`, `!` or `?`.
149 SentenceEnd,
150 /// An opening bracket, such as `(` and `「`.
151 OpenBracket,
152 /// A closing bracket, such as `)` and `」`.
153 CloseBracket,
154 /// Any other mark, such as `~`, `%` and `、`.
155 Other,
156}
157
158/// The marks of a surface, one for each of its characters.
159///
160/// A dictionary can join marks into one word. IPADIC has no half-width
161/// symbol among its words, and an unknown word of symbols is the whole run
162/// of them: `(笑)。` comes out as `(`, 笑 and `)。`, and `「本当?」` as
163/// `「`, 本当 and `?」`. Such a word is no period and no bracket as a
164/// whole, so it is read one character at a time: `)。` is a closing
165/// bracket and then a sentence end.
166///
167/// # Arguments
168///
169/// * `surface` - The surface of a morpheme.
170///
171/// # Returns
172///
173/// The marks, when the surface has a character and no letter, no digit and
174/// no white space; nothing otherwise, as for モーニング娘。, a word that
175/// ends with a `。` and ends no sentence. The brackets are those of the
176/// schemas of this crate.
177///
178/// # Examples
179///
180/// ```
181/// use lindera_dependency::morpheme::{Mark, marks};
182///
183/// let read = |surface| marks(surface).map(|marks| marks.collect::<Vec<_>>());
184/// assert_eq!(read(")。"), Some(vec![Mark::CloseBracket, Mark::SentenceEnd]));
185/// assert_eq!(read("~"), Some(vec![Mark::Other]));
186/// assert_eq!(read("本。"), None);
187/// ```
188pub fn marks(surface: &str) -> Option<impl Iterator<Item = Mark> + '_> {
189 if surface.is_empty()
190 || surface
191 .chars()
192 .any(|letter| letter.is_alphanumeric() || letter.is_whitespace())
193 {
194 return None;
195 }
196 Some(surface.chars().map(|letter| match letter {
197 '。' | '!' | '?' | '!' | '?' => Mark::SentenceEnd,
198 _ if OPEN_BRACKETS.contains(letter) => Mark::OpenBracket,
199 _ if CLOSE_BRACKETS.contains(letter) => Mark::CloseBracket,
200 _ => Mark::Other,
201 }))
202}
203
204/// Whether a morpheme ends a sentence, and whether a closing bracket of
205/// the morpheme follows the end.
206///
207/// # Arguments
208///
209/// * `morpheme` - The morpheme.
210/// * `next` - The morpheme after it, when there is one.
211///
212/// # Returns
213///
214/// Nothing when the morpheme ends no sentence ([`is_sentence_end`]);
215/// otherwise whether it closes a bracket after its end, as `?」` does.
216pub(crate) fn sentence_end<M: Morpheme>(morpheme: &M, next: Option<&M>) -> Option<bool> {
217 let surface = morpheme.surface();
218 if surface == "." {
219 let digit = next.is_some_and(|next| {
220 next.surface().starts_with(|letter: char| {
221 letter.is_ascii_digit() || ('0'..='9').contains(&letter)
222 })
223 });
224 return (!digit).then_some(false);
225 }
226 // Whether the last mark that is no closing bracket is an end, and
227 // whether a bracket was closed since the ends it is the last of began:
228 // what holds for an end and the ends and closing brackets after it
229 // when they are words of their own. The brackets around the end are
230 // not looked at, as they are not for 。 inside 「…」.
231 let mut ended = false;
232 let mut closed = false;
233 for mark in marks(surface)? {
234 match mark {
235 Mark::SentenceEnd => ended = true,
236 Mark::CloseBracket => closed |= ended,
237 Mark::OpenBracket | Mark::Other => {
238 ended = false;
239 closed = false;
240 }
241 }
242 }
243 ended.then_some(closed)
244}
245
246/// Whether a morpheme ends a sentence.
247///
248/// The marks are told by the surface, so that they are the same for every
249/// dictionary: UniDic gives the part of speech of a period (補助記号,句点)
250/// to the half-width `.` of `1.060` and of `L.E.D.`, which ends nothing.
251///
252/// The token filter `japanese_dependency` cuts a text into sentences where
253/// this holds outside brackets, and a chunker cuts its words after it
254/// ([`Schema::sentence_starts`](crate::Schema::sentence_starts)).
255///
256/// # Arguments
257///
258/// * `morpheme` - The morpheme.
259/// * `next` - The morpheme after it, when there is one.
260///
261/// # Returns
262///
263/// Whether its surface is of `。`, `!`, `?`, `!` and `?` alone, or is
264/// `.` and no digit follows. The half-width `.` is not an end: it is in
265/// `4.20` and in `...`.
266///
267/// A morpheme of several [`marks`], which a dictionary joined into one
268/// word, also ends a sentence when its last mark that is no closing
269/// bracket is one of the five: `~。`, `)。`, `?」` and `(?)` do, as `。`
270/// and `?` do when they are words of their own, and `,“` and `~」` do not.
271/// Whether the end is inside brackets is not asked here.
272///
273/// # Examples
274///
275/// ```
276/// use lindera_dependency::lattice::LatticeMorpheme;
277/// use lindera_dependency::morpheme::is_sentence_end;
278///
279/// let period = LatticeMorpheme::new("。", "記号,句点");
280/// let dot = LatticeMorpheme::new(".", "記号,句点");
281/// let word = LatticeMorpheme::new("本", "名詞,一般");
282/// assert!(is_sentence_end(&period, Some(&word)));
283/// assert!(is_sentence_end(&period, None));
284/// assert!(!is_sentence_end(&dot, Some(&word)));
285/// assert!(!is_sentence_end(&word, None));
286///
287/// // IPADIC gives `)。` as one unknown word.
288/// let joined = LatticeMorpheme::new(")。", "名詞,サ変接続");
289/// assert!(is_sentence_end(&joined, Some(&word)));
290/// ```
291pub fn is_sentence_end<M: Morpheme>(morpheme: &M, next: Option<&M>) -> bool {
292 sentence_end(morpheme, next).is_some()
293}
294
295/// Appends a feature column to a feature string, quoted when it holds a comma
296/// or a double quote.
297///
298/// # Arguments
299///
300/// * `joined` - The feature string so far.
301/// * `column` - The column to append.
302fn push_column(joined: &mut String, column: &str) {
303 if column.contains([',', '"']) {
304 joined.push('"');
305 for c in column.chars() {
306 if c == '"' {
307 joined.push('"');
308 }
309 joined.push(c);
310 }
311 joined.push('"');
312 } else {
313 joined.push_str(column);
314 }
315}
316
317/// Splits a feature string into its columns, as a row of CSV.
318///
319/// A column that starts with a double quote runs to the closing quote, and
320/// two quotes inside it stand for one, so that a quoted comma does not end
321/// the column (MeCab writes the columns of its dictionary's CSV this way). A
322/// quote elsewhere, and an opening quote without a closing one, are kept as
323/// they are: the function gives columns for any string.
324///
325/// # Arguments
326///
327/// * `features` - The feature string.
328///
329/// # Returns
330///
331/// The columns. The empty string has none.
332pub(crate) fn split_features(features: &str) -> Vec<String> {
333 let mut columns = Vec::new();
334 if features.is_empty() {
335 return columns;
336 }
337 let mut rest = features;
338 loop {
339 let (column, after) = split_column(rest);
340 columns.push(column);
341 match after {
342 Some(after) => rest = after,
343 None => break,
344 }
345 }
346 columns
347}
348
349/// Takes the first column of a feature string.
350///
351/// # Arguments
352///
353/// * `rest` - The feature string from the start of a column.
354///
355/// # Returns
356///
357/// The column, and what follows its comma, or `None` when the column is the
358/// last one.
359fn split_column(rest: &str) -> (String, Option<&str>) {
360 if let Some(quoted) = rest.strip_prefix('"')
361 && let Some((column, after)) = split_quoted(quoted)
362 {
363 return (column, after);
364 }
365 match rest.split_once(',') {
366 Some((column, after)) => (column.to_string(), Some(after)),
367 None => (rest.to_string(), None),
368 }
369}
370
371/// Takes a quoted column, from after its opening quote.
372///
373/// # Arguments
374///
375/// * `quoted` - The feature string from after the opening quote.
376///
377/// # Returns
378///
379/// The column without its quotes, and what follows its comma (`None` for the
380/// last column); or `None` when there is no closing quote, or when the
381/// closing quote is followed by something other than a comma.
382fn split_quoted(quoted: &str) -> Option<(String, Option<&str>)> {
383 let mut column = String::new();
384 let mut chars = quoted.char_indices();
385 while let Some((at, c)) = chars.next() {
386 if c != '"' {
387 column.push(c);
388 continue;
389 }
390 let after = "ed[at + 1..];
391 if after.starts_with('"') {
392 column.push('"');
393 chars.next();
394 } else if after.is_empty() {
395 return Some((column, None));
396 } else {
397 let after = after.strip_prefix(',')?;
398 return Some((column, Some(after)));
399 }
400 }
401 None
402}
403
404/// A morpheme of a dictionary: its surface and its feature columns.
405///
406/// What a tokenizer gives, when it has no type of its own that implements
407/// [`Morpheme`]: the `lindera dependency` command makes one from each token
408/// of Lindera.
409///
410/// # Examples
411///
412/// ```
413/// use lindera_dependency::{DictionaryMorpheme, Morpheme};
414///
415/// let morpheme = DictionaryMorpheme::new(
416/// "本".to_string(),
417/// vec!["名詞".to_string(), "一般".to_string()],
418/// );
419/// assert_eq!(morpheme.surface(), "本");
420/// assert_eq!(morpheme.feature(1), Some("一般"));
421/// assert_eq!(morpheme.features(), "名詞,一般");
422/// ```
423#[derive(Debug, Clone, PartialEq, Eq)]
424pub struct DictionaryMorpheme {
425 /// The surface.
426 pub surface: String,
427 /// The feature columns.
428 pub features: Vec<String>,
429}
430
431impl DictionaryMorpheme {
432 /// Makes a morpheme.
433 ///
434 /// # Arguments
435 ///
436 /// * `surface` - The surface.
437 /// * `features` - The feature columns.
438 ///
439 /// # Returns
440 ///
441 /// The morpheme.
442 pub fn new(surface: String, features: Vec<String>) -> Self {
443 Self { surface, features }
444 }
445}
446
447impl Morpheme for DictionaryMorpheme {
448 fn surface(&self) -> &str {
449 &self.surface
450 }
451
452 fn feature(&self, index: usize) -> Option<&str> {
453 self.features.get(index).map(String::as_str)
454 }
455}
456
457#[cfg(test)]
458mod tests {
459 use super::*;
460
461 struct Columns(Vec<&'static str>);
462
463 impl Morpheme for Columns {
464 fn surface(&self) -> &str {
465 "surface"
466 }
467
468 fn feature(&self, index: usize) -> Option<&str> {
469 self.0.get(index).copied()
470 }
471 }
472
473 #[test]
474 fn splits_plain_columns() {
475 assert_eq!(split_features("名詞,一般,*"), ["名詞", "一般", "*"]);
476 assert_eq!(split_features("名詞"), ["名詞"]);
477 assert!(split_features("").is_empty());
478 }
479
480 #[test]
481 fn keeps_empty_columns() {
482 assert_eq!(split_features("a,,b,"), ["a", "", "b", ""]);
483 assert_eq!(split_features(","), ["", ""]);
484 }
485
486 #[test]
487 fn a_quoted_comma_does_not_end_the_column() {
488 assert_eq!(
489 split_features(r#"記号,読点,*,*,*,*,",",",",",""#),
490 ["記号", "読点", "*", "*", "*", "*", ",", ",", ","]
491 );
492 }
493
494 #[test]
495 fn two_quotes_in_a_quoted_column_are_one() {
496 assert_eq!(split_features(r#""a""b",c"#), ["a\"b", "c"]);
497 assert_eq!(split_features(r#""""""#), ["\""]);
498 assert_eq!(split_features(r#""a""""#), ["a\""]);
499 }
500
501 #[test]
502 fn an_unquoted_comma_row_has_more_columns() {
503 // What `lindera tokenize -o mecab` writes for the morpheme `,`.
504 assert_eq!(
505 split_features("記号,読点,*,*,*,*,,,,,,"),
506 ["記号", "読点", "*", "*", "*", "*", "", "", "", "", "", ""]
507 );
508 }
509
510 #[test]
511 fn a_quote_that_does_not_quote_a_column_is_kept() {
512 assert_eq!(split_features(r#"a"b,c"#), ["a\"b", "c"]);
513 assert_eq!(split_features(r#""abc"#), ["\"abc"]);
514 assert_eq!(split_features(r#""a"b,c"#), ["\"a\"b", "c"]);
515 }
516
517 #[test]
518 fn the_default_feature_string_joins_the_columns() {
519 assert_eq!(Columns(vec!["名詞", "一般", "*"]).features(), "名詞,一般,*");
520 assert_eq!(Columns(vec![]).features(), "");
521 }
522
523 #[test]
524 fn the_default_feature_string_quotes_commas_and_quotes() {
525 let morpheme = Columns(vec!["記号", ",", "a\"b", ""]);
526 let features = morpheme.features();
527 assert_eq!(features, r#"記号,",","a""b","#);
528 assert_eq!(split_features(&features), ["記号", ",", "a\"b", ""]);
529 }
530
531 #[test]
532 fn a_morpheme_has_no_named_entity_by_default() {
533 assert_eq!(Columns(vec!["名詞"]).named_entity(), None);
534 }
535
536 /// A morpheme by its surface alone.
537 struct Surface(&'static str);
538
539 impl Morpheme for Surface {
540 fn surface(&self) -> &str {
541 self.0
542 }
543
544 fn feature(&self, _index: usize) -> Option<&str> {
545 None
546 }
547 }
548
549 #[test]
550 fn the_marks_that_end_a_sentence() {
551 for mark in ["。", "!", "?", "!", "?", "!?", "。。", "?!"] {
552 assert!(is_sentence_end(&Surface(mark), None), "{mark}");
553 assert!(
554 is_sentence_end(&Surface(mark), Some(&Surface("本"))),
555 "{mark}"
556 );
557 assert!(
558 is_sentence_end(&Surface(mark), Some(&Surface("3"))),
559 "{mark}"
560 );
561 }
562 // The half-width period, a comma, a word, a mark with something
563 // else, and no surface.
564 for other in [".", "...", "、", ",", "本", "。本", "」", "\u{3000}", ""] {
565 assert!(!is_sentence_end(&Surface(other), None), "{other:?}");
566 assert!(
567 !is_sentence_end(&Surface(other), Some(&Surface("本"))),
568 "{other:?}"
569 );
570 }
571 }
572
573 /// The marks of a surface, written with one letter each.
574 fn read(surface: &str) -> Option<String> {
575 marks(surface).map(|marks| {
576 marks
577 .map(|mark| match mark {
578 Mark::SentenceEnd => 'E',
579 Mark::OpenBracket => 'O',
580 Mark::CloseBracket => 'C',
581 Mark::Other => 'X',
582 })
583 .collect()
584 })
585 }
586
587 #[test]
588 fn the_marks_of_a_surface_are_read_one_character_at_a_time() {
589 assert_eq!(read(")。").as_deref(), Some("CE"));
590 assert_eq!(read("?」").as_deref(), Some("EC"));
591 assert_eq!(read("(?)").as_deref(), Some("OEC"));
592 assert_eq!(read("~。").as_deref(), Some("XE"));
593 assert_eq!(read(",“").as_deref(), Some("XO"));
594 // Each of the five ends, in both widths, and the two periods that
595 // are none.
596 assert_eq!(read("。!?!?").as_deref(), Some("EEEEE"));
597 assert_eq!(read("..、").as_deref(), Some("XXX"));
598 // The brackets of both widths.
599 assert_eq!(read("((「『").as_deref(), Some("OOOO"));
600 assert_eq!(read("))」』").as_deref(), Some("CCCC"));
601 // One mark is read as several are.
602 assert_eq!(read("。").as_deref(), Some("E"));
603 }
604
605 #[test]
606 fn a_surface_with_a_letter_a_digit_or_a_space_has_no_marks() {
607 for surface in [
608 "",
609 "本",
610 "本。",
611 "モーニング娘。",
612 "a!",
613 "1。",
614 "1。",
615 "ー。",
616 ] {
617 assert_eq!(read(surface), None, "{surface:?}");
618 }
619 for surface in [" 。", "。 ", "\u{3000}。", "\u{3000}"] {
620 assert_eq!(read(surface), None, "{surface:?}");
621 }
622 }
623
624 #[test]
625 fn marks_joined_into_one_word_end_a_sentence_by_their_last_mark() {
626 // An end after other marks, and after a closing bracket.
627 for joined in [
628 "~。",
629 "%。",
630 "......。",
631 ")。",
632 "~!",
633 "~?",
634 "」。",
635 "(笑)。",
636 ] {
637 let expected = read(joined).is_some();
638 assert_eq!(
639 is_sentence_end(&Surface(joined), Some(&Surface("本"))),
640 expected,
641 "{joined}"
642 );
643 }
644 for joined in ["~。", "%。", "......。", ")。", "~!", "~?", "」。"] {
645 assert!(is_sentence_end(&Surface(joined), None), "{joined}");
646 assert_eq!(
647 sentence_end(&Surface(joined), Some(&Surface("本"))),
648 Some(false),
649 "{joined}"
650 );
651 }
652 // A closing bracket after the end: the end is still the end, and
653 // the bracket is closed after it.
654 for joined in [
655 "?」",
656 "!”",
657 "。)",
658 "!?」』",
659 "~。)",
660 "?」。",
661 "?」)。",
662 "(?)",
663 "「。」",
664 "(?)。",
665 ] {
666 assert_eq!(
667 sentence_end(&Surface(joined), Some(&Surface("本"))),
668 Some(true),
669 "{joined}"
670 );
671 }
672 // No end, an end that is not the last mark, and a word with a
673 // letter.
674 for other in [",“", "~」", "%、", "。~", "?「", "()", "本。", "...", "~."] {
675 assert_eq!(sentence_end(&Surface(other), None), None, "{other}");
676 assert!(
677 !is_sentence_end(&Surface(other), Some(&Surface("本"))),
678 "{other}"
679 );
680 }
681 // A bracket the word opens before the end changes nothing: (?) is
682 // as ( / ? / ) are, and an end right after it closes nothing.
683 assert_eq!(sentence_end(&Surface("(?"), None), Some(false));
684 assert_eq!(sentence_end(&Surface(":(。"), None), Some(false));
685 assert_eq!(sentence_end(&Surface("?)"), None), Some(true));
686 // A bracket closed before another mark, or before a bracket that
687 // opens, is not one closed after the end: the end is a new one.
688 assert_eq!(sentence_end(&Surface("?」~。"), None), Some(false));
689 assert_eq!(sentence_end(&Surface("?」()。"), None), Some(false));
690 }
691
692 #[test]
693 fn a_full_width_period_ends_a_sentence_unless_a_digit_follows() {
694 let period = Surface(".");
695 assert!(is_sentence_end(&period, None));
696 assert!(is_sentence_end(&period, Some(&Surface("本"))));
697 assert!(is_sentence_end(&period, Some(&Surface(""))));
698 for digits in ["1", "14", "14", "9本"] {
699 assert!(
700 !is_sentence_end(&period, Some(&Surface(digits))),
701 "{digits}"
702 );
703 }
704 // It closes no bracket.
705 assert_eq!(sentence_end(&period, None), Some(false));
706 }
707}