lindera-dependency 7.2.0

Japanese bunsetsu dependency analysis for Lindera.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! The morpheme trait, and the feature string of a morpheme.

use std::borrow::Cow;

/// A morpheme: a surface and the feature columns of its dictionary.
///
/// The crate works on any sequence of morphemes, so a type outside Lindera
/// can implement this trait. What a column means depends on the dictionary:
/// in IPADIC, column 0 is the part of speech and column 6 the base form.
///
/// # Examples
///
/// ```
/// use lindera_dependency::Morpheme;
///
/// struct Word {
///     surface: &'static str,
///     features: [&'static str; 2],
/// }
///
/// impl Morpheme for Word {
///     fn surface(&self) -> &str {
///         self.surface
///     }
///
///     fn feature(&self, index: usize) -> Option<&str> {
///         self.features.get(index).copied()
///     }
/// }
///
/// let word = Word { surface: "本", features: ["名詞", "一般"] };
/// assert_eq!(word.feature(1), Some("一般"));
/// assert_eq!(word.features(), "名詞,一般");
/// ```
pub trait Morpheme {
    /// The surface of the morpheme.
    ///
    /// # Returns
    ///
    /// The surface, as it stands in the text.
    fn surface(&self) -> &str;

    /// A feature column of the morpheme.
    ///
    /// # Arguments
    ///
    /// * `index` - The index of the column, from 0.
    ///
    /// # Returns
    ///
    /// The column, or `None` past the last one. The columns have no gap: when
    /// an index gives `None`, so does every larger one.
    fn feature(&self, index: usize) -> Option<&str>;

    /// The feature columns as the one string that follows the surface in the
    /// lattice format.
    ///
    /// The default joins the columns with commas, and quotes a column that
    /// holds a comma or a double quote, as CSV does. An implementation that
    /// has the string as it was read returns that instead, so that writing a
    /// sentence gives back the bytes it was read from.
    ///
    /// # Returns
    ///
    /// The feature string.
    fn features(&self) -> Cow<'_, str> {
        let mut joined = String::new();
        let mut index = 0;
        while let Some(column) = self.feature(index) {
            if index > 0 {
                joined.push(',');
            }
            push_column(&mut joined, column);
            index += 1;
        }
        Cow::Owned(joined)
    }

    /// The named entity tag of the morpheme: the third column of its line in
    /// the lattice format.
    ///
    /// # Returns
    ///
    /// The tag, or `None` (the default) for a morpheme without one.
    fn named_entity(&self) -> Option<&str> {
        None
    }
}

/// A reference to a morpheme is a morpheme: a selection of the morphemes of
/// a sentence, such as those that are not spaces, is read as a sentence
/// without a copy.
impl<M: Morpheme + ?Sized> Morpheme for &M {
    fn surface(&self) -> &str {
        (**self).surface()
    }

    fn feature(&self, index: usize) -> Option<&str> {
        (**self).feature(index)
    }

    fn features(&self) -> Cow<'_, str> {
        (**self).features()
    }

    fn named_entity(&self) -> Option<&str> {
        (**self).named_entity()
    }
}

/// Whether a morpheme is a space: its surface is of white space alone.
///
/// A tokenizer gives a full-width space (U+3000) as a token, and a
/// half-width one when it is told to keep white space. A space is no word:
/// the chunker and the parser do not read it, and it is neither the head
/// word nor the function word of a bunsetsu. It is told by its surface, so
/// that it is the same for every dictionary, whatever part of speech the
/// dictionary gives it.
///
/// # Arguments
///
/// * `morpheme` - The morpheme.
///
/// # Returns
///
/// Whether the surface has a character and every one is white space.
///
/// # Examples
///
/// ```
/// use lindera_dependency::lattice::LatticeMorpheme;
/// use lindera_dependency::morpheme::is_space;
///
/// assert!(is_space(&LatticeMorpheme::new("\u{3000}", "記号,空白")));
/// assert!(!is_space(&LatticeMorpheme::new("本", "名詞,一般")));
/// ```
pub fn is_space<M: Morpheme>(morpheme: &M) -> bool {
    let surface = morpheme.surface();
    !surface.is_empty() && surface.chars().all(char::is_whitespace)
}

