Skip to main content

lindera_dependency/schema/
symbols.rs

1//! Recognizing symbols, punctuation and brackets.
2
3use super::Schema;
4use super::pattern::{has_part_of_speech, owned};
5use crate::bytes::{Reader, push_string, push_strings, push_u32};
6use crate::error::Result;
7use crate::morpheme::Morpheme;
8
9/// What recognizes one kind of mark: parts of speech, and the characters
10/// its surface is made of.
11///
12/// A morpheme is of the kind when its part of speech starts with one of
13/// the lists of levels, or when its surface is not empty and every
14/// character of it is one of `characters` (or, with
15/// [`SurfaceRule::OneCharacter`], when its surface is one of them). The
16/// surface is needed because a
17/// dictionary does not always give a mark the part of speech of a mark:
18/// IPADIC has no half-width symbols, so `,` is an unknown word and comes
19/// out as 名詞,サ変接続.
20///
21/// The surface is the one of the schema, normalized when the schema has a
22/// normalization. The schemas of this crate have none: their characters
23/// hold the full-width and the half-width forms side by side.
24#[derive(Debug, Clone, PartialEq, Eq, Default)]
25pub struct Marks {
26    /// The parts of speech of the kind: each one the first levels, from the
27    /// coarsest, as `記号`, `読点`.
28    pub part_of_speech: Vec<Vec<String>>,
29    /// The characters a surface of the kind is made of.
30    pub characters: String,
31}
32
33impl Marks {
34    /// Makes the marks of a kind.
35    ///
36    /// # Arguments
37    ///
38    /// * `part_of_speech` - The parts of speech of the kind, each one its
39    ///   first levels.
40    /// * `characters` - The characters a surface of the kind is made of.
41    ///
42    /// # Returns
43    ///
44    /// The marks.
45    pub fn new(part_of_speech: &[&[&str]], characters: &str) -> Self {
46        Self {
47            part_of_speech: part_of_speech.iter().map(|levels| owned(levels)).collect(),
48            characters: characters.to_string(),
49        }
50    }
51
52    /// Whether a morpheme is of the kind.
53    ///
54    /// # Arguments
55    ///
56    /// * `schema` - The schema of the dictionary of the morpheme.
57    /// * `morpheme` - The morpheme.
58    ///
59    /// # Returns
60    ///
61    /// Whether its part of speech or its surface is of the kind.
62    pub(super) fn matches<M: Morpheme>(&self, schema: &Schema, morpheme: &M) -> bool {
63        if self
64            .part_of_speech
65            .iter()
66            .any(|levels| has_part_of_speech(schema, morpheme, levels))
67        {
68            return true;
69        }
70        schema
71            .symbols
72            .surface
73            .matches(&schema.surface_of(morpheme), |character| {
74                self.characters.contains(character)
75            })
76    }
77
78    /// Appends the marks to the bytes of a schema.
79    ///
80    /// # Arguments
81    ///
82    /// * `bytes` - The bytes to append to.
83    fn write(&self, bytes: &mut Vec<u8>) {
84        push_u32(bytes, self.part_of_speech.len() as u32);
85        for levels in &self.part_of_speech {
86            push_strings(bytes, levels);
87        }
88        push_string(bytes, &self.characters);
89    }
90
91    /// Reads marks from the bytes of a schema.
92    ///
93    /// # Arguments
94    ///
95    /// * `reader` - The bytes, at the marks.
96    ///
97    /// # Returns
98    ///
99    /// The marks, or the error of bytes that end early.
100    fn read(reader: &mut Reader) -> Result<Self> {
101        let count = reader.u32()?;
102        let mut part_of_speech = Vec::new();
103        for _ in 0..count {
104            part_of_speech.push(reader.strings()?);
105        }
106        Ok(Self {
107            part_of_speech,
108            characters: reader.string()?,
109        })
110    }
111}
112
113/// How the surface of a morpheme is matched against the characters of a
114/// kind of mark, and what such a match says.
115#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
116pub enum SurfaceRule {
117    /// A surface made of characters of a kind is of the kind, as `!?` or
118    /// `」」`, and the morpheme is a symbol: it is not the head of a
119    /// bunsetsu, whatever its part of speech. The rule of the schemas of
120    /// this crate.
121    #[default]
122    EveryCharacter,
123    /// A surface that is one character of a kind is of the kind, and `((`
124    /// is not a bracket. The match is for the features of the parser only:
125    /// the morpheme is a symbol by its part of speech alone, so that an
126    /// unknown word `(` with the part of speech of a noun can be the head
127    /// of its bunsetsu. CaboCha's rule.
128    OneCharacter,
129}
130
131impl SurfaceRule {
132    /// The two rules with their codes in a model file.
133    const ALL: [(SurfaceRule, u8); 2] = [
134        (SurfaceRule::EveryCharacter, 0),
135        (SurfaceRule::OneCharacter, 1),
136    ];
137
138    /// Whether a surface is of a kind of mark.
139    ///
140    /// # Arguments
141    ///
142    /// * `surface` - The surface, normalized.
143    /// * `is_of_kind` - Whether a character is one of the kind.
144    ///
145    /// # Returns
146    ///
147    /// Whether the surface is of the kind by this rule; `false` for an
148    /// empty surface.
149    fn matches(self, surface: &str, is_of_kind: impl Fn(char) -> bool) -> bool {
150        let mut characters = surface.chars();
151        match self {
152            SurfaceRule::EveryCharacter => !surface.is_empty() && characters.all(is_of_kind),
153            SurfaceRule::OneCharacter => {
154                characters.next().is_some_and(is_of_kind) && characters.next().is_none()
155            }
156        }
157    }
158
159    /// The code of the rule in a model file.
160    fn code(self) -> u8 {
161        Self::ALL
162            .iter()
163            .find(|(one, _)| *one == self)
164            .map_or(u8::MAX, |(_, code)| *code)
165    }
166}
167
168/// How the symbols of a dictionary are recognized, by kind.
169///
170/// A morpheme of any kind is a symbol ([`Schema::is_symbol`]): it is
171/// neither the head nor the function word of a bunsetsu. Commas, periods
172/// and brackets are kinds of their own because the parser has features for
173/// them.
174#[derive(Debug, Clone, PartialEq, Eq, Default)]
175pub struct Symbols {
176    /// The symbols that are of none of the other kinds.
177    pub others: Marks,
178    /// The commas (読点).
179    pub commas: Marks,
180    /// The periods (句点).
181    pub periods: Marks,
182    /// The opening brackets.
183    pub open_brackets: Marks,
184    /// The closing brackets.
185    pub close_brackets: Marks,
186    /// How a surface is matched against the characters of a kind.
187    pub surface: SurfaceRule,
188}
189
190impl Symbols {
191    /// The kinds, in the order of their bytes.
192    fn kinds(&self) -> [&Marks; 5] {
193        [
194            &self.others,
195            &self.commas,
196            &self.periods,
197            &self.open_brackets,
198            &self.close_brackets,
199        ]
200    }
201
202    /// Whether a morpheme is a symbol of any kind.
203    ///
204    /// A surface that mixes the kinds, as `,“` (which IPADIC gives as one
205    /// unknown word), is a symbol too: every character of it is of some
206    /// kind.
207    ///
208    /// # Arguments
209    ///
210    /// * `schema` - The schema of the dictionary of the morpheme.
211    /// * `morpheme` - The morpheme.
212    ///
213    /// # Returns
214    ///
215    /// Whether the morpheme is a symbol.
216    pub(super) fn matches<M: Morpheme>(&self, schema: &Schema, morpheme: &M) -> bool {
217        let kinds = self.kinds();
218        if kinds.iter().any(|kind| {
219            kind.part_of_speech
220                .iter()
221                .any(|levels| has_part_of_speech(schema, morpheme, levels))
222        }) {
223            return true;
224        }
225        // With the rule of one character a surface says nothing about
226        // what the morpheme is: only its part of speech makes it a symbol.
227        self.surface == SurfaceRule::EveryCharacter
228            && self
229                .surface
230                .matches(&schema.surface_of(morpheme), |character| {
231                    kinds.iter().any(|kind| kind.characters.contains(character))
232                })
233    }
234
235    /// Appends the symbols to the bytes of a schema.
236    ///
237    /// # Arguments
238    ///
239    /// * `bytes` - The bytes to append to.
240    pub(super) fn write(&self, bytes: &mut Vec<u8>) {
241        for kind in self.kinds() {
242            kind.write(bytes);
243        }
244        bytes.push(self.surface.code());
245    }
246
247    /// Reads symbols from the bytes of a schema.
248    ///
249    /// # Arguments
250    ///
251    /// * `reader` - The bytes, at the symbols.
252    ///
253    /// # Returns
254    ///
255    /// The symbols, or the error of bytes that end early or have a rule of
256    /// the surface that is not one.
257    pub(super) fn read(reader: &mut Reader) -> Result<Self> {
258        let others = Marks::read(reader)?;
259        let commas = Marks::read(reader)?;
260        let periods = Marks::read(reader)?;
261        let open_brackets = Marks::read(reader)?;
262        let close_brackets = Marks::read(reader)?;
263        let code = reader.u8()?;
264        let surface = SurfaceRule::ALL
265            .iter()
266            .find(|(_, other)| *other == code)
267            .map(|(rule, _)| *rule)
268            .ok_or_else(|| {
269                reader.error(format_args!(
270                    "has the rule {code} for the surface of a mark"
271                ))
272            })?;
273        Ok(Self {
274            others,
275            commas,
276            periods,
277            open_brackets,
278            close_brackets,
279            surface,
280        })
281    }
282}
283
284#[cfg(test)]
285mod tests {
286    use super::*;
287    use crate::error::Error;
288    use crate::lattice::LatticeMorpheme;
289
290    /// Symbols with one part of speech and one or two characters per kind.
291    fn symbols() -> Symbols {
292        Symbols {
293            others: Marks::new(&[&["記号"]], "!-"),
294            commas: Marks::new(&[&["記号", "読点"]], "、,"),
295            periods: Marks::new(&[&["記号", "句点"]], "。."),
296            open_brackets: Marks::new(&[&["記号", "括弧開"]], "「("),
297            close_brackets: Marks::new(&[&["記号", "括弧閉"]], "」)"),
298            surface: SurfaceRule::EveryCharacter,
299        }
300    }
301
302    #[test]
303    fn a_kind_is_recognized_by_the_part_of_speech_or_by_the_surface() {
304        let schema = Schema::ipadic();
305        let commas = symbols().commas;
306        // By the part of speech, whatever the surface.
307        assert!(commas.matches(&schema, &LatticeMorpheme::new("x", "記号,読点,*,*")));
308        // By the surface, whatever the part of speech.
309        assert!(commas.matches(&schema, &LatticeMorpheme::new(",", "名詞,サ変接続,*,*")));
310        assert!(commas.matches(&schema, &LatticeMorpheme::new(",、", "名詞,サ変接続,*,*")));
311        // Neither.
312        assert!(!commas.matches(&schema, &LatticeMorpheme::new("x", "記号,句点,*,*")));
313        assert!(!commas.matches(&schema, &LatticeMorpheme::new(".", "名詞,サ変接続,*,*")));
314        // Every character has to be of the kind, and there has to be one.
315        assert!(!commas.matches(&schema, &LatticeMorpheme::new(",a", "名詞,一般,*,*")));
316        assert!(!commas.matches(&schema, &LatticeMorpheme::new("", "名詞,一般,*,*")));
317    }
318
319    #[test]
320    fn a_symbol_is_a_morpheme_of_any_kind_or_of_characters_of_several() {
321        let schema = Schema::ipadic();
322        let symbols = symbols();
323        for (surface, features) in [
324            ("★", "記号,一般,*,*"),
325            ("x", "記号,括弧閉,*,*"),
326            ("!", "名詞,サ変接続,*,*"),
327            (")", "名詞,サ変接続,*,*"),
328            // A comma and a bracket in one unknown word.
329            (",「", "名詞,サ変接続,*,*"),
330        ] {
331            let morpheme = LatticeMorpheme::new(surface, features);
332            assert!(symbols.matches(&schema, &morpheme), "{surface}");
333        }
334        for (surface, features) in [
335            ("%", "名詞,サ変接続,*,*"),
336            ("%,", "名詞,サ変接続,*,*"),
337            ("本", "名詞,一般,*,*"),
338            ("", "名詞,一般,*,*"),
339        ] {
340            let morpheme = LatticeMorpheme::new(surface, features);
341            assert!(!symbols.matches(&schema, &morpheme), "{surface}");
342        }
343    }
344
345    #[test]
346    fn symbols_come_back_from_their_bytes() {
347        let symbols = symbols();
348        let mut bytes = Vec::new();
349        symbols.write(&mut bytes);
350        let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
351        assert_eq!(Symbols::read(&mut reader).unwrap(), symbols);
352        assert_eq!(reader.remaining(), 0);
353        // Each kind is where it was: none is read into the place of
354        // another.
355        let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
356        let read = Symbols::read(&mut reader).unwrap();
357        assert_eq!(read.others.characters, "!-");
358        assert_eq!(read.commas.characters, "、,");
359        assert_eq!(read.periods.characters, "。.");
360        assert_eq!(read.open_brackets.characters, "「(");
361        assert_eq!(read.close_brackets.characters, "」)");
362    }
363
364    /// A schema of IPADIC with these symbols and a rule of the surface.
365    fn schema_with(surface: SurfaceRule) -> Schema {
366        Schema {
367            symbols: Symbols {
368                surface,
369                ..symbols()
370            },
371            ..Schema::ipadic()
372        }
373    }
374
375    #[test]
376    fn with_the_rule_of_one_character_a_surface_is_one_character_of_the_kind() {
377        let schema = schema_with(SurfaceRule::OneCharacter);
378        let open = &schema.symbols.open_brackets;
379        let noun = "名詞,サ変接続,*,*";
380        assert!(open.matches(&schema, &LatticeMorpheme::new("(", noun)));
381        assert!(open.matches(&schema, &LatticeMorpheme::new("「", noun)));
382        // Two brackets are not a bracket, as they are with the other rule.
383        assert!(!open.matches(&schema, &LatticeMorpheme::new("((", noun)));
384        assert!(!open.matches(&schema, &LatticeMorpheme::new("(「", noun)));
385        assert!(!open.matches(&schema, &LatticeMorpheme::new("", noun)));
386        assert!(!open.matches(&schema, &LatticeMorpheme::new(")", noun)));
387        let every = schema_with(SurfaceRule::EveryCharacter);
388        assert!(
389            every
390                .symbols
391                .open_brackets
392                .matches(&every, &LatticeMorpheme::new("((", noun))
393        );
394        // The part of speech still says it, whatever the surface.
395        assert!(open.matches(&schema, &LatticeMorpheme::new("((", "記号,括弧開,*,*")));
396    }
397
398    #[test]
399    fn with_the_rule_of_one_character_only_a_part_of_speech_makes_a_symbol() {
400        let schema = schema_with(SurfaceRule::OneCharacter);
401        // A bracket by its surface is a bracket and not a symbol: it can be
402        // the head of a bunsetsu.
403        let bracket = LatticeMorpheme::new("(", "名詞,サ変接続,*,*");
404        assert!(schema.is_open_bracket(&bracket));
405        assert!(!schema.is_symbol(&bracket));
406        assert_eq!(
407            schema.positions(std::slice::from_ref(&bracket)),
408            Some((0, 0))
409        );
410        let noun = LatticeMorpheme::new("本", "名詞,一般,*,*");
411        assert_eq!(
412            schema.positions(&[noun.clone(), bracket.clone()]),
413            Some((1, 1))
414        );
415        // By its part of speech it is a symbol, as with the other rule.
416        let symbol = LatticeMorpheme::new("(", "記号,括弧開,*,*");
417        assert!(schema.is_symbol(&symbol));
418        assert_eq!(schema.positions(&[noun.clone(), symbol]), Some((0, 0)));
419
420        let every = schema_with(SurfaceRule::EveryCharacter);
421        assert!(every.is_symbol(&bracket));
422        assert_eq!(every.positions(&[noun, bracket]), Some((0, 0)));
423    }
424
425    #[test]
426    fn a_mark_is_matched_on_the_normalized_surface() {
427        let mut schema = schema_with(SurfaceRule::OneCharacter);
428        let full = LatticeMorpheme::new("(", "名詞,サ変接続,*,*");
429        assert!(!schema.is_open_bracket(&full));
430        schema.normalization = crate::schema::Normalization::new(&[("(", "(")]).unwrap();
431        assert!(schema.is_open_bracket(&full));
432        assert!(!schema.is_close_bracket(&full));
433    }
434
435    #[test]
436    fn the_rule_of_the_surface_comes_back_from_the_bytes() {
437        for rule in [SurfaceRule::EveryCharacter, SurfaceRule::OneCharacter] {
438            let symbols = Symbols {
439                surface: rule,
440                ..symbols()
441            };
442            let mut bytes = Vec::new();
443            symbols.write(&mut bytes);
444            let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
445            assert_eq!(Symbols::read(&mut reader).unwrap().surface, rule);
446            assert_eq!(reader.remaining(), 0);
447        }
448        let mut bytes = Vec::new();
449        symbols().write(&mut bytes);
450        *bytes.last_mut().unwrap() = 2;
451        let mut reader = Reader::new(&bytes, "test bytes", Error::Chunker);
452        let error = Symbols::read(&mut reader).unwrap_err().to_string();
453        assert!(
454            error.contains("the rule 2 for the surface of a mark"),
455            "{error}"
456        );
457    }
458}