Skip to main content

lindera_dependency/schema/
normalization.rs

1//! The normalization of a surface before it is used.
2
3use std::borrow::Cow;
4
5use crate::bytes::{Reader, push_string, push_u32};
6use crate::error::{Error, Result};
7
8/// The largest number of rules a table read from a model file may have.
9const MAX_RULES: u32 = 1 << 20;
10
11/// A table that replaces parts of a surface before the surface becomes a
12/// feature of the chunker or of the parser, or is matched as punctuation
13/// or as a bracket.
14///
15/// A rule replaces a string by another one. At each position of a surface
16/// the longest rule that matches there is applied; where none matches, one
17/// character is kept as it is. The result of a rule is not looked at
18/// again. An empty table changes nothing, which is what the schemas of
19/// this crate have: they recognize a mark in its full-width and its
20/// half-width form instead.
21///
22/// The table is there for models made by another program that normalizes:
23/// CaboCha writes the half-width katakana in full width, and the
24/// full-width letters, digits and signs in ASCII, before it makes a
25/// feature. A model converted from CaboCha carries CaboCha's table, so
26/// that its features are the ones CaboCha makes.
27///
28/// # Examples
29///
30/// ```
31/// use lindera_dependency::schema::Normalization;
32///
33/// let table = Normalization::new(&[("カ", "カ"), ("ガ", "ガ"), ("1", "1")]).unwrap();
34/// // The longest rule first: ガ is ガ, not カ and a mark.
35/// assert_eq!(table.apply("ガカ1番"), "ガカ1番");
36/// assert_eq!(Normalization::default().apply("ガ"), "ガ");
37/// ```
38#[derive(Debug, Clone, PartialEq, Eq, Default)]
39pub struct Normalization {
40    /// The rules, sorted by the bytes of what they replace, each once.
41    rules: Vec<(String, String)>,
42    /// The number of bytes of the longest string a rule replaces.
43    longest: usize,
44}
45
46impl Normalization {
47    /// Makes a table.
48    ///
49    /// # Arguments
50    ///
51    /// * `rules` - The rules: what is replaced, and by what. Their order
52    ///   does not matter. A rule given twice with the same result is one
53    ///   rule.
54    ///
55    /// # Returns
56    ///
57    /// The table, or [`Error::Schema`] for a rule that replaces an empty
58    /// string, or for two rules that replace the same string by different
59    /// ones.
60    pub fn new(rules: &[(&str, &str)]) -> Result<Self> {
61        let mut sorted: Vec<(String, String)> = rules
62            .iter()
63            .map(|(from, to)| (from.to_string(), to.to_string()))
64            .collect();
65        sorted.sort();
66        sorted.dedup();
67        Self::from_sorted(sorted)
68    }
69
70    /// Makes a table from rules that are sorted.
71    ///
72    /// # Arguments
73    ///
74    /// * `rules` - The rules, sorted by what they replace.
75    ///
76    /// # Returns
77    ///
78    /// The table, or [`Error::Schema`] for a rule that replaces an empty
79    /// string, or for rules that are not sorted with each string once.
80    fn from_sorted(rules: Vec<(String, String)>) -> Result<Self> {
81        if let Some((_, to)) = rules.iter().find(|(from, _)| from.is_empty()) {
82            return Err(Error::Schema(format!(
83                "a rule of the normalization replaces an empty string by {to:?}"
84            )));
85        }
86        if let Some(pair) = rules.windows(2).find(|pair| pair[0].0 >= pair[1].0) {
87            return Err(Error::Schema(format!(
88                "the rules of the normalization replace {:?} twice, or are not sorted",
89                pair[1].0
90            )));
91        }
92        let longest = rules.iter().map(|(from, _)| from.len()).max().unwrap_or(0);
93        Ok(Self { rules, longest })
94    }
95
96    /// Whether the table has no rule, and changes nothing.
97    ///
98    /// # Returns
99    ///
100    /// Whether it is empty.
101    pub fn is_empty(&self) -> bool {
102        self.rules.is_empty()
103    }
104
105    /// The rules of the table: what is replaced, and by what, sorted by
106    /// the bytes of what is replaced.
107    ///
108    /// # Returns
109    ///
110    /// The rules.
111    pub fn rules(&self) -> impl Iterator<Item = (&str, &str)> {
112        self.rules
113            .iter()
114            .map(|(from, to)| (from.as_str(), to.as_str()))
115    }
116
117    /// Normalizes a surface.
118    ///
119    /// # Arguments
120    ///
121    /// * `surface` - The surface.
122    ///
123    /// # Returns
124    ///
125    /// The surface with the rules applied; the surface itself, borrowed,
126    /// when no rule matches in it.
127    pub fn apply<'a>(&self, surface: &'a str) -> Cow<'a, str> {
128        if self.rules.is_empty() {
129            return Cow::Borrowed(surface);
130        }
131        let mut output: Option<String> = None;
132        let mut position = 0;
133        while position < surface.len() {
134            let rest = &surface[position..];
135            let step = match self.longest_rule(rest) {
136                Some((from, to)) => {
137                    output
138                        .get_or_insert_with(|| surface[..position].to_string())
139                        .push_str(to);
140                    from.len()
141                }
142                None => {
143                    let step = rest.chars().next().map_or(1, char::len_utf8);
144                    if let Some(output) = output.as_mut() {
145                        output.push_str(&rest[..step]);
146                    }
147                    step
148                }
149            };
150            position += step;
151        }
152        output.map_or(Cow::Borrowed(surface), Cow::Owned)
153    }
154
155    /// The longest rule that matches at the start of a string.
156    ///
157    /// # Arguments
158    ///
159    /// * `rest` - The string.
160    ///
161    /// # Returns
162    ///
163    /// What the rule replaces and by what, or `None` when no rule matches.
164    fn longest_rule(&self, rest: &str) -> Option<(&str, &str)> {
165        let mut end = self.longest.min(rest.len());
166        while end > 0 {
167            if rest.is_char_boundary(end) {
168                let prefix = &rest[..end];
169                if let Ok(index) = self
170                    .rules
171                    .binary_search_by(|(from, _)| from.as_str().cmp(prefix))
172                {
173                    let (from, to) = &self.rules[index];
174                    return Some((from.as_str(), to.as_str()));
175                }
176            }
177            end -= 1;
178        }
179        None
180    }
181
182    /// Appends the table to the bytes of a schema: the number of rules,
183    /// then for each what it replaces and by what.
184    ///
185    /// # Arguments
186    ///
187    /// * `bytes` - The bytes to append to.
188    pub(super) fn write(&self, bytes: &mut Vec<u8>) {
189        push_u32(bytes, self.rules.len() as u32);
190        for (from, to) in &self.rules {
191            push_string(bytes, from);
192            push_string(bytes, to);
193        }
194    }
195
196    /// Reads a table from the bytes of a schema.
197    ///
198    /// # Arguments
199    ///
200    /// * `reader` - The bytes, at the table.
201    ///
202    /// # Returns
203    ///
204    /// The table, or the error of bytes that are not one.
205    pub(super) fn read(reader: &mut Reader) -> Result<Self> {
206        let count = reader.u32()?;
207        if count > MAX_RULES {
208            return Err(reader.error(format_args!(
209                "has {count} rules of normalization, more than {MAX_RULES}"
210            )));
211        }
212        let mut rules = Vec::new();
213        for _ in 0..count {
214            let from = reader.string()?;
215            let to = reader.string()?;
216            rules.push((from, to));
217        }
218        Self::from_sorted(rules).map_err(|error| {
219            reader.error(format_args!("has a normalization that is not one: {error}"))
220        })
221    }
222}
223
224#[cfg(test)]
225mod tests {
226    use super::*;
227
228    #[test]
229    fn the_longest_rule_at_a_position_is_applied() {
230        let table = Normalization::new(&[("カ", "カ"), ("ガ", "ガ"), ("゙", "゛")]).unwrap();
231        assert_eq!(table.apply("ガ"), "ガ");
232        assert_eq!(table.apply("カ"), "カ");
233        assert_eq!(table.apply("カガ゙"), "カガ゛");
234    }
235
236    #[test]
237    fn what_no_rule_matches_is_kept() {
238        let table = Normalization::new(&[("1", "1"), (" ", "___")]).unwrap();
239        assert_eq!(table.apply("第10回 大会"), "第10回___大会");
240        assert_eq!(table.apply(""), "");
241    }
242
243    #[test]
244    fn the_result_of_a_rule_is_not_normalized_again() {
245        let table = Normalization::new(&[("a", "b"), ("b", "c")]).unwrap();
246        assert_eq!(table.apply("ab"), "bc");
247    }
248
249    #[test]
250    fn a_surface_without_a_match_is_borrowed() {
251        let table = Normalization::new(&[("1", "1")]).unwrap();
252        assert!(matches!(table.apply("読ん"), Cow::Borrowed("読ん")));
253        assert!(matches!(table.apply("1"), Cow::Owned(_)));
254        assert!(matches!(
255            Normalization::default().apply("1"),
256            Cow::Borrowed("1")
257        ));
258    }
259
260    #[test]
261    fn an_empty_table_changes_nothing() {
262        let table = Normalization::default();
263        assert!(table.is_empty());
264        assert_eq!(table.apply("ガ1 "), "ガ1 ");
265        assert_eq!(table, Normalization::new(&[]).unwrap());
266    }
267
268    #[test]
269    fn the_rules_are_sorted_and_each_is_there_once() {
270        let table = Normalization::new(&[("イ", "イ"), ("ア", "ア"), ("イ", "イ")]).unwrap();
271        let rules: Vec<(&str, &str)> = table.rules().collect();
272        assert_eq!(rules, [("ア", "ア"), ("イ", "イ")]);
273        assert!(!table.is_empty());
274    }
275
276    #[test]
277    fn refuses_rules_that_are_not_a_table() {
278        let error = Normalization::new(&[("", "x")]).unwrap_err();
279        assert!(error.to_string().contains("empty string"), "{error}");
280        let error = Normalization::new(&[("a", "x"), ("a", "y")]).unwrap_err();
281        assert!(error.to_string().contains("\"a\" twice"), "{error}");
282    }
283
284    #[test]
285    fn a_table_is_read_as_it_was_written() {
286        let table = Normalization::new(&[("ガ", "ガ"), ("1", "1"), (" ", "___")]).unwrap();
287        let mut bytes = Vec::new();
288        table.write(&mut bytes);
289        let mut reader = Reader::new(&bytes, "model", Error::Model);
290        assert_eq!(Normalization::read(&mut reader).unwrap(), table);
291
292        let mut bytes = Vec::new();
293        Normalization::default().write(&mut bytes);
294        assert_eq!(bytes, [0, 0, 0, 0]);
295    }
296
297    #[test]
298    fn refuses_bytes_that_are_not_a_table() {
299        // Two rules that are not sorted.
300        let mut bytes = Vec::new();
301        push_u32(&mut bytes, 2);
302        for text in ["b", "x", "a", "y"] {
303            push_string(&mut bytes, text);
304        }
305        let error =
306            Normalization::read(&mut Reader::new(&bytes, "model", Error::Model)).unwrap_err();
307        assert!(error.to_string().contains("normalization"), "{error}");
308
309        // More rules than a table may have.
310        let mut bytes = Vec::new();
311        push_u32(&mut bytes, MAX_RULES + 1);
312        let error =
313            Normalization::read(&mut Reader::new(&bytes, "model", Error::Model)).unwrap_err();
314        assert!(
315            error.to_string().contains("rules of normalization"),
316            "{error}"
317        );
318
319        // A table that ends before its rules.
320        let mut bytes = Vec::new();
321        push_u32(&mut bytes, 1);
322        assert!(Normalization::read(&mut Reader::new(&bytes, "model", Error::Model)).is_err());
323    }
324}