Skip to main content

lindera_dependency/parser/
features.rs

1//! The features of a decision of the parser.
2//!
3//! A decision is about two bunsetsu, the source and the target: does the
4//! source depend on the target? Its features are strings, with the names
5//! CaboCha gives them. Most are made once for each bunsetsu of a sentence,
6//! and a decision puts together those of the bunsetsu it looks at.
7//!
8//! What the strings are made from is in the [`Schema`]: the head and the
9//! function word, the levels of the part of speech, the conjugation form,
10//! the particles, the symbols. Nothing here names a part of speech or a
11//! column.
12
13use std::borrow::Cow;
14use std::fmt;
15use std::ops::Range;
16
17use crate::error::{Error, Result};
18use crate::morpheme::{Morpheme, is_space};
19use crate::schema::Schema;
20
21/// The value of a feature column that holds nothing.
22const EMPTY: &str = "*";
23
24/// A group of features of a decision.
25///
26/// The name of a feature starts as CaboCha writes it; the examples are for
27/// 彼 / は as the source.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
29#[non_exhaustive]
30pub enum Group {
31    /// The number of bunsetsu from the source to the target, in three
32    /// classes: `DIST:1`, `DIST:2-5`, `DIST:6-`.
33    Distance,
34    /// The source: the surface, the levels of the part of speech and the
35    /// conjugation form of its head (`SHS:彼`, `SHP0:名詞`), its function
36    /// word (`SFS:は`), its first and its last morpheme (`SLS:`, `SRS:`);
37    /// its punctuation (`SPUNC:、`), its brackets (`SOB:「`, `SOB:1`,
38    /// `SCB:」`, `SCB:1`), each of its particles (`SCASE:は`), and whether
39    /// it is the first or the last bunsetsu of the sentence (`SBOS:1`,
40    /// `SEOS:1`).
41    Source,
42    /// The target: what [`Group::Source`] has, with `D` in front
43    /// (`DHS:読ん`).
44    Target,
45    /// The bunsetsu before the source: the surface of its function word
46    /// (`LF:`).
47    Left,
48    /// The bunsetsu after the target: the surfaces of its first morpheme,
49    /// its head and its function word (`RL:`, `RH:`, `RF:`).
50    Right,
51    /// The bunsetsu already attached to the source (`a:`) and to the target
52    /// (`A:`), each by its function word: the surface of a word of
53    /// [`Schema::lexicalized`], or else the conjugation form, or else the
54    /// part of speech. These are the only features that depend on the
55    /// decisions made before.
56    Children,
57    /// The bunsetsu between the source and the target: their punctuation
58    /// (`GPUNC:、`), their brackets (`GOB:「`, `GCB:」`), the function word
59    /// of each when it is a particle (`GCASE:を`), and whether brackets
60    /// open or close in between: `GNB:1` for neither, `GOB:1`, `GCB:1`,
61    /// `GBB:1` for both.
62    Gap,
63    /// The morpheme after the head of the source (`SNS:`, `SNP0:`, `SNF:`)
64    /// and of the target (`DNS:`): its surface, the levels of its part of
65    /// speech and its conjugation form. CaboCha has no such feature. Its
66    /// head is the last word of a bunsetsu that is not a function word;
67    /// the head of a [`Schema`] can be the content word before it (利用 in
68    /// 利用 / し / た, 読む in 読む / こと / を), and the word that follows
69    /// says what the bunsetsu is as a whole.
70    AfterHead,
71}
72
73impl Group {
74    /// Every group, with its name, in the order of the list of a
75    /// [`FeatureSet`].
76    const ALL: [(Group, &'static str); 8] = [
77        (Group::Distance, "distance"),
78        (Group::Source, "source"),
79        (Group::Target, "target"),
80        (Group::Left, "left"),
81        (Group::Right, "right"),
82        (Group::Children, "children"),
83        (Group::Gap, "gap"),
84        (Group::AfterHead, "after"),
85    ];
86
87    /// The name of the group: `distance`, `source`, `target`, `left`,
88    /// `right`, `children`, `gap` or `after`.
89    ///
90    /// # Returns
91    ///
92    /// The name.
93    pub fn name(self) -> &'static str {
94        Self::ALL
95            .iter()
96            .find(|(group, _)| *group == self)
97            .map_or("", |(_, name)| name)
98    }
99
100    /// The group with a name.
101    ///
102    /// # Arguments
103    ///
104    /// * `name` - A name that [`Group::name`] gives.
105    ///
106    /// # Returns
107    ///
108    /// The group, or `None` for another name.
109    pub fn from_name(name: &str) -> Option<Self> {
110        Self::ALL
111            .iter()
112            .find(|(_, other)| *other == name)
113            .map(|(group, _)| *group)
114    }
115}
116
117/// The groups of features a model uses.
118///
119/// A feature set is data of a model, as the template of the chunker is: the
120/// features of training and of parsing are made from the same value, and
121/// two sets are compared without a change of code. It is written as the
122/// names of its groups with commas, as in `distance,source,target,gap`.
123///
124/// A set can also limit the levels of the part of speech its features
125/// take ([`FeatureSet::with_part_of_speech_levels`]), written after the
126/// groups as in `distance,source,pos-levels=2`. Without a limit the
127/// features take every level of the schema.
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub struct FeatureSet {
130    /// The groups, in the order of [`Group::ALL`], each at most once.
131    groups: Vec<Group>,
132    /// The number of levels of the part of speech the features take, when
133    /// it is not all of the schema.
134    part_of_speech_levels: Option<usize>,
135}
136
137/// What a limit of the levels of the part of speech is written with in the
138/// text of a feature set.
139const LEVELS_KEY: &str = "pos-levels=";
140
141impl FeatureSet {
142    /// Makes a feature set of groups.
143    ///
144    /// # Arguments
145    ///
146    /// * `groups` - The groups, in any order.
147    ///
148    /// # Returns
149    ///
150    /// The set, or [`Error::Parser`] for no group or a group given twice.
151    pub fn new(groups: &[Group]) -> Result<Self> {
152        if groups.is_empty() {
153            return Err(Error::Parser("a feature set needs a group".to_string()));
154        }
155        for (index, group) in groups.iter().enumerate() {
156            if groups[..index].contains(group) {
157                return Err(Error::Parser(format!(
158                    "the group {} is given twice",
159                    group.name()
160                )));
161            }
162        }
163        Ok(Self {
164            groups: Group::ALL
165                .iter()
166                .map(|(group, _)| *group)
167                .filter(|group| groups.contains(group))
168                .collect(),
169            part_of_speech_levels: None,
170        })
171    }
172
173    /// Limits the levels of the part of speech the features take.
174    ///
175    /// The features of a morpheme name the levels of its part of speech
176    /// (`HP0:名詞`, `HP1:普通名詞`), and the feature of a bunsetsu that
177    /// ends in a word without a conjugation form is its part of speech,
178    /// the levels joined (`A:名詞-普通名詞`). With a limit, both stop at
179    /// that many levels, though the schema has more: the chunker and the
180    /// patterns of the schema still read all of them. CaboCha reads two
181    /// levels of UniDic in its parser and four in its chunker.
182    ///
183    /// # Arguments
184    ///
185    /// * `levels` - The number of levels, 1 or more.
186    ///
187    /// # Returns
188    ///
189    /// The set with the limit, or [`Error::Parser`] for 0.
190    ///
191    /// # Examples
192    ///
193    /// ```
194    /// use lindera_dependency::parser::FeatureSet;
195    ///
196    /// let set = FeatureSet::cabocha().with_part_of_speech_levels(2)?;
197    /// assert_eq!(set.part_of_speech_levels(), Some(2));
198    /// assert_eq!(
199    ///     set.to_string(),
200    ///     "distance,source,target,left,right,children,gap,pos-levels=2"
201    /// );
202    /// assert_eq!(FeatureSet::parse(&set.to_string())?, set);
203    /// # Ok::<(), lindera_dependency::Error>(())
204    /// ```
205    pub fn with_part_of_speech_levels(mut self, levels: usize) -> Result<Self> {
206        if levels == 0 {
207            return Err(Error::Parser(
208                "the features need a level of the part of speech: pos-levels is 1 or more"
209                    .to_string(),
210            ));
211        }
212        self.part_of_speech_levels = Some(levels);
213        Ok(self)
214    }
215
216    /// The limit of the levels of the part of speech.
217    ///
218    /// # Returns
219    ///
220    /// The number of levels the features take, or `None` for every level
221    /// of the schema.
222    pub fn part_of_speech_levels(&self) -> Option<usize> {
223        self.part_of_speech_levels
224    }
225
226    /// The columns of the part of speech the features read, of a schema.
227    ///
228    /// # Arguments
229    ///
230    /// * `schema` - The schema.
231    ///
232    /// # Returns
233    ///
234    /// The columns of the schema, cut at the limit of the set.
235    fn levels(&self, schema: &Schema) -> Range<usize> {
236        let all = schema.part_of_speech.clone();
237        match self.part_of_speech_levels {
238            Some(levels) => all.start..all.end.min(all.start.saturating_add(levels)),
239            None => all,
240        }
241    }
242
243    /// The feature set of CaboCha: every group but [`Group::AfterHead`].
244    ///
245    /// # Returns
246    ///
247    /// The set.
248    pub fn cabocha() -> Self {
249        Self {
250            groups: Group::ALL
251                .iter()
252                .map(|(group, _)| *group)
253                .filter(|group| *group != Group::AfterHead)
254                .collect(),
255            part_of_speech_levels: None,
256        }
257    }
258
259    /// Reads a feature set from its text.
260    ///
261    /// # Arguments
262    ///
263    /// * `text` - The names of the groups, separated by commas; spaces
264    ///   around a name are ignored. `pos-levels=<number>` among them is
265    ///   the limit of [`FeatureSet::with_part_of_speech_levels`].
266    ///
267    /// # Returns
268    ///
269    /// The set, or [`Error::Parser`] for a name that is not a group, no
270    /// group, a group given twice, or a limit that is not a number of 1 or
271    /// more, or is given twice.
272    pub fn parse(text: &str) -> Result<Self> {
273        let mut groups = Vec::new();
274        let mut levels = None;
275        for name in text.split(',') {
276            let name = name.trim();
277            if let Some(value) = name.strip_prefix(LEVELS_KEY) {
278                if levels.is_some() {
279                    return Err(Error::Parser(format!("{LEVELS_KEY} is given twice")));
280                }
281                levels = Some(value.parse::<usize>().map_err(|_| {
282                    Error::Parser(format!(
283                        "{name:?} is not a number of levels of the part of speech"
284                    ))
285                })?);
286                continue;
287            }
288            groups
289                .push(Group::from_name(name).ok_or_else(|| {
290                    Error::Parser(format!("{name:?} is not a group of features"))
291                })?);
292        }
293        let set = Self::new(&groups)?;
294        match levels {
295            Some(levels) => set.with_part_of_speech_levels(levels),
296            None => Ok(set),
297        }
298    }
299
300    /// The groups of the set.
301    ///
302    /// # Returns
303    ///
304    /// The groups, in the order `distance`, `source`, `target`, `left`,
305    /// `right`, `children`, `gap`, `after`.
306    pub fn groups(&self) -> &[Group] {
307        &self.groups
308    }
309
310    /// Whether the set has a group.
311    ///
312    /// # Arguments
313    ///
314    /// * `group` - The group.
315    ///
316    /// # Returns
317    ///
318    /// Whether the features of the group are made.
319    pub fn has(&self, group: Group) -> bool {
320        self.groups.contains(&group)
321    }
322}
323
324impl Default for FeatureSet {
325    /// Every group: the feature set of CaboCha and [`Group::AfterHead`],
326    /// which is what a model is trained with unless another set is given.
327    fn default() -> Self {
328        Self {
329            groups: Group::ALL.iter().map(|(group, _)| *group).collect(),
330            part_of_speech_levels: None,
331        }
332    }
333}
334
335impl fmt::Display for FeatureSet {
336    /// Writes the names of the groups with commas, and the limit of the
337    /// levels of the part of speech after them when the set has one: the
338    /// text [`FeatureSet::parse`] reads.
339    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
340        for (index, group) in self.groups.iter().enumerate() {
341            if index > 0 {
342                write!(f, ",")?;
343            }
344            write!(f, "{}", group.name())?;
345        }
346        if let Some(levels) = self.part_of_speech_levels {
347            write!(f, ",{LEVELS_KEY}{levels}")?;
348        }
349        Ok(())
350    }
351}
352
353/// The features of one bunsetsu, in each of the roles it can have in a
354/// decision.
355///
356/// `T` is what a feature string was turned into: an id of the classifier
357/// when parsing, the string itself for training instances.
358#[derive(Debug, Clone, PartialEq)]
359struct Roles<T> {
360    /// As the source of a decision.
361    source: Vec<T>,
362    /// As the target of a decision.
363    target: Vec<T>,
364    /// As the bunsetsu before the source.
365    left: Vec<T>,
366    /// As the bunsetsu after the target.
367    right: Vec<T>,
368    /// As a bunsetsu between the source and the target, without the state
369    /// of the brackets.
370    gap: Vec<T>,
371    /// The morpheme after its head, as the source of a decision.
372    after_source: Vec<T>,
373    /// The morpheme after its head, as the target of a decision.
374    after_target: Vec<T>,
375    /// As a bunsetsu attached to the source.
376    child_of_source: Option<T>,
377    /// As a bunsetsu attached to the target.
378    child_of_target: Option<T>,
379    /// Whether the bunsetsu has an opening bracket.
380    opens: bool,
381    /// Whether the bunsetsu has a closing bracket.
382    closes: bool,
383}
384
385/// The features of the bunsetsu of a sentence, from which the features of
386/// each decision are put together.
387#[derive(Debug, Clone, PartialEq)]
388pub(crate) struct Prepared<T> {
389    /// The features of each bunsetsu.
390    bunsetsu: Vec<Roles<T>>,
391    /// The three classes of the distance: 1, 2 to 5, 6 or more.
392    distance: [Option<T>; 3],
393    /// The four states of the brackets in the gap: none, opening only,
394    /// closing only, both.
395    brackets: [Option<T>; 4],
396}
397
398impl<T: Clone + Ord> Prepared<T> {
399    /// Makes the features of the bunsetsu of a sentence.
400    ///
401    /// # Arguments
402    ///
403    /// * `schema` - The schema of the dictionary of the morphemes.
404    /// * `set` - The groups to make.
405    /// * `morphemes` - The morphemes of the sentence.
406    /// * `bunsetsu` - The bunsetsu, as ranges of indices into `morphemes`;
407    ///   none is empty or past the morphemes.
408    /// * `intern` - Turns a feature string into a `T`, or into `None` for a
409    ///   feature to leave out.
410    ///
411    /// # Returns
412    ///
413    /// The features.
414    pub(crate) fn new<M: Morpheme>(
415        schema: &Schema,
416        set: &FeatureSet,
417        morphemes: &[M],
418        bunsetsu: &[Range<usize>],
419        mut intern: impl FnMut(&str) -> Option<T>,
420    ) -> Self {
421        let last = bunsetsu.len().saturating_sub(1);
422        let roles = bunsetsu
423            .iter()
424            .enumerate()
425            .map(|(index, range)| {
426                let strings = Strings::new(
427                    schema,
428                    set.levels(schema),
429                    &morphemes[range.clone()],
430                    index == 0,
431                    index == last,
432                );
433                let mut role = |group: Group, prefix: &str, names: &[String]| -> Vec<T> {
434                    if !set.has(group) {
435                        return Vec::new();
436                    }
437                    names
438                        .iter()
439                        .filter_map(|name| intern(&format!("{prefix}{name}")))
440                        .collect()
441                };
442                let source = role(Group::Source, "S", &strings.statics);
443                let target = role(Group::Target, "D", &strings.statics);
444                let left = role(Group::Left, "", &strings.left);
445                let right = role(Group::Right, "", &strings.right);
446                let gap = role(Group::Gap, "", &strings.gap);
447                let after_source = role(Group::AfterHead, "S", &strings.after);
448                let after_target = role(Group::AfterHead, "D", &strings.after);
449                let child = std::slice::from_ref(&strings.child);
450                let child_of_source = role(Group::Children, "a:", child).pop();
451                let child_of_target = role(Group::Children, "A:", child).pop();
452                Roles {
453                    source,
454                    target,
455                    left,
456                    right,
457                    gap,
458                    after_source,
459                    after_target,
460                    child_of_source,
461                    child_of_target,
462                    opens: strings.opens,
463                    closes: strings.closes,
464                }
465            })
466            .collect();
467        let mut named = |group: Group, name: &str| {
468            if set.has(group) { intern(name) } else { None }
469        };
470        Self {
471            bunsetsu: roles,
472            distance: [
473                named(Group::Distance, "DIST:1"),
474                named(Group::Distance, "DIST:2-5"),
475                named(Group::Distance, "DIST:6-"),
476            ],
477            brackets: [
478                named(Group::Gap, "GNB:1"),
479                named(Group::Gap, "GOB:1"),
480                named(Group::Gap, "GCB:1"),
481                named(Group::Gap, "GBB:1"),
482            ],
483        }
484    }
485
486    /// Puts together the features of a decision.
487    ///
488    /// # Arguments
489    ///
490    /// * `source` - The index of the source bunsetsu.
491    /// * `target` - The index of the target bunsetsu, after the source.
492    /// * `children` - For each bunsetsu, the bunsetsu attached to it so
493    ///   far.
494    /// * `features` - Where the features are written: sorted, each once.
495    pub(crate) fn decision(
496        &self,
497        source: usize,
498        target: usize,
499        children: &[Vec<usize>],
500        features: &mut Vec<T>,
501    ) {
502        features.clear();
503        let class = match target - source {
504            1 => 0,
505            2..=5 => 1,
506            _ => 2,
507        };
508        features.extend(self.distance[class].clone());
509        features.extend_from_slice(&self.bunsetsu[source].source);
510        features.extend_from_slice(&self.bunsetsu[target].target);
511        features.extend_from_slice(&self.bunsetsu[source].after_source);
512        features.extend_from_slice(&self.bunsetsu[target].after_target);
513        if source > 0 {
514            features.extend_from_slice(&self.bunsetsu[source - 1].left);
515        }
516        if let Some(after) = self.bunsetsu.get(target + 1) {
517            features.extend_from_slice(&after.right);
518        }
519        // A group that is not in the feature set gives nothing below: the
520        // features of its bunsetsu are empty, and its named ones are `None`.
521        for &child in &children[source] {
522            features.extend(self.bunsetsu[child].child_of_source.clone());
523        }
524        for &child in &children[target] {
525            features.extend(self.bunsetsu[child].child_of_target.clone());
526        }
527        let mut opens = false;
528        let mut closes = false;
529        for between in &self.bunsetsu[source + 1..target] {
530            features.extend_from_slice(&between.gap);
531            opens |= between.opens;
532            closes |= between.closes;
533        }
534        let state = usize::from(opens) + 2 * usize::from(closes);
535        features.extend(self.brackets[state].clone());
536        features.sort_unstable();
537        features.dedup();
538    }
539}
540
541/// The feature strings of one bunsetsu, before the role is put in front.
542#[derive(Debug, Clone, PartialEq, Eq)]
543struct Strings {
544    /// The features of the bunsetsu as a source or a target, without the
545    /// `S` or `D` in front.
546    statics: Vec<String>,
547    /// The features as the bunsetsu before the source.
548    left: Vec<String>,
549    /// The features as the bunsetsu after the target.
550    right: Vec<String>,
551    /// The features as a bunsetsu in the gap.
552    gap: Vec<String>,
553    /// The features of the morpheme after the head, without the `S` or `D`
554    /// in front; none when the head is the last morpheme.
555    after: Vec<String>,
556    /// The feature as a child, without the `a:` or `A:` in front.
557    child: String,
558    /// Whether the bunsetsu has an opening bracket.
559    opens: bool,
560    /// Whether the bunsetsu has a closing bracket.
561    closes: bool,
562}
563
564impl Strings {
565    /// Makes the feature strings of a bunsetsu.
566    ///
567    /// # Arguments
568    ///
569    /// * `schema` - The schema of the dictionary of the morphemes.
570    /// * `morphemes` - The morphemes of the bunsetsu, at least one.
571    /// * `first` - Whether it is the first bunsetsu of the sentence.
572    /// * `last` - Whether it is the last bunsetsu of the sentence.
573    ///
574    /// # Returns
575    ///
576    /// The strings.
577    fn new<M: Morpheme>(
578        schema: &Schema,
579        levels: Range<usize>,
580        morphemes: &[M],
581        first: bool,
582        last: bool,
583    ) -> Self {
584        // A space is no word: the features are those of the bunsetsu
585        // without its spaces, so that the first morpheme, the last one and
586        // the one after the head are words. A bunsetsu of spaces alone is
587        // read as it is.
588        let words: Vec<&M> = morphemes
589            .iter()
590            .filter(|morpheme| !is_space(*morpheme))
591            .collect();
592        if words.is_empty() || words.len() == morphemes.len() {
593            Self::of_words(schema, levels, morphemes, first, last)
594        } else {
595            Self::of_words(schema, levels, &words, first, last)
596        }
597    }
598
599    /// Makes the feature strings of a bunsetsu from its words.
600    ///
601    /// # Arguments
602    ///
603    /// * `schema` - The schema of the dictionary of the morphemes.
604    /// * `levels` - The columns of the part of speech the features read.
605    /// * `morphemes` - The morphemes of the bunsetsu that are not spaces, at
606    ///   least one, or its spaces when it has nothing else.
607    /// * `first` - Whether it is the first bunsetsu of the sentence.
608    /// * `last` - Whether it is the last bunsetsu of the sentence.
609    ///
610    /// # Returns
611    ///
612    /// The strings.
613    fn of_words<M: Morpheme>(
614        schema: &Schema,
615        levels: Range<usize>,
616        morphemes: &[M],
617        first: bool,
618        last: bool,
619    ) -> Self {
620        let mut statics = Vec::new();
621        let mut gap = Vec::new();
622        let mut opens = false;
623        let mut closes = false;
624        for (index, morpheme) in morphemes.iter().enumerate() {
625            let surface = schema.surface_of(morpheme);
626            if schema.is_comma(morpheme) || schema.is_period(morpheme) {
627                gap.push(format!("GPUNC:{surface}"));
628                statics.push(format!("PUNC:{surface}"));
629            }
630            if schema.is_open_bracket(morpheme) {
631                gap.push(format!("GOB:{surface}"));
632                statics.push(format!("OB:{surface}"));
633                statics.push("OB:1".to_string());
634                opens = true;
635            }
636            if schema.is_close_bracket(morpheme) {
637                gap.push(format!("GCB:{surface}"));
638                statics.push(format!("CB:{surface}"));
639                statics.push("CB:1".to_string());
640                closes = true;
641            }
642            if schema.is_particle(morphemes, index) {
643                statics.push(format!("CASE:{surface}"));
644            }
645        }
646
647        let (head, function) = schema.positions(morphemes).unwrap_or((0, 0));
648        let end = morphemes.len().saturating_sub(1);
649        for (role, index) in [('H', head), ('F', function), ('L', 0), ('R', end)] {
650            if let Some(morpheme) = morphemes.get(index) {
651                push_morpheme(schema, levels.clone(), role, morpheme, &mut statics);
652            }
653        }
654        let mut after = Vec::new();
655        if let Some(morpheme) = morphemes.get(head + 1) {
656            push_morpheme(schema, levels.clone(), 'N', morpheme, &mut after);
657        }
658        if first {
659            statics.push("BOS:1".to_string());
660        }
661        if last {
662            statics.push("EOS:1".to_string());
663        }
664
665        let surface = |index: usize| {
666            morphemes
667                .get(index)
668                .map_or(Cow::Borrowed(""), |morpheme| schema.surface_of(morpheme))
669        };
670        let left = vec![format!("LF:{}", surface(function))];
671        let right = vec![
672            format!("RL:{}", surface(0)),
673            format!("RH:{}", surface(head)),
674            format!("RF:{}", surface(function)),
675        ];
676        if schema.is_particle(morphemes, function) {
677            gap.push(format!("GCASE:{}", surface(function)));
678        }
679
680        let child = if schema.is_lexicalized(morphemes, function) {
681            surface(function).to_string()
682        } else {
683            morphemes
684                .get(function)
685                .and_then(|morpheme| conjugation_form(schema, morpheme))
686                .map(str::to_string)
687                .or_else(|| {
688                    morphemes
689                        .get(function)
690                        .map(|morpheme| schema.levels_of(morpheme, levels.clone()))
691                })
692                .unwrap_or_default()
693        };
694
695        Self {
696            statics,
697            left,
698            right,
699            gap,
700            after,
701            child,
702            opens,
703            closes,
704        }
705    }
706}
707
708/// The conjugation form of a morpheme.
709///
710/// # Arguments
711///
712/// * `schema` - The schema of the dictionary of the morpheme.
713/// * `morpheme` - The morpheme.
714///
715/// # Returns
716///
717/// The form, or `None` when the schema has no column for it, the morpheme
718/// does not have the column, or the column holds `*`.
719fn conjugation_form<'a, M: Morpheme>(schema: &Schema, morpheme: &'a M) -> Option<&'a str> {
720    schema
721        .conjugation_form
722        .and_then(|index| morpheme.feature(index))
723        .filter(|form| *form != EMPTY)
724}
725
726/// Appends the features of one morpheme of a bunsetsu: its surface, the
727/// levels of its part of speech up to the first that holds nothing, and its
728/// conjugation form.
729///
730/// # Arguments
731///
732/// * `schema` - The schema of the dictionary of the morpheme.
733/// * `levels` - The columns of the part of speech the features read.
734/// * `role` - The letter of the morpheme in the bunsetsu: `H` for the head,
735///   `F` for the function word, `L` for the first, `R` for the last, `N`
736///   for the one after the head.
737/// * `morpheme` - The morpheme.
738/// * `features` - The features to append to.
739fn push_morpheme<M: Morpheme>(
740    schema: &Schema,
741    levels: Range<usize>,
742    role: char,
743    morpheme: &M,
744    features: &mut Vec<String>,
745) {
746    features.push(format!("{role}S:{}", schema.surface_of(morpheme)));
747    for (level, index) in levels.enumerate() {
748        match morpheme.feature(index) {
749            Some(value) if value != EMPTY => features.push(format!("{role}P{level}:{value}")),
750            _ => break,
751        }
752    }
753    if let Some(form) = conjugation_form(schema, morpheme) {
754        features.push(format!("{role}F:{form}"));
755    }
756}
757
758#[cfg(test)]
759// A sentence that is one bunsetsu is given as `[0..n]`: an array of one
760// range, which is what is meant.
761#[allow(clippy::single_range_in_vec_init)]
762mod tests {
763    use super::*;
764    use crate::lattice::LatticeMorpheme;
765    use crate::parser::fixtures;
766
767    /// The features of the bunsetsu of a sentence, as strings.
768    fn prepared(
769        set: &FeatureSet,
770        sentence: &(Vec<LatticeMorpheme>, Vec<Range<usize>>),
771    ) -> Prepared<String> {
772        Prepared::new(
773            &Schema::ipadic(),
774            set,
775            &sentence.0,
776            &sentence.1,
777            |feature| Some(feature.to_string()),
778        )
779    }
780
781    /// The features of a decision, as strings.
782    fn decision(
783        prepared: &Prepared<String>,
784        source: usize,
785        target: usize,
786        children: &[Vec<usize>],
787    ) -> Vec<String> {
788        let mut features = Vec::new();
789        prepared.decision(source, target, children, &mut features);
790        features
791    }
792
793    /// No bunsetsu attached to any of `count` bunsetsu.
794    fn no_children(count: usize) -> Vec<Vec<usize>> {
795        vec![Vec::new(); count]
796    }
797
798    /// Whether a feature string is of a group.
799    fn is_of(group: Group, feature: &str) -> bool {
800        match group {
801            Group::Distance => feature.starts_with("DIST:"),
802            Group::Source => feature.starts_with('S') && !feature.starts_with("SN"),
803            Group::Target => {
804                feature.starts_with('D')
805                    && !feature.starts_with("DIST:")
806                    && !feature.starts_with("DN")
807            }
808            Group::Left => feature.starts_with("LF:"),
809            Group::Right => feature.starts_with('R'),
810            Group::Children => feature.starts_with("a:") || feature.starts_with("A:"),
811            Group::Gap => feature.starts_with('G'),
812            Group::AfterHead => feature.starts_with("SN") || feature.starts_with("DN"),
813        }
814    }
815
816    #[test]
817    fn the_surfaces_of_the_features_are_the_normalized_ones_of_the_schema() {
818        // A ヲ / B ( ヲ / C ヲ / D ヲ / 本: every surface of a feature, and
819        // the bracket.
820        let noun = "名詞,一般,*,*,*,*,*";
821        let particle = "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ";
822        let morphemes = vec![
823            LatticeMorpheme::new("A", noun),
824            LatticeMorpheme::new("ヲ", particle),
825            LatticeMorpheme::new("B", noun),
826            LatticeMorpheme::new("(", "名詞,サ変接続,*,*,*,*,*"),
827            LatticeMorpheme::new("ヲ", particle),
828            LatticeMorpheme::new("C", noun),
829            LatticeMorpheme::new("ヲ", particle),
830            LatticeMorpheme::new("D", noun),
831            LatticeMorpheme::new("ヲ", particle),
832            LatticeMorpheme::new("本", "名詞,一般,*,*,*,*,本,ホン,ホン"),
833        ];
834        let ranges = vec![0..2, 2..5, 5..7, 7..9, 9..10];
835        // The first bunsetsu is attached to the second.
836        let mut children = no_children(5);
837        children[1].push(0);
838        let features = |schema: &Schema, source: usize, target: usize| -> Vec<String> {
839            let prepared = Prepared::new(
840                schema,
841                &FeatureSet::cabocha(),
842                &morphemes,
843                &ranges,
844                |feature| Some(feature.to_string()),
845            );
846            decision(&prepared, source, target, &children)
847        };
848        let schema = Schema {
849            normalization: crate::schema::Normalization::new(&[
850                ("A", "A"),
851                ("B", "B"),
852                ("C", "C"),
853                ("D", "D"),
854                ("(", "("),
855                ("ヲ", "ヲ"),
856            ])
857            .unwrap(),
858            ..Schema::ipadic()
859        };
860        // B ( ヲ -> D ヲ, over C ヲ, with A ヲ before and 本 after.
861        let normalized = features(&schema, 1, 3);
862        for feature in [
863            // The source and the target.
864            "SHS:B",
865            "SLS:B",
866            "SFS:ヲ",
867            "SRS:ヲ",
868            "SOB:(",
869            "SOB:1",
870            "SCASE:ヲ",
871            "DHS:D",
872            "DCASE:ヲ",
873            // The bunsetsu before the source, and the one attached to it.
874            "LF:ヲ",
875            "a:ヲ",
876            // The bunsetsu in between.
877            "GCASE:ヲ",
878        ] {
879            assert!(
880                normalized.iter().any(|one| one == feature),
881                "{feature}: {normalized:?}"
882            );
883        }
884        // A ヲ -> B ( ヲ, with C ヲ after, and the bracket in between for
885        // A ヲ -> C ヲ.
886        let first = features(&schema, 0, 1);
887        for feature in ["RL:C", "RH:C", "RF:ヲ", "DOB:("] {
888            assert!(
889                first.iter().any(|one| one == feature),
890                "{feature}: {first:?}"
891            );
892        }
893        let over = features(&schema, 0, 2);
894        assert!(over.iter().any(|one| one == "GOB:("), "{over:?}");
895        for all in [&normalized, &first, &over] {
896            assert!(
897                !all.iter()
898                    .any(|one| "ABCD(ヲ".chars().any(|wide| one.contains(wide))),
899                "{all:?}"
900            );
901        }
902        // Without a normalization the surfaces are as they are.
903        let plain = features(&Schema::ipadic(), 1, 3);
904        for feature in [
905            "SHS:B",
906            "SFS:ヲ",
907            "SOB:(",
908            "SCASE:ヲ",
909            "DHS:D",
910            "LF:ヲ",
911            "a:ヲ",
912            "GCASE:ヲ",
913        ] {
914            assert!(
915                plain.iter().any(|one| one == feature),
916                "{feature}: {plain:?}"
917            );
918        }
919    }
920
921    #[test]
922    fn a_decision_has_the_features_of_cabocha() {
923        let prepared = prepared(&FeatureSet::cabocha(), &fixtures::sentence());
924        // 彼 は -> 「 本, with 」 を after the target.
925        let mut expected = vec![
926            "DIST:1",
927            // The source: its head 彼, its function word は, its first
928            // morpheme 彼 and its last は.
929            "SHS:彼",
930            "SHP0:名詞",
931            "SHP1:代名詞",
932            "SHP2:一般",
933            "SFS:は",
934            "SFP0:助詞",
935            "SFP1:係助詞",
936            "SLS:彼",
937            "SLP0:名詞",
938            "SLP1:代名詞",
939            "SLP2:一般",
940            "SRS:は",
941            "SRP0:助詞",
942            "SRP1:係助詞",
943            "SCASE:は",
944            "SBOS:1",
945            // The target: the bracket is no head, so 本 is the head and
946            // the function word.
947            "DHS:本",
948            "DHP0:名詞",
949            "DHP1:一般",
950            "DFS:本",
951            "DFP0:名詞",
952            "DFP1:一般",
953            "DLS:「",
954            "DLP0:記号",
955            "DLP1:括弧開",
956            "DRS:本",
957            "DRP0:名詞",
958            "DRP1:一般",
959            "DOB:「",
960            "DOB:1",
961            // After the target: 」 を, whose head stays at its first
962            // morpheme.
963            "RL:」",
964            "RH:」",
965            "RF:を",
966            // Nothing in between.
967            "GNB:1",
968        ];
969        expected.sort_unstable();
970        assert_eq!(decision(&prepared, 0, 1, &no_children(5)), expected);
971    }
972
973    #[test]
974    fn the_conjugation_form_and_the_marks_of_a_bunsetsu_are_features() {
975        let prepared = prepared(&FeatureSet::cabocha(), &fixtures::sentence());
976        // 静か に 、 -> 読ん だ 。
977        let features = decision(&prepared, 3, 4, &no_children(5));
978        let missing: Vec<&str> = [
979            "SPUNC:、",
980            "SCASE:に",
981            "LF:を",
982            "DHF:連用タ接続",
983            "DFF:基本形",
984            "DPUNC:。",
985            "DEOS:1",
986        ]
987        .into_iter()
988        .filter(|expected| !features.iter().any(|feature| feature == expected))
989        .collect();
990        assert!(missing.is_empty(), "{missing:?} not in {features:?}");
991        // The target is the last bunsetsu: nothing is after it, and the
992        // source is not the first.
993        let present: Vec<&str> = ["RL:", "RH:", "RF:", "SBOS:", "SEOS:", "DBOS:"]
994            .into_iter()
995            .filter(|absent| features.iter().any(|feature| feature.starts_with(absent)))
996            .collect();
997        assert!(present.is_empty(), "{present:?} in {features:?}");
998        // A closing bracket: 」 を -> 静か に 、.
999        let features = decision(&prepared, 2, 3, &no_children(5));
1000        let missing: Vec<&str> = ["SCB:」", "SCB:1"]
1001            .into_iter()
1002            .filter(|expected| !features.iter().any(|feature| feature == expected))
1003            .collect();
1004        assert!(missing.is_empty(), "{missing:?} not in {features:?}");
1005    }
1006
1007    #[test]
1008    fn the_levels_of_the_part_of_speech_stop_at_the_first_empty_one() {
1009        // A level after an empty one is not read, as in CaboCha.
1010        let morphemes = [LatticeMorpheme::new("語", "名詞,*,一般,*,*,*,語,ゴ,ゴ")];
1011        let strings = Strings::new(&Schema::ipadic(), 0..4, &morphemes, false, false);
1012        let levels: Vec<&str> = strings
1013            .statics
1014            .iter()
1015            .map(String::as_str)
1016            .filter(|feature| feature.starts_with("HP"))
1017            .collect();
1018        assert_eq!(levels, ["HP0:名詞"]);
1019    }
1020
1021    #[test]
1022    fn a_limit_holds_the_features_to_that_many_levels_of_the_part_of_speech() {
1023        // A schema of four levels, as the one of UniDic.
1024        let schema = Schema {
1025            part_of_speech: 0..4,
1026            conjugation_form: Some(5),
1027            ..Schema::default()
1028        };
1029        let all = FeatureSet::cabocha();
1030        let two = FeatureSet::cabocha().with_part_of_speech_levels(2).unwrap();
1031        assert_eq!(all.levels(&schema), 0..4);
1032        assert_eq!(two.levels(&schema), 0..2);
1033        // A limit past the levels of the schema is all of them.
1034        let nine = FeatureSet::cabocha().with_part_of_speech_levels(9).unwrap();
1035        assert_eq!(nine.levels(&schema), 0..4);
1036        // A schema that starts later is cut from its start.
1037        let later = Schema {
1038            part_of_speech: 3..7,
1039            ..Schema::default()
1040        };
1041        assert_eq!(two.levels(&later), 3..5);
1042
1043        // 太郎: four levels, and no conjugation form.
1044        let morphemes = [LatticeMorpheme::new(
1045            "太郎",
1046            "名詞,固有名詞,人名,名,*,*,タロウ,タロウ",
1047        )];
1048        let levels = |set: &FeatureSet| -> (Vec<String>, String) {
1049            let strings = Strings::new(&schema, set.levels(&schema), &morphemes, false, false);
1050            let names = strings
1051                .statics
1052                .iter()
1053                .filter(|feature| feature.starts_with("HP"))
1054                .cloned()
1055                .collect();
1056            (names, strings.child)
1057        };
1058        // The features of the levels, and the feature of the bunsetsu as a
1059        // child: its part of speech, as it has no conjugation form.
1060        assert_eq!(
1061            levels(&all),
1062            (
1063                vec![
1064                    "HP0:名詞".to_string(),
1065                    "HP1:固有名詞".to_string(),
1066                    "HP2:人名".to_string(),
1067                    "HP3:名".to_string()
1068                ],
1069                "名詞-固有名詞-人名-名".to_string()
1070            )
1071        );
1072        assert_eq!(
1073            levels(&two),
1074            (
1075                vec!["HP0:名詞".to_string(), "HP1:固有名詞".to_string()],
1076                "名詞-固有名詞".to_string()
1077            )
1078        );
1079        // The limit reaches the features of a decision: 太郎 -> 太郎.
1080        let pair = [morphemes[0].clone(), morphemes[0].clone()];
1081        let decisions = |set: &FeatureSet| -> Vec<String> {
1082            let prepared = Prepared::new(&schema, set, &pair, &[0..1, 1..2], |feature| {
1083                Some(feature.to_string())
1084            });
1085            decision(&prepared, 0, 1, &no_children(2))
1086        };
1087        assert!(decisions(&all).iter().any(|one| one == "SHP3:名"));
1088        assert!(!decisions(&two).iter().any(|one| one == "SHP2:人名"));
1089        assert!(decisions(&two).iter().any(|one| one == "SHP1:固有名詞"));
1090    }
1091
1092    #[test]
1093    fn the_limit_of_the_levels_is_part_of_the_text_of_a_set() {
1094        let set = FeatureSet::parse("gap, pos-levels=2 ,source").unwrap();
1095        assert_eq!(set.groups(), [Group::Source, Group::Gap]);
1096        assert_eq!(set.part_of_speech_levels(), Some(2));
1097        // It is written after the groups, and read back.
1098        assert_eq!(set.to_string(), "source,gap,pos-levels=2");
1099        assert_eq!(FeatureSet::parse(&set.to_string()).unwrap(), set);
1100        // A set without a limit is written as before, and is another set.
1101        let plain = FeatureSet::parse("source,gap").unwrap();
1102        assert_eq!(plain.part_of_speech_levels(), None);
1103        assert_eq!(plain.to_string(), "source,gap");
1104        assert_ne!(plain, set);
1105        assert_eq!(FeatureSet::cabocha().part_of_speech_levels(), None);
1106        assert_eq!(FeatureSet::default().part_of_speech_levels(), None);
1107
1108        let message = |text: &str| FeatureSet::parse(text).unwrap_err().to_string();
1109        assert_eq!(
1110            message("source,pos-levels=0"),
1111            "the features need a level of the part of speech: pos-levels is 1 or more"
1112        );
1113        assert_eq!(
1114            message("source,pos-levels=two"),
1115            "\"pos-levels=two\" is not a number of levels of the part of speech"
1116        );
1117        assert_eq!(
1118            message("source,pos-levels="),
1119            "\"pos-levels=\" is not a number of levels of the part of speech"
1120        );
1121        assert_eq!(
1122            message("pos-levels=2,source,pos-levels=3"),
1123            "pos-levels= is given twice"
1124        );
1125        // The limit alone is not a set.
1126        assert_eq!(message("pos-levels=2"), "a feature set needs a group");
1127        assert!(matches!(
1128            FeatureSet::cabocha().with_part_of_speech_levels(0),
1129            Err(Error::Parser(_))
1130        ));
1131    }
1132
1133    #[test]
1134    fn the_distance_has_three_classes() {
1135        let prepared = prepared(&FeatureSet::cabocha(), &fixtures::repeated(8));
1136        let classes: Vec<String> = [1, 2, 5, 6, 7]
1137            .iter()
1138            .map(|&target| {
1139                decision(&prepared, 0, target, &no_children(8))
1140                    .into_iter()
1141                    .find(|feature| feature.starts_with("DIST:"))
1142                    .unwrap_or_default()
1143            })
1144            .collect();
1145        assert_eq!(
1146            classes,
1147            ["DIST:1", "DIST:2-5", "DIST:2-5", "DIST:6-", "DIST:6-"]
1148        );
1149    }
1150
1151    #[test]
1152    fn the_gap_has_the_marks_in_between_and_the_state_of_the_brackets() {
1153        let prepared = prepared(&FeatureSet::cabocha(), &fixtures::sentence());
1154        let gap = |source: usize, target: usize| -> Vec<String> {
1155            decision(&prepared, source, target, &no_children(5))
1156                .into_iter()
1157                .filter(|feature| feature.starts_with('G'))
1158                .collect()
1159        };
1160        // Nothing in between: the brackets of the source and of the target
1161        // do not count.
1162        assert_eq!(gap(1, 2), ["GNB:1"]);
1163        // 「 本 in between: opening only.
1164        assert_eq!(gap(0, 2), ["GOB:1", "GOB:「"]);
1165        // 」 を in between: closing only, and the particle.
1166        assert_eq!(gap(1, 3), ["GCASE:を", "GCB:1", "GCB:」"]);
1167        // Both, and the comma of 静か に 、.
1168        assert_eq!(
1169            gap(0, 4),
1170            [
1171                "GBB:1",
1172                "GCASE:に",
1173                "GCASE:を",
1174                "GCB:」",
1175                "GOB:「",
1176                "GPUNC:、"
1177            ]
1178        );
1179    }
1180
1181    #[test]
1182    fn the_children_are_named_by_their_function_word() {
1183        let prepared = prepared(&FeatureSet::cabocha(), &fixtures::sentence());
1184        let children = |features: Vec<String>| -> Vec<String> {
1185            features
1186                .into_iter()
1187                .filter(|feature| is_of(Group::Children, feature))
1188                .collect()
1189        };
1190        // Nothing attached yet.
1191        assert_eq!(
1192            children(decision(&prepared, 1, 3, &no_children(5))),
1193            [""; 0]
1194        );
1195        // 彼 は is attached to the source, 」 を to the target: particles,
1196        // by their surface.
1197        let attached = vec![vec![], vec![0], vec![], vec![2], vec![]];
1198        assert_eq!(
1199            children(decision(&prepared, 1, 3, &attached)),
1200            ["A:を", "a:は"]
1201        );
1202        // 「 本 ends in a noun, which has no conjugation form: its part of
1203        // speech. 読ん だ 。 ends in an auxiliary: its conjugation form.
1204        let attached = vec![vec![], vec![], vec![1], vec![4], vec![]];
1205        assert_eq!(
1206            children(decision(&prepared, 2, 3, &attached)),
1207            ["A:基本形", "a:名詞-一般"]
1208        );
1209    }
1210
1211    #[test]
1212    fn a_feature_is_in_a_decision_once() {
1213        // 本 を twice in between: one GCASE:を.
1214        let prepared = prepared(&FeatureSet::cabocha(), &fixtures::repeated(4));
1215        let features = decision(&prepared, 0, 3, &no_children(4));
1216        let particles = features
1217            .iter()
1218            .filter(|feature| *feature == "GCASE:を")
1219            .count();
1220        assert_eq!(particles, 1);
1221        let mut sorted = features.clone();
1222        sorted.sort_unstable();
1223        sorted.dedup();
1224        assert_eq!(features, sorted);
1225    }
1226
1227    #[test]
1228    fn a_feature_that_is_not_interned_is_left_out() {
1229        let (morphemes, ranges) = fixtures::sentence();
1230        let known = ["GNB:1", "RF:を", "SFS:は", "DIST:1"];
1231        let prepared: Prepared<u32> = Prepared::new(
1232            &Schema::ipadic(),
1233            &FeatureSet::cabocha(),
1234            &morphemes,
1235            &ranges,
1236            |feature| {
1237                known
1238                    .iter()
1239                    .position(|one| *one == feature)
1240                    .map(|index| index as u32)
1241            },
1242        );
1243        let mut features = Vec::new();
1244        prepared.decision(0, 1, &no_children(5), &mut features);
1245        // In the order of the numbers, not of the making.
1246        assert_eq!(features, [0, 1, 2, 3]);
1247    }
1248
1249    #[test]
1250    fn a_group_left_out_gives_none_of_its_features() {
1251        let sentence = fixtures::sentence();
1252        let attached = vec![vec![], vec![0], vec![], vec![2], vec![]];
1253        let all = decision(
1254            &prepared(&FeatureSet::default(), &sentence),
1255            1,
1256            3,
1257            &attached,
1258        );
1259        let mut failures = Vec::new();
1260        for (group, name) in Group::ALL {
1261            // The decision has features of every group.
1262            if !all.iter().any(|feature| is_of(group, feature)) {
1263                failures.push(format!("the decision has no feature of {name}"));
1264            }
1265            let others: Vec<Group> = Group::ALL
1266                .iter()
1267                .map(|(other, _)| *other)
1268                .filter(|other| *other != group)
1269                .collect();
1270            let without = decision(
1271                &prepared(&FeatureSet::new(&others).unwrap(), &sentence),
1272                1,
1273                3,
1274                &attached,
1275            );
1276            let expected: Vec<String> = all
1277                .iter()
1278                .filter(|feature| !is_of(group, feature))
1279                .cloned()
1280                .collect();
1281            if without != expected {
1282                failures.push(format!("without {name}: {without:?}"));
1283            }
1284        }
1285        assert!(failures.is_empty(), "{failures:#?}");
1286    }
1287
1288    #[test]
1289    fn the_morpheme_after_the_head_is_a_feature_of_the_source_and_of_the_target() {
1290        // 利用 し た / 読む こと を / 知っ た: the heads are 利用 and 読む, as
1291        // the schema of IPADIC has them, and し and こと follow them.
1292        let morphemes: Vec<LatticeMorpheme> = [
1293            ("利用", "名詞,サ変接続,*,*,*,*,利用,リヨウ,リヨー"),
1294            ("し", "動詞,自立,*,*,サ変・スル,連用形,する,シ,シ"),
1295            ("た", "助動詞,*,*,*,特殊・タ,基本形,た,タ,タ"),
1296            ("読む", "動詞,自立,*,*,五段・マ行,基本形,読む,ヨム,ヨム"),
1297            ("こと", "名詞,非自立,一般,*,*,*,こと,コト,コト"),
1298            ("を", "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ"),
1299            ("知っ", "動詞,自立,*,*,五段・ラ行,連用タ接続,知る,シッ,シッ"),
1300            ("た", "助動詞,*,*,*,特殊・タ,基本形,た,タ,タ"),
1301        ]
1302        .iter()
1303        .map(|(surface, features)| LatticeMorpheme::new(*surface, *features))
1304        .collect();
1305        let sentence = (morphemes, vec![0..3, 3..6, 6..8]);
1306        let after = |set: &FeatureSet, source: usize, target: usize| -> Vec<String> {
1307            decision(&prepared(set, &sentence), source, target, &no_children(3))
1308                .into_iter()
1309                .filter(|feature| is_of(Group::AfterHead, feature))
1310                .collect()
1311        };
1312        assert_eq!(
1313            after(&FeatureSet::default(), 0, 1),
1314            [
1315                "DNP0:名詞",
1316                "DNP1:非自立",
1317                "DNP2:一般",
1318                "DNS:こと",
1319                "SNF:連用形",
1320                "SNP0:動詞",
1321                "SNP1:自立",
1322                "SNS:し"
1323            ]
1324        );
1325        // The head of 知っ た is 知っ, and た follows it.
1326        assert_eq!(
1327            after(&FeatureSet::default(), 1, 2),
1328            [
1329                "DNF:基本形",
1330                "DNP0:助動詞",
1331                "DNS:た",
1332                "SNP0:名詞",
1333                "SNP1:非自立",
1334                "SNP2:一般",
1335                "SNS:こと"
1336            ]
1337        );
1338        // CaboCha's set has none of them, and a head that ends its
1339        // bunsetsu gives none.
1340        assert!(after(&FeatureSet::cabocha(), 0, 1).is_empty());
1341        let (morphemes, _) = &sentence;
1342        let alone = (morphemes[3..4].to_vec(), vec![0..1]);
1343        let prepared = prepared(&FeatureSet::default(), &alone);
1344        assert!(prepared.bunsetsu[0].after_source.is_empty());
1345        assert!(prepared.bunsetsu[0].after_target.is_empty());
1346    }
1347
1348    #[test]
1349    fn a_feature_set_is_read_from_its_text_and_written_back() {
1350        assert_eq!(
1351            FeatureSet::cabocha().to_string(),
1352            "distance,source,target,left,right,children,gap"
1353        );
1354        // The default has the morpheme after the head as well.
1355        assert_eq!(
1356            FeatureSet::default().to_string(),
1357            "distance,source,target,left,right,children,gap,after"
1358        );
1359        assert!(!FeatureSet::cabocha().has(Group::AfterHead));
1360        assert_eq!(Group::ALL.len(), 8);
1361        // The order of the text does not matter, nor do spaces.
1362        let set = FeatureSet::parse("gap, source ,distance").unwrap();
1363        assert_eq!(set.groups(), [Group::Distance, Group::Source, Group::Gap]);
1364        assert_eq!(set.to_string(), "distance,source,gap");
1365        assert_eq!(FeatureSet::parse(&set.to_string()).unwrap(), set);
1366        assert!(set.has(Group::Gap));
1367        assert!(!set.has(Group::Children));
1368        for (group, name) in Group::ALL {
1369            assert_eq!(group.name(), name);
1370            assert_eq!(Group::from_name(name), Some(group));
1371        }
1372    }
1373
1374    #[test]
1375    fn a_feature_set_that_cannot_be_read_is_refused() {
1376        let accepted: Vec<&str> = ["", "distance,", "distance,head", "gap,distance,gap"]
1377            .into_iter()
1378            .filter(|text| !matches!(FeatureSet::parse(text), Err(Error::Parser(_))))
1379            .collect();
1380        assert!(accepted.is_empty(), "not refused: {accepted:?}");
1381        assert!(matches!(FeatureSet::new(&[]), Err(Error::Parser(_))));
1382    }
1383
1384    #[test]
1385    fn the_features_of_a_bunsetsu_are_those_of_its_words() {
1386        let schema = Schema::ipadic();
1387        let space =
1388            LatticeMorpheme::new("\u{3000}", "記号,空白,*,*,*,*,\u{3000},\u{3000},\u{3000}");
1389        let hon = LatticeMorpheme::new("本", "名詞,一般,*,*,*,*,本,ホン,ホン");
1390        let wo = LatticeMorpheme::new("を", "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ");
1391        let levels = FeatureSet::default().levels(&schema);
1392        let strings = |morphemes: &[LatticeMorpheme]| {
1393            Strings::new(&schema, levels.clone(), morphemes, false, false)
1394        };
1395        let plain = strings(&[hon.clone(), wo.clone()]);
1396        // A space at the start, after the head and at the end: the first
1397        // morpheme, the one after the head and the last one are words.
1398        for spaced in [
1399            vec![space.clone(), hon.clone(), wo.clone()],
1400            vec![hon.clone(), space.clone(), wo.clone()],
1401            vec![hon.clone(), wo.clone(), space.clone()],
1402            vec![
1403                space.clone(),
1404                hon.clone(),
1405                space.clone(),
1406                wo.clone(),
1407                space.clone(),
1408            ],
1409        ] {
1410            assert_eq!(strings(&spaced), plain);
1411        }
1412        assert!(plain.statics.contains(&"LS:本".to_string()));
1413        assert!(plain.statics.contains(&"RS:を".to_string()));
1414        assert_eq!(plain.after, ["NS:を", "NP0:助詞", "NP1:格助詞", "NP2:一般"]);
1415
1416        // A bunsetsu of spaces alone is read as it is.
1417        let spaces = strings(&[space.clone(), space]);
1418        assert!(spaces.statics.contains(&"HS:\u{3000}".to_string()));
1419    }
1420}