Skip to main content

lindera_dependency/schema/
pattern.rs

1//! Patterns over the morphemes of a bunsetsu.
2
3use super::Schema;
4use crate::bytes::{Reader, push_strings};
5use crate::error::Result;
6use crate::morpheme::Morpheme;
7
8/// How deep the `after` of a pattern may go in the bytes of a schema.
9const MAX_DEPTH: usize = 8;
10
11/// A pattern a morpheme of a bunsetsu matches or not: a prefix of its
12/// part-of-speech levels, and optionally its base form and the morpheme
13/// before it.
14///
15/// CaboCha matches a prefix of the whole feature string; a pattern states
16/// the same thing over the columns of a [`Schema`], so it holds no column
17/// number. Every condition has to hold. The pattern without a condition
18/// ([`Pattern::default`]) matches every morpheme.
19///
20/// # Examples
21///
22/// ```
23/// use lindera_dependency::lattice::LatticeMorpheme;
24/// use lindera_dependency::{Pattern, Schema};
25///
26/// let schema = Schema::ipadic();
27/// let bunsetsu = [
28///     LatticeMorpheme::new("利用", "名詞,サ変接続,*,*,*,*,利用,リヨウ,リヨー"),
29///     LatticeMorpheme::new("し", "動詞,自立,*,*,サ変・スル,連用形,する,シ,シ"),
30/// ];
31///
32/// // する after a verbal noun.
33/// let pattern = Pattern::new(&["動詞", "自立"])
34///     .with_base_forms(&["する"])
35///     .after(Pattern::new(&["名詞", "サ変接続"]));
36/// assert!(pattern.matches(&schema, &bunsetsu, 1));
37/// assert!(!pattern.matches(&schema, &bunsetsu, 0));
38/// ```
39#[derive(Debug, Clone, PartialEq, Eq, Default)]
40pub struct Pattern {
41    /// The first part-of-speech levels the morpheme has to have, from the
42    /// coarsest: `動詞`, `非自立`. Empty for any part of speech.
43    pub part_of_speech: Vec<String>,
44    /// The base forms the morpheme may have. Empty for any base form.
45    pub base_forms: Vec<String>,
46    /// What the morpheme before it in the bunsetsu has to match. With it,
47    /// the first morpheme of a bunsetsu never matches.
48    pub after: Option<Box<Pattern>>,
49}
50
51impl Pattern {
52    /// Makes a pattern for a part of speech.
53    ///
54    /// # Arguments
55    ///
56    /// * `part_of_speech` - The first part-of-speech levels, from the
57    ///   coarsest.
58    ///
59    /// # Returns
60    ///
61    /// The pattern, without a condition on the base form or on the morpheme
62    /// before.
63    pub fn new<S: AsRef<str>>(part_of_speech: &[S]) -> Self {
64        Self {
65            part_of_speech: owned(part_of_speech),
66            base_forms: Vec::new(),
67            after: None,
68        }
69    }
70
71    /// Limits the pattern to some base forms.
72    ///
73    /// # Arguments
74    ///
75    /// * `base_forms` - The base forms the morpheme may have.
76    ///
77    /// # Returns
78    ///
79    /// The pattern with the condition.
80    pub fn with_base_forms<S: AsRef<str>>(mut self, base_forms: &[S]) -> Self {
81        self.base_forms = owned(base_forms);
82        self
83    }
84
85    /// Limits the pattern to a morpheme that follows another one in its
86    /// bunsetsu.
87    ///
88    /// # Arguments
89    ///
90    /// * `before` - What the morpheme before has to match;
91    ///   [`Pattern::default`] for any morpheme.
92    ///
93    /// # Returns
94    ///
95    /// The pattern with the condition.
96    pub fn after(mut self, before: Pattern) -> Self {
97        self.after = Some(Box::new(before));
98        self
99    }
100
101    /// Whether a morpheme of a bunsetsu matches the pattern.
102    ///
103    /// A column the morpheme does not have matches nothing, and neither
104    /// does a base form when the schema has no column for it.
105    ///
106    /// # Arguments
107    ///
108    /// * `schema` - The schema of the dictionary of the morphemes.
109    /// * `bunsetsu` - The morphemes of the bunsetsu.
110    /// * `index` - The index of the morpheme in the bunsetsu.
111    ///
112    /// # Returns
113    ///
114    /// Whether the morpheme matches; `false` for an index outside the
115    /// bunsetsu.
116    pub fn matches<M: Morpheme>(&self, schema: &Schema, bunsetsu: &[M], index: usize) -> bool {
117        let Some(morpheme) = bunsetsu.get(index) else {
118            return false;
119        };
120        if !has_part_of_speech(schema, morpheme, &self.part_of_speech) {
121            return false;
122        }
123        if !self.base_forms.is_empty() {
124            let base_form = schema.base_form.and_then(|column| morpheme.feature(column));
125            if !base_form
126                .is_some_and(|base_form| self.base_forms.iter().any(|one| one == base_form))
127            {
128                return false;
129            }
130        }
131        match &self.after {
132            None => true,
133            Some(before) => index > 0 && before.matches(schema, bunsetsu, index - 1),
134        }
135    }
136
137    /// Appends the pattern to the bytes of a schema.
138    ///
139    /// # Arguments
140    ///
141    /// * `bytes` - The bytes to append to.
142    pub(super) fn write(&self, bytes: &mut Vec<u8>) {
143        push_strings(bytes, &self.part_of_speech);
144        push_strings(bytes, &self.base_forms);
145        match &self.after {
146            None => bytes.push(0),
147            Some(before) => {
148                bytes.push(1);
149                before.write(bytes);
150            }
151        }
152    }
153
154    /// Reads a pattern from the bytes of a schema.
155    ///
156    /// # Arguments
157    ///
158    /// * `reader` - The bytes, at the pattern.
159    /// * `depth` - How many patterns this one is the `after` of.
160    ///
161    /// # Returns
162    ///
163    /// The pattern, or the error of bytes that end early, of a flag that is
164    /// neither 0 nor 1, or of patterns nested deeper than this crate writes.
165    pub(super) fn read(reader: &mut Reader, depth: usize) -> Result<Self> {
166        if depth > MAX_DEPTH {
167            return Err(reader.error(format_args!("has patterns nested deeper than {MAX_DEPTH}")));
168        }
169        let part_of_speech = reader.strings()?;
170        let base_forms = reader.strings()?;
171        let after = match reader.u8()? {
172            0 => None,
173            1 => Some(Box::new(Self::read(reader, depth + 1)?)),
174            flag => {
175                return Err(reader.error(format_args!("has the unknown pattern flag {flag}")));
176            }
177        };
178        Ok(Self {
179            part_of_speech,
180            base_forms,
181            after,
182        })
183    }
184}
185
186/// Whether the part of speech of a morpheme starts with some levels.
187///
188/// # Arguments
189///
190/// * `schema` - The schema of the dictionary of the morpheme.
191/// * `morpheme` - The morpheme.
192/// * `levels` - The levels, from the coarsest.
193///
194/// # Returns
195///
196/// Whether each level is the one of the morpheme; `false` when there are
197/// more levels than the schema has part-of-speech columns, or than the
198/// morpheme has columns.
199pub(super) fn has_part_of_speech<M: Morpheme, S: AsRef<str>>(
200    schema: &Schema,
201    morpheme: &M,
202    levels: &[S],
203) -> bool {
204    if levels.len() > schema.part_of_speech.len() {
205        return false;
206    }
207    levels
208        .iter()
209        .zip(schema.part_of_speech.clone())
210        .all(|(level, column)| morpheme.feature(column) == Some(level.as_ref()))
211}
212
213/// Strings as owned strings.
214///
215/// # Arguments
216///
217/// * `values` - The strings.
218///
219/// # Returns
220///
221/// The owned strings, in the same order.
222pub(super) fn owned<S: AsRef<str>>(values: &[S]) -> Vec<String> {
223    values
224        .iter()
225        .map(|value| value.as_ref().to_string())
226        .collect()
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232    use crate::error::Error;
233    use crate::lattice::LatticeMorpheme;
234
235    /// 利用 / し / た, with the features of IPADIC.
236    fn bunsetsu() -> Vec<LatticeMorpheme> {
237        vec![
238            LatticeMorpheme::new("利用", "名詞,サ変接続,*,*,*,*,利用,リヨウ,リヨー"),
239            LatticeMorpheme::new("し", "動詞,自立,*,*,サ変・スル,連用形,する,シ,シ"),
240            LatticeMorpheme::new("た", "助動詞,*,*,*,特殊・タ,基本形,た,タ,タ"),
241        ]
242    }
243
244    #[test]
245    fn the_part_of_speech_is_matched_by_a_prefix_of_its_levels() {
246        let schema = Schema::ipadic();
247        let bunsetsu = bunsetsu();
248        assert!(Pattern::new(&["名詞"]).matches(&schema, &bunsetsu, 0));
249        assert!(Pattern::new(&["名詞", "サ変接続"]).matches(&schema, &bunsetsu, 0));
250        assert!(Pattern::new(&["名詞", "サ変接続", "*", "*"]).matches(&schema, &bunsetsu, 0));
251        assert!(!Pattern::new(&["名詞", "一般"]).matches(&schema, &bunsetsu, 0));
252        assert!(!Pattern::new(&["動詞"]).matches(&schema, &bunsetsu, 0));
253        // A level is compared as a whole, not by its first characters.
254        assert!(!Pattern::new(&["名"]).matches(&schema, &bunsetsu, 0));
255        // More levels than the schema has are never matched: the fifth
256        // column of IPADIC is the conjugation type.
257        assert!(
258            !Pattern::new(&["動詞", "自立", "*", "*", "サ変・スル"]).matches(&schema, &bunsetsu, 1)
259        );
260    }
261
262    #[test]
263    fn the_columns_of_the_part_of_speech_come_from_the_schema() {
264        // A dictionary with one column before the part of speech.
265        let schema = Schema {
266            part_of_speech: 1..3,
267            base_form: Some(3),
268            ..Schema::default()
269        };
270        let bunsetsu = [LatticeMorpheme::new("読む", "x,動詞,自立,読む")];
271        assert!(Pattern::new(&["動詞", "自立"]).matches(&schema, &bunsetsu, 0));
272        assert!(!Pattern::new(&["x"]).matches(&schema, &bunsetsu, 0));
273        assert!(
274            Pattern::new(&["動詞"])
275                .with_base_forms(&["読む"])
276                .matches(&schema, &bunsetsu, 0)
277        );
278    }
279
280    #[test]
281    fn the_pattern_without_a_condition_matches_every_morpheme() {
282        let schema = Schema::ipadic();
283        let bunsetsu = bunsetsu();
284        for index in 0..bunsetsu.len() {
285            assert!(Pattern::default().matches(&schema, &bunsetsu, index));
286        }
287        assert!(!Pattern::default().matches(&schema, &bunsetsu, bunsetsu.len()));
288    }
289
290    #[test]
291    fn the_base_form_limits_the_pattern() {
292        let schema = Schema::ipadic();
293        let bunsetsu = bunsetsu();
294        let verb = Pattern::new(&["動詞", "自立"]);
295        assert!(
296            verb.clone()
297                .with_base_forms(&["できる", "する"])
298                .matches(&schema, &bunsetsu, 1)
299        );
300        assert!(
301            !verb
302                .clone()
303                .with_base_forms(&["なる"])
304                .matches(&schema, &bunsetsu, 1)
305        );
306        // The surface is not the base form.
307        assert!(
308            !verb
309                .clone()
310                .with_base_forms(&["し"])
311                .matches(&schema, &bunsetsu, 1)
312        );
313        // Without a column for the base form, a base form matches nothing.
314        let without = Schema {
315            base_form: None,
316            ..Schema::ipadic()
317        };
318        assert!(
319            !verb
320                .with_base_forms(&["する"])
321                .matches(&without, &bunsetsu, 1)
322        );
323    }
324
325    #[test]
326    fn after_looks_at_the_morpheme_before_in_the_bunsetsu() {
327        let schema = Schema::ipadic();
328        let bunsetsu = bunsetsu();
329        let verb = Pattern::new(&["動詞"]);
330        assert!(
331            verb.clone()
332                .after(Pattern::new(&["名詞", "サ変接続"]))
333                .matches(&schema, &bunsetsu, 1)
334        );
335        assert!(
336            !verb
337                .clone()
338                .after(Pattern::new(&["助詞"]))
339                .matches(&schema, &bunsetsu, 1)
340        );
341        // After any morpheme: every morpheme but the first.
342        let any = Pattern::default().after(Pattern::default());
343        assert!(!any.matches(&schema, &bunsetsu, 0));
344        assert!(any.matches(&schema, &bunsetsu, 1));
345        assert!(any.matches(&schema, &bunsetsu, 2));
346        // The morpheme before, not any earlier one: た is after し, not
347        // after 利用.
348        let auxiliary = Pattern::new(&["助動詞"]);
349        assert!(
350            !auxiliary
351                .clone()
352                .after(Pattern::new(&["名詞"]))
353                .matches(&schema, &bunsetsu, 2)
354        );
355        // A pattern before may have one before it too.
356        assert!(
357            auxiliary
358                .after(verb.after(Pattern::new(&["名詞"])))
359                .matches(&schema, &bunsetsu, 2)
360        );
361    }
362
363    #[test]
364    fn a_morpheme_with_fewer_columns_matches_no_column_it_lacks() {
365        let schema = Schema::ipadic();
366        let bunsetsu = [
367            LatticeMorpheme::new("x", ""),
368            LatticeMorpheme::new("y", "動詞"),
369        ];
370        assert!(Pattern::default().matches(&schema, &bunsetsu, 0));
371        assert!(!Pattern::new(&["動詞"]).matches(&schema, &bunsetsu, 0));
372        assert!(Pattern::new(&["動詞"]).matches(&schema, &bunsetsu, 1));
373        assert!(!Pattern::new(&["動詞", "自立"]).matches(&schema, &bunsetsu, 1));
374        assert!(
375            !Pattern::new(&["動詞"])
376                .with_base_forms(&["する"])
377                .matches(&schema, &bunsetsu, 1)
378        );
379    }
380
381    #[test]
382    fn a_pattern_comes_back_from_its_bytes() {
383        let pattern = Pattern::new(&["動詞", "自立"])
384            .with_base_forms(&["する", "できる"])
385            .after(Pattern::default().after(Pattern::new(&["名詞"])));
386        let mut bytes = Vec::new();
387        pattern.write(&mut bytes);
388        let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
389        assert_eq!(Pattern::read(&mut reader, 0).unwrap(), pattern);
390        assert_eq!(reader.remaining(), 0);
391    }
392
393    #[test]
394    fn bytes_that_are_not_a_pattern_are_errors() {
395        // No part of speech, no base form, and the flag 2.
396        let bytes = [0, 0, 0, 0, 0, 0, 0, 0, 2];
397        let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
398        let message = Pattern::read(&mut reader, 0).unwrap_err().to_string();
399        assert!(message.contains("unknown pattern flag 2"), "{message}");
400
401        // Patterns that each have one before them, without an end.
402        let bytes = [0, 0, 0, 0, 0, 0, 0, 0, 1].repeat(100);
403        let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
404        let message = Pattern::read(&mut reader, 0).unwrap_err().to_string();
405        assert!(message.contains("nested deeper than 8"), "{message}");
406    }
407}