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.
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.
13 # This script uses the following Unicode tables:
14 # - DerivedCoreProperties.txt
15 # - DerivedNormalizationProps.txt
16 # - EastAsianWidth.txt
17 # - auxiliary/GraphemeBreakProperty.txt
23 # Since this should not require frequent updates, we just store this
24 # out-of-line and check the tables.rs file into git.
26 import fileinput, re, os, sys, operator, math, datetime
28 # The directory in which this file resides.
29 fdir = os.path.dirname(os.path.realpath(__file__)) + "/"
31 preamble = '''// Copyright 2012-{year} The Rust Project Developers. See the COPYRIGHT
32 // file at the top-level directory of this distribution and at
33 // http://rust-lang.org/COPYRIGHT.
35 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
36 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
37 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
38 // option. This file may not be copied, modified, or distributed
39 // except according to those terms.
41 // NOTE: The following code was generated by "./unicode.py", do not edit directly
43 #![allow(missing_docs, non_upper_case_globals, non_snake_case)]
45 use unicode::version::UnicodeVersion;
46 use unicode::bool_trie::{{BoolTrie, SmallBoolTrie}};
47 '''.format(year = datetime.datetime.now().year)
49 # Mapping taken from Table 12 from:
50 # http://www.unicode.org/reports/tr44/#General_Category_Values
51 expanded_categories = {
52 'Lu': ['LC', 'L'], 'Ll': ['LC', 'L'], 'Lt': ['LC', 'L'],
53 'Lm': ['L'], 'Lo': ['L'],
54 'Mn': ['M'], 'Mc': ['M'], 'Me': ['M'],
55 'Nd': ['N'], 'Nl': ['N'], 'No': ['N'],
56 'Pc': ['P'], 'Pd': ['P'], 'Ps': ['P'], 'Pe': ['P'],
57 'Pi': ['P'], 'Pf': ['P'], 'Po': ['P'],
58 'Sm': ['S'], 'Sc': ['S'], 'Sk': ['S'], 'So': ['S'],
59 'Zs': ['Z'], 'Zl': ['Z'], 'Zp': ['Z'],
60 'Cc': ['C'], 'Cf': ['C'], 'Cs': ['C'], 'Co': ['C'], 'Cn': ['C'],
63 # these are the surrogate codepoints, which are not valid rust characters
64 surrogate_codepoints = (0xd800, 0xdfff)
67 path = fdir + os.path.basename(f)
68 if not os.path.exists(path):
69 os.system("curl -o {0}{1} ftp://ftp.unicode.org/Public/UNIDATA/{1}".format(fdir, f))
71 if not os.path.exists(path):
72 sys.stderr.write("cannot load %s" % f)
76 return surrogate_codepoints[0] <= n <= surrogate_codepoints[1]
78 def load_unicode_data(f):
90 for line in fileinput.input(fdir + f):
91 data = line.split(';')
98 for i in range(range_start, cp):
101 if data[1].endswith(", First>"):
107 (code_org, name, gencat, combine, bidi,
108 decomp, deci, digit, num, mirror,
109 old, iso, upcase, lowcase, titlecase) = udict[code]
111 # generate char to char direct common and simple conversions
112 # uppercase to lowercase
113 if lowcase != "" and code_org != lowcase:
114 to_lower[code] = (int(lowcase, 16), 0, 0)
116 # lowercase to uppercase
117 if upcase != "" and code_org != upcase:
118 to_upper[code] = (int(upcase, 16), 0, 0)
121 if titlecase.strip() != "" and code_org != titlecase:
122 to_title[code] = (int(titlecase, 16), 0, 0)
124 # store decomposition, if given
126 if decomp.startswith('<'):
128 for i in decomp.split()[1:]:
129 seq.append(int(i, 16))
130 compat_decomp[code] = seq
133 for i in decomp.split():
134 seq.append(int(i, 16))
135 canon_decomp[code] = seq
137 # place letter in categories as appropriate
138 for cat in [gencat, "Assigned"] + expanded_categories.get(gencat, []):
139 if cat not in gencats:
141 gencats[cat].append(code)
143 # record combining class, if any
145 if combine not in combines:
146 combines[combine] = []
147 combines[combine].append(code)
149 # generate Not_Assigned from Assigned
150 gencats["Cn"] = gen_unassigned(gencats["Assigned"])
151 # Assigned is not a real category
152 del(gencats["Assigned"])
153 # Other contains Not_Assigned
154 gencats["C"].extend(gencats["Cn"])
155 gencats = group_cats(gencats)
156 combines = to_combines(group_cats(combines))
158 return (canon_decomp, compat_decomp, gencats, combines, to_upper, to_lower, to_title)
160 def load_special_casing(f, to_upper, to_lower, to_title):
162 for line in fileinput.input(fdir + f):
163 data = line.split('#')[0].split(';')
165 code, lower, title, upper, _comment = data
167 code, lower, title, upper, condition, _comment = data
168 if condition.strip(): # Only keep unconditional mappins
173 lower = lower.strip()
174 title = title.strip()
175 upper = upper.strip()
177 for (map_, values) in [(to_lower, lower), (to_upper, upper), (to_title, title)]:
179 values = [int(i, 16) for i in values.split()]
180 for _ in range(len(values), 3):
182 assert len(values) == 3
185 def group_cats(cats):
188 cats_out[cat] = group_cat(cats[cat])
193 letters = sorted(set(cat))
194 cur_start = letters.pop(0)
196 for letter in letters:
197 assert letter > cur_end, \
198 "cur_end: %s, letter: %s" % (hex(cur_end), hex(letter))
199 if letter == cur_end + 1:
202 cat_out.append((cur_start, cur_end))
203 cur_start = cur_end = letter
204 cat_out.append((cur_start, cur_end))
207 def ungroup_cat(cat):
215 def gen_unassigned(assigned):
216 assigned = set(assigned)
217 return ([i for i in range(0, 0xd800) if i not in assigned] +
218 [i for i in range(0xe000, 0x110000) if i not in assigned])
220 def to_combines(combs):
223 for (lo, hi) in combs[comb]:
224 combs_out.append((lo, hi, comb))
225 combs_out.sort(key=lambda comb: comb[0])
228 def format_table_content(f, content, indent):
231 for chunk in content.split(","):
232 if len(line) + len(chunk) < 98:
239 f.write(line + ",\n")
240 line = " "*indent + chunk
243 def load_properties(f, interestingprops):
246 re1 = re.compile("^ *([0-9A-F]+) *; *(\w+)")
247 re2 = re.compile("^ *([0-9A-F]+)\.\.([0-9A-F]+) *; *(\w+)")
249 for line in fileinput.input(fdir + os.path.basename(f)):
266 if interestingprops and prop not in interestingprops:
270 if prop not in props:
272 props[prop].append((d_lo, d_hi))
274 # optimize if possible
276 props[prop] = group_cat(ungroup_cat(props[prop]))
281 return "'\\u{%x}'" % c if c != 0 else "'\\0'"
283 def emit_table(f, name, t_data, t_type = "&[(char, char)]", is_pub=True,
284 pfun=lambda x: "(%s,%s)" % (escape_char(x[0]), escape_char(x[1]))):
288 f.write(" %sconst %s: %s = &[\n" % (pub_string, name, t_type))
296 format_table_content(f, data, 8)
299 def compute_trie(rawdata, chunksize):
303 for i in range(len(rawdata) // chunksize):
304 data = rawdata[i * chunksize: (i + 1) * chunksize]
305 child = '|'.join(map(str, data))
306 if child not in childmap:
307 childmap[child] = len(childmap)
308 child_data.extend(data)
309 root.append(childmap[child])
310 return (root, child_data)
312 def emit_bool_trie(f, name, t_data, is_pub=True):
314 rawdata = [False] * 0x110000
315 for (lo, hi) in t_data:
316 for cp in range(lo, hi + 1):
319 # convert to bitmap chunks of 64 bits each
321 for i in range(0x110000 // CHUNK):
324 if rawdata[i * 64 + j]:
331 f.write(" %sconst %s: &super::BoolTrie = &super::BoolTrie {\n" % (pub_string, name))
333 data = ','.join('0x%016x' % chunk for chunk in chunks[0:0x800 // CHUNK])
334 format_table_content(f, data, 12)
337 # 0x800..0x10000 trie
338 (r2, r3) = compute_trie(chunks[0x800 // CHUNK : 0x10000 // CHUNK], 64 // CHUNK)
340 data = ','.join(str(node) for node in r2)
341 format_table_content(f, data, 12)
344 data = ','.join('0x%016x' % chunk for chunk in r3)
345 format_table_content(f, data, 12)
348 # 0x10000..0x110000 trie
349 (mid, r6) = compute_trie(chunks[0x10000 // CHUNK : 0x110000 // CHUNK], 64 // CHUNK)
350 (r4, r5) = compute_trie(mid, 64)
352 data = ','.join(str(node) for node in r4)
353 format_table_content(f, data, 12)
356 data = ','.join(str(node) for node in r5)
357 format_table_content(f, data, 12)
360 data = ','.join('0x%016x' % chunk for chunk in r6)
361 format_table_content(f, data, 12)
366 def emit_small_bool_trie(f, name, t_data, is_pub=True):
367 last_chunk = max(hi // 64 for (lo, hi) in t_data)
368 n_chunks = last_chunk + 1
369 chunks = [0] * n_chunks
370 for (lo, hi) in t_data:
371 for cp in range(lo, hi + 1):
372 if cp // 64 >= len(chunks):
373 print(cp, cp // 64, len(chunks), lo, hi)
374 chunks[cp // 64] |= 1 << (cp & 63)
379 f.write(" %sconst %s: &super::SmallBoolTrie = &super::SmallBoolTrie {\n"
380 % (pub_string, name))
382 (r1, r2) = compute_trie(chunks, 1)
385 data = ','.join(str(node) for node in r1)
386 format_table_content(f, data, 12)
390 data = ','.join('0x%016x' % node for node in r2)
391 format_table_content(f, data, 12)
396 def emit_property_module(f, mod, tbl, emit):
397 f.write("pub mod %s {\n" % mod)
398 for cat in sorted(emit):
399 if cat in ["Cc", "White_Space", "Pattern_White_Space"]:
400 emit_small_bool_trie(f, "%s_table" % cat, tbl[cat])
401 f.write(" pub fn %s(c: char) -> bool {\n" % cat)
402 f.write(" %s_table.lookup(c)\n" % cat)
405 emit_bool_trie(f, "%s_table" % cat, tbl[cat])
406 f.write(" pub fn %s(c: char) -> bool {\n" % cat)
407 f.write(" %s_table.lookup(c)\n" % cat)
411 def emit_conversions_module(f, to_upper, to_lower, to_title):
412 f.write("pub mod conversions {")
414 pub fn to_lower(c: char) -> [char; 3] {
415 match bsearch_case_table(c, to_lowercase_table) {
416 None => [c, '\\0', '\\0'],
417 Some(index) => to_lowercase_table[index].1,
421 pub fn to_upper(c: char) -> [char; 3] {
422 match bsearch_case_table(c, to_uppercase_table) {
423 None => [c, '\\0', '\\0'],
424 Some(index) => to_uppercase_table[index].1,
428 fn bsearch_case_table(c: char, table: &[(char, [char; 3])]) -> Option<usize> {
429 table.binary_search_by(|&(key, _)| key.cmp(&c)).ok()
433 t_type = "&[(char, [char; 3])]"
434 pfun = lambda x: "(%s,[%s,%s,%s])" % (
435 escape_char(x[0]), escape_char(x[1][0]), escape_char(x[1][1]), escape_char(x[1][2]))
436 emit_table(f, "to_lowercase_table",
437 sorted(to_lower.items(), key=operator.itemgetter(0)),
438 is_pub=False, t_type = t_type, pfun=pfun)
439 emit_table(f, "to_uppercase_table",
440 sorted(to_upper.items(), key=operator.itemgetter(0)),
441 is_pub=False, t_type = t_type, pfun=pfun)
444 def emit_norm_module(f, canon, compat, combine, norm_props):
445 canon_keys = sorted(canon.keys())
447 compat_keys = sorted(compat.keys())
450 comp_exclusions = norm_props["Full_Composition_Exclusion"]
451 for char in canon_keys:
452 if any(lo <= char <= hi for lo, hi in comp_exclusions):
456 if decomp[0] not in canon_comp:
457 canon_comp[decomp[0]] = []
458 canon_comp[decomp[0]].append( (decomp[1], char) )
459 canon_comp_keys = sorted(canon_comp.keys())
461 if __name__ == "__main__":
462 r = fdir + "tables.rs"
463 if os.path.exists(r):
465 with open(r, "w") as rf:
466 # write the file's preamble
469 # download and parse all the data
471 with open(fdir + "ReadMe.txt") as readme:
472 pattern = "for Version (\d+)\.(\d+)\.(\d+) of the Unicode"
473 unicode_version = re.search(pattern, readme.read()).groups()
475 /// The version of [Unicode](http://www.unicode.org/) that the Unicode parts of
476 /// `char` and `str` methods are based on.
477 #[unstable(feature = "unicode_version", issue = "49726")]
478 pub const UNICODE_VERSION: UnicodeVersion = UnicodeVersion {
484 """ % unicode_version)
485 (canon_decomp, compat_decomp, gencats, combines,
486 to_upper, to_lower, to_title) = load_unicode_data("UnicodeData.txt")
487 load_special_casing("SpecialCasing.txt", to_upper, to_lower, to_title)
488 want_derived = ["XID_Start", "XID_Continue", "Alphabetic", "Lowercase", "Uppercase",
489 "Cased", "Case_Ignorable", "Grapheme_Extend"]
490 derived = load_properties("DerivedCoreProperties.txt", want_derived)
491 scripts = load_properties("Scripts.txt", [])
492 props = load_properties("PropList.txt",
493 ["White_Space", "Join_Control", "Noncharacter_Code_Point", "Pattern_White_Space"])
494 norm_props = load_properties("DerivedNormalizationProps.txt",
495 ["Full_Composition_Exclusion"])
498 for (name, cat, pfuns) in ("general_category", gencats, ["N", "Cc"]), \
499 ("derived_property", derived, want_derived), \
500 ("property", props, ["White_Space", "Pattern_White_Space"]):
501 emit_property_module(rf, name, cat, pfuns)
503 # normalizations and conversions module
504 emit_norm_module(rf, canon_decomp, compat_decomp, combines, norm_props)
505 emit_conversions_module(rf, to_upper, to_lower, to_title)
506 print("Regenerated tables.rs.")