]> git.proxmox.com Git - rustc.git/blob - src/libcore/unicode/unicode.py
New upstream version 1.27.1+dfsg1
[rustc.git] / src / libcore / unicode / unicode.py
1 #!/usr/bin/env python
2 #
3 # Copyright 2011-2013 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 # - DerivedNormalizationProps.txt
16 # - EastAsianWidth.txt
17 # - auxiliary/GraphemeBreakProperty.txt
18 # - PropList.txt
19 # - ReadMe.txt
20 # - Scripts.txt
21 # - UnicodeData.txt
22 #
23 # Since this should not require frequent updates, we just store this
24 # out-of-line and check the unicode.rs file into git.
25
26 import fileinput, re, os, sys, operator, math
27
28 preamble = '''// Copyright 2012-2016 The Rust Project Developers. See the COPYRIGHT
29 // file at the top-level directory of this distribution and at
30 // http://rust-lang.org/COPYRIGHT.
31 //
32 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
33 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
34 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
35 // option. This file may not be copied, modified, or distributed
36 // except according to those terms.
37
38 // NOTE: The following code was generated by "./unicode.py", do not edit directly
39
40 #![allow(missing_docs, non_upper_case_globals, non_snake_case)]
41
42 use unicode::version::UnicodeVersion;
43 use unicode::bool_trie::{BoolTrie, SmallBoolTrie};
44 '''
45
46 # Mapping taken from Table 12 from:
47 # http://www.unicode.org/reports/tr44/#General_Category_Values
48 expanded_categories = {
49 'Lu': ['LC', 'L'], 'Ll': ['LC', 'L'], 'Lt': ['LC', 'L'],
50 'Lm': ['L'], 'Lo': ['L'],
51 'Mn': ['M'], 'Mc': ['M'], 'Me': ['M'],
52 'Nd': ['N'], 'Nl': ['N'], 'No': ['No'],
53 'Pc': ['P'], 'Pd': ['P'], 'Ps': ['P'], 'Pe': ['P'],
54 'Pi': ['P'], 'Pf': ['P'], 'Po': ['P'],
55 'Sm': ['S'], 'Sc': ['S'], 'Sk': ['S'], 'So': ['S'],
56 'Zs': ['Z'], 'Zl': ['Z'], 'Zp': ['Z'],
57 'Cc': ['C'], 'Cf': ['C'], 'Cs': ['C'], 'Co': ['C'], 'Cn': ['C'],
58 }
59
60 # these are the surrogate codepoints, which are not valid rust characters
61 surrogate_codepoints = (0xd800, 0xdfff)
62
63 def fetch(f):
64 if not os.path.exists(os.path.basename(f)):
65 os.system("curl -O http://www.unicode.org/Public/UNIDATA/%s"
66 % f)
67
68 if not os.path.exists(os.path.basename(f)):
69 sys.stderr.write("cannot load %s" % f)
70 exit(1)
71
72 def is_surrogate(n):
73 return surrogate_codepoints[0] <= n <= surrogate_codepoints[1]
74
75 def load_unicode_data(f):
76 fetch(f)
77 gencats = {}
78 to_lower = {}
79 to_upper = {}
80 to_title = {}
81 combines = {}
82 canon_decomp = {}
83 compat_decomp = {}
84
85 udict = {}
86 range_start = -1
87 for line in fileinput.input(f):
88 data = line.split(';')
89 if len(data) != 15:
90 continue
91 cp = int(data[0], 16)
92 if is_surrogate(cp):
93 continue
94 if range_start >= 0:
95 for i in range(range_start, cp):
96 udict[i] = data
97 range_start = -1
98 if data[1].endswith(", First>"):
99 range_start = cp
100 continue
101 udict[cp] = data
102
103 for code in udict:
104 (code_org, name, gencat, combine, bidi,
105 decomp, deci, digit, num, mirror,
106 old, iso, upcase, lowcase, titlecase) = udict[code]
107
108 # generate char to char direct common and simple conversions
109 # uppercase to lowercase
110 if lowcase != "" and code_org != lowcase:
111 to_lower[code] = (int(lowcase, 16), 0, 0)
112
113 # lowercase to uppercase
114 if upcase != "" and code_org != upcase:
115 to_upper[code] = (int(upcase, 16), 0, 0)
116
117 # title case
118 if titlecase.strip() != "" and code_org != titlecase:
119 to_title[code] = (int(titlecase, 16), 0, 0)
120
121 # store decomposition, if given
122 if decomp != "":
123 if decomp.startswith('<'):
124 seq = []
125 for i in decomp.split()[1:]:
126 seq.append(int(i, 16))
127 compat_decomp[code] = seq
128 else:
129 seq = []
130 for i in decomp.split():
131 seq.append(int(i, 16))
132 canon_decomp[code] = seq
133
134 # place letter in categories as appropriate
135 for cat in [gencat, "Assigned"] + expanded_categories.get(gencat, []):
136 if cat not in gencats:
137 gencats[cat] = []
138 gencats[cat].append(code)
139
140 # record combining class, if any
141 if combine != "0":
142 if combine not in combines:
143 combines[combine] = []
144 combines[combine].append(code)
145
146 # generate Not_Assigned from Assigned
147 gencats["Cn"] = gen_unassigned(gencats["Assigned"])
148 # Assigned is not a real category
149 del(gencats["Assigned"])
150 # Other contains Not_Assigned
151 gencats["C"].extend(gencats["Cn"])
152 gencats = group_cats(gencats)
153 combines = to_combines(group_cats(combines))
154
155 return (canon_decomp, compat_decomp, gencats, combines, to_upper, to_lower, to_title)
156
157 def load_special_casing(f, to_upper, to_lower, to_title):
158 fetch(f)
159 for line in fileinput.input(f):
160 data = line.split('#')[0].split(';')
161 if len(data) == 5:
162 code, lower, title, upper, _comment = data
163 elif len(data) == 6:
164 code, lower, title, upper, condition, _comment = data
165 if condition.strip(): # Only keep unconditional mappins
166 continue
167 else:
168 continue
169 code = code.strip()
170 lower = lower.strip()
171 title = title.strip()
172 upper = upper.strip()
173 key = int(code, 16)
174 for (map_, values) in [(to_lower, lower), (to_upper, upper), (to_title, title)]:
175 if values != code:
176 values = [int(i, 16) for i in values.split()]
177 for _ in range(len(values), 3):
178 values.append(0)
179 assert len(values) == 3
180 map_[key] = values
181
182 def group_cats(cats):
183 cats_out = {}
184 for cat in cats:
185 cats_out[cat] = group_cat(cats[cat])
186 return cats_out
187
188 def group_cat(cat):
189 cat_out = []
190 letters = sorted(set(cat))
191 cur_start = letters.pop(0)
192 cur_end = cur_start
193 for letter in letters:
194 assert letter > cur_end, \
195 "cur_end: %s, letter: %s" % (hex(cur_end), hex(letter))
196 if letter == cur_end + 1:
197 cur_end = letter
198 else:
199 cat_out.append((cur_start, cur_end))
200 cur_start = cur_end = letter
201 cat_out.append((cur_start, cur_end))
202 return cat_out
203
204 def ungroup_cat(cat):
205 cat_out = []
206 for (lo, hi) in cat:
207 while lo <= hi:
208 cat_out.append(lo)
209 lo += 1
210 return cat_out
211
212 def gen_unassigned(assigned):
213 assigned = set(assigned)
214 return ([i for i in range(0, 0xd800) if i not in assigned] +
215 [i for i in range(0xe000, 0x110000) if i not in assigned])
216
217 def to_combines(combs):
218 combs_out = []
219 for comb in combs:
220 for (lo, hi) in combs[comb]:
221 combs_out.append((lo, hi, comb))
222 combs_out.sort(key=lambda comb: comb[0])
223 return combs_out
224
225 def format_table_content(f, content, indent):
226 line = " "*indent
227 first = True
228 for chunk in content.split(","):
229 if len(line) + len(chunk) < 98:
230 if first:
231 line += chunk
232 else:
233 line += ", " + chunk
234 first = False
235 else:
236 f.write(line + ",\n")
237 line = " "*indent + chunk
238 f.write(line)
239
240 def load_properties(f, interestingprops):
241 fetch(f)
242 props = {}
243 re1 = re.compile("^ *([0-9A-F]+) *; *(\w+)")
244 re2 = re.compile("^ *([0-9A-F]+)\.\.([0-9A-F]+) *; *(\w+)")
245
246 for line in fileinput.input(os.path.basename(f)):
247 prop = None
248 d_lo = 0
249 d_hi = 0
250 m = re1.match(line)
251 if m:
252 d_lo = m.group(1)
253 d_hi = m.group(1)
254 prop = m.group(2)
255 else:
256 m = re2.match(line)
257 if m:
258 d_lo = m.group(1)
259 d_hi = m.group(2)
260 prop = m.group(3)
261 else:
262 continue
263 if interestingprops and prop not in interestingprops:
264 continue
265 d_lo = int(d_lo, 16)
266 d_hi = int(d_hi, 16)
267 if prop not in props:
268 props[prop] = []
269 props[prop].append((d_lo, d_hi))
270
271 # optimize if possible
272 for prop in props:
273 props[prop] = group_cat(ungroup_cat(props[prop]))
274
275 return props
276
277 def escape_char(c):
278 return "'\\u{%x}'" % c if c != 0 else "'\\0'"
279
280 def emit_table(f, name, t_data, t_type = "&[(char, char)]", is_pub=True,
281 pfun=lambda x: "(%s,%s)" % (escape_char(x[0]), escape_char(x[1]))):
282 pub_string = ""
283 if is_pub:
284 pub_string = "pub "
285 f.write(" %sconst %s: %s = &[\n" % (pub_string, name, t_type))
286 data = ""
287 first = True
288 for dat in t_data:
289 if not first:
290 data += ","
291 first = False
292 data += pfun(dat)
293 format_table_content(f, data, 8)
294 f.write("\n ];\n\n")
295
296 def compute_trie(rawdata, chunksize):
297 root = []
298 childmap = {}
299 child_data = []
300 for i in range(len(rawdata) // chunksize):
301 data = rawdata[i * chunksize: (i + 1) * chunksize]
302 child = '|'.join(map(str, data))
303 if child not in childmap:
304 childmap[child] = len(childmap)
305 child_data.extend(data)
306 root.append(childmap[child])
307 return (root, child_data)
308
309 def emit_bool_trie(f, name, t_data, is_pub=True):
310 CHUNK = 64
311 rawdata = [False] * 0x110000
312 for (lo, hi) in t_data:
313 for cp in range(lo, hi + 1):
314 rawdata[cp] = True
315
316 # convert to bitmap chunks of 64 bits each
317 chunks = []
318 for i in range(0x110000 // CHUNK):
319 chunk = 0
320 for j in range(64):
321 if rawdata[i * 64 + j]:
322 chunk |= 1 << j
323 chunks.append(chunk)
324
325 pub_string = ""
326 if is_pub:
327 pub_string = "pub "
328 f.write(" %sconst %s: &super::BoolTrie = &super::BoolTrie {\n" % (pub_string, name))
329 f.write(" r1: [\n")
330 data = ','.join('0x%016x' % chunk for chunk in chunks[0:0x800 // CHUNK])
331 format_table_content(f, data, 12)
332 f.write("\n ],\n")
333
334 # 0x800..0x10000 trie
335 (r2, r3) = compute_trie(chunks[0x800 // CHUNK : 0x10000 // CHUNK], 64 // CHUNK)
336 f.write(" r2: [\n")
337 data = ','.join(str(node) for node in r2)
338 format_table_content(f, data, 12)
339 f.write("\n ],\n")
340 f.write(" r3: &[\n")
341 data = ','.join('0x%016x' % chunk for chunk in r3)
342 format_table_content(f, data, 12)
343 f.write("\n ],\n")
344
345 # 0x10000..0x110000 trie
346 (mid, r6) = compute_trie(chunks[0x10000 // CHUNK : 0x110000 // CHUNK], 64 // CHUNK)
347 (r4, r5) = compute_trie(mid, 64)
348 f.write(" r4: [\n")
349 data = ','.join(str(node) for node in r4)
350 format_table_content(f, data, 12)
351 f.write("\n ],\n")
352 f.write(" r5: &[\n")
353 data = ','.join(str(node) for node in r5)
354 format_table_content(f, data, 12)
355 f.write("\n ],\n")
356 f.write(" r6: &[\n")
357 data = ','.join('0x%016x' % chunk for chunk in r6)
358 format_table_content(f, data, 12)
359 f.write("\n ],\n")
360
361 f.write(" };\n\n")
362
363 def emit_small_bool_trie(f, name, t_data, is_pub=True):
364 last_chunk = max(hi // 64 for (lo, hi) in t_data)
365 n_chunks = last_chunk + 1
366 chunks = [0] * n_chunks
367 for (lo, hi) in t_data:
368 for cp in range(lo, hi + 1):
369 if cp // 64 >= len(chunks):
370 print(cp, cp // 64, len(chunks), lo, hi)
371 chunks[cp // 64] |= 1 << (cp & 63)
372
373 pub_string = ""
374 if is_pub:
375 pub_string = "pub "
376 f.write(" %sconst %s: &super::SmallBoolTrie = &super::SmallBoolTrie {\n"
377 % (pub_string, name))
378
379 (r1, r2) = compute_trie(chunks, 1)
380
381 f.write(" r1: &[\n")
382 data = ','.join(str(node) for node in r1)
383 format_table_content(f, data, 12)
384 f.write("\n ],\n")
385
386 f.write(" r2: &[\n")
387 data = ','.join('0x%016x' % node for node in r2)
388 format_table_content(f, data, 12)
389 f.write("\n ],\n")
390
391 f.write(" };\n\n")
392
393 def emit_property_module(f, mod, tbl, emit):
394 f.write("pub mod %s {\n" % mod)
395 for cat in sorted(emit):
396 if cat in ["Cc", "White_Space", "Pattern_White_Space"]:
397 emit_small_bool_trie(f, "%s_table" % cat, tbl[cat])
398 f.write(" pub fn %s(c: char) -> bool {\n" % cat)
399 f.write(" %s_table.lookup(c)\n" % cat)
400 f.write(" }\n\n")
401 else:
402 emit_bool_trie(f, "%s_table" % cat, tbl[cat])
403 f.write(" pub fn %s(c: char) -> bool {\n" % cat)
404 f.write(" %s_table.lookup(c)\n" % cat)
405 f.write(" }\n\n")
406 f.write("}\n\n")
407
408 def emit_conversions_module(f, to_upper, to_lower, to_title):
409 f.write("pub mod conversions {")
410 f.write("""
411 pub fn to_lower(c: char) -> [char; 3] {
412 match bsearch_case_table(c, to_lowercase_table) {
413 None => [c, '\\0', '\\0'],
414 Some(index) => to_lowercase_table[index].1,
415 }
416 }
417
418 pub fn to_upper(c: char) -> [char; 3] {
419 match bsearch_case_table(c, to_uppercase_table) {
420 None => [c, '\\0', '\\0'],
421 Some(index) => to_uppercase_table[index].1,
422 }
423 }
424
425 fn bsearch_case_table(c: char, table: &[(char, [char; 3])]) -> Option<usize> {
426 table.binary_search_by(|&(key, _)| key.cmp(&c)).ok()
427 }
428
429 """)
430 t_type = "&[(char, [char; 3])]"
431 pfun = lambda x: "(%s,[%s,%s,%s])" % (
432 escape_char(x[0]), escape_char(x[1][0]), escape_char(x[1][1]), escape_char(x[1][2]))
433 emit_table(f, "to_lowercase_table",
434 sorted(to_lower.items(), key=operator.itemgetter(0)),
435 is_pub=False, t_type = t_type, pfun=pfun)
436 emit_table(f, "to_uppercase_table",
437 sorted(to_upper.items(), key=operator.itemgetter(0)),
438 is_pub=False, t_type = t_type, pfun=pfun)
439 f.write("}\n\n")
440
441 def emit_norm_module(f, canon, compat, combine, norm_props):
442 canon_keys = sorted(canon.keys())
443
444 compat_keys = sorted(compat.keys())
445
446 canon_comp = {}
447 comp_exclusions = norm_props["Full_Composition_Exclusion"]
448 for char in canon_keys:
449 if any(lo <= char <= hi for lo, hi in comp_exclusions):
450 continue
451 decomp = canon[char]
452 if len(decomp) == 2:
453 if decomp[0] not in canon_comp:
454 canon_comp[decomp[0]] = []
455 canon_comp[decomp[0]].append( (decomp[1], char) )
456 canon_comp_keys = sorted(canon_comp.keys())
457
458 if __name__ == "__main__":
459 r = "tables.rs"
460 if os.path.exists(r):
461 os.remove(r)
462 with open(r, "w") as rf:
463 # write the file's preamble
464 rf.write(preamble)
465
466 # download and parse all the data
467 fetch("ReadMe.txt")
468 with open("ReadMe.txt") as readme:
469 pattern = "for Version (\d+)\.(\d+)\.(\d+) of the Unicode"
470 unicode_version = re.search(pattern, readme.read()).groups()
471 rf.write("""
472 /// The version of [Unicode](http://www.unicode.org/) that the Unicode parts of
473 /// `char` and `str` methods are based on.
474 #[unstable(feature = "unicode_version", issue = "49726")]
475 pub const UNICODE_VERSION: UnicodeVersion = UnicodeVersion {
476 major: %s,
477 minor: %s,
478 micro: %s,
479 _priv: (),
480 };
481 """ % unicode_version)
482 (canon_decomp, compat_decomp, gencats, combines,
483 to_upper, to_lower, to_title) = load_unicode_data("UnicodeData.txt")
484 load_special_casing("SpecialCasing.txt", to_upper, to_lower, to_title)
485 want_derived = ["XID_Start", "XID_Continue", "Alphabetic", "Lowercase", "Uppercase",
486 "Cased", "Case_Ignorable"]
487 derived = load_properties("DerivedCoreProperties.txt", want_derived)
488 scripts = load_properties("Scripts.txt", [])
489 props = load_properties("PropList.txt",
490 ["White_Space", "Join_Control", "Noncharacter_Code_Point", "Pattern_White_Space"])
491 norm_props = load_properties("DerivedNormalizationProps.txt",
492 ["Full_Composition_Exclusion"])
493
494 # category tables
495 for (name, cat, pfuns) in ("general_category", gencats, ["N", "Cc"]), \
496 ("derived_property", derived, want_derived), \
497 ("property", props, ["White_Space", "Pattern_White_Space"]):
498 emit_property_module(rf, name, cat, pfuns)
499
500 # normalizations and conversions module
501 emit_norm_module(rf, canon_decomp, compat_decomp, combines, norm_props)
502 emit_conversions_module(rf, to_upper, to_lower, to_title)