]>
git.proxmox.com Git - rustc.git/blob - src/vendor/unicode-width/scripts/unicode.py
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.
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 # - EastAsianWidth.txt
18 # Since this should not require frequent updates, we just store this
19 # out-of-line and check the unicode.rs file into git.
21 import fileinput
, re
, os
, sys
, operator
23 preamble
= '''// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
24 // file at the top-level directory of this distribution and at
25 // http://rust-lang.org/COPYRIGHT.
27 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
28 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
29 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
30 // option. This file may not be copied, modified, or distributed
31 // except according to those terms.
33 // NOTE: The following code was generated by "scripts/unicode.py", do not edit directly
35 #![allow(missing_docs, non_upper_case_globals, non_snake_case)]
38 # Mapping taken from Table 12 from:
39 # http://www.unicode.org/reports/tr44/#General_Category_Values
40 expanded_categories
= {
41 'Lu': ['LC', 'L'], 'Ll': ['LC', 'L'], 'Lt': ['LC', 'L'],
42 'Lm': ['L'], 'Lo': ['L'],
43 'Mn': ['M'], 'Mc': ['M'], 'Me': ['M'],
44 'Nd': ['N'], 'Nl': ['N'], 'No': ['No'],
45 'Pc': ['P'], 'Pd': ['P'], 'Ps': ['P'], 'Pe': ['P'],
46 'Pi': ['P'], 'Pf': ['P'], 'Po': ['P'],
47 'Sm': ['S'], 'Sc': ['S'], 'Sk': ['S'], 'So': ['S'],
48 'Zs': ['Z'], 'Zl': ['Z'], 'Zp': ['Z'],
49 'Cc': ['C'], 'Cf': ['C'], 'Cs': ['C'], 'Co': ['C'], 'Cn': ['C'],
52 # these are the surrogate codepoints, which are not valid rust characters
53 surrogate_codepoints
= (0xd800, 0xdfff)
56 if not os
.path
.exists(os
.path
.basename(f
)):
57 os
.system("curl -O http://www.unicode.org/Public/UNIDATA/%s"
60 if not os
.path
.exists(os
.path
.basename(f
)):
61 sys
.stderr
.write("cannot load %s" % f
)
65 return surrogate_codepoints
[0] <= n
<= surrogate_codepoints
[1]
67 def load_unicode_data(f
):
73 for line
in fileinput
.input(f
):
74 data
= line
.split(';');
77 cp
= int(data
[0], 16);
81 for i
in xrange(range_start
, cp
):
84 if data
[1].endswith(", First>"):
90 [code_org
, name
, gencat
, combine
, bidi
,
91 decomp
, deci
, digit
, num
, mirror
,
92 old
, iso
, upcase
, lowcase
, titlecase
] = udict
[code
];
94 # place letter in categories as appropriate
95 for cat
in [gencat
, "Assigned"] + expanded_categories
.get(gencat
, []):
96 if cat
not in gencats
:
98 gencats
[cat
].append(code
)
100 gencats
= group_cats(gencats
)
104 def group_cats(cats
):
107 cats_out
[cat
] = group_cat(cats
[cat
])
112 letters
= sorted(set(cat
))
113 cur_start
= letters
.pop(0)
115 for letter
in letters
:
116 assert letter
> cur_end
, \
117 "cur_end: %s, letter: %s" % (hex(cur_end
), hex(letter
))
118 if letter
== cur_end
+ 1:
121 cat_out
.append((cur_start
, cur_end
))
122 cur_start
= cur_end
= letter
123 cat_out
.append((cur_start
, cur_end
))
126 def format_table_content(f
, content
, indent
):
129 for chunk
in content
.split(","):
130 if len(line
) + len(chunk
) < 98:
137 f
.write(line
+ ",\n")
138 line
= " "*indent
+ chunk
141 # load all widths of want_widths, except those in except_cats
142 def load_east_asian_width(want_widths
, except_cats
):
143 f
= "EastAsianWidth.txt"
146 re1
= re
.compile("^([0-9A-F]+);(\w+) +# (\w+)")
147 re2
= re
.compile("^([0-9A-F]+)\.\.([0-9A-F]+);(\w+) +# (\w+)")
149 for line
in fileinput
.input(f
):
169 if cat
in except_cats
or width
not in want_widths
:
173 if width
not in widths
:
175 widths
[width
].append((d_lo
, d_hi
))
179 return "'\\u{%x}'" % c
181 def emit_table(f
, name
, t_data
, t_type
= "&'static [(char, char)]", is_pub
=True,
182 pfun
=lambda x
: "(%s,%s)" % (escape_char(x
[0]), escape_char(x
[1])), is_const
=True):
187 pub_string
= "pub " + pub_string
188 f
.write(" %s %s: %s = &[\n" % (pub_string
, name
, t_type
))
196 format_table_content(f
, data
, 8)
199 def emit_charwidth_module(f
, width_table
):
200 f
.write("pub mod charwidth {")
202 use core::option::Option::{self, Some, None};
203 use core::result::Result::{Ok, Err};
206 fn bsearch_range_value_table(c: char, is_cjk: bool, r: &'static [(char, char, u8, u8)]) -> u8 {
207 use core::cmp::Ordering::{Equal, Less, Greater};
208 match r.binary_search_by(|&(lo, hi, _, _)| {
209 if lo <= c && c <= hi { Equal }
210 else if hi < c { Less }
214 let (_, _, r_ncjk, r_cjk) = r[idx];
215 if is_cjk { r_cjk } else { r_ncjk }
224 pub fn width(c: char, is_cjk: bool) -> Option<usize> {
226 _c @ 0 => Some(0), // null is zero width
227 cu if cu < 0x20 => None, // control sequences have no width
228 cu if cu < 0x7F => Some(1), // ASCII
229 cu if cu < 0xA0 => None, // more control sequences
230 _ => Some(bsearch_range_value_table(c, is_cjk, charwidth_table) as usize)
236 f
.write(" // character width table. Based on Markus Kuhn's free wcwidth() implementation,\n")
237 f
.write(" // http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c\n")
238 emit_table(f
, "charwidth_table", width_table
, "&'static [(char, char, u8, u8)]", is_pub
=False,
239 pfun
=lambda x
: "(%s,%s,%s,%s)" % (escape_char(x
[0]), escape_char(x
[1]), x
[2], x
[3]))
242 def remove_from_wtable(wtable
, val
):
245 if wtable
[0][1] < val
:
246 wtable_out
.append(wtable
.pop(0))
247 elif wtable
[0][0] > val
:
250 (wt_lo
, wt_hi
, width
, width_cjk
) = wtable
.pop(0)
251 if wt_lo
== wt_hi
== val
:
254 wtable_out
.append((wt_lo
+1, wt_hi
, width
, width_cjk
))
256 wtable_out
.append((wt_lo
, wt_hi
-1, width
, width_cjk
))
258 wtable_out
.append((wt_lo
, val
-1, width
, width_cjk
))
259 wtable_out
.append((val
+1, wt_hi
, width
, width_cjk
))
261 wtable_out
.extend(wtable
)
266 def optimize_width_table(wtable
):
268 w_this
= wtable
.pop(0)
270 if w_this
[1] == wtable
[0][0] - 1 and w_this
[2:3] == wtable
[0][2:3]:
271 w_tmp
= wtable
.pop(0)
272 w_this
= (w_this
[0], w_tmp
[1], w_tmp
[2], w_tmp
[3])
274 wtable_out
.append(w_this
)
275 w_this
= wtable
.pop(0)
276 wtable_out
.append(w_this
)
279 if __name__
== "__main__":
281 if os
.path
.exists(r
):
283 with
open(r
, "w") as rf
:
284 # write the file's preamble
287 # download and parse all the data
289 with
open("ReadMe.txt") as readme
:
290 pattern
= "for Version (\d+)\.(\d+)\.(\d+) of the Unicode"
291 unicode_version
= re
.search(pattern
, readme
.read()).groups()
293 /// The version of [Unicode](http://www.unicode.org/)
294 /// that this version of unicode-width is based on.
295 pub const UNICODE_VERSION: (u64, u64, u64) = (%s, %s, %s);
297 """ % unicode_version
)
298 gencats
= load_unicode_data("UnicodeData.txt")
300 ### character width module
302 for zwcat
in ["Me", "Mn", "Cf"]:
303 width_table
.extend(map(lambda (lo
, hi
): (lo
, hi
, 0, 0), gencats
[zwcat
]))
304 width_table
.append((4448, 4607, 0, 0))
306 # get widths, except those that are explicitly marked zero-width above
307 ea_widths
= load_east_asian_width(["W", "F", "A"], ["Me", "Mn", "Cf"])
308 # these are doublewidth
309 for dwcat
in ["W", "F"]:
310 width_table
.extend(map(lambda (lo
, hi
): (lo
, hi
, 2, 2), ea_widths
[dwcat
]))
311 width_table
.extend(map(lambda (lo
, hi
): (lo
, hi
, 1, 2), ea_widths
["A"]))
313 width_table
.sort(key
=lambda w
: w
[0])
315 # soft hyphen is not zero width in preformatted text; it's used to indicate
316 # a hyphen inserted to facilitate a linebreak.
317 width_table
= remove_from_wtable(width_table
, 173)
319 # optimize the width table by collapsing adjacent entities when possible
320 width_table
= optimize_width_table(width_table
)
321 emit_charwidth_module(rf
, width_table
)