]> git.lizzy.rs Git - rust.git/blob - src/libcore/unicode/unicode.py
Auto merge of #52712 - oli-obk:const_eval_cleanups, r=RalfJung
[rust.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 tables.rs file into git.
25
26 import fileinput, re, os, sys, operator, math, datetime
27
28 # The directory in which this file resides.
29 fdir = os.path.dirname(os.path.realpath(__file__)) + "/"
30
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.
34 //
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.
40
41 // NOTE: The following code was generated by "./unicode.py", do not edit directly
42
43 #![allow(missing_docs, non_upper_case_globals, non_snake_case)]
44
45 use unicode::version::UnicodeVersion;
46 use unicode::bool_trie::{{BoolTrie, SmallBoolTrie}};
47 '''.format(year = datetime.datetime.now().year)
48
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'],
61 }
62
63 # these are the surrogate codepoints, which are not valid rust characters
64 surrogate_codepoints = (0xd800, 0xdfff)
65
66 def fetch(f):
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))
70
71     if not os.path.exists(path):
72         sys.stderr.write("cannot load %s" % f)
73         exit(1)
74
75 def is_surrogate(n):
76     return surrogate_codepoints[0] <= n <= surrogate_codepoints[1]
77
78 def load_unicode_data(f):
79     fetch(f)
80     gencats = {}
81     to_lower = {}
82     to_upper = {}
83     to_title = {}
84     combines = {}
85     canon_decomp = {}
86     compat_decomp = {}
87
88     udict = {}
89     range_start = -1
90     for line in fileinput.input(fdir + f):
91         data = line.split(';')
92         if len(data) != 15:
93             continue
94         cp = int(data[0], 16)
95         if is_surrogate(cp):
96             continue
97         if range_start >= 0:
98             for i in range(range_start, cp):
99                 udict[i] = data
100             range_start = -1
101         if data[1].endswith(", First>"):
102             range_start = cp
103             continue
104         udict[cp] = data
105
106     for code in udict:
107         (code_org, name, gencat, combine, bidi,
108          decomp, deci, digit, num, mirror,
109          old, iso, upcase, lowcase, titlecase) = udict[code]
110
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)
115
116         # lowercase to uppercase
117         if upcase != "" and code_org != upcase:
118             to_upper[code] = (int(upcase, 16), 0, 0)
119
120         # title case
121         if titlecase.strip() != "" and code_org != titlecase:
122             to_title[code] = (int(titlecase, 16), 0, 0)
123
124         # store decomposition, if given
125         if decomp != "":
126             if decomp.startswith('<'):
127                 seq = []
128                 for i in decomp.split()[1:]:
129                     seq.append(int(i, 16))
130                 compat_decomp[code] = seq
131             else:
132                 seq = []
133                 for i in decomp.split():
134                     seq.append(int(i, 16))
135                 canon_decomp[code] = seq
136
137         # place letter in categories as appropriate
138         for cat in [gencat, "Assigned"] + expanded_categories.get(gencat, []):
139             if cat not in gencats:
140                 gencats[cat] = []
141             gencats[cat].append(code)
142
143         # record combining class, if any
144         if combine != "0":
145             if combine not in combines:
146                 combines[combine] = []
147             combines[combine].append(code)
148
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))
157
158     return (canon_decomp, compat_decomp, gencats, combines, to_upper, to_lower, to_title)
159
160 def load_special_casing(f, to_upper, to_lower, to_title):
161     fetch(f)
162     for line in fileinput.input(fdir + f):
163         data = line.split('#')[0].split(';')
164         if len(data) == 5:
165             code, lower, title, upper, _comment = data
166         elif len(data) == 6:
167             code, lower, title, upper, condition, _comment = data
168             if condition.strip():  # Only keep unconditional mappins
169                 continue
170         else:
171             continue
172         code = code.strip()
173         lower = lower.strip()
174         title = title.strip()
175         upper = upper.strip()
176         key = int(code, 16)
177         for (map_, values) in [(to_lower, lower), (to_upper, upper), (to_title, title)]:
178             if values != code:
179                 values = [int(i, 16) for i in values.split()]
180                 for _ in range(len(values), 3):
181                     values.append(0)
182                 assert len(values) == 3
183                 map_[key] = values
184
185 def group_cats(cats):
186     cats_out = {}
187     for cat in cats:
188         cats_out[cat] = group_cat(cats[cat])
189     return cats_out
190
191 def group_cat(cat):
192     cat_out = []
193     letters = sorted(set(cat))
194     cur_start = letters.pop(0)
195     cur_end = cur_start
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:
200             cur_end = letter
201         else:
202             cat_out.append((cur_start, cur_end))
203             cur_start = cur_end = letter
204     cat_out.append((cur_start, cur_end))
205     return cat_out
206
207 def ungroup_cat(cat):
208     cat_out = []
209     for (lo, hi) in cat:
210         while lo <= hi:
211             cat_out.append(lo)
212             lo += 1
213     return cat_out
214
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])
219
220 def to_combines(combs):
221     combs_out = []
222     for comb in combs:
223         for (lo, hi) in combs[comb]:
224             combs_out.append((lo, hi, comb))
225     combs_out.sort(key=lambda comb: comb[0])
226     return combs_out
227
228 def format_table_content(f, content, indent):
229     line = " "*indent
230     first = True
231     for chunk in content.split(","):
232         if len(line) + len(chunk) < 98:
233             if first:
234                 line += chunk
235             else:
236                 line += ", " + chunk
237             first = False
238         else:
239             f.write(line + ",\n")
240             line = " "*indent + chunk
241     f.write(line)
242
243 def load_properties(f, interestingprops):
244     fetch(f)
245     props = {}
246     re1 = re.compile("^ *([0-9A-F]+) *; *(\w+)")
247     re2 = re.compile("^ *([0-9A-F]+)\.\.([0-9A-F]+) *; *(\w+)")
248
249     for line in fileinput.input(fdir + os.path.basename(f)):
250         prop = None
251         d_lo = 0
252         d_hi = 0
253         m = re1.match(line)
254         if m:
255             d_lo = m.group(1)
256             d_hi = m.group(1)
257             prop = m.group(2)
258         else:
259             m = re2.match(line)
260             if m:
261                 d_lo = m.group(1)
262                 d_hi = m.group(2)
263                 prop = m.group(3)
264             else:
265                 continue
266         if interestingprops and prop not in interestingprops:
267             continue
268         d_lo = int(d_lo, 16)
269         d_hi = int(d_hi, 16)
270         if prop not in props:
271             props[prop] = []
272         props[prop].append((d_lo, d_hi))
273
274     # optimize if possible
275     for prop in props:
276         props[prop] = group_cat(ungroup_cat(props[prop]))
277
278     return props
279
280 def escape_char(c):
281     return "'\\u{%x}'" % c if c != 0 else "'\\0'"
282
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]))):
285     pub_string = ""
286     if is_pub:
287         pub_string = "pub "
288     f.write("    %sconst %s: %s = &[\n" % (pub_string, name, t_type))
289     data = ""
290     first = True
291     for dat in t_data:
292         if not first:
293             data += ","
294         first = False
295         data += pfun(dat)
296     format_table_content(f, data, 8)
297     f.write("\n    ];\n\n")
298
299 def compute_trie(rawdata, chunksize):
300     root = []
301     childmap = {}
302     child_data = []
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)
311
312 def emit_bool_trie(f, name, t_data, is_pub=True):
313     CHUNK = 64
314     rawdata = [False] * 0x110000
315     for (lo, hi) in t_data:
316         for cp in range(lo, hi + 1):
317             rawdata[cp] = True
318
319     # convert to bitmap chunks of 64 bits each
320     chunks = []
321     for i in range(0x110000 // CHUNK):
322         chunk = 0
323         for j in range(64):
324             if rawdata[i * 64 + j]:
325                 chunk |= 1 << j
326         chunks.append(chunk)
327
328     pub_string = ""
329     if is_pub:
330         pub_string = "pub "
331     f.write("    %sconst %s: &super::BoolTrie = &super::BoolTrie {\n" % (pub_string, name))
332     f.write("        r1: [\n")
333     data = ','.join('0x%016x' % chunk for chunk in chunks[0:0x800 // CHUNK])
334     format_table_content(f, data, 12)
335     f.write("\n        ],\n")
336
337     # 0x800..0x10000 trie
338     (r2, r3) = compute_trie(chunks[0x800 // CHUNK : 0x10000 // CHUNK], 64 // CHUNK)
339     f.write("        r2: [\n")
340     data = ','.join(str(node) for node in r2)
341     format_table_content(f, data, 12)
342     f.write("\n        ],\n")
343     f.write("        r3: &[\n")
344     data = ','.join('0x%016x' % chunk for chunk in r3)
345     format_table_content(f, data, 12)
346     f.write("\n        ],\n")
347
348     # 0x10000..0x110000 trie
349     (mid, r6) = compute_trie(chunks[0x10000 // CHUNK : 0x110000 // CHUNK], 64 // CHUNK)
350     (r4, r5) = compute_trie(mid, 64)
351     f.write("        r4: [\n")
352     data = ','.join(str(node) for node in r4)
353     format_table_content(f, data, 12)
354     f.write("\n        ],\n")
355     f.write("        r5: &[\n")
356     data = ','.join(str(node) for node in r5)
357     format_table_content(f, data, 12)
358     f.write("\n        ],\n")
359     f.write("        r6: &[\n")
360     data = ','.join('0x%016x' % chunk for chunk in r6)
361     format_table_content(f, data, 12)
362     f.write("\n        ],\n")
363
364     f.write("    };\n\n")
365
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)
375
376     pub_string = ""
377     if is_pub:
378         pub_string = "pub "
379     f.write("    %sconst %s: &super::SmallBoolTrie = &super::SmallBoolTrie {\n"
380             % (pub_string, name))
381
382     (r1, r2) = compute_trie(chunks, 1)
383
384     f.write("        r1: &[\n")
385     data = ','.join(str(node) for node in r1)
386     format_table_content(f, data, 12)
387     f.write("\n        ],\n")
388
389     f.write("        r2: &[\n")
390     data = ','.join('0x%016x' % node for node in r2)
391     format_table_content(f, data, 12)
392     f.write("\n        ],\n")
393
394     f.write("    };\n\n")
395
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)
403             f.write("    }\n\n")
404         else:
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)
408             f.write("    }\n\n")
409     f.write("}\n\n")
410
411 def emit_conversions_module(f, to_upper, to_lower, to_title):
412     f.write("pub mod conversions {")
413     f.write("""
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,
418         }
419     }
420
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,
425         }
426     }
427
428     fn bsearch_case_table(c: char, table: &[(char, [char; 3])]) -> Option<usize> {
429         table.binary_search_by(|&(key, _)| key.cmp(&c)).ok()
430     }
431
432 """)
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)
442     f.write("}\n\n")
443
444 def emit_norm_module(f, canon, compat, combine, norm_props):
445     canon_keys = sorted(canon.keys())
446
447     compat_keys = sorted(compat.keys())
448
449     canon_comp = {}
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):
453             continue
454         decomp = canon[char]
455         if len(decomp) == 2:
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())
460
461 if __name__ == "__main__":
462     r = fdir + "tables.rs"
463     if os.path.exists(r):
464         os.remove(r)
465     with open(r, "w") as rf:
466         # write the file's preamble
467         rf.write(preamble)
468
469         # download and parse all the data
470         fetch("ReadMe.txt")
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()
474         rf.write("""
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 {
479     major: %s,
480     minor: %s,
481     micro: %s,
482     _priv: (),
483 };
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"])
496
497         # category tables
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)
502
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.")