Skip to main content

lindera_dependency/
lattice.rs

1//! The lattice format of CaboCha (`cabocha -f1`): reading and writing.
2//!
3//! ```text
4//! * 0 2D 0/1 0.000000
5//! 彼\t名詞,代名詞,一般,*,*,*,彼,カレ,カレ
6//! は\t助詞,係助詞,*,*,*,*,は,ハ,ワ
7//! * 1 2D 0/1 0.000000
8//! 本\t名詞,一般,*,*,*,*,本,ホン,ホン
9//! を\t助詞,格助詞,一般,*,*,*,を,ヲ,ヲ
10//! * 2 -1D 0/1 0.000000
11//! 読ん\t動詞,自立,*,*,五段・マ行,連用タ接続,読む,ヨン,ヨン
12//! だ\t助動詞,*,*,*,特殊・タ,基本形,だ,ダ,ダ
13//! 。\t記号,句点,*,*,*,*,。,。,。
14//! EOS
15//! ```
16//!
17//! (`\t` stands for a tab.)
18//!
19//! # The lines
20//!
21//! A line is, in this order:
22//!
23//! 1. a morpheme, if it holds a tab: the surface, the feature string and,
24//!    optionally, a named entity tag, separated by tabs. The tab is what tells
25//!    a morpheme from the other lines, so a surface may be `*`, start with
26//!    `#`, or be `EOS`;
27//! 2. the end of a sentence, if it is `EOS`;
28//! 3. a bunsetsu line, if it starts with `*` and a space: the id of the
29//!    bunsetsu, counted from 0; the id of its head, `-1` for the root,
30//!    followed by the letter of the arc type (see
31//!    [`ArcType`]; `D` when there is none); then, optionally,
32//!    the positions of the head word and of the function word in the
33//!    bunsetsu, as `head/function`, and the score;
34//! 4. a comment, if it starts with `#`. Comments stand before the first line
35//!    of a sentence, and belong to it.
36//!
37//! Anything else, an empty line included, is an error, as is an input that
38//! ends inside a sentence. Lines end with a line feed.
39//!
40//! # Reading and writing back
41//!
42//! A sentence without bunsetsu lines is a sentence of morphemes only. A
43//! bunsetsu line with the head only is what CaboCha writes for its chunk
44//! layer, `* 0 2D` followed by a space, and is written back so. The writer
45//! gives back the bytes the reader read, with two exceptions: a score is
46//! written with six decimals, as CaboCha writes it, and a bunsetsu line with
47//! the head only gets the space after it.
48//!
49//! The reader checks the structure of a sentence ([`Sentence::check`]), not
50//! its tree: a sentence with two roots or with crossing arcs is read, and
51//! [`Sentence::violations`] reports it.
52
53use std::borrow::Cow;
54use std::io::{BufRead, Write};
55
56use crate::error::{Error, Result};
57use crate::morpheme::{Morpheme, split_features};
58use crate::sentence::{ArcType, Bunsetsu, Sentence};
59
60/// The line that ends a sentence.
61const END_OF_SENTENCE: &str = "EOS";
62
63/// A morpheme of the lattice format.
64///
65/// It keeps the feature string as it is in the input, next to the columns it
66/// is split into, so that writing it gives the same bytes whether a column
67/// with a comma was quoted (MeCab) or not (`lindera tokenize -o mecab`).
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct LatticeMorpheme {
70    surface: String,
71    features: String,
72    columns: Vec<String>,
73    named_entity: Option<String>,
74}
75
76impl LatticeMorpheme {
77    /// Makes a morpheme from a surface and a feature string.
78    ///
79    /// # Arguments
80    ///
81    /// * `surface` - The surface.
82    /// * `features` - The feature string: the columns of the dictionary,
83    ///   separated by commas, a column with a comma quoted as in CSV.
84    ///
85    /// # Returns
86    ///
87    /// The morpheme, without a named entity tag.
88    pub fn new(surface: impl Into<String>, features: impl Into<String>) -> Self {
89        let features = features.into();
90        let columns = split_features(&features);
91        Self {
92            surface: surface.into(),
93            features,
94            columns,
95            named_entity: None,
96        }
97    }
98
99    /// Sets the named entity tag of the morpheme.
100    ///
101    /// # Arguments
102    ///
103    /// * `named_entity` - The tag, or `None` for no tag.
104    ///
105    /// # Returns
106    ///
107    /// The morpheme with the tag.
108    pub fn with_named_entity(mut self, named_entity: Option<String>) -> Self {
109        self.named_entity = named_entity;
110        self
111    }
112}
113
114impl Morpheme for LatticeMorpheme {
115    fn surface(&self) -> &str {
116        &self.surface
117    }
118
119    fn feature(&self, index: usize) -> Option<&str> {
120        self.columns.get(index).map(String::as_str)
121    }
122
123    fn features(&self) -> Cow<'_, str> {
124        Cow::Borrowed(&self.features)
125    }
126
127    fn named_entity(&self) -> Option<&str> {
128        self.named_entity.as_deref()
129    }
130}
131
132/// Reads every sentence of a text in the lattice format.
133///
134/// # Arguments
135///
136/// * `input` - The text.
137///
138/// # Returns
139///
140/// The sentences, or the first error; see [`Reader`].
141///
142/// # Examples
143///
144/// ```
145/// use lindera_dependency::lattice;
146///
147/// let text = "* 0 1D 0/1 0.000000\n\
148///     本\t名詞,一般,*,*,*,*,本,ホン,ホン\n\
149///     を\t助詞,格助詞,一般,*,*,*,を,ヲ,ヲ\n\
150///     * 1 -1D 0/0 0.000000\n\
151///     読む\t動詞,自立,*,*,五段・マ行,基本形,読む,ヨム,ヨム\n\
152///     EOS\n";
153/// let sentences = lattice::parse(text)?;
154/// assert_eq!(sentences.len(), 1);
155/// assert_eq!(sentences[0].bunsetsu[0].head, Some(1));
156/// # Ok::<(), lindera_dependency::Error>(())
157/// ```
158pub fn parse(input: &str) -> Result<Vec<Sentence<LatticeMorpheme>>> {
159    Reader::new(input.as_bytes()).collect()
160}
161
162/// Reads the sentences of an input in the lattice format, one at a time.
163///
164/// An iterator of `Result<Sentence<LatticeMorpheme>>`. An error is
165/// [`Error::Format`] with the number of the line that is wrong, or
166/// [`Error::Io`]; after an error, the iterator ends.
167#[derive(Debug)]
168pub struct Reader<R> {
169    input: R,
170    /// The number of the last line read, from 1.
171    line: usize,
172    /// The buffer a line is read into.
173    buffer: String,
174    /// Set after an error or the end of the input.
175    done: bool,
176}
177
178impl<R: BufRead> Reader<R> {
179    /// Makes a reader of an input.
180    ///
181    /// # Arguments
182    ///
183    /// * `input` - The input, in UTF-8.
184    ///
185    /// # Returns
186    ///
187    /// The reader.
188    pub fn new(input: R) -> Self {
189        Self {
190            input,
191            line: 0,
192            buffer: String::new(),
193            done: false,
194        }
195    }
196
197    /// Reads the next line into the buffer, without its line feed.
198    ///
199    /// # Returns
200    ///
201    /// `false` at the end of the input.
202    fn read_line(&mut self) -> Result<bool> {
203        self.buffer.clear();
204        if self.input.read_line(&mut self.buffer)? == 0 {
205            return Ok(false);
206        }
207        self.line += 1;
208        if self.buffer.ends_with('\n') {
209            self.buffer.pop();
210        }
211        Ok(true)
212    }
213
214    /// Reads the next sentence.
215    ///
216    /// # Returns
217    ///
218    /// The sentence, or `None` at the end of the input.
219    fn read_sentence(&mut self) -> Result<Option<Sentence<LatticeMorpheme>>> {
220        let mut sentence = Sentence {
221            comments: Vec::new(),
222            morphemes: Vec::new(),
223            bunsetsu: Vec::new(),
224        };
225        // The line of each bunsetsu, for the errors found at the end of the
226        // sentence.
227        let mut bunsetsu_lines = Vec::new();
228        // Whether a morpheme has been read before the first bunsetsu line.
229        let mut morphemes_first = false;
230
231        loop {
232            if !self.read_line()? {
233                if sentence.comments.is_empty()
234                    && sentence.morphemes.is_empty()
235                    && sentence.bunsetsu.is_empty()
236                {
237                    return Ok(None);
238                }
239                return Err(Error::format(
240                    self.line,
241                    "the input ends inside a sentence, without `EOS`",
242                ));
243            }
244            let line = self.buffer.as_str();
245
246            if line.contains('\t') {
247                let morpheme = parse_morpheme(line).map_err(|m| Error::format(self.line, m))?;
248                match sentence.bunsetsu.last_mut() {
249                    Some(bunsetsu) => bunsetsu.morphemes.end += 1,
250                    None => morphemes_first = true,
251                }
252                sentence.morphemes.push(morpheme);
253            } else if line == END_OF_SENTENCE {
254                break;
255            } else if line.starts_with("* ") {
256                if morphemes_first {
257                    return Err(Error::format(
258                        self.line,
259                        "a bunsetsu line follows morphemes that belong to no bunsetsu",
260                    ));
261                }
262                if let Some(last) = sentence.bunsetsu.last()
263                    && last.morphemes.is_empty()
264                {
265                    return Err(Error::format(
266                        self.line,
267                        format!("bunsetsu {} has no morpheme", sentence.bunsetsu.len() - 1),
268                    ));
269                }
270                let bunsetsu =
271                    parse_bunsetsu(line, sentence.bunsetsu.len(), sentence.morphemes.len())
272                        .map_err(|m| Error::format(self.line, m))?;
273                sentence.bunsetsu.push(bunsetsu);
274                bunsetsu_lines.push(self.line);
275            } else if line.starts_with('#') {
276                if !sentence.morphemes.is_empty() || !sentence.bunsetsu.is_empty() {
277                    return Err(Error::format(self.line, "a comment inside a sentence"));
278                }
279                sentence.comments.push(line.to_string());
280            } else if line.is_empty() {
281                return Err(Error::format(self.line, "an empty line"));
282            } else {
283                return Err(Error::format(
284                    self.line,
285                    format!("not a morpheme, a bunsetsu line, a comment or `EOS`: {line:?}"),
286                ));
287            }
288        }
289
290        // What can only be told once the sentence is complete.
291        let count = sentence.bunsetsu.len();
292        for (index, bunsetsu) in sentence.bunsetsu.iter().enumerate() {
293            let line = bunsetsu_lines[index];
294            let size = bunsetsu.morphemes.len();
295            if size == 0 {
296                return Err(Error::format(
297                    line,
298                    format!("bunsetsu {index} has no morpheme"),
299                ));
300            }
301            if let Some(head) = bunsetsu.head
302                && head >= count
303            {
304                return Err(Error::format(
305                    line,
306                    format!(
307                        "the head of bunsetsu {index} is {head}, but there are {count} bunsetsu"
308                    ),
309                ));
310            }
311            if let Some((head_word, function_word)) = bunsetsu.positions
312                && (head_word >= size || function_word >= size)
313            {
314                return Err(Error::format(
315                    line,
316                    format!(
317                        "the positions {head_word}/{function_word} of bunsetsu {index} are outside its {size} morpheme(s)"
318                    ),
319                ));
320            }
321        }
322
323        Ok(Some(sentence))
324    }
325}
326
327impl<R: BufRead> Iterator for Reader<R> {
328    type Item = Result<Sentence<LatticeMorpheme>>;
329
330    fn next(&mut self) -> Option<Self::Item> {
331        if self.done {
332            return None;
333        }
334        match self.read_sentence() {
335            Ok(Some(sentence)) => Some(Ok(sentence)),
336            Ok(None) => {
337                self.done = true;
338                None
339            }
340            Err(error) => {
341                self.done = true;
342                Some(Err(error))
343            }
344        }
345    }
346}
347
348/// Reads a morpheme line.
349///
350/// # Arguments
351///
352/// * `line` - The line, which holds a tab.
353///
354/// # Returns
355///
356/// The morpheme, or what is wrong with the line.
357fn parse_morpheme(line: &str) -> std::result::Result<LatticeMorpheme, String> {
358    let mut columns = line.split('\t');
359    let surface = columns.next().unwrap_or_default();
360    let features = columns.next().unwrap_or_default();
361    let named_entity = columns.next();
362    if columns.next().is_some() {
363        return Err("a morpheme line has more than three columns".to_string());
364    }
365    if surface.is_empty() {
366        return Err("a morpheme line has no surface".to_string());
367    }
368    if features.is_empty() {
369        return Err("a morpheme line has no feature".to_string());
370    }
371    Ok(LatticeMorpheme::new(surface, features).with_named_entity(named_entity.map(str::to_string)))
372}
373
374/// Reads a bunsetsu line.
375///
376/// # Arguments
377///
378/// * `line` - The line, which starts with `*` and a space.
379/// * `index` - The index the bunsetsu has to have.
380/// * `start` - The index of its first morpheme.
381///
382/// # Returns
383///
384/// The bunsetsu, without a morpheme yet, or what is wrong with the line.
385fn parse_bunsetsu(line: &str, index: usize, start: usize) -> std::result::Result<Bunsetsu, String> {
386    let mut columns: Vec<&str> = line[2..].split(' ').collect();
387    // CaboCha ends the line of its chunk layer, `* 0 2D `, with a space.
388    if columns.len() == 3 && columns[2].is_empty() {
389        columns.pop();
390    }
391    if !(2..=4).contains(&columns.len()) || columns.iter().any(|column| column.is_empty()) {
392        return Err(format!(
393            "a bunsetsu line is `* id head`, `* id head head/function` or `* id head head/function score`: {line:?}"
394        ));
395    }
396
397    let id: usize = columns[0]
398        .parse()
399        .map_err(|_| format!("the id of a bunsetsu is not a number: {:?}", columns[0]))?;
400    if id != index {
401        return Err(format!("the id of the bunsetsu is {id}, not {index}"));
402    }
403
404    let (head, arc_type) = parse_head(columns[1])?;
405
406    let positions = match columns.get(2) {
407        Some(column) => {
408            let parsed = column
409                .split_once('/')
410                .and_then(|(head_word, function_word)| {
411                    Some((head_word.parse().ok()?, function_word.parse().ok()?))
412                });
413            Some(parsed.ok_or_else(|| {
414                format!("the positions of a bunsetsu are not `head/function`: {column:?}")
415            })?)
416        }
417        None => None,
418    };
419
420    let score = match columns.get(3) {
421        Some(column) => {
422            let score: f64 = column
423                .parse()
424                .map_err(|_| format!("the score of a bunsetsu is not a number: {column:?}"))?;
425            if !score.is_finite() {
426                return Err(format!("the score of a bunsetsu is not finite: {column:?}"));
427            }
428            Some(score)
429        }
430        None => None,
431    };
432
433    Ok(Bunsetsu {
434        morphemes: start..start,
435        head,
436        arc_type,
437        positions,
438        score,
439    })
440}
441
442/// Reads the head column of a bunsetsu line: the id of the head, `-1` for the
443/// root, and the letter of the arc type.
444///
445/// # Arguments
446///
447/// * `column` - The column, such as `2D`, `-1D` or `2`.
448///
449/// # Returns
450///
451/// The head and the arc type (`D` without a letter), or what is wrong.
452fn parse_head(column: &str) -> std::result::Result<(Option<usize>, ArcType), String> {
453    let (number, arc_type) = match column.chars().last() {
454        Some(letter) if letter.is_ascii_alphabetic() => {
455            let arc_type = ArcType::from_char(letter)
456                .ok_or_else(|| format!("unknown arc type {letter:?} in {column:?}"))?;
457            (&column[..column.len() - 1], arc_type)
458        }
459        _ => (column, ArcType::Dependency),
460    };
461    if number == "-1" {
462        return Ok((None, arc_type));
463    }
464    let head = number
465        .parse()
466        .map_err(|_| format!("the head of a bunsetsu is not `-1` or the id of one: {column:?}"))?;
467    Ok((Some(head), arc_type))
468}
469
470/// Writes a sentence in the lattice format.
471///
472/// The comments, then each bunsetsu line followed by its morphemes (the
473/// morphemes alone for a sentence without bunsetsu), then `EOS`.
474///
475/// # Arguments
476///
477/// * `writer` - Where to write.
478/// * `sentence` - The sentence.
479///
480/// # Returns
481///
482/// `Ok(())`; [`Error::Structure`], before anything is written, when
483/// [`Sentence::check`] fails or a morpheme cannot stand on a line (an empty
484/// surface or feature string, a tab or a line break in one of its strings);
485/// or [`Error::Io`].
486///
487/// # Examples
488///
489/// ```
490/// use lindera_dependency::lattice::{self, LatticeMorpheme};
491/// use lindera_dependency::{Bunsetsu, Sentence};
492///
493/// let sentence = Sentence::new(
494///     vec![
495///         LatticeMorpheme::new("本", "名詞,一般"),
496///         LatticeMorpheme::new("を", "助詞,格助詞"),
497///         LatticeMorpheme::new("読む", "動詞,自立"),
498///     ],
499///     vec![Bunsetsu::new(0..2, Some(1)), Bunsetsu::new(2..3, None)],
500/// )?;
501/// let mut output = Vec::new();
502/// lattice::write(&mut output, &sentence)?;
503/// assert_eq!(
504///     String::from_utf8(output).unwrap(),
505///     "* 0 1D \n本\t名詞,一般\nを\t助詞,格助詞\n* 1 -1D \n読む\t動詞,自立\nEOS\n"
506/// );
507/// # Ok::<(), lindera_dependency::Error>(())
508/// ```
509pub fn write<W: Write, M: Morpheme>(writer: &mut W, sentence: &Sentence<M>) -> Result<()> {
510    sentence.check()?;
511    for (index, morpheme) in sentence.morphemes.iter().enumerate() {
512        check_morpheme(index, morpheme)?;
513    }
514
515    for comment in &sentence.comments {
516        writeln!(writer, "{comment}")?;
517    }
518    if sentence.bunsetsu.is_empty() {
519        for morpheme in &sentence.morphemes {
520            write_morpheme(writer, morpheme)?;
521        }
522    }
523    for (index, bunsetsu) in sentence.bunsetsu.iter().enumerate() {
524        write!(writer, "* {index} ")?;
525        match bunsetsu.head {
526            Some(head) => write!(writer, "{head}")?,
527            None => write!(writer, "-1")?,
528        }
529        write!(writer, "{}", bunsetsu.arc_type.as_char())?;
530        match (bunsetsu.positions, bunsetsu.score) {
531            (Some((head_word, function_word)), Some(score)) => {
532                writeln!(writer, " {head_word}/{function_word} {score:.6}")?
533            }
534            (Some((head_word, function_word)), None) => {
535                writeln!(writer, " {head_word}/{function_word}")?
536            }
537            // As CaboCha writes its chunk layer.
538            (None, _) => writeln!(writer, " ")?,
539        }
540        for morpheme in &sentence.morphemes[bunsetsu.morphemes.clone()] {
541            write_morpheme(writer, morpheme)?;
542        }
543    }
544    writeln!(writer, "{END_OF_SENTENCE}")?;
545    Ok(())
546}
547
548/// Checks that a morpheme can stand on a line of the lattice format.
549///
550/// # Arguments
551///
552/// * `index` - The index of the morpheme in its sentence, for the message.
553/// * `morpheme` - The morpheme.
554///
555/// # Returns
556///
557/// `Ok(())`, or [`Error::Structure`].
558fn check_morpheme<M: Morpheme>(index: usize, morpheme: &M) -> Result<()> {
559    let features = morpheme.features();
560    if morpheme.surface().is_empty() {
561        return Err(Error::Structure(format!("morpheme {index} has no surface")));
562    }
563    if features.is_empty() {
564        return Err(Error::Structure(format!("morpheme {index} has no feature")));
565    }
566    let strings = [
567        Some(morpheme.surface()),
568        Some(features.as_ref()),
569        morpheme.named_entity(),
570    ];
571    if strings.iter().flatten().any(|s| s.contains(['\t', '\n'])) {
572        return Err(Error::Structure(format!(
573            "morpheme {index} holds a tab or a line break"
574        )));
575    }
576    Ok(())
577}
578
579/// Writes a morpheme line.
580///
581/// # Arguments
582///
583/// * `writer` - Where to write.
584/// * `morpheme` - The morpheme.
585///
586/// # Returns
587///
588/// `Ok(())`, or the error of the write.
589fn write_morpheme<W: Write, M: Morpheme>(writer: &mut W, morpheme: &M) -> Result<()> {
590    write!(writer, "{}\t{}", morpheme.surface(), morpheme.features())?;
591    if let Some(named_entity) = morpheme.named_entity() {
592        write!(writer, "\t{named_entity}")?;
593    }
594    writeln!(writer)?;
595    Ok(())
596}
597
598#[cfg(test)]
599mod tests {
600    use super::*;
601
602    const FULL: &str = "* 0 2D 0/1 0.000000\n\
603        彼\t名詞,代名詞,一般,*,*,*,彼,カレ,カレ\n\
604        は\t助詞,係助詞,*,*,*,*,は,ハ,ワ\n\
605        * 1 2D 0/1 1.234500\n\
606        本\t名詞,一般,*,*,*,*,本,ホン,ホン\n\
607        を\t助詞,格助詞,一般,*,*,*,を,ヲ,ヲ\n\
608        * 2 -1D 0/1 0.000000\n\
609        読ん\t動詞,自立,*,*,五段・マ行,連用タ接続,読む,ヨン,ヨン\n\
610        だ\t助動詞,*,*,*,特殊・タ,基本形,だ,ダ,ダ\n\
611        。\t記号,句点,*,*,*,*,。,。,。\n\
612        EOS\n";
613
614    fn write_all<M: Morpheme>(sentences: &[Sentence<M>]) -> String {
615        let mut output = Vec::new();
616        for sentence in sentences {
617            write(&mut output, sentence).unwrap();
618        }
619        String::from_utf8(output).unwrap()
620    }
621
622    fn round_trip(text: &str) {
623        let sentences = parse(text).unwrap();
624        assert_eq!(write_all(&sentences), text);
625    }
626
627    fn format_error(text: &str) -> (usize, String) {
628        match parse(text) {
629            Err(Error::Format { line, message }) => (line, message),
630            other => panic!("expected a format error, got {other:?}"),
631        }
632    }
633
634    #[test]
635    fn reads_bunsetsu_with_positions_and_scores() {
636        let sentences = parse(FULL).unwrap();
637        assert_eq!(sentences.len(), 1);
638        let sentence = &sentences[0];
639        assert_eq!(sentence.morphemes.len(), 7);
640        assert_eq!(sentence.bunsetsu.len(), 3);
641        assert_eq!(sentence.bunsetsu[0].morphemes, 0..2);
642        assert_eq!(sentence.bunsetsu[1].morphemes, 2..4);
643        assert_eq!(sentence.bunsetsu[2].morphemes, 4..7);
644        assert_eq!(sentence.bunsetsu[0].head, Some(2));
645        assert_eq!(sentence.bunsetsu[2].head, None);
646        assert_eq!(sentence.bunsetsu[1].positions, Some((0, 1)));
647        assert_eq!(sentence.bunsetsu[1].score, Some(1.2345));
648        assert_eq!(sentence.morphemes[4].surface(), "読ん");
649        assert_eq!(sentence.morphemes[4].feature(6), Some("読む"));
650        assert_eq!(sentence.morphemes[4].feature(9), None);
651        assert!(sentence.violations().is_empty());
652        round_trip(FULL);
653    }
654
655    #[test]
656    fn keeps_the_head_only_form_of_the_chunk_layer() {
657        let text = "* 0 1D \n本\t名詞\nを\t助詞\n* 1 -1D \n読む\t動詞\nEOS\n";
658        let sentences = parse(text).unwrap();
659        assert_eq!(sentences[0].bunsetsu[0].positions, None);
660        assert_eq!(sentences[0].bunsetsu[0].score, None);
661        round_trip(text);
662    }
663
664    #[test]
665    fn reads_a_head_only_line_without_the_trailing_space() {
666        let sentences = parse("* 0 -1D\n本\t名詞\nEOS\n").unwrap();
667        assert_eq!(write_all(&sentences), "* 0 -1D \n本\t名詞\nEOS\n");
668    }
669
670    #[test]
671    fn keeps_positions_without_a_score() {
672        round_trip("* 0 -1D 0/1\n本\t名詞\nを\t助詞\nEOS\n");
673    }
674
675    #[test]
676    fn keeps_morphemes_without_bunsetsu() {
677        let text = "本\t名詞,一般\nを\t助詞,格助詞\nEOS\n";
678        let sentences = parse(text).unwrap();
679        assert!(sentences[0].bunsetsu.is_empty());
680        assert_eq!(sentences[0].morphemes.len(), 2);
681        round_trip(text);
682    }
683
684    #[test]
685    fn keeps_several_sentences_and_empty_ones() {
686        let text = "本\t名詞\nEOS\nEOS\n* 0 -1D 0/0 0.000000\n山\t名詞\nEOS\n";
687        let sentences = parse(text).unwrap();
688        assert_eq!(sentences.len(), 3);
689        assert!(sentences[1].morphemes.is_empty());
690        round_trip(text);
691        assert!(parse("").unwrap().is_empty());
692    }
693
694    #[test]
695    fn keeps_comments_before_a_sentence() {
696        let text =
697            "# S-ID: 1\n#second\n* 0 -1D 0/0 0.000000\n山\t名詞\nEOS\n# S-ID: 2\n川\t名詞\nEOS\n";
698        let sentences = parse(text).unwrap();
699        assert_eq!(sentences[0].comments, ["# S-ID: 1", "#second"]);
700        assert_eq!(sentences[1].comments, ["# S-ID: 2"]);
701        round_trip(text);
702    }
703
704    #[test]
705    fn a_line_with_a_tab_is_a_morpheme_whatever_its_surface() {
706        let text = "* 0 1D 0/0 0.000000\n\
707            *\t記号,一般,*,*,*,*,*,*,*\n\
708            * 1 2D 0/0 0.000000\n\
709            #タグ\t名詞,一般,*,*,*,*,*\n\
710            * 2 -1D 1/1 0.000000\n\
711            * 3\t名詞,一般,*,*,*,*,*\n\
712            EOS\t名詞,一般,*,*,*,*,*\n\
713            EOS\n";
714        let sentences = parse(text).unwrap();
715        let sentence = &sentences[0];
716        assert_eq!(sentence.bunsetsu.len(), 3);
717        let surfaces: Vec<&str> = sentence.morphemes.iter().map(|m| m.surface()).collect();
718        assert_eq!(surfaces, ["*", "#タグ", "* 3", "EOS"]);
719        assert!(sentence.comments.is_empty());
720        round_trip(text);
721    }
722
723    #[test]
724    fn keeps_the_feature_string_quoted_or_not() {
725        let text = ",\t記号,読点,*,*,*,*,\",\",\",\",\",\"\n,\t記号,読点,*,*,*,*,,,,,,\nEOS\n";
726        let sentences = parse(text).unwrap();
727        let quoted = &sentences[0].morphemes[0];
728        assert_eq!(quoted.feature(6), Some(","));
729        assert_eq!(quoted.feature(8), Some(","));
730        assert_eq!(quoted.feature(9), None);
731        let unquoted = &sentences[0].morphemes[1];
732        assert_eq!(unquoted.feature(1), Some("読点"));
733        assert_eq!(unquoted.feature(6), Some(""));
734        assert_eq!(unquoted.feature(11), Some(""));
735        round_trip(text);
736    }
737
738    #[test]
739    fn keeps_the_arc_type() {
740        let text = "* 0 1P 0/0 0.000000\n山\t名詞\n* 1 2A 0/0 0.000000\n川\t名詞\n* 2 3I 0/0 0.000000\n海\t名詞\n* 3 -1D 0/0 0.000000\n空\t名詞\nEOS\n";
741        let sentences = parse(text).unwrap();
742        let arc_types: Vec<ArcType> = sentences[0].bunsetsu.iter().map(|b| b.arc_type).collect();
743        assert_eq!(
744            arc_types,
745            [
746                ArcType::Parallel,
747                ArcType::Apposition,
748                ArcType::Incomplete,
749                ArcType::Dependency,
750            ]
751        );
752        round_trip(text);
753    }
754
755    #[test]
756    fn a_head_without_a_letter_is_a_dependency() {
757        let sentences =
758            parse("* 0 1 0/0 0.000000\n山\t名詞\n* 1 -1 0/0 0.000000\n川\t名詞\nEOS\n").unwrap();
759        assert_eq!(sentences[0].bunsetsu[0].head, Some(1));
760        assert_eq!(sentences[0].bunsetsu[0].arc_type, ArcType::Dependency);
761        assert_eq!(sentences[0].bunsetsu[1].head, None);
762    }
763
764    #[test]
765    fn keeps_the_named_entity_tag() {
766        let text = "東京\t名詞,固有名詞\tB-LOCATION\nへ\t助詞,格助詞\tO\nEOS\n";
767        let sentences = parse(text).unwrap();
768        assert_eq!(sentences[0].morphemes[0].named_entity(), Some("B-LOCATION"));
769        round_trip(text);
770    }
771
772    #[test]
773    fn writes_a_score_with_six_decimals() {
774        let sentences = parse("* 0 -1D 0/0 1.5\n山\t名詞\nEOS\n").unwrap();
775        assert_eq!(
776            write_all(&sentences),
777            "* 0 -1D 0/0 1.500000\n山\t名詞\nEOS\n"
778        );
779        round_trip("* 0 -1D 0/0 -12.345678\n山\t名詞\nEOS\n");
780    }
781
782    #[test]
783    fn reads_a_tree_that_breaks_the_assumptions() {
784        let sentences = parse("* 0 -1D \n山\t名詞\n* 1 0D \n川\t名詞\nEOS\n").unwrap();
785        assert_eq!(sentences[0].violations().len(), 2);
786    }
787
788    #[test]
789    fn reads_the_last_line_without_a_line_feed() {
790        let sentences = parse("山\t名詞\nEOS").unwrap();
791        assert_eq!(sentences.len(), 1);
792    }
793
794    #[test]
795    fn refuses_ids_out_of_sequence() {
796        let (line, message) = format_error("* 0 1D \n山\t名詞\n* 2 -1D \n川\t名詞\nEOS\n");
797        assert_eq!(
798            (line, message.as_str()),
799            (3, "the id of the bunsetsu is 2, not 1")
800        );
801        let (line, _) = format_error("* 1 -1D \n山\t名詞\nEOS\n");
802        assert_eq!(line, 1);
803    }
804
805    #[test]
806    fn refuses_a_bunsetsu_without_a_morpheme() {
807        let (line, message) = format_error("* 0 1D \n* 1 -1D \n川\t名詞\nEOS\n");
808        assert_eq!((line, message.as_str()), (2, "bunsetsu 0 has no morpheme"));
809        let (line, message) = format_error("* 0 1D \n山\t名詞\n* 1 -1D \nEOS\n");
810        assert_eq!((line, message.as_str()), (3, "bunsetsu 1 has no morpheme"));
811    }
812
813    #[test]
814    fn refuses_a_head_out_of_range() {
815        let (line, message) = format_error("* 0 2D \n山\t名詞\n* 1 -1D \n川\t名詞\nEOS\n");
816        assert_eq!(
817            (line, message.as_str()),
818            (1, "the head of bunsetsu 0 is 2, but there are 2 bunsetsu")
819        );
820        let (line, _) = format_error("* 0 -2D \n山\t名詞\nEOS\n");
821        assert_eq!(line, 1);
822    }
823
824    #[test]
825    fn refuses_positions_out_of_range() {
826        let (line, message) = format_error("* 0 -1D 0/1 0.000000\n山\t名詞\nEOS\n");
827        assert_eq!(line, 1);
828        assert!(message.contains("positions 0/1 of bunsetsu 0"), "{message}");
829        let (line, _) = format_error("* 0 -1D 0-1 0.000000\n山\t名詞\nEOS\n");
830        assert_eq!(line, 1);
831    }
832
833    #[test]
834    fn refuses_an_input_that_ends_inside_a_sentence() {
835        let (line, message) = format_error("* 0 -1D \n山\t名詞\n");
836        assert_eq!(line, 2);
837        assert!(message.contains("without `EOS`"), "{message}");
838        let (line, _) = format_error("山\t名詞\nEOS\n# comment\n");
839        assert_eq!(line, 3);
840    }
841
842    #[test]
843    fn refuses_an_empty_line() {
844        let (line, message) = format_error("山\t名詞\nEOS\n\n川\t名詞\nEOS\n");
845        assert_eq!((line, message.as_str()), (3, "an empty line"));
846    }
847
848    #[test]
849    fn refuses_a_comment_inside_a_sentence() {
850        let (line, message) = format_error("山\t名詞\n# comment\nEOS\n");
851        assert_eq!((line, message.as_str()), (2, "a comment inside a sentence"));
852        let (line, _) = format_error("* 0 -1D \n# comment\n山\t名詞\nEOS\n");
853        assert_eq!(line, 2);
854    }
855
856    #[test]
857    fn refuses_an_unknown_arc_type() {
858        let (line, message) = format_error("* 0 -1X \n山\t名詞\nEOS\n");
859        assert_eq!(line, 1);
860        assert!(message.contains("unknown arc type 'X'"), "{message}");
861    }
862
863    #[test]
864    fn refuses_a_malformed_bunsetsu_line() {
865        for text in [
866            "* 0\n山\t名詞\nEOS\n",
867            "* 0 -1D 0/0 0.000000 extra\n山\t名詞\nEOS\n",
868            "* 0  -1D\n山\t名詞\nEOS\n",
869            "* x -1D \n山\t名詞\nEOS\n",
870            "* 0 xD \n山\t名詞\nEOS\n",
871            "* 0 -1D 0/0 abc\n山\t名詞\nEOS\n",
872            "* 0 -1D 0/0 inf\n山\t名詞\nEOS\n",
873        ] {
874            let (line, _) = format_error(text);
875            assert_eq!(line, 1, "{text:?}");
876        }
877    }
878
879    #[test]
880    fn refuses_a_bunsetsu_line_after_loose_morphemes() {
881        let (line, _) = format_error("山\t名詞\n* 0 -1D \n川\t名詞\nEOS\n");
882        assert_eq!(line, 2);
883    }
884
885    #[test]
886    fn refuses_a_malformed_morpheme_line() {
887        for text in ["\t名詞\nEOS\n", "山\t\nEOS\n", "山\t名詞\tO\textra\nEOS\n"] {
888            let (line, _) = format_error(text);
889            assert_eq!(line, 1, "{text:?}");
890        }
891    }
892
893    #[test]
894    fn refuses_a_line_that_is_nothing() {
895        let (line, _) = format_error("山 名詞\nEOS\n");
896        assert_eq!(line, 1);
897        let (line, _) = format_error("*0 -1D\n山\t名詞\nEOS\n");
898        assert_eq!(line, 1);
899    }
900
901    #[test]
902    fn the_reader_ends_after_an_error() {
903        let mut reader = Reader::new("山\t名詞\nEOS\n\n川\t名詞\nEOS\n".as_bytes());
904        assert!(matches!(reader.next(), Some(Ok(_))));
905        assert!(matches!(
906            reader.next(),
907            Some(Err(Error::Format { line: 3, .. }))
908        ));
909        assert!(reader.next().is_none());
910    }
911
912    #[test]
913    fn write_refuses_a_sentence_that_does_not_fit() {
914        let mut sentence = parse("* 0 -1D \n山\t名詞\nEOS\n").unwrap().remove(0);
915        sentence.bunsetsu[0].head = Some(3);
916        let mut output = Vec::new();
917        assert!(matches!(
918            write(&mut output, &sentence),
919            Err(Error::Structure(_))
920        ));
921        assert!(output.is_empty());
922    }
923
924    #[test]
925    fn write_refuses_a_morpheme_that_cannot_stand_on_a_line() {
926        for morpheme in [
927            LatticeMorpheme::new("", "名詞"),
928            LatticeMorpheme::new("山", ""),
929            LatticeMorpheme::new("山\t川", "名詞"),
930            LatticeMorpheme::new("山", "名詞\n一般"),
931            LatticeMorpheme::new("山", "名詞").with_named_entity(Some("B\tI".to_string())),
932        ] {
933            let sentence = Sentence::new(vec![morpheme], Vec::new()).unwrap();
934            let mut output = Vec::new();
935            assert!(matches!(
936                write(&mut output, &sentence),
937                Err(Error::Structure(_))
938            ));
939            assert!(output.is_empty());
940        }
941    }
942}