Debian Codegraph @

scripts/unicode.py

raw symbols SCIP
1 #!/usr/bin/env python
2 #
3 # Copyright 2011-2015 The Rust Project Developers. See the COPYRIGHT
4 # file at the top-level directory of this distribution and at
5 # http://rust-lang.org/COPYRIGHT.
6 #
7 # Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
8 # http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
9 # <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
10 # option. This file may not be copied, modified, or distributed
11 # except according to those terms.
12 #
13 # This script uses the following Unicode tables:
14 # - DerivedCoreProperties.txt
15 # - Scripts.txt
16 # - SpecialCasing.txt
17 # - UnicodeData.txt
18 #
19 # Since this should not require frequent updates, we just store this
20 # out-of-line and check the tables.rs file into git.
21
22 import fileinput, re, os, sys, operator, datetime
23
24 preamble = '''// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
25 // file at the top-level directory of this distribution and at
26 // http://rust-lang.org/COPYRIGHT.
27 //
28 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
29 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
30 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
31 // option. This file may not be copied, modified, or distributed
32 // except according to those terms.
33
34 // NOTE: The following code was generated by "./unicode.py", do not edit directly
35
36 #![allow(missing_docs, non_upper_case_globals, non_snake_case)]
37
38 use crate::bool_trie::BoolTrie;
39 '''.format(year = datetime.datetime.now().year)
40
41 # Mapping taken from Table 12 from:
42 # http://www.unicode.org/reports/tr44/#General_Category_Values
43 expanded_categories = {
44 'Lu': ['LC', 'L'], 'Ll': ['LC', 'L'], 'Lt': ['LC', 'L'],
45 'Lm': ['L'], 'Lo': ['L'],
46 'Mn': ['M'], 'Mc': ['M'], 'Me': ['M'],
47 'Nd': ['N'], 'Nl': ['N'], 'No': ['N'],
48 'Pc': ['P'], 'Pd': ['P'], 'Ps': ['P'], 'Pe': ['P'],
49 'Pi': ['P'], 'Pf': ['P'], 'Po': ['P'],
50 'Sm': ['S'], 'Sc': ['S'], 'Sk': ['S'], 'So': ['S'],
51 'Zs': ['Z'], 'Zl': ['Z'], 'Zp': ['Z'],
52 'Cc': ['C'], 'Cf': ['C'], 'Cs': ['C'], 'Co': ['C'], 'Cn': ['C'],
53 }
54
55 # these are the surrogate codepoints, which are not valid rust characters
56 surrogate_codepoints = (0xd800, 0xdfff)
57
58 def fetch(f):
59 if not os.path.exists(os.path.basename(f)):
60 os.system("curl -O http://www.unicode.org/Public/UNIDATA/%s"
61 % f)
62
63 if not os.path.exists(os.path.basename(f)):
64 sys.stderr.write("cannot load %s" % f)
65 exit(1)
66
67 def is_surrogate(n):
68 return surrogate_codepoints[0] <= n <= surrogate_codepoints[1]
69
70 def load_unicode_data(f):
71 fetch(f)
72 gencats = {}
73 to_title = {}
74 combines = {}
75 canon_decomp = {}
76 compat_decomp = {}
77
78 udict = {}
79 range_start = -1
80 for line in fileinput.input(f):
81 data = line.split(';')
82 if len(data) != 15:
83 continue
84 cp = int(data[0], 16)
85 if is_surrogate(cp):
86 continue
87 if range_start >= 0:
88 for i in range(range_start, cp):
89 udict[i] = data
90 range_start = -1
91 if data[1].endswith(", First>"):
92 range_start = cp
93 continue
94 udict[cp] = data
95
96 for code in udict:
97 (code_org, name, gencat, combine, bidi,
98 decomp, deci, digit, num, mirror,
99 old, iso, upcase, lowcase, titlecase) = udict[code]
100
101 # title case
102 if titlecase.strip() != "" and code_org != titlecase:
103 to_title[code] = (int(titlecase, 16), 0, 0)
104
105 # store decomposition, if given
106 if decomp != "":
107 if decomp.startswith('<'):
108 seq = []
109 for i in decomp.split()[1:]:
110 seq.append(int(i, 16))
111 compat_decomp[code] = seq
112 else:
113 seq = []
114 for i in decomp.split():
115 seq.append(int(i, 16))
116 canon_decomp[code] = seq
117
118 # place letter in categories as appropriate
119 for cat in [gencat, "Assigned"] + expanded_categories.get(gencat, []):
120 if cat not in gencats:
121 gencats[cat] = []
122 gencats[cat].append(code)
123
124 # record combining class, if any
125 if combine != "0":
126 if combine not in combines:
127 combines[combine] = []
128 combines[combine].append(code)
129
130 # generate Not_Assigned from Assigned
131 gencats["Cn"] = gen_unassigned(gencats["Assigned"])
132 # Assigned is not a real category
133 del(gencats["Assigned"])
134 # Other contains Not_Assigned
135 gencats["C"].extend(gencats["Cn"])
136 gencats = group_cats(gencats)
137 combines = to_combines(group_cats(combines))
138
139 return (canon_decomp, compat_decomp, gencats, combines, to_title)
140
141 def load_special_casing(f, to_title):
142 fetch(f)
143 for line in fileinput.input(f):
144 data = line.split('#')[0].split(';')
145 if len(data) == 5:
146 code, lower, title, upper, _comment = data
147 elif len(data) == 6:
148 code, lower, title, upper, condition, _comment = data
149 if condition.strip(): # Only keep unconditional mappins
150 continue
151 else:
152 continue
153 code = code.strip()
154 lower = lower.strip()
155 title = title.strip()
156 upper = upper.strip()
157 key = int(code, 16)
158 for (map_, values) in [(to_title, title)]:
159 if values != code:
160 values = [int(i, 16) for i in values.split()]
161 for _ in range(len(values), 3):
162 values.append(0)
163 assert len(values) == 3
164 map_[key] = values
165
166 def group_cats(cats):
167 cats_out = {}
168 for cat in cats:
169 cats_out[cat] = group_cat(cats[cat])
170 return cats_out
171
172 def group_cat(cat):
173 cat_out = []
174 letters = sorted(set(cat))
175 cur_start = letters.pop(0)
176 cur_end = cur_start
177 for letter in letters:
178 assert letter > cur_end, \
179 "cur_end: %s, letter: %s" % (hex(cur_end), hex(letter))
180 if letter == cur_end + 1:
181 cur_end = letter
182 else:
183 cat_out.append((cur_start, cur_end))
184 cur_start = cur_end = letter
185 cat_out.append((cur_start, cur_end))
186 return cat_out
187
188 def ungroup_cat(cat):
189 cat_out = []
190 for (lo, hi) in cat:
191 while lo <= hi:
192 cat_out.append(lo)
193 lo += 1
194 return cat_out
195
196 def gen_unassigned(assigned):
197 assigned = set(assigned)
198 return ([i for i in range(0, 0xd800) if i not in assigned] +
199 [i for i in range(0xe000, 0x110000) if i not in assigned])
200
201 def to_combines(combs):
202 combs_out = []
203 for comb in combs:
204 for (lo, hi) in combs[comb]:
205 combs_out.append((lo, hi, comb))
206 combs_out.sort(key=lambda comb: comb[0])
207 return combs_out
208
209 def format_table_content(f, content, indent):
210 line = " "*indent
211 first = True
212 for chunk in content.split(","):
213 if len(line) + len(chunk) < 98:
214 if first:
215 line += chunk
216 else:
217 line += ", " + chunk
218 first = False
219 else:
220 f.write(line + ",\n")
221 line = " "*indent + chunk
222 f.write(line)
223
224 def load_properties(f, interestingprops):
225 fetch(f)
226 props = {}
227 re1 = re.compile("^ *([0-9A-F]+) *; *(\w+)")
228 re2 = re.compile("^ *([0-9A-F]+)\.\.([0-9A-F]+) *; *(\w+)")
229
230 for line in fileinput.input(os.path.basename(f)):
231 prop = None
232 d_lo = 0
233 d_hi = 0
234 m = re1.match(line)
235 if m:
236 d_lo = m.group(1)
237 d_hi = m.group(1)
238 prop = m.group(2)
239 else:
240 m = re2.match(line)
241 if m:
242 d_lo = m.group(1)
243 d_hi = m.group(2)
244 prop = m.group(3)
245 else:
246 continue
247 if interestingprops and prop not in interestingprops:
248 continue
249 d_lo = int(d_lo, 16)
250 d_hi = int(d_hi, 16)
251 if prop not in props:
252 props[prop] = []
253 props[prop].append((d_lo, d_hi))
254
255 # optimize if possible
256 for prop in props:
257 props[prop] = group_cat(ungroup_cat(props[prop]))
258
259 return props
260
261 def escape_char(c):
262 return "'\\u{%x}'" % c if c != 0 else "'\\0'"
263
264 def emit_table(f, name, t_data, t_type = "&[(char, char)]", is_pub=True,
265 pfun=lambda x: "(%s,%s)" % (escape_char(x[0]), escape_char(x[1]))):
266 pub_string = ""
267 if is_pub:
268 pub_string = "pub "
269 f.write(" %sconst %s: %s = &[\n" % (pub_string, name, t_type))
270 data = ""
271 first = True
272 for dat in t_data:
273 if not first:
274 data += ","
275 first = False
276 data += pfun(dat)
277 format_table_content(f, data, 8)
278 f.write("\n ];\n\n")
279
280 def compute_trie(rawdata, chunksize):
281 root = []
282 childmap = {}
283 child_data = []
284 for i in range(len(rawdata) // chunksize):
285 data = rawdata[i * chunksize: (i + 1) * chunksize]
286 child = '|'.join(map(str, data))
287 if child not in childmap:
288 childmap[child] = len(childmap)
289 child_data.extend(data)
290 root.append(childmap[child])
291 return (root, child_data)
292
293 def emit_bool_trie(f, name, t_data, is_pub=True):
294 CHUNK = 64
295 rawdata = [False] * 0x110000
296 for (lo, hi) in t_data:
297 for cp in range(lo, hi + 1):
298 rawdata[cp] = True
299
300 # convert to bitmap chunks of 64 bits each
301 chunks = []
302 for i in range(0x110000 // CHUNK):
303 chunk = 0
304 for j in range(64):
305 if rawdata[i * 64 + j]:
306 chunk |= 1 << j
307 chunks.append(chunk)
308
309 pub_string = ""
310 if is_pub:
311 pub_string = "pub "
312 f.write(" %sconst %s: &super::BoolTrie = &super::BoolTrie {\n" % (pub_string, name))
313 f.write(" r1: [\n")
314 data = ','.join('0x%016x' % chunk for chunk in chunks[0:0x800 // CHUNK])
315 format_table_content(f, data, 12)
316 f.write("\n ],\n")
317
318 # 0x800..0x10000 trie
319 (r2, r3) = compute_trie(chunks[0x800 // CHUNK : 0x10000 // CHUNK], 64 // CHUNK)
320 f.write(" r2: [\n")
321 data = ','.join(str(node) for node in r2)
322 format_table_content(f, data, 12)
323 f.write("\n ],\n")
324 f.write(" r3: &[\n")
325 data = ','.join('0x%016x' % chunk for chunk in r3)
326 format_table_content(f, data, 12)
327 f.write("\n ],\n")
328
329 # 0x10000..0x110000 trie
330 (mid, r6) = compute_trie(chunks[0x10000 // CHUNK : 0x110000 // CHUNK], 64 // CHUNK)
331 (r4, r5) = compute_trie(mid, 64)
332 f.write(" r4: [\n")
333 data = ','.join(str(node) for node in r4)
334 format_table_content(f, data, 12)
335 f.write("\n ],\n")
336 f.write(" r5: &[\n")
337 data = ','.join(str(node) for node in r5)
338 format_table_content(f, data, 12)
339 f.write("\n ],\n")
340 f.write(" r6: &[\n")
341 data = ','.join('0x%016x' % chunk for chunk in r6)
342 format_table_content(f, data, 12)
343 f.write("\n ],\n")
344
345 f.write(" };\n\n")
346
347 def emit_property_module(f, mod, tbl, emit):
348 f.write("pub mod %s {\n" % mod)
349 for cat in sorted(emit):
350 emit_bool_trie(f, "%s_table" % cat, tbl[cat])
351 f.write(" pub fn %s(c: char) -> bool {\n" % cat)
352 f.write(" %s_table.lookup(c)\n" % cat)
353 f.write(" }\n\n")
354 f.write("}\n\n")
355
356 def emit_conversions_module(f, to_title):
357 f.write("pub mod conversions {")
358 f.write("""
359 pub fn to_title(c: char) -> [char; 3] {
360 match bsearch_case_table(c, to_titlecase_table) {
361 None => [c, '\\0', '\\0'],
362 Some(index) => to_titlecase_table[index].1
363 }
364 }
365
366 fn bsearch_case_table(c: char, table: &[(char, [char; 3])]) -> Option<usize> {
367 table.binary_search_by(|&(key, _)| key.cmp(&c)).ok()
368 }
369
370 """)
371 t_type = "&[(char, [char; 3])]"
372 pfun = lambda x: "(%s,[%s,%s,%s])" % (
373 escape_char(x[0]), escape_char(x[1][0]), escape_char(x[1][1]), escape_char(x[1][2]))
374 emit_table(f, "to_titlecase_table",
375 sorted(to_title.items(), key=operator.itemgetter(0)),
376 is_pub=False, t_type = t_type, pfun=pfun)
377 f.write("}\n\n")
378
379 if __name__ == "__main__":
380 r = "src/tables.rs"
381 if os.path.exists(r):
382 os.remove(r)
383 with open(r, "w") as rf:
384 # write the file's preamble
385 rf.write(preamble)
386
387 (canon_decomp, compat_decomp, gencats, combines, to_title) = load_unicode_data("UnicodeData.txt")
388 load_special_casing("SpecialCasing.txt", to_title)
389 want_derived = []
390 derived = load_properties("DerivedCoreProperties.txt", want_derived)
391 scripts = load_properties("Scripts.txt", [])
392
393 # category tables
394 for (name, cat, pfuns) in ("general_category", gencats, ["Lt"]), \
395 ("derived_property", derived, want_derived):
396 emit_property_module(rf, name, cat, pfuns)
397 emit_conversions_module(rf, to_title)
398 print("Regenerated tables.rs.")