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