/// Whether a morpheme ends a sentence.
///
/// The marks are told by the surface, so that they are the same for every
/// dictionary: UniDic gives the part of speech of a period (補助記号,句点)
/// to the half-width `.` of `1.060` and of `L.E.D.`, which ends nothing.
///
/// The token filter `japanese_dependency` cuts a text into sentences where
/// this holds outside brackets, and a chunker cuts its words after it
/// ([`Schema::sentence_starts`](crate::Schema::sentence_starts)).
///
/// # Arguments
///
/// * `morpheme` - The morpheme.
/// * `next` - The morpheme after it, when there is one.
///
/// # Returns
///
/// Whether its surface is of `。`, `!`, `?`, `!` and `?` alone, or is
/// `.` and no digit follows. The half-width `.` is not an end: it is in
/// `4.20` and in `...`.
///
/// # Examples
///
/// ```
/// use lindera_dependency::lattice::LatticeMorpheme;
/// use lindera_dependency::morpheme::is_sentence_end;
///
/// let period = LatticeMorpheme::new("。", "記号,句点");
/// let dot = LatticeMorpheme::new(".", "記号,句点");
/// let word = LatticeMorpheme::new("本", "名詞,一般");
/// assert!(is_sentence_end(&period, Some(&word)));
/// assert!(is_sentence_end(&period, None));
/// assert!(!is_sentence_end(&dot, Some(&word)));
/// assert!(!is_sentence_end(&word, None));
/// ```
pub fn is_sentence_end<M: Morpheme>(morpheme: &M, next: Option<&M>) -> bool {
    let surface = morpheme.surface();
    if surface == "." {
        return !next.is_some_and(|next| {
            next.surface().starts_with(|letter: char| {
                letter.is_ascii_digit() || ('0'..='9').contains(&letter)
            })
        });
    }
    !surface.is_empty()
        && surface
            .chars()
            .all(|letter| matches!(letter, '。' | '!' | '?' | '!' | '?'))
}

/// Appends a feature column to a feature string, quoted when it holds a comma
/// or a double quote.
///
/// # Arguments
///
/// * `joined` - The feature string so far.
/// * `column` - The column to append.
fn push_column(joined: &mut String, column: &str) {
    if column.contains([',', '"']) {
        joined.push('"');
        for c in column.chars() {
            if c == '"' {
                joined.push('"');
            }
            joined.push(c);
        }
        joined.push('"');
    } else {
        joined.push_str(column);
    }
}

/// Splits a feature string into its columns, as a row of CSV.
///
/// A column that starts with a double quote runs to the closing quote, and
/// two quotes inside it stand for one, so that a quoted comma does not end
/// the column (MeCab writes the columns of its dictionary's CSV this way). A
/// quote elsewhere, and an opening quote without a closing one, are kept as
/// they are: the function gives columns for any string.
///
/// # Arguments
///
/// * `features` - The feature string.
///
/// # Returns
///
/// The columns. The empty string has none.
pub(crate) fn split_features(features: &str) -> Vec<String> {
    let mut columns = Vec::new();
    if features.is_empty() {
        return columns;
    }
    let mut rest = features;
    loop {
        let (column, after) = split_column(rest);
        columns.push(column);
        match after {
            Some(after) => rest = after,
            None => break,
        }
    }
    columns
}

/// Takes the first column of a feature string.
///
/// # Arguments
///
/// * `rest` - The feature string from the start of a column.
///
/// # Returns
///
/// The column, and what follows its comma, or `None` when the column is the
/// last one.
fn split_column(rest: &str) -> (String, Option<&str>) {
    if let Some(quoted) = rest.strip_prefix('"')
        && let Some((column, after)) = split_quoted(quoted)
    {
        return (column, after);
    }
    match rest.split_once(',') {
        Some((column, after)) => (column.to_string(), Some(after)),
        None => (rest.to_string(), None),
    }
}

/// Takes a quoted column, from after its opening quote.
///
/// # Arguments
///
/// * `quoted` - The feature string from after the opening quote.
///
/// # Returns
///
/// The column without its quotes, and what follows its comma (`None` for the
/// last column); or `None` when there is no closing quote, or when the
/// closing quote is followed by something other than a comma.
fn split_quoted(quoted: &str) -> Option<(String, Option<&str>)> {
    let mut column = String::new();
    let mut chars = quoted.char_indices();
    while let Some((at, c)) = chars.next() {
        if c != '"' {
            column.push(c);
            continue;
        }
        let after = &quoted[at + 1..];
        if after.starts_with('"') {
            column.push('"');
            chars.next();
        } else if after.is_empty() {
            return Some((column, None));
        } else {
            let after = after.strip_prefix(',')?;
            return Some((column, Some(after)));
        }
    }
    None
}

/// A morpheme of a dictionary: its surface and its feature columns.
///
/// What a tokenizer gives, when it has no type of its own that implements
/// [`Morpheme`]: the `lindera dependency` command makes one from each token
/// of Lindera.
///
/// # Examples
///
/// ```
/// use lindera_dependency::{DictionaryMorpheme, Morpheme};
///
/// let morpheme = DictionaryMorpheme::new(
///     "本".to_string(),
///     vec!["名詞".to_string(), "一般".to_string()],
/// );
/// assert_eq!(morpheme.surface(), "本");
/// assert_eq!(morpheme.feature(1), Some("一般"));
/// assert_eq!(morpheme.features(), "名詞,一般");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DictionaryMorpheme {
    /// The surface.
    pub surface: String,
    /// The feature columns.
    pub features: Vec<String>,
}

