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 unicode.rs file into git.
26 import fileinput, re, os, sys, operator
28 preamble = '''// Copyright 2012-2015 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.
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.
38 // NOTE: The following code was generated by "src/etc/unicode.py", do not edit directly
40 #![allow(missing_docs, non_upper_case_globals, non_snake_case)]
43 # Mapping taken from Table 12 from:
44 # http://www.unicode.org/reports/tr44/#General_Category_Values
45 expanded_categories = {
46 'Lu': ['LC', 'L'], 'Ll': ['LC', 'L'], 'Lt': ['LC', 'L'],
47 'Lm': ['L'], 'Lo': ['L'],
48 'Mn': ['M'], 'Mc': ['M'], 'Me': ['M'],
49 'Nd': ['N'], 'Nl': ['N'], 'No': ['No'],
50 'Pc': ['P'], 'Pd': ['P'], 'Ps': ['P'], 'Pe': ['P'],
51 'Pi': ['P'], 'Pf': ['P'], 'Po': ['P'],
52 'Sm': ['S'], 'Sc': ['S'], 'Sk': ['S'], 'So': ['S'],
53 'Zs': ['Z'], 'Zl': ['Z'], 'Zp': ['Z'],
54 'Cc': ['C'], 'Cf': ['C'], 'Cs': ['C'], 'Co': ['C'], 'Cn': ['C'],
57 # these are the surrogate codepoints, which are not valid rust characters
58 surrogate_codepoints = (0xd800, 0xdfff)
61 if not os.path.exists(os.path.basename(f)):
62 os.system("curl -O http://www.unicode.org/Public/UNIDATA/%s"
65 if not os.path.exists(os.path.basename(f)):
66 sys.stderr.write("cannot load %s" % f)
70 return surrogate_codepoints[0] <= n <= surrogate_codepoints[1]
72 def load_unicode_data(f):
84 for line in fileinput.input(f):
85 data = line.split(';');
88 cp = int(data[0], 16);
92 for i in xrange(range_start, cp):
95 if data[1].endswith(", First>"):
101 [code_org, name, gencat, combine, bidi,
102 decomp, deci, digit, num, mirror,
103 old, iso, upcase, lowcase, titlecase ] = udict[code];
105 # generate char to char direct common and simple conversions
106 # uppercase to lowercase
107 if lowcase != "" and code_org != lowcase:
108 to_lower[code] = (int(lowcase, 16), 0, 0)
110 # lowercase to uppercase
111 if upcase != "" and code_org != upcase:
112 to_upper[code] = (int(upcase, 16), 0, 0)
115 if titlecase.strip() != "" and code_org != titlecase:
116 to_title[code] = (int(titlecase, 16), 0, 0)
118 # store decomposition, if given
120 if decomp.startswith('<'):
122 for i in decomp.split()[1:]:
123 seq.append(int(i, 16))
124 compat_decomp[code] = seq
127 for i in decomp.split():
128 seq.append(int(i, 16))
129 canon_decomp[code] = seq
131 # place letter in categories as appropriate
132 for cat in [gencat, "Assigned"] + expanded_categories.get(gencat, []):
133 if cat not in gencats:
135 gencats[cat].append(code)
137 # record combining class, if any
139 if combine not in combines:
140 combines[combine] = []
141 combines[combine].append(code)
143 # generate Not_Assigned from Assigned
144 gencats["Cn"] = gen_unassigned(gencats["Assigned"])
145 # Assigned is not a real category
146 del(gencats["Assigned"])
147 # Other contains Not_Assigned
148 gencats["C"].extend(gencats["Cn"])
149 gencats = group_cats(gencats)
150 combines = to_combines(group_cats(combines))
152 return (canon_decomp, compat_decomp, gencats, combines, to_upper, to_lower, to_title)
154 def load_special_casing(f, to_upper, to_lower, to_title):
156 for line in fileinput.input(f):
157 data = line.split('#')[0].split(';')
159 code, lower, title, upper, _comment = data
161 code, lower, title, upper, condition, _comment = data
162 if condition.strip(): # Only keep unconditional mappins
167 lower = lower.strip()
168 title = title.strip()
169 upper = upper.strip()
171 for (map_, values) in [(to_lower, lower), (to_upper, upper), (to_title, title)]:
173 values = [int(i, 16) for i in values.split()]
174 for _ in range(len(values), 3):
176 assert len(values) == 3
179 def group_cats(cats):
182 cats_out[cat] = group_cat(cats[cat])
187 letters = sorted(set(cat))
188 cur_start = letters.pop(0)
190 for letter in letters:
191 assert letter > cur_end, \
192 "cur_end: %s, letter: %s" % (hex(cur_end), hex(letter))
193 if letter == cur_end + 1:
196 cat_out.append((cur_start, cur_end))
197 cur_start = cur_end = letter
198 cat_out.append((cur_start, cur_end))
201 def ungroup_cat(cat):
209 def gen_unassigned(assigned):
210 assigned = set(assigned)
211 return ([i for i in range(0, 0xd800) if i not in assigned] +
212 [i for i in range(0xe000, 0x110000) if i not in assigned])
214 def to_combines(combs):
217 for (lo, hi) in combs[comb]:
218 combs_out.append((lo, hi, comb))
219 combs_out.sort(key=lambda comb: comb[0])
222 def format_table_content(f, content, indent):
225 for chunk in content.split(","):
226 if len(line) + len(chunk) < 98:
233 f.write(line + ",\n")
234 line = " "*indent + chunk
237 def load_properties(f, interestingprops):
240 re1 = re.compile("^ *([0-9A-F]+) *; *(\w+)")
241 re2 = re.compile("^ *([0-9A-F]+)\.\.([0-9A-F]+) *; *(\w+)")
243 for line in fileinput.input(os.path.basename(f)):
260 if interestingprops and prop not in interestingprops:
264 if prop not in props:
266 props[prop].append((d_lo, d_hi))
268 # optimize if possible
270 props[prop] = group_cat(ungroup_cat(props[prop]))
275 return "'\\u{%x}'" % c if c != 0 else "'\\0'"
277 def emit_bsearch_range_table(f):
279 fn bsearch_range_table(c: char, r: &'static [(char, char)]) -> bool {
280 use core::cmp::Ordering::{Equal, Less, Greater};
281 r.binary_search_by(|&(lo, hi)| {
294 def emit_table(f, name, t_data, t_type = "&'static [(char, char)]", is_pub=True,
295 pfun=lambda x: "(%s,%s)" % (escape_char(x[0]), escape_char(x[1]))):
299 f.write(" %sconst %s: %s = &[\n" % (pub_string, name, t_type))
307 format_table_content(f, data, 8)
310 def emit_trie_lookup_range_table(f):
312 pub struct BoolTrie {
313 // 0..0x800 (corresponding to 1 and 2 byte utf-8 sequences)
314 r1: [u64; 32], // leaves
316 // 0x800..0x10000 (corresponding to 3 byte utf-8 sequences)
317 r2: [u8; 1024], // first level
318 r3: &'static [u64], // leaves
320 // 0x10000..0x110000 (corresponding to 4 byte utf-8 sequences)
321 r4: [u8; 272], // first level
322 r5: &'static [u8], // second level
323 r6: &'static [u64], // leaves
326 fn trie_range_leaf(c: usize, bitmap_chunk: u64) -> bool {
327 ((bitmap_chunk >> (c & 63)) & 1) != 0
330 fn trie_lookup_range_table(c: char, r: &'static BoolTrie) -> bool {
333 trie_range_leaf(c, r.r1[c >> 8])
334 } else if c < 0x10000 {
335 let child = r.r2[c >> 6];
336 trie_range_leaf(c, r.r3[child as usize])
338 let child = r.r4[c >> 12];
339 let leaf = r.r5[((child as usize) << 6) + ((c >> 6) & 0x3f)];
340 trie_range_leaf(c, r.r6[leaf as usize])
345 def compute_trie(rawdata, chunksize):
349 for i in range(len(rawdata) / chunksize):
350 data = rawdata[i * chunksize: (i + 1) * chunksize]
351 child = '|'.join(map(str, data))
352 if child not in childmap:
353 childmap[child] = len(childmap)
354 child_data.extend(data)
355 root.append(childmap[child])
356 return (root, child_data)
358 def emit_bool_trie(f, name, t_data, is_pub=True):
360 rawdata = [False] * 0x110000;
361 for (lo, hi) in t_data:
362 for cp in range(lo, hi + 1):
365 # convert to bitmap chunks of 64 bits each
367 for i in range(0x110000 / CHUNK):
370 if rawdata[i * 64 + j]:
377 f.write(" %sconst %s: &'static super::BoolTrie = &super::BoolTrie {\n" % (pub_string, name))
379 data = ','.join('0x%016x' % chunk for chunk in chunks[0:0x800 / CHUNK])
380 format_table_content(f, data, 12)
383 # 0x800..0x10000 trie
384 (r2, r3) = compute_trie(chunks[0x800 / CHUNK : 0x10000 / CHUNK], 64 / CHUNK)
386 data = ','.join(str(node) for node in [255] * 32 + r2)
387 format_table_content(f, data, 12)
390 data = ','.join('0x%016x' % chunk for chunk in r3)
391 format_table_content(f, data, 12)
394 # 0x10000..0x110000 trie
395 (mid, r6) = compute_trie(chunks[0x10000 / CHUNK : 0x110000 / CHUNK], 64 / CHUNK)
396 (r4, r5) = compute_trie(mid, 64)
398 data = ','.join(str(node) for node in [255] * 16 + r4)
399 format_table_content(f, data, 12)
402 data = ','.join(str(node) for node in r5)
403 format_table_content(f, data, 12)
406 data = ','.join('0x%016x' % chunk for chunk in r6)
407 format_table_content(f, data, 12)
412 def emit_property_module(f, mod, tbl, emit):
413 f.write("pub mod %s {\n" % mod)
414 for cat in sorted(emit):
415 emit_bool_trie(f, "%s_table" % cat, tbl[cat])
416 f.write(" pub fn %s(c: char) -> bool {\n" % cat)
417 f.write(" super::trie_lookup_range_table(c, %s_table)\n" % cat)
421 def emit_conversions_module(f, to_upper, to_lower, to_title):
422 f.write("pub mod conversions {")
424 use core::option::Option;
425 use core::option::Option::{Some, None};
427 pub fn to_lower(c: char) -> [char; 3] {
428 match bsearch_case_table(c, to_lowercase_table) {
429 None => [c, '\\0', '\\0'],
430 Some(index) => to_lowercase_table[index].1,
434 pub fn to_upper(c: char) -> [char; 3] {
435 match bsearch_case_table(c, to_uppercase_table) {
436 None => [c, '\\0', '\\0'],
437 Some(index) => to_uppercase_table[index].1,
441 fn bsearch_case_table(c: char, table: &'static [(char, [char; 3])]) -> Option<usize> {
442 table.binary_search_by(|&(key, _)| key.cmp(&c)).ok()
446 t_type = "&'static [(char, [char; 3])]"
447 pfun = lambda x: "(%s,[%s,%s,%s])" % (
448 escape_char(x[0]), escape_char(x[1][0]), escape_char(x[1][1]), escape_char(x[1][2]))
449 emit_table(f, "to_lowercase_table",
450 sorted(to_lower.iteritems(), key=operator.itemgetter(0)),
451 is_pub=False, t_type = t_type, pfun=pfun)
452 emit_table(f, "to_uppercase_table",
453 sorted(to_upper.iteritems(), key=operator.itemgetter(0)),
454 is_pub=False, t_type = t_type, pfun=pfun)
457 def emit_norm_module(f, canon, compat, combine, norm_props):
458 canon_keys = canon.keys()
461 compat_keys = compat.keys()
465 comp_exclusions = norm_props["Full_Composition_Exclusion"]
466 for char in canon_keys:
467 if True in map(lambda (lo, hi): lo <= char <= hi, comp_exclusions):
471 if not canon_comp.has_key(decomp[0]):
472 canon_comp[decomp[0]] = []
473 canon_comp[decomp[0]].append( (decomp[1], char) )
474 canon_comp_keys = canon_comp.keys()
475 canon_comp_keys.sort()
477 if __name__ == "__main__":
479 if os.path.exists(r):
481 with open(r, "w") as rf:
482 # write the file's preamble
485 # download and parse all the data
487 with open("ReadMe.txt") as readme:
488 pattern = "for Version (\d+)\.(\d+)\.(\d+) of the Unicode"
489 unicode_version = re.search(pattern, readme.read()).groups()
491 /// The version of [Unicode](http://www.unicode.org/)
492 /// that the unicode parts of `CharExt` and `UnicodeStrPrelude` traits are based on.
493 pub const UNICODE_VERSION: (u64, u64, u64) = (%s, %s, %s);
494 """ % unicode_version)
495 (canon_decomp, compat_decomp, gencats, combines,
496 to_upper, to_lower, to_title) = load_unicode_data("UnicodeData.txt")
497 load_special_casing("SpecialCasing.txt", to_upper, to_lower, to_title)
498 want_derived = ["XID_Start", "XID_Continue", "Alphabetic", "Lowercase", "Uppercase",
499 "Cased", "Case_Ignorable"]
500 derived = load_properties("DerivedCoreProperties.txt", want_derived)
501 scripts = load_properties("Scripts.txt", [])
502 props = load_properties("PropList.txt",
503 ["White_Space", "Join_Control", "Noncharacter_Code_Point", "Pattern_White_Space"])
504 norm_props = load_properties("DerivedNormalizationProps.txt",
505 ["Full_Composition_Exclusion"])
507 # trie_lookup_table is used in all the property modules below
508 emit_trie_lookup_range_table(rf)
509 # emit_bsearch_range_table(rf)
512 for (name, cat, pfuns) in ("general_category", gencats, ["N", "Cc"]), \
513 ("derived_property", derived, want_derived), \
514 ("property", props, ["White_Space", "Pattern_White_Space"]):
515 emit_property_module(rf, name, cat, pfuns)
517 # normalizations and conversions module
518 emit_norm_module(rf, canon_decomp, compat_decomp, combines, norm_props)
519 emit_conversions_module(rf, to_upper, to_lower, to_title)