]> git.proxmox.com Git - rustc.git/blob - src/vendor/unicode-segmentation/scripts/unicode.py
New upstream version 1.17.0+dfsg1
[rustc.git] / src / vendor / unicode-segmentation / scripts / unicode.py
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 # - auxiliary/GraphemeBreakProperty.txt
16 # - auxiliary/WordBreakProperty.txt
17 # - ReadMe.txt
18 # - UnicodeData.txt
19 #
20 # Since this should not require frequent updates, we just store this
21 # out-of-line and check the unicode.rs file into git.
22
23 import fileinput, re, os, sys, operator
24
25 preamble = '''// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
26 // file at the top-level directory of this distribution and at
27 // http://rust-lang.org/COPYRIGHT.
28 //
29 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
30 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
31 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
32 // option. This file may not be copied, modified, or distributed
33 // except according to those terms.
34
35 // NOTE: The following code was generated by "scripts/unicode.py", do not edit directly
36
37 #![allow(missing_docs, non_upper_case_globals, non_snake_case)]
38 '''
39
40 # Mapping taken from Table 12 from:
41 # http://www.unicode.org/reports/tr44/#General_Category_Values
42 expanded_categories = {
43 'Lu': ['LC', 'L'], 'Ll': ['LC', 'L'], 'Lt': ['LC', 'L'],
44 'Lm': ['L'], 'Lo': ['L'],
45 'Mn': ['M'], 'Mc': ['M'], 'Me': ['M'],
46 'Nd': ['N'], 'Nl': ['N'], 'No': ['No'],
47 'Pc': ['P'], 'Pd': ['P'], 'Ps': ['P'], 'Pe': ['P'],
48 'Pi': ['P'], 'Pf': ['P'], 'Po': ['P'],
49 'Sm': ['S'], 'Sc': ['S'], 'Sk': ['S'], 'So': ['S'],
50 'Zs': ['Z'], 'Zl': ['Z'], 'Zp': ['Z'],
51 'Cc': ['C'], 'Cf': ['C'], 'Cs': ['C'], 'Co': ['C'], 'Cn': ['C'],
52 }
53
54 # these are the surrogate codepoints, which are not valid rust characters
55 surrogate_codepoints = (0xd800, 0xdfff)
56
57 def is_surrogate(n):
58 return surrogate_codepoints[0] <= n <= surrogate_codepoints[1]
59
60 def fetch(f):
61 if not os.path.exists(os.path.basename(f)):
62 os.system("curl -O http://www.unicode.org/Public/UNIDATA/%s"
63 % f)
64
65 if not os.path.exists(os.path.basename(f)):
66 sys.stderr.write("cannot load %s" % f)
67 exit(1)
68
69 def load_gencats(f):
70 fetch(f)
71 gencats = {}
72
73 udict = {};
74 range_start = -1;
75 for line in fileinput.input(f):
76 data = line.split(';');
77 if len(data) != 15:
78 continue
79 cp = int(data[0], 16);
80 if is_surrogate(cp):
81 continue
82 if range_start >= 0:
83 for i in xrange(range_start, cp):
84 udict[i] = data;
85 range_start = -1;
86 if data[1].endswith(", First>"):
87 range_start = cp;
88 continue;
89 udict[cp] = data;
90
91 for code in udict:
92 [code_org, name, gencat, combine, bidi,
93 decomp, deci, digit, num, mirror,
94 old, iso, upcase, lowcase, titlecase ] = udict[code];
95
96 # place letter in categories as appropriate
97 for cat in [gencat, "Assigned"] + expanded_categories.get(gencat, []):
98 if cat not in gencats:
99 gencats[cat] = []
100 gencats[cat].append(code)
101
102 gencats = group_cats(gencats)
103 return gencats
104
105 def group_cats(cats):
106 cats_out = {}
107 for cat in cats:
108 cats_out[cat] = group_cat(cats[cat])
109 return cats_out
110
111 def group_cat(cat):
112 cat_out = []
113 letters = sorted(set(cat))
114 cur_start = letters.pop(0)
115 cur_end = cur_start
116 for letter in letters:
117 assert letter > cur_end, \
118 "cur_end: %s, letter: %s" % (hex(cur_end), hex(letter))
119 if letter == cur_end + 1:
120 cur_end = letter
121 else:
122 cat_out.append((cur_start, cur_end))
123 cur_start = cur_end = letter
124 cat_out.append((cur_start, cur_end))
125 return cat_out
126
127 def ungroup_cat(cat):
128 cat_out = []
129 for (lo, hi) in cat:
130 while lo <= hi:
131 cat_out.append(lo)
132 lo += 1
133 return cat_out
134
135 def format_table_content(f, content, indent):
136 line = " "*indent
137 first = True
138 for chunk in content.split(","):
139 if len(line) + len(chunk) < 98:
140 if first:
141 line += chunk
142 else:
143 line += ", " + chunk
144 first = False
145 else:
146 f.write(line + ",\n")
147 line = " "*indent + chunk
148 f.write(line)
149
150 def load_properties(f, interestingprops):
151 fetch(f)
152 props = {}
153 re1 = re.compile("^ *([0-9A-F]+) *; *(\w+)")
154 re2 = re.compile("^ *([0-9A-F]+)\.\.([0-9A-F]+) *; *(\w+)")
155
156 for line in fileinput.input(os.path.basename(f)):
157 prop = None
158 d_lo = 0
159 d_hi = 0
160 m = re1.match(line)
161 if m:
162 d_lo = m.group(1)
163 d_hi = m.group(1)
164 prop = m.group(2)
165 else:
166 m = re2.match(line)
167 if m:
168 d_lo = m.group(1)
169 d_hi = m.group(2)
170 prop = m.group(3)
171 else:
172 continue
173 if interestingprops and prop not in interestingprops:
174 continue
175 d_lo = int(d_lo, 16)
176 d_hi = int(d_hi, 16)
177 if prop not in props:
178 props[prop] = []
179 props[prop].append((d_lo, d_hi))
180
181 # optimize if possible
182 for prop in props:
183 props[prop] = group_cat(ungroup_cat(props[prop]))
184
185 return props
186
187 def escape_char(c):
188 return "'\\u{%x}'" % c
189
190 def emit_table(f, name, t_data, t_type = "&'static [(char, char)]", is_pub=True,
191 pfun=lambda x: "(%s,%s)" % (escape_char(x[0]), escape_char(x[1])), is_const=True):
192 pub_string = "const"
193 if not is_const:
194 pub_string = "let"
195 if is_pub:
196 pub_string = "pub " + pub_string
197 f.write(" %s %s: %s = &[\n" % (pub_string, name, t_type))
198 data = ""
199 first = True
200 for dat in t_data:
201 if not first:
202 data += ","
203 first = False
204 data += pfun(dat)
205 format_table_content(f, data, 8)
206 f.write("\n ];\n\n")
207
208 def emit_util_mod(f):
209 f.write("""
210 pub mod util {
211 #[inline]
212 pub fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool {
213 use core::cmp::Ordering::{Equal, Less, Greater};
214 r.binary_search_by(|&(lo,hi)| {
215 if lo <= c && c <= hi { Equal }
216 else if hi < c { Less }
217 else { Greater }
218 }).is_ok()
219 }
220
221 #[inline]
222 fn is_alphabetic(c: char) -> bool {
223 match c {
224 'a' ... 'z' | 'A' ... 'Z' => true,
225 c if c > '\x7f' => super::derived_property::Alphabetic(c),
226 _ => false,
227 }
228 }
229
230 #[inline]
231 fn is_numeric(c: char) -> bool {
232 match c {
233 '0' ... '9' => true,
234 c if c > '\x7f' => super::general_category::N(c),
235 _ => false,
236 }
237 }
238
239 #[inline]
240 pub fn is_alphanumeric(c: char) -> bool {
241 is_alphabetic(c) || is_numeric(c)
242 }
243 }
244
245 """)
246
247 def emit_property_module(f, mod, tbl, emit):
248 f.write("mod %s {\n" % mod)
249 for cat in sorted(emit):
250 emit_table(f, "%s_table" % cat, tbl[cat], is_pub=False)
251 f.write(" #[inline]\n")
252 f.write(" pub fn %s(c: char) -> bool {\n" % cat)
253 f.write(" super::util::bsearch_range_table(c, %s_table)\n" % cat)
254 f.write(" }\n\n")
255 f.write("}\n\n")
256
257 def emit_break_module(f, break_table, break_cats, name):
258 Name = name.capitalize()
259 f.write("""pub mod %s {
260 use core::result::Result::{Ok, Err};
261
262 pub use self::%sCat::*;
263
264 #[allow(non_camel_case_types)]
265 #[derive(Clone, Copy, PartialEq, Eq)]
266 pub enum %sCat {
267 """ % (name, Name, Name))
268
269 break_cats.append("Any")
270 break_cats.sort()
271 for cat in break_cats:
272 f.write((" %sC_" % Name[0]) + cat + ",\n")
273 f.write(""" }
274
275 fn bsearch_range_value_table(c: char, r: &'static [(char, char, %sCat)]) -> %sCat {
276 use core::cmp::Ordering::{Equal, Less, Greater};
277 match r.binary_search_by(|&(lo, hi, _)| {
278 if lo <= c && c <= hi { Equal }
279 else if hi < c { Less }
280 else { Greater }
281 }) {
282 Ok(idx) => {
283 let (_, _, cat) = r[idx];
284 cat
285 }
286 Err(_) => %sC_Any
287 }
288 }
289
290 pub fn %s_category(c: char) -> %sCat {
291 bsearch_range_value_table(c, %s_cat_table)
292 }
293
294 """ % (Name, Name, Name[0], name, Name, name))
295
296 emit_table(f, "%s_cat_table" % name, break_table, "&'static [(char, char, %sCat)]" % Name,
297 pfun=lambda x: "(%s,%s,%sC_%s)" % (escape_char(x[0]), escape_char(x[1]), Name[0], x[2]),
298 is_pub=False, is_const=True)
299 f.write("}\n")
300
301 if __name__ == "__main__":
302 r = "tables.rs"
303 if os.path.exists(r):
304 os.remove(r)
305 with open(r, "w") as rf:
306 # write the file's preamble
307 rf.write(preamble)
308
309 # download and parse all the data
310 fetch("ReadMe.txt")
311 with open("ReadMe.txt") as readme:
312 pattern = "for Version (\d+)\.(\d+)\.(\d+) of the Unicode"
313 unicode_version = re.search(pattern, readme.read()).groups()
314 rf.write("""
315 /// The version of [Unicode](http://www.unicode.org/)
316 /// that this version of unicode-segmentation is based on.
317 pub const UNICODE_VERSION: (u64, u64, u64) = (%s, %s, %s);
318 """ % unicode_version)
319
320 gencats = load_gencats("UnicodeData.txt")
321 derived = load_properties("DerivedCoreProperties.txt", ["Alphabetic"])
322
323 emit_util_mod(rf)
324 for (name, cat, pfuns) in ("general_category", gencats, ["N"]), \
325 ("derived_property", derived, ["Alphabetic"]):
326 emit_property_module(rf, name, cat, pfuns)
327
328 ### grapheme cluster module
329 # from http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Break_Property_Values
330 grapheme_cats = load_properties("auxiliary/GraphemeBreakProperty.txt", [])
331
332 # Control
333 # Note 1:
334 # This category also includes Cs (surrogate codepoints), but Rust's `char`s are
335 # Unicode Scalar Values only, and surrogates are thus invalid `char`s.
336 # Thus, we have to remove Cs from the Control category
337 # Note 2:
338 # 0x0a and 0x0d (CR and LF) are not in the Control category for Graphemes.
339 # However, the Graphemes iterator treats these as a special case, so they
340 # should be included in grapheme_cats["Control"] for our implementation.
341 grapheme_cats["Control"] = group_cat(list(
342 (set(ungroup_cat(grapheme_cats["Control"]))
343 | set(ungroup_cat(grapheme_cats["CR"]))
344 | set(ungroup_cat(grapheme_cats["LF"])))
345 - set(ungroup_cat([surrogate_codepoints]))))
346 del(grapheme_cats["CR"])
347 del(grapheme_cats["LF"])
348
349 grapheme_table = []
350 for cat in grapheme_cats:
351 grapheme_table.extend([(x, y, cat) for (x, y) in grapheme_cats[cat]])
352 grapheme_table.sort(key=lambda w: w[0])
353 emit_break_module(rf, grapheme_table, grapheme_cats.keys(), "grapheme")
354 rf.write("\n")
355
356 word_cats = load_properties("auxiliary/WordBreakProperty.txt", [])
357 word_table = []
358 for cat in word_cats:
359 word_table.extend([(x, y, cat) for (x, y) in word_cats[cat]])
360 word_table.sort(key=lambda w: w[0])
361 emit_break_module(rf, word_table, word_cats.keys(), "word")