impl DictionaryMorpheme {
    /// Makes a morpheme.
    ///
    /// # Arguments
    ///
    /// * `surface` - The surface.
    /// * `features` - The feature columns.
    ///
    /// # Returns
    ///
    /// The morpheme.
    pub fn new(surface: String, features: Vec<String>) -> Self {
        Self { surface, features }
    }
}

impl Morpheme for DictionaryMorpheme {
    fn surface(&self) -> &str {
        &self.surface
    }

    fn feature(&self, index: usize) -> Option<&str> {
        self.features.get(index).map(String::as_str)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    struct Columns(Vec<&'static str>);

    impl Morpheme for Columns {
        fn surface(&self) -> &str {
            "surface"
        }

        fn feature(&self, index: usize) -> Option<&str> {
            self.0.get(index).copied()
        }
    }

    #[test]
    fn splits_plain_columns() {
        assert_eq!(split_features("名詞,一般,*"), ["名詞", "一般", "*"]);
        assert_eq!(split_features("名詞"), ["名詞"]);
        assert!(split_features("").is_empty());
    }

    #[test]
    fn keeps_empty_columns() {
        assert_eq!(split_features("a,,b,"), ["a", "", "b", ""]);
        assert_eq!(split_features(","), ["", ""]);
    }

    #[test]
    fn a_quoted_comma_does_not_end_the_column() {
        assert_eq!(
            split_features(r#"記号,読点,*,*,*,*,",",",",",""#),
            ["記号", "読点", "*", "*", "*", "*", ",", ",", ","]
        );
    }

    #[test]
    fn two_quotes_in_a_quoted_column_are_one() {
        assert_eq!(split_features(r#""a""b",c"#), ["a\"b", "c"]);
        assert_eq!(split_features(r#""""""#), ["\""]);
        assert_eq!(split_features(r#""a""""#), ["a\""]);
    }

    #[test]
    fn an_unquoted_comma_row_has_more_columns() {
        // What `lindera tokenize -o mecab` writes for the morpheme `,`.
        assert_eq!(
            split_features("記号,読点,*,*,*,*,,,,,,"),
            ["記号", "読点", "*", "*", "*", "*", "", "", "", "", "", ""]
        );
    }

    #[test]
    fn a_quote_that_does_not_quote_a_column_is_kept() {
        assert_eq!(split_features(r#"a"b,c"#), ["a\"b", "c"]);
        assert_eq!(split_features(r#""abc"#), ["\"abc"]);
        assert_eq!(split_features(r#""a"b,c"#), ["\"a\"b", "c"]);
    }

    #[test]
    fn the_default_feature_string_joins_the_columns() {
        assert_eq!(Columns(vec!["名詞", "一般", "*"]).features(), "名詞,一般,*");
        assert_eq!(Columns(vec![]).features(), "");
    }

    #[test]
    fn the_default_feature_string_quotes_commas_and_quotes() {
        let morpheme = Columns(vec!["記号", ",", "a\"b", ""]);
        let features = morpheme.features();
        assert_eq!(features, r#"記号,",","a""b","#);
        assert_eq!(split_features(&features), ["記号", ",", "a\"b", ""]);
    }

    #[test]
    fn a_morpheme_has_no_named_entity_by_default() {
        assert_eq!(Columns(vec!["名詞"]).named_entity(), None);
    }

    /// A morpheme by its surface alone.
    struct Surface(&'static str);

    impl Morpheme for Surface {
        fn surface(&self) -> &str {
            self.0
        }

        fn feature(&self, _index: usize) -> Option<&str> {
            None
        }
    }

    #[test]
    fn the_marks_that_end_a_sentence() {
        for mark in ["。", "!", "?", "!", "?", "!?", "。。", "?!"] {
            assert!(is_sentence_end(&Surface(mark), None), "{mark}");
            assert!(
                is_sentence_end(&Surface(mark), Some(&Surface("本"))),
                "{mark}"
            );
            assert!(
                is_sentence_end(&Surface(mark), Some(&Surface("3"))),
                "{mark}"
            );
        }
        // The half-width period, a comma, a word, a mark with something
        // else, and no surface.
        for other in [".", "...", "、", ",", "本", "。本", "」", "\u{3000}", ""] {
            assert!(!is_sentence_end(&Surface(other), None), "{other:?}");
            assert!(
                !is_sentence_end(&Surface(other), Some(&Surface("本"))),
                "{other:?}"
            );
        }
    }

    #[test]
    fn a_full_width_period_ends_a_sentence_unless_a_digit_follows() {
        let period = Surface(".");
        assert!(is_sentence_end(&period, None));
        assert!(is_sentence_end(&period, Some(&Surface("本"))));
        assert!(is_sentence_end(&period, Some(&Surface(""))));
        for digits in ["1", "14", "14", "9本"] {
            assert!(
                !is_sentence_end(&period, Some(&Surface(digits))),
                "{digits}"
            );
        }
    }
}