lindera-dependency 7.3.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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
//! The morpheme trait, and the feature string of a morpheme.

use std::borrow::Cow;

use crate::schema::{CLOSE_BRACKETS, OPEN_BRACKETS};

/// 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)
}

/// What a character of a morpheme made of marks is, for the sentences of a
/// text: see [`marks`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mark {
    /// A mark that ends a sentence: `。`, `!`, `?`, `!` or `?`.
    SentenceEnd,
    /// An opening bracket, such as `(` and `「`.
    OpenBracket,
    /// A closing bracket, such as `)` and `」`.
    CloseBracket,
    /// Any other mark, such as `~`, `%` and `、`.
    Other,
}

/// The marks of a surface, one for each of its characters.
///
/// A dictionary can join marks into one word. IPADIC has no half-width
/// symbol among its words, and an unknown word of symbols is the whole run
/// of them: `(笑)。` comes out as `(`, 笑 and `)。`, and `「本当?」` as
/// `「`, 本当 and `?」`. Such a word is no period and no bracket as a
/// whole, so it is read one character at a time: `)。` is a closing
/// bracket and then a sentence end.
///
/// # Arguments
///
/// * `surface` - The surface of a morpheme.
///
/// # Returns
///
/// The marks, when the surface has a character and no letter, no digit and
/// no white space; nothing otherwise, as for モーニング娘。, a word that
/// ends with a `。` and ends no sentence. The brackets are those of the
/// schemas of this crate.
///
/// # Examples
///
/// ```
/// use lindera_dependency::morpheme::{Mark, marks};
///
/// let read = |surface| marks(surface).map(|marks| marks.collect::<Vec<_>>());
/// assert_eq!(read(")。"), Some(vec![Mark::CloseBracket, Mark::SentenceEnd]));
/// assert_eq!(read("~"), Some(vec![Mark::Other]));
/// assert_eq!(read("本。"), None);
/// ```
pub fn marks(surface: &str) -> Option<impl Iterator<Item = Mark> + '_> {
    if surface.is_empty()
        || surface
            .chars()
            .any(|letter| letter.is_alphanumeric() || letter.is_whitespace())
    {
        return None;
    }
    Some(surface.chars().map(|letter| match letter {
        '。' | '!' | '?' | '!' | '?' => Mark::SentenceEnd,
        _ if OPEN_BRACKETS.contains(letter) => Mark::OpenBracket,
        _ if CLOSE_BRACKETS.contains(letter) => Mark::CloseBracket,
        _ => Mark::Other,
    }))
}

/// Whether a morpheme ends a sentence, and whether a closing bracket of
/// the morpheme follows the end.
///
/// # Arguments
///
/// * `morpheme` - The morpheme.
/// * `next` - The morpheme after it, when there is one.
///
/// # Returns
///
/// Nothing when the morpheme ends no sentence ([`is_sentence_end`]);
/// otherwise whether it closes a bracket after its end, as `?」` does.
pub(crate) fn sentence_end<M: Morpheme>(morpheme: &M, next: Option<&M>) -> Option<bool> {
    let surface = morpheme.surface();
    if surface == "." {
        let digit = next.is_some_and(|next| {
            next.surface().starts_with(|letter: char| {
                letter.is_ascii_digit() || ('0'..='9').contains(&letter)
            })
        });
        return (!digit).then_some(false);
    }
    // Whether the last mark that is no closing bracket is an end, and
    // whether a bracket was closed since the ends it is the last of began:
    // what holds for an end and the ends and closing brackets after it
    // when they are words of their own. The brackets around the end are
    // not looked at, as they are not for 。 inside 「…」.
    let mut ended = false;
    let mut closed = false;
    for mark in marks(surface)? {
        match mark {
            Mark::SentenceEnd => ended = true,
            Mark::CloseBracket => closed |= ended,
            Mark::OpenBracket | Mark::Other => {
                ended = false;
                closed = false;
            }
        }
    }
    ended.then_some(closed)
}

/// 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 `...`.
///
/// A morpheme of several [`marks`], which a dictionary joined into one
/// word, also ends a sentence when its last mark that is no closing
/// bracket is one of the five: `~。`, `)。`, `?」` and `(?)` do, as `。`
/// and `?` do when they are words of their own, and `,“` and `~」` do not.
/// Whether the end is inside brackets is not asked here.
///
/// # 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));
///
/// // IPADIC gives `)。` as one unknown word.
/// let joined = LatticeMorpheme::new(")。", "名詞,サ変接続");
/// assert!(is_sentence_end(&joined, Some(&word)));
/// ```
pub fn is_sentence_end<M: Morpheme>(morpheme: &M, next: Option<&M>) -> bool {
    sentence_end(morpheme, next).is_some()
}

