Debian Codegraph @

debian/missing-sources/generate-sources/src/main.rs

raw symbols SCIP
1 use std::collections::HashMap;
2 use std::env;
3 use std::ffi::{OsStr, OsString};
4 use std::fs::File;
5 use std::io::{BufRead, BufReader,Write};
6 use std::ops::RangeInclusive;
7 use std::path::{Path, PathBuf};
8 // use reqwest::blocking::Client;
9 use itertools::Itertools;
10
11 fn main() -> anyhow::Result<()> {
12 let unicode_version = "17.0.0";
13 let mut out_dir = env::var_os("CARGO_MANIFEST_DIR").unwrap();
14 out_dir.push("/target/tmp/");
15 if !Path::new(&out_dir).try_exists()? {
16 std::fs::create_dir(&out_dir)?;
17 }
18 let mut code_dir = env::var_os("CARGO_MANIFEST_DIR").unwrap();
19 code_dir.push("/../src/data/");
20 if !Path::new(&code_dir).try_exists()? {
21 std::fs::create_dir(&code_dir)?;
22 }
23 let data_dir = Path::new(&out_dir).join("data").join(unicode_version);
24 std::fs::create_dir_all(&data_dir)?;
25 let unicode_data_txt = data_dir.join("UnicodeData.txt");
26 let grapheme_break_test_txt = data_dir.join("GraphemeBreakTest.txt");
27 let grapheme_break_property_txt = data_dir.join("GraphemeBreakProperty.txt");
28 let derived_core_properties_txt = data_dir.join("DerivedCoreProperties.txt");
29 let emoji_data_txt = data_dir.join("emoji-data.txt");
30
31
32 // eprintln!("Downloading Unicode data...");
33 // download_unicode_data(&unicode_data_txt, "ucd/UnicodeData.txt", unicode_version)?;
34 eprintln!("Generating category data...");
35 build_character_tables(&code_dir, &unicode_data_txt)?;
36 // eprintln!("Downloading grapheme test data...");
37 // download_unicode_data(&grapheme_break_test_txt, "ucd/auxiliary/GraphemeBreakTest.txt", unicode_version)?;
38 eprintln!("Generating grapheme tests...");
39 build_grapheme_break_test(&code_dir, &grapheme_break_test_txt)?;
40 // eprintln!("Downloading grapheme break properties...");
41 // download_unicode_data(&grapheme_break_property_txt, "ucd/auxiliary/GraphemeBreakProperty.txt", unicode_version)?;
42 // eprintln!("Downloading emoji data...");
43 // download_unicode_data(&emoji_data_txt, "ucd/emoji/emoji-data.txt", unicode_version)?;
44 // eprintln!("Downloading derived core properties...");
45 // download_unicode_data(&derived_core_properties_txt, "ucd/DerivedCoreProperties.txt", unicode_version)?;
46 eprintln!("Generating grapheme break data...");
47 build_grapheme_break_property(&code_dir, &grapheme_break_property_txt, &emoji_data_txt, &derived_core_properties_txt)?;
48 Ok(())
49 }
50
51
52 // We store the category code as a u8 value with the following meaning:
53 // High nibble:
54 // - 1 mark
55 // - 2 Number
56 // - 3 Punctuation
57 // - 4 Symbol
58 // - 5 Separator
59 // - 6 Control
60 // - 7 Control
61 // - 8 Letter
62 // - 9 Cased letter
63 //
64 // code & xF0 to get the larger category.
65 // 8/9 for letters allows us to do code & x80 to see if its a letter
66 //
67 // Specific codes map as follows:
68 // Lu Uppercase_Letter x90
69 // Ll Lowercase_Letter x91
70 // Lt Titlecase_Letter x92
71 // Lm Modifier_Letter x80
72 // Lo Other_Letter x81
73 // Mn Nonspacing_Mark x10
74 // Mc Spacing_Mark x11
75 // Me Enclosing_Mark x12
76 // Nd Decimal_Number x20
77 // Nl Letter_Number x21
78 // No Other_Number x22
79 // Pc Connector_Punctuation x30
80 // Pd Dash_Punctuation x31
81 // Ps Open_Punctuation x32
82 // Pe Close_Punctuation x33
83 // Pi Initial_Punctuation x34
84 // Pf Final_Punctuation x35
85 // Po Other_Punctuation x36
86 // Sm Math_Symbol x40
87 // Sc Currency_Symbol x41
88 // Sk Modifier_Symbol x42
89 // So Other_Symbol x43
90 // Zs Space_Separator x50
91 // Zl Line_Separator x51
92 // Zp Paragraph_Separator x52
93 // Cc Control x60
94 // Cf Format x61
95 // Cs Surrogate x62
96 // Co Private_Use x63
97 // Cn Unassigned x64
98 fn cat_to_u8(cat: &str) -> u8 {
99 match cat {
100 "Lu" => 0x90,
101 "Ll" => 0x91,
102 "Lt" => 0x92,
103 "Lm" => 0x83,
104 "Lo" => 0x84,
105 "Mn" => 0x10,
106 "Mc" => 0x11,
107 "Me" => 0x12,
108 "Nd" => 0x20,
109 "Nl" => 0x21,
110 "No" => 0x22,
111 "Pc" => 0x30,
112 "Pd" => 0x31,
113 "Ps" => 0x32,
114 "Pe" => 0x33,
115 "Pi" => 0x34,
116 "Pf" => 0x35,
117 "Po" => 0x36,
118 "Sm" => 0x40,
119 "Sc" => 0x41,
120 "Sk" => 0x42,
121 "So" => 0x43,
122 "Zs" => 0x50,
123 "Zl" => 0x51,
124 "Zp" => 0x52,
125 "Cc" => 0x61,
126 "Cf" => 0x62,
127 "Cs" => 0x63,
128 "Co" => 0x64,
129 _ => 0x60 // Anything we don't recognize is x60, which is Cn - Unassigned
130 }
131 }
132
133 // Credit to https://here-be-braces.com/fast-lookup-of-unicode-properties/ for the broad outline of
134 // how this would work. The coding of categories into bytes is my own.
135 fn build_character_tables(out_dir: &OsStr, unicode_data_txt: &PathBuf) -> anyhow::Result<()> {
136 let characters_rs = Path::new(out_dir).join("characters.rs");
137 let characters_rs = File::create(characters_rs)?;
138 let unicode_data = File::open(unicode_data_txt)?;
139 let unicode_data = BufReader::new(unicode_data);
140
141 // First we build a raw (large) index of all the character codes in numeric format
142 // Note that we actually allocate an array slightly larger than Unicode uses
143 let mut raw_categories = [0x60u8;0x110000];
144 let mut range_start = 0;
145 for line in unicode_data.lines() {
146 let line = line.unwrap();
147 let mut fields = line.split(";");
148 let char_code = fields.next();
149 let char_name = fields.next();
150 let category = fields.next().unwrap();
151 if let Some(char_code) = char_code {
152 let char_code = usize::from_str_radix(char_code, 16)?;
153 if let Some(char_name) = char_name {
154 if char_name.ends_with(", First>") {
155 range_start = char_code;
156 }
157 else if char_name.ends_with(", Last>") {
158 let cat_code = cat_to_u8(category);
159 for i in range_start..=char_code {
160 raw_categories[i] = cat_code;
161 }
162 }
163 else {
164 raw_categories[char_code] = cat_to_u8(category);
165 }
166 }
167 }
168 }
169
170 write_data_tables(characters_rs, &raw_categories, "CAT_TABLE", "CAT_PAGES")
171 }
172
173 fn build_grapheme_break_test(out_dir: &OsString, grapheme_break_test_txt: &PathBuf) -> anyhow::Result<()> {
174 let grapheme_test_rs = Path::new(out_dir).join("grapheme_test.rs");
175 let mut grapheme_test_rs = File::create(grapheme_test_rs)?;
176 let grapheme_break_test = File::open(grapheme_break_test_txt)?;
177 let grapheme_break_test = BufReader::new(grapheme_break_test);
178 // let mut grapheme_bench_txt = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
179 // grapheme_bench_txt.push("..");
180 // grapheme_bench_txt.push("resources");
181 // grapheme_bench_txt.push("graphemes.txt");
182 // let mut grapheme_bench_txt = File::create(grapheme_bench_txt)?;
183
184 // writeln!(grapheme_bench_txt, "Automatically generated data file DO NOT EDIT MANUALLY")?;
185
186 writeln!(grapheme_test_rs, "// GENERATED CODE DO NOT MANUALLY EDIT")?;
187 writeln!(grapheme_test_rs)?;
188 writeln!(grapheme_test_rs, "use crate::grapheme_clusters::tests::grapheme_test;")?;
189 writeln!(grapheme_test_rs)?;
190 writeln!(grapheme_test_rs, "#[test]")?;
191 writeln!(grapheme_test_rs, "fn standard_grapheme_test() {{")?;
192 for line in grapheme_break_test.lines() {
193 let line = line.unwrap();
194 if let Some((map, comment)) = line.split_once('#') {
195 if map.len() > 0 {
196 let mut input_string = String::new();
197 let mut output_string:Vec<String> = vec!();
198 let mut current_grapheme = String::new();
199 // writeln!(grapheme_bench_txt, "{}", map)?;
200 for token in map.split_whitespace() {
201 match token {
202 "÷" => {
203 if current_grapheme.len() > 0 {
204 output_string.push(current_grapheme);
205 current_grapheme = String::new();
206 }
207 }
208 "×" => {} // No action necessary here (!)
209 hex_code => {
210 // write!(grapheme_bench_txt, "{}", char::from_u32(u32::from_str_radix(hex_code, 16).unwrap()).unwrap())?;
211 let hex_code = "\\u{".to_string() + hex_code + "}";
212 input_string.push_str(&hex_code);
213 current_grapheme.push_str(&hex_code);
214 }
215 }
216 }
217 // writeln!(grapheme_bench_txt)?;
218 let output_string = output_string.join("\", \"");
219
220 writeln!(grapheme_test_rs, "\tgrapheme_test(\"{input_string}\",\n\t\t&[\"{output_string}\"],\n\t\t\"{comment}\"\n\t);")?;
221 }
222 }
223 }
224 writeln!(grapheme_test_rs, "}}")?;
225 Ok(())
226 }
227
228
229 fn encode_property(property: &str) -> u8 {
230 match property {
231 "Prepend" => 0x05,
232 "CR" => 0x04,
233 "LF" => 0x04,
234 "Control" => 0x04,
235 "Extend" => 0x01,
236 "SpacingMark" => 0x02,
237 "L" => 0x0c,
238 "V" => 0x08,
239 "T" => 0x09,
240 "LV" => 0x0d,
241 "LVT" => 0x0e,
242 "ZWJ" => 0x03,
243 "Extended_Grapheme" => 0x06,
244 "Regional_Indicator" => 0x07,
245 _ => 0x00,
246 }
247 }
248
249 fn str_to_range(range: &str) -> RangeInclusive<usize> {
250 if let Some((first, last)) = range.split_once("..") {
251 u32::from_str_radix(first, 16).unwrap() as usize ..=
252 u32::from_str_radix(last,16).unwrap() as usize
253 }
254 else {
255 let val = u32::from_str_radix(range, 16).unwrap() as usize;
256 val..=val
257 }
258 }
259
260 fn build_grapheme_break_property(out_dir: &OsString, grapheme_break_property_txt: &PathBuf, emoji_data_txt: &PathBuf, derived_core_properties_txt: &PathBuf) -> anyhow::Result<()> {
261 let grapheme_property_rs = Path::new(out_dir).join("grapheme_property.rs");
262 let grapheme_property_rs = File::create(grapheme_property_rs)?;
263 let grapheme_break_property = File::open(grapheme_break_property_txt)?;
264 let grapheme_break_property = BufReader::new(grapheme_break_property);
265 let emoji_data = File::open(emoji_data_txt)?;
266 let emoji_data = BufReader::new(emoji_data);
267 let derived_core_properties = File::open(derived_core_properties_txt)?;
268 let derived_core_properties = BufReader::new(derived_core_properties);
269
270 // first pass: build an array of all the properties
271 let mut raw_grapheme_properties = [0u8;0x110000];
272 for line in grapheme_break_property.lines() {
273 let line = line.unwrap();
274 if let Some((line, _)) = line.split_once('#') {
275 if let Some((range, property)) = line.split_once(';') {
276 let range = range.trim();
277 let property = property.trim();
278 raw_grapheme_properties.get_mut(str_to_range(range)).unwrap().fill(encode_property(property));
279 }
280 }
281 }
282
283 // add extended graphemes from emoji data
284 for line in emoji_data.lines() {
285 let line = line.unwrap();
286 if let Some((line, _)) = line.split_once('#') {
287 if let Some((range, property)) = line.split_once(';') {
288 let range = range.trim();
289 let property = property.trim();
290 if property == "Extended_Pictographic" {
291 raw_grapheme_properties.get_mut(str_to_range(range)).unwrap().fill(0x06);
292 }
293 }
294 }
295 }
296
297 // update conjunct cluster characteristics
298 // We set the high nibble to 2x for consonants and 1x for linkers
299 for line in derived_core_properties.lines() {
300 let line = line.unwrap();
301 if let Some((line, _)) = line.split_once('#') {
302 if let Some((range, property)) = line.split_once(';') {
303 let range = range.trim();
304 let property = property.trim();
305 if property == "InCB; Linker" {
306 raw_grapheme_properties.get_mut(str_to_range(range)).unwrap().iter_mut().for_each(|x| *x |= 0x10);
307
308 }
309 if property == "InCB; Consonant" {
310 raw_grapheme_properties.get_mut(str_to_range(range)).unwrap().iter_mut().for_each(|x| *x |= 0x20);
311 }
312 }
313 }
314 }
315
316 write_data_tables(grapheme_property_rs, &raw_grapheme_properties, "GP_TABLE", "GP_PAGES")
317 }
318
319 fn write_data_tables(mut rust_file : File, raw_data: &[u8], table_name: &str, pages_name: &str) -> anyhow::Result<()> {
320 writeln!(rust_file, "// GENERATED CODE DO NOT MANUALLY EDIT")?;
321 writeln!(rust_file, "pub const {table_name}: [u8;0x1100] = [")?;
322 let mut page_index = HashMap::new();
323 let mut page_number = 0u8;
324 for page in 0 .. 0x1100 {
325 let page_start = page << 8;
326 let page_data = raw_data[page_start..page_start+0x100].to_vec();
327 let &mut page_ref = page_index.entry(page_data).or_insert(page_number);
328 if page_ref == page_number {
329 page_number += 1
330 }
331 writeln!(rust_file, "\t {page_ref}, // {page:#x}")?;
332 }
333 writeln!(rust_file, "];")?;
334 let pages = page_index.iter()
335 .map(|(k, v)| (v,k))
336 .sorted_by(|(a,_),(b,_)| Ord::cmp(a,b))
337 .map(|(_, page)| page )
338 .collect_vec();
339 writeln!(rust_file, "pub const {pages_name}: [[u8;256];{}] = {pages:#x?};", pages.len())?;
340 Ok(())
341 }
342
343 // fn download_unicode_data(local_txt_data_file: &PathBuf, remote_txt_data_file: &str, unicode_version: &str) -> anyhow::Result<()> {
344 // let url_base = "https://www.unicode.org/Public/".to_owned() + unicode_version + "/";
345 // let client = Client::new();
346 // if !local_txt_data_file.exists() {
347 // let mut remote_data = client.get(url_base.clone() + remote_txt_data_file).send()?;
348 // let mut file = File::create(local_txt_data_file)?;
349 // std::io::copy(&mut remote_data, &mut file)?;
350 // }
351 // Ok(())
352 // }