Debian Codegraph @

third_party/rust/mapped_hyph/src/builder.rs

raw
1 // Copyright 2019-2020 Mozilla Foundation. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 /// Functions to compile human-readable patterns into a mapped_hyph
11 /// flattened representation of the hyphenation state machine.
12
13 use std::io::{Read,BufRead,BufReader,Write,Error,ErrorKind};
14 use std::collections::HashMap;
15 use std::convert::TryInto;
16 use std::hash::{Hash,Hasher};
17
18 // Wrap a HashMap so that we can implement the Hash trait.
19 #[derive(PartialEq, Eq, Clone)]
20 struct TransitionMap (HashMap<u8,i32>);
21
22 impl TransitionMap {
23 fn new() -> TransitionMap {
24 TransitionMap(HashMap::<u8,i32>::new())
25 }
26 }
27
28 impl Hash for TransitionMap {
29 fn hash<H: Hasher>(&self, state: &mut H) {
30 // We only look at the values here; that's likely to be enough
31 // for a reasonable hash.
32 let mut transitions: Vec<&i32> = self.0.values().collect();
33 transitions.sort();
34 for t in transitions {
35 t.hash(state);
36 }
37 }
38 }
39
40 #[derive(PartialEq, Eq, Hash, Clone)]
41 struct State {
42 match_string: Option<Vec<u8>>,
43 #[allow(dead_code)]
44 repl_string: Option<Vec<u8>>,
45 #[allow(dead_code)]
46 repl_index: i32,
47 #[allow(dead_code)]
48 repl_cut: i32,
49 fallback_state: i32,
50 transitions: TransitionMap,
51 }
52
53 impl State {
54 fn new() -> State {
55 State {
56 match_string: None,
57 repl_string: None,
58 repl_index: -1,
59 repl_cut: -1,
60 fallback_state: -1,
61 transitions: TransitionMap::new(),
62 }
63 }
64 }
65
66 /// Structures returned by the read_dic_file() function;
67 /// array of these can then be passed to write_hyf_file()
68 /// to create the flattened output.
69 struct LevelBuilder {
70 states: Vec<State>,
71 str_to_state: HashMap<Vec<u8>,i32>,
72 encoding: Option<String>,
73 nohyphen: Option<String>,
74 lh_min: u8,
75 rh_min: u8,
76 clh_min: u8,
77 crh_min: u8,
78 }
79
80 impl LevelBuilder {
81 fn new() -> LevelBuilder {
82 let mut result = LevelBuilder {
83 states: Vec::<State>::new(),
84 str_to_state: HashMap::<Vec<u8>,i32>::new(),
85 encoding: None,
86 nohyphen: None,
87 lh_min: 0,
88 rh_min: 0,
89 clh_min: 0,
90 crh_min: 0,
91 };
92 // Initialize the builder with an empty start state.
93 result.str_to_state.insert(vec![], 0);
94 result.states.push(State::new());
95 result
96 }
97
98 fn find_state_number_for(&mut self, text: &[u8]) -> i32 {
99 let count = self.states.len() as i32;
100 let index = *self.str_to_state.entry(text.to_vec()).or_insert(count);
101 if index == count {
102 self.states.push(State::new());
103 }
104 index
105 }
106
107 fn add_pattern(&mut self, pattern: &str) {
108 let mut bytes = pattern.as_bytes();
109 let mut text = Vec::<u8>::with_capacity(bytes.len());
110 let mut digits = Vec::<u8>::with_capacity(bytes.len() + 1);
111 let mut repl_str = None;
112 let mut repl_index = 0;
113 let mut repl_cut = 0;
114
115 // Check for replacement rule (non-standard hyphenation spelling change).
116 if let Some(slash) = bytes.iter().position(|x| *x == b'/') {
117 let parts = bytes.split_at(slash);
118 bytes = parts.0;
119 let mut it = parts.1[1 ..].split(|x| *x == b',');
120 if let Some(repl) = it.next() {
121 repl_str = Some(repl.to_vec());
122 }
123 if let Some(num) = it.next() {
124 repl_index = std::str::from_utf8(num).unwrap().parse::<i32>().unwrap() - 1;
125 }
126 if let Some(num) = it.next() {
127 repl_cut = std::str::from_utf8(num).unwrap().parse::<i32>().unwrap();
128 }
129 }
130
131 // Separate the input pattern into parallel arrays of text (bytes) and digits.
132 let mut got_digit = false;
133 for byte in bytes {
134 if *byte <= b'9' && *byte >= b'0' {
135 if got_digit {
136 warn!("invalid pattern \"{}\": consecutive digits", pattern);
137 return;
138 }
139 digits.push(*byte);
140 got_digit = true;
141 } else {
142 text.push(*byte);
143 if got_digit {
144 got_digit = false;
145 } else {
146 digits.push(b'0');
147 }
148 }
149 }
150 if !got_digit {
151 digits.push(b'0');
152 }
153
154 if repl_str.is_none() {
155 // Optimize away leading zeroes from the digits array.
156 while !digits.is_empty() && digits[0] == b'0' {
157 digits.remove(0);
158 }
159 } else {
160 // Convert repl_index and repl_cut from Unicode char to byte indexing.
161 let start = if text[0] == b'.' { 1 } else { 0 };
162 if start == 1 {
163 if digits[0] != b'0' {
164 warn!("invalid pattern \"{}\": unexpected digit before start of word", pattern);
165 return;
166 }
167 digits.remove(0);
168 }
169 let word = std::str::from_utf8(&text[start..]).unwrap();
170 let mut chars: Vec<_> = word.char_indices().collect();
171 chars.push((word.len(), '.'));
172 repl_cut = chars[(repl_index + repl_cut) as usize].0 as i32 - chars[repl_index as usize].0 as i32;
173 repl_index = chars[repl_index as usize].0 as i32;
174 }
175
176 // Create the new state, or add pattern into an existing state
177 // (which should not already have a match_string).
178 let mut state_num = self.find_state_number_for(&text);
179 let mut state = &mut self.states[state_num as usize];
180 if state.match_string.is_some() {
181 warn!("duplicate pattern \"{}\" discarded", pattern);
182 return;
183 }
184 if !digits.is_empty() {
185 state.match_string = Some(digits);
186 }
187 if repl_str.is_some() {
188 state.repl_string = repl_str;
189 state.repl_index = repl_index;
190 state.repl_cut = repl_cut;
191 }
192
193 // Set up prefix transitions, inserting additional states as needed.
194 while !text.is_empty() {
195 let last_state = state_num;
196 let ch = *text.last().unwrap();
197 text.truncate(text.len() - 1);
198 state_num = self.find_state_number_for(&text);
199 if let Some(exists) = self.states[state_num as usize].transitions.0.insert(ch, last_state) {
200 assert_eq!(exists, last_state, "overwriting existing transition at pattern \"{}\"", pattern);
201 break;
202 }
203 }
204 }
205
206 fn merge_duplicate_states(&mut self) {
207 // We loop here because when we eliminate a duplicate, and update the transitons
208 // that referenced it, we may thereby create new duplicates that another pass
209 // will find and compress further.
210 loop {
211 let orig_len = self.states.len();
212 // Used to map State records to the (first) index at which they occur.
213 let mut state_to_index = HashMap::<&State,i32>::new();
214 // Mapping of old->new state indexes, and whether each old state is
215 // a duplicate that should be dropped.
216 let mut mappings = Vec::<(i32,bool)>::with_capacity(orig_len);
217 let mut next_new_index: i32 = 0;
218 for index in 0 .. self.states.len() {
219 // Find existing index for this state, or allocate the next new index to it.
220 let new_index = *state_to_index.entry(&self.states[index]).or_insert(next_new_index);
221 // Record the mapping, and whether the state was a duplicate.
222 mappings.push((new_index, new_index != next_new_index));
223 // If we used next_new_index for this state, increment it.
224 if new_index == next_new_index {
225 next_new_index += 1;
226 }
227 }
228 // If we didn't find any duplicates, next_new_index will have kept pace with
229 // index, so we know we're finished.
230 if next_new_index as usize == self.states.len() {
231 break;
232 }
233 // Iterate over all the states, either deleting them or updating indexes
234 // according to the mapping we created; then repeat the search.
235 for index in (0 .. self.states.len()).rev() {
236 if mappings[index].1 {
237 self.states.remove(index);
238 } else {
239 let state = &mut self.states[index];
240 if state.fallback_state != -1 {
241 state.fallback_state = mappings[state.fallback_state as usize].0;
242 }
243 for t in state.transitions.0.iter_mut() {
244 *t.1 = mappings[*t.1 as usize].0;
245 }
246 }
247 }
248 }
249 }
250
251 fn flatten(&self) -> Vec<u8> {
252 // Calculate total space needed for state data, and build the state_to_offset table.
253 let mut state_data_size = 0;
254 let mut state_to_offset = Vec::<usize>::with_capacity(self.states.len());
255 for state in &self.states {
256 state_to_offset.push(state_data_size);
257 state_data_size += if state.repl_string.is_some() { 12 } else { 8 };
258 state_data_size += state.transitions.0.len() * 4;
259 }
260
261 // Helper to map a state index to its offset in the final data block.
262 let get_state_offset_for = |state_index: i32| -> u32 {
263 if state_index < 0 {
264 return super::INVALID_STATE_OFFSET;
265 }
266 state_to_offset[state_index as usize] as u32
267 };
268
269 // Helper to map a byte string to its offset in the final data block, and
270 // store the bytes into string_data unless using an already-existing string.
271 let mut string_to_offset = HashMap::<Vec<u8>,usize>::new();
272 let mut string_data = Vec::<u8>::new();
273 let mut get_string_offset_for = |bytes: &Option<Vec<u8>>| -> u16 {
274 if bytes.is_none() {
275 return super::INVALID_STRING_OFFSET;
276 }
277 assert!(bytes.as_ref().unwrap().len() < 256);
278 let new_offset = string_data.len();
279 let offset = *string_to_offset.entry(bytes.as_ref().unwrap().clone()).or_insert(new_offset);
280 if offset == new_offset {
281 string_data.push(bytes.as_ref().unwrap().len() as u8);
282 string_data.extend_from_slice(bytes.as_ref().unwrap().as_ref());
283 }
284 offset.try_into().unwrap()
285 };
286
287 // Handle nohyphen string list if present, converting comma separators to NULs
288 // and trimming any surplus whitespace.
289 let mut nohyphen_string_offset: u16 = super::INVALID_STRING_OFFSET;
290 let mut nohyphen_count: u16 = 0;
291 if self.nohyphen.is_some() {
292 let nohyphen_strings: Vec<_> = self.nohyphen.as_ref().unwrap().split(',').map(|x| x.trim()).collect();
293 nohyphen_count = nohyphen_strings.len().try_into().unwrap();
294 nohyphen_string_offset = get_string_offset_for(&Some(nohyphen_strings.join("\0").as_bytes().to_vec()));
295 }
296
297 let mut state_data = Vec::<u8>::with_capacity(state_data_size);
298 for state in &self.states {
299 state_data.extend(&get_state_offset_for(state.fallback_state).to_le_bytes());
300 state_data.extend(&get_string_offset_for(&state.match_string).to_le_bytes());
301 state_data.push(state.transitions.0.len() as u8);
302 // Determine whether to use an extended state record, and if so add the
303 // replacement string and index fields.
304 if state.repl_string.is_none() {
305 state_data.push(0);
306 } else {
307 state_data.push(1);
308 state_data.extend(&get_string_offset_for(&state.repl_string).to_le_bytes());
309 state_data.push(state.repl_index as u8);
310 state_data.push(state.repl_cut as u8);
311 }
312 // Collect transitions into an array so we can sort them.
313 let mut transitions = vec![];
314 for (key, value) in state.transitions.0.iter() {
315 transitions.push((*key, get_state_offset_for(*value)))
316 }
317 transitions.sort();
318 for t in transitions {
319 // New state offset is stored as a 24-bit value, so we do this manually.
320 state_data.push((t.1 & 0xff) as u8);
321 state_data.push(((t.1 >> 8) & 0xff) as u8);
322 state_data.push(((t.1 >> 16) & 0xff) as u8);
323 state_data.push(t.0);
324 }
325 }
326 assert_eq!(state_data.len(), state_data_size);
327
328 // Pad string data to a 4-byte boundary
329 while string_data.len() & 3 != 0 {
330 string_data.push(0);
331 }
332
333 let total_size = super::LEVEL_HEADER_SIZE as usize + state_data_size + string_data.len();
334 let mut result = Vec::<u8>::with_capacity(total_size);
335
336 let state_data_base: u32 = super::LEVEL_HEADER_SIZE as u32;
337 let string_data_base: u32 = state_data_base + state_data_size as u32;
338
339 result.extend(&state_data_base.to_le_bytes());
340 result.extend(&string_data_base.to_le_bytes());
341 result.extend(&nohyphen_string_offset.to_le_bytes());
342 result.extend(&nohyphen_count.to_le_bytes());
343 result.push(self.lh_min);
344 result.push(self.rh_min);
345 result.push(self.clh_min);
346 result.push(self.crh_min);
347
348 result.extend(state_data.iter());
349 result.extend(string_data.iter());
350
351 assert_eq!(result.len(), total_size);
352
353 result
354 }
355 }
356
357 /// Read a libhyphen-style pattern file and create the corresponding state
358 /// machine transitions, etc.
359 /// The returned Vec can be passed to write_hyf_file() to generate a flattened
360 /// representation of the state machine in mapped_hyph's binary format.
361 fn read_dic_file<T: Read>(dic_file: T, compress: bool) -> Result<Vec<LevelBuilder>, &'static str> {
362 let reader = BufReader::new(dic_file);
363
364 let mut builders = Vec::<LevelBuilder>::new();
365 builders.push(LevelBuilder::new());
366 let mut builder = &mut builders[0];
367
368 for (index, line) in reader.lines().enumerate() {
369 let mut trimmed = line.unwrap().trim().to_string();
370 // Strip comments.
371 if let Some(i) = trimmed.find('%') {
372 trimmed = trimmed[..i].trim().to_string();
373 }
374 // Ignore empty lines.
375 if trimmed.is_empty() {
376 continue;
377 }
378 // Uppercase indicates keyword rather than pattern.
379 if trimmed.as_bytes()[0] >= b'A' && trimmed.as_bytes()[0] <= b'Z' {
380 // First line is encoding; we only support UTF-8.
381 if builder.encoding.is_none() {
382 if trimmed != "UTF-8" {
383 return Err("Only UTF-8 patterns are accepted!");
384 };
385 builder.encoding = Some(trimmed);
386 continue;
387 }
388 // Check for valid keyword-value pairs.
389 if trimmed.contains(' ') {
390 let parts: Vec<&str> = trimmed.split(' ').collect();
391 if parts.len() != 2 {
392 warn!("unrecognized keyword/values: {}", trimmed);
393 continue;
394 }
395 let keyword = parts[0];
396 let value = parts[1];
397 match keyword {
398 "LEFTHYPHENMIN" => builder.lh_min = value.parse::<u8>().unwrap(),
399 "RIGHTHYPHENMIN" => builder.rh_min = value.parse::<u8>().unwrap(),
400 "COMPOUNDLEFTHYPHENMIN" => builder.clh_min = value.parse::<u8>().unwrap(),
401 "COMPOUNDRIGHTHYPHENMIN" => builder.crh_min = value.parse::<u8>().unwrap(),
402 "NOHYPHEN" => builder.nohyphen = Some(trimmed),
403 _ => warn!("unknown keyword: {}", trimmed),
404 }
405 continue;
406 }
407 // Start a new hyphenation level?
408 if trimmed == "NEXTLEVEL" {
409 builders.push(LevelBuilder::new());
410 builder = builders.last_mut().unwrap();
411 continue;
412 }
413 warn!("unknown keyword: {}", trimmed);
414 continue;
415 }
416 // Patterns should always be provided in lowercase; complain if not, and discard
417 // the bad pattern.
418 if trimmed != trimmed.to_lowercase() {
419 warn!("pattern \"{}\" not lowercased at line {}", trimmed, index);
420 continue;
421 }
422 builder.add_pattern(&trimmed);
423 }
424
425 // Create default first (compound-word) level if only one level was provided.
426 // (Maybe this should be optional? Currently just copying libhyphen behavior.)
427 if builders.len() == 1 {
428 let (lh_min, rh_min, clh_min, crh_min) =
429 (builders[0].lh_min, builders[0].rh_min, builders[0].clh_min, builders[0].crh_min);
430 builders.insert(0, LevelBuilder::new());
431 builder = builders.first_mut().unwrap();
432 builder.add_pattern("1-1");
433 builder.add_pattern("1'1");
434 builder.add_pattern("1\u{2013}1"); // en-dash
435 builder.add_pattern("1\u{2019}1"); // curly apostrophe
436 builder.nohyphen = Some("',\u{2013},\u{2019},-".to_string());
437 builder.lh_min = lh_min;
438 builder.rh_min = rh_min;
439 builder.clh_min = if clh_min > 0 { clh_min } else if lh_min > 0 { lh_min } else { 3 };
440 builder.crh_min = if crh_min > 0 { crh_min } else if rh_min > 0 { rh_min } else { 3 };
441 }
442
443 // Put in fallback states in each builder.
444 for builder in &mut builders {
445 for (key, state_index) in builder.str_to_state.iter() {
446 if key.is_empty() {
447 continue;
448 }
449 let mut fallback_key = key.clone();
450 while !fallback_key.is_empty() {
451 fallback_key.remove(0);
452 if builder.str_to_state.contains_key(&fallback_key) {
453 break;
454 }
455 }
456 builder.states[*state_index as usize].fallback_state = builder.str_to_state[&fallback_key];
457 }
458 }
459
460 if compress {
461 // Merge duplicate states to reduce size.
462 for builder in &mut builders {
463 builder.merge_duplicate_states();
464 }
465 }
466
467 Ok(builders)
468 }
469
470 /// Write out the state machines representing a set of hyphenation rules
471 /// to the given output stream.
472 fn write_hyf_file<T: Write>(hyf_file: &mut T, levels: Vec<LevelBuilder>) -> std::io::Result<()> {
473 if levels.is_empty() {
474 return Err(Error::from(ErrorKind::InvalidData));
475 }
476 let mut flattened = vec![];
477 for level in levels {
478 flattened.push(level.flatten());
479 }
480 // Write file header: magic number, count of levels.
481 hyf_file.write_all(&[b'H', b'y', b'f', b'0'])?;
482 let level_count: u32 = flattened.len() as u32;
483 hyf_file.write_all(&level_count.to_le_bytes())?;
484 // Write array of offsets to each level. First level will begin immediately
485 // after the array of offsets.
486 let mut offset: u32 = super::FILE_HEADER_SIZE as u32 + 4 * level_count;
487 for flat in &flattened {
488 hyf_file.write_all(&offset.to_le_bytes())?;
489 offset += flat.len() as u32;
490 }
491 // Write the flattened data for each level.
492 for flat in &flattened {
493 hyf_file.write_all(&flat)?;
494 }
495 Ok(())
496 }
497
498 /// The public API to the compilation process: reads `dic_file` and writes compiled tables
499 /// to `hyf_file`. The `compress` param determines whether extra processing to reduce the
500 /// size of the output is performed.
501 pub fn compile<T1: Read, T2: Write>(dic_file: T1, hyf_file: &mut T2, compress: bool) -> std::io::Result<()> {
502 match read_dic_file(dic_file, compress) {
503 Ok(dic) => write_hyf_file(hyf_file, dic),
504 Err(e) => {
505 warn!("parse error: {}", e);
506 return Err(Error::from(ErrorKind::InvalidData))
507 }
508 }
509 }