/// 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:?}"
            );
        }
    }

    /// The marks of a surface, written with one letter each.
    fn read(surface: &str) -> Option<String> {
        marks(surface).map(|marks| {
            marks
                .map(|mark| match mark {
                    Mark::SentenceEnd => 'E',
                    Mark::OpenBracket => 'O',
                    Mark::CloseBracket => 'C',
                    Mark::Other => 'X',
                })
                .collect()
        })
    }

    #[test]
    fn the_marks_of_a_surface_are_read_one_character_at_a_time() {
        assert_eq!(read(")。").as_deref(), Some("CE"));
        assert_eq!(read("?」").as_deref(), Some("EC"));
        assert_eq!(read("(?)").as_deref(), Some("OEC"));
        assert_eq!(read("~。").as_deref(), Some("XE"));
        assert_eq!(read(",“").as_deref(), Some("XO"));
        // Each of the five ends, in both widths, and the two periods that
        // are none.
        assert_eq!(read("。!?!?").as_deref(), Some("EEEEE"));
        assert_eq!(read("..、").as_deref(), Some("XXX"));
        // The brackets of both widths.
        assert_eq!(read("((「『").as_deref(), Some("OOOO"));
        assert_eq!(read("))」』").as_deref(), Some("CCCC"));
        // One mark is read as several are.
        assert_eq!(read("。").as_deref(), Some("E"));
    }

    #[test]
    fn a_surface_with_a_letter_a_digit_or_a_space_has_no_marks() {
        for surface in [
            "",
            "本",
            "本。",
            "モーニング娘。",
            "a!",
            "1。",
            "1。",
            "ー。",
        ] {
            assert_eq!(read(surface), None, "{surface:?}");
        }
        for surface in [" 。", "。 ", "\u{3000}。", "\u{3000}"] {
            assert_eq!(read(surface), None, "{surface:?}");
        }
    }

    #[test]
    fn marks_joined_into_one_word_end_a_sentence_by_their_last_mark() {
        // An end after other marks, and after a closing bracket.
        for joined in [
            "~。",
            "%。",
            "......。",
            ")。",
            "~!",
            "~?",
            "」。",
            "(笑)。",
        ] {
            let expected = read(joined).is_some();
            assert_eq!(
                is_sentence_end(&Surface(joined), Some(&Surface("本"))),
                expected,
                "{joined}"
            );
        }
        for joined in ["~。", "%。", "......。", ")。", "~!", "~?", "」。"] {
            assert!(is_sentence_end(&Surface(joined), None), "{joined}");
            assert_eq!(
                sentence_end(&Surface(joined), Some(&Surface("本"))),
                Some(false),
                "{joined}"
            );
        }
        // A closing bracket after the end: the end is still the end, and
        // the bracket is closed after it.
        for joined in [
            "?」",
            "!”",
            "。)",
            "!?」』",
            "~。)",
            "?」。",
            "?」)。",
            "(?)",
            "「。」",
            "(?)。",
        ] {
            assert_eq!(
                sentence_end(&Surface(joined), Some(&Surface("本"))),
                Some(true),
                "{joined}"
            );
        }
        // No end, an end that is not the last mark, and a word with a
        // letter.
        for other in [",“", "~」", "%、", "。~", "?「", "()", "本。", "...", "~."] {
            assert_eq!(sentence_end(&Surface(other), None), None, "{other}");
            assert!(
                !is_sentence_end(&Surface(other), Some(&Surface("本"))),
                "{other}"
            );
        }
        // A bracket the word opens before the end changes nothing: (?) is
        // as ( / ? / ) are, and an end right after it closes nothing.
        assert_eq!(sentence_end(&Surface("(?"), None), Some(false));
        assert_eq!(sentence_end(&Surface(":(。"), None), Some(false));
        assert_eq!(sentence_end(&Surface("?)"), None), Some(true));
        // A bracket closed before another mark, or before a bracket that
        // opens, is not one closed after the end: the end is a new one.
        assert_eq!(sentence_end(&Surface("?」~。"), None), Some(false));
        assert_eq!(sentence_end(&Surface("?」()。"), None), Some(false));
    }

    #[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}"
            );
        }
        // It closes no bracket.
        assert_eq!(sentence_end(&period, None), Some(false));
    }
}