]>
git.proxmox.com Git - rustc.git/blob - src/etc/unicode.py
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-2014 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
):
83 for line
in fileinput
.input(f
):
84 data
= line
.split(';');
87 cp
= int(data
[0], 16);
91 for i
in xrange(range_start
, cp
):
94 if data
[1].endswith(", First>"):
100 [code_org
, name
, gencat
, combine
, bidi
,
101 decomp
, deci
, digit
, num
, mirror
,
102 old
, iso
, upcase
, lowcase
, titlecase
] = udict
[code
];
104 # generate char to char direct common and simple conversions
105 # uppercase to lowercase
106 if gencat
== "Lu" and lowcase
!= "" and code_org
!= lowcase
:
107 upperlower
[code
] = int(lowcase
, 16)
109 # lowercase to uppercase
110 if gencat
== "Ll" and upcase
!= "" and code_org
!= upcase
:
111 lowerupper
[code
] = int(upcase
, 16)
113 # store decomposition, if given
115 if decomp
.startswith('<'):
117 for i
in decomp
.split()[1:]:
118 seq
.append(int(i
, 16))
119 compat_decomp
[code
] = seq
122 for i
in decomp
.split():
123 seq
.append(int(i
, 16))
124 canon_decomp
[code
] = seq
126 # place letter in categories as appropriate
127 for cat
in [gencat
, "Assigned"] + expanded_categories
.get(gencat
, []):
128 if cat
not in gencats
:
130 gencats
[cat
].append(code
)
132 # record combining class, if any
134 if combine
not in combines
:
135 combines
[combine
] = []
136 combines
[combine
].append(code
)
138 # generate Not_Assigned from Assigned
139 gencats
["Cn"] = gen_unassigned(gencats
["Assigned"])
140 # Assigned is not a real category
141 del(gencats
["Assigned"])
142 # Other contains Not_Assigned
143 gencats
["C"].extend(gencats
["Cn"])
144 gencats
= group_cats(gencats
)
145 combines
= to_combines(group_cats(combines
))
147 return (canon_decomp
, compat_decomp
, gencats
, combines
, lowerupper
, upperlower
)
149 def group_cats(cats
):
152 cats_out
[cat
] = group_cat(cats
[cat
])
157 letters
= sorted(set(cat
))
158 cur_start
= letters
.pop(0)
160 for letter
in letters
:
161 assert letter
> cur_end
, \
162 "cur_end: %s, letter: %s" % (hex(cur_end
), hex(letter
))
163 if letter
== cur_end
+ 1:
166 cat_out
.append((cur_start
, cur_end
))
167 cur_start
= cur_end
= letter
168 cat_out
.append((cur_start
, cur_end
))
171 def ungroup_cat(cat
):
179 def gen_unassigned(assigned
):
180 assigned
= set(assigned
)
181 return ([i
for i
in range(0, 0xd800) if i
not in assigned
] +
182 [i
for i
in range(0xe000, 0x110000) if i
not in assigned
])
184 def to_combines(combs
):
187 for (lo
, hi
) in combs
[comb
]:
188 combs_out
.append((lo
, hi
, comb
))
189 combs_out
.sort(key
=lambda comb
: comb
[0])
192 def format_table_content(f
, content
, indent
):
195 for chunk
in content
.split(","):
196 if len(line
) + len(chunk
) < 98:
203 f
.write(line
+ ",\n")
204 line
= " "*indent
+ chunk
207 def load_properties(f
, interestingprops
):
210 re1
= re
.compile("^([0-9A-F]+) +; (\w+)")
211 re2
= re
.compile("^([0-9A-F]+)\.\.([0-9A-F]+) +; (\w+)")
213 for line
in fileinput
.input(os
.path
.basename(f
)):
230 if interestingprops
and prop
not in interestingprops
:
234 if prop
not in props
:
236 props
[prop
].append((d_lo
, d_hi
))
239 # load all widths of want_widths, except those in except_cats
240 def load_east_asian_width(want_widths
, except_cats
):
241 f
= "EastAsianWidth.txt"
244 re1
= re
.compile("^([0-9A-F]+);(\w+) +# (\w+)")
245 re2
= re
.compile("^([0-9A-F]+)\.\.([0-9A-F]+);(\w+) +# (\w+)")
247 for line
in fileinput
.input(f
):
267 if cat
in except_cats
or width
not in want_widths
:
271 if width
not in widths
:
273 widths
[width
].append((d_lo
, d_hi
))
277 return "'\\u{%x}'" % c
279 def emit_bsearch_range_table(f
):
281 fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool {
282 use core::cmp::Ordering::{Equal, Less, Greater};
283 use core::slice::SliceExt;
284 r.binary_search_by(|&(lo,hi)| {
285 if lo <= c && c <= hi { Equal }
286 else if hi < c { Less }
292 def emit_table(f
, name
, t_data
, t_type
= "&'static [(char, char)]", is_pub
=True,
293 pfun
=lambda x
: "(%s,%s)" % (escape_char(x
[0]), escape_char(x
[1]))):
297 f
.write(" %sconst %s: %s = &[\n" % (pub_string
, name
, t_type
))
305 format_table_content(f
, data
, 8)
308 def emit_property_module(f
, mod
, tbl
, emit
):
309 f
.write("pub mod %s {\n" % mod
)
310 for cat
in sorted(emit
):
311 emit_table(f
, "%s_table" % cat
, tbl
[cat
])
312 f
.write(" pub fn %s(c: char) -> bool {\n" % cat
)
313 f
.write(" super::bsearch_range_table(c, %s_table)\n" % cat
)
317 def emit_conversions_module(f
, lowerupper
, upperlower
):
318 f
.write("pub mod conversions {")
320 use core::cmp::Ordering::{Equal, Less, Greater};
321 use core::slice::SliceExt;
322 use core::option::Option;
323 use core::option::Option::{Some, None};
324 use core::result::Result::{Ok, Err};
326 pub fn to_lower(c: char) -> char {
327 match bsearch_case_table(c, LuLl_table) {
329 Some(index) => LuLl_table[index].1
333 pub fn to_upper(c: char) -> char {
334 match bsearch_case_table(c, LlLu_table) {
336 Some(index) => LlLu_table[index].1
340 fn bsearch_case_table(c: char, table: &'static [(char, char)]) -> Option<usize> {
341 match table.binary_search_by(|&(key, _)| {
342 if c == key { Equal }
343 else if key < c { Less }
352 emit_table(f
, "LuLl_table",
353 sorted(upperlower
.iteritems(), key
=operator
.itemgetter(0)), is_pub
=False)
354 emit_table(f
, "LlLu_table",
355 sorted(lowerupper
.iteritems(), key
=operator
.itemgetter(0)), is_pub
=False)
358 def emit_grapheme_module(f
, grapheme_table
, grapheme_cats
):
359 f
.write("""pub mod grapheme {
360 use core::slice::SliceExt;
361 pub use self::GraphemeCat::*;
362 use core::result::Result::{Ok, Err};
364 #[allow(non_camel_case_types)]
365 #[derive(Clone, Copy)]
366 pub enum GraphemeCat {
368 for cat
in grapheme_cats
+ ["Any"]:
369 f
.write(" GC_" + cat
+ ",\n")
372 fn bsearch_range_value_table(c: char, r: &'static [(char, char, GraphemeCat)]) -> GraphemeCat {
373 use core::cmp::Ordering::{Equal, Less, Greater};
374 match r.binary_search_by(|&(lo, hi, _)| {
375 if lo <= c && c <= hi { Equal }
376 else if hi < c { Less }
380 let (_, _, cat) = r[idx];
387 pub fn grapheme_category(c: char) -> GraphemeCat {
388 bsearch_range_value_table(c, grapheme_cat_table)
393 emit_table(f
, "grapheme_cat_table", grapheme_table
, "&'static [(char, char, GraphemeCat)]",
394 pfun
=lambda x
: "(%s,%s,GC_%s)" % (escape_char(x
[0]), escape_char(x
[1]), x
[2]),
398 def emit_charwidth_module(f
, width_table
):
399 f
.write("pub mod charwidth {\n")
400 f
.write(" use core::option::Option;\n")
401 f
.write(" use core::option::Option::{Some, None};\n")
402 f
.write(" use core::slice::SliceExt;\n")
403 f
.write(" use core::result::Result::{Ok, Err};\n")
405 fn bsearch_range_value_table(c: char, is_cjk: bool, r: &'static [(char, char, u8, u8)]) -> u8 {
406 use core::cmp::Ordering::{Equal, Less, Greater};
407 match r.binary_search_by(|&(lo, hi, _, _)| {
408 if lo <= c && c <= hi { Equal }
409 else if hi < c { Less }
413 let (_, _, r_ncjk, r_cjk) = r[idx];
414 if is_cjk { r_cjk } else { r_ncjk }
422 pub fn width(c: char, is_cjk: bool) -> Option<usize> {
424 _c @ 0 => Some(0), // null is zero width
425 cu if cu < 0x20 => None, // control sequences have no width
426 cu if cu < 0x7F => Some(1), // ASCII
427 cu if cu < 0xA0 => None, // more control sequences
428 _ => Some(bsearch_range_value_table(c, is_cjk, charwidth_table) as usize)
434 f
.write(" // character width table. Based on Markus Kuhn's free wcwidth() implementation,\n")
435 f
.write(" // http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c\n")
436 emit_table(f
, "charwidth_table", width_table
, "&'static [(char, char, u8, u8)]", is_pub
=False,
437 pfun
=lambda x
: "(%s,%s,%s,%s)" % (escape_char(x
[0]), escape_char(x
[1]), x
[2], x
[3]))
440 def emit_norm_module(f
, canon
, compat
, combine
, norm_props
):
441 canon_keys
= canon
.keys()
444 compat_keys
= compat
.keys()
448 comp_exclusions
= norm_props
["Full_Composition_Exclusion"]
449 for char
in canon_keys
:
450 if True in map(lambda (lo
, hi
): lo
<= char
<= hi
, comp_exclusions
):
454 if not canon_comp
.has_key(decomp
[0]):
455 canon_comp
[decomp
[0]] = []
456 canon_comp
[decomp
[0]].append( (decomp
[1], char
) )
457 canon_comp_keys
= canon_comp
.keys()
458 canon_comp_keys
.sort()
460 f
.write("pub mod normalization {\n")
462 def mkdata_fun(table
):
464 data
= "(%s,&[" % escape_char(char
)
466 for d
in table
[char
]:
470 data
+= escape_char(d
)
475 f
.write(" // Canonical decompositions\n")
476 emit_table(f
, "canonical_table", canon_keys
, "&'static [(char, &'static [char])]",
477 pfun
=mkdata_fun(canon
))
479 f
.write(" // Compatibility decompositions\n")
480 emit_table(f
, "compatibility_table", compat_keys
, "&'static [(char, &'static [char])]",
481 pfun
=mkdata_fun(compat
))
484 data
= "(%s,&[" % escape_char(char
)
485 canon_comp
[char
].sort(lambda x
, y
: x
[0] - y
[0])
487 for pair
in canon_comp
[char
]:
491 data
+= "(%s,%s)" % (escape_char(pair
[0]), escape_char(pair
[1]))
495 f
.write(" // Canonical compositions\n")
496 emit_table(f
, "composition_table", canon_comp_keys
,
497 "&'static [(char, &'static [(char, char)])]", pfun
=comp_pfun
)
500 fn bsearch_range_value_table(c: char, r: &'static [(char, char, u8)]) -> u8 {
501 use core::cmp::Ordering::{Equal, Less, Greater};
502 use core::slice::SliceExt;
503 use core::result::Result::{Ok, Err};
504 match r.binary_search_by(|&(lo, hi, _)| {
505 if lo <= c && c <= hi { Equal }
506 else if hi < c { Less }
510 let (_, _, result) = r[idx];
518 emit_table(f
, "combining_class_table", combine
, "&'static [(char, char, u8)]", is_pub
=False,
519 pfun
=lambda x
: "(%s,%s,%s)" % (escape_char(x
[0]), escape_char(x
[1]), x
[2]))
521 f
.write(" pub fn canonical_combining_class(c: char) -> u8 {\n"
522 + " bsearch_range_value_table(c, combining_class_table)\n"
530 def remove_from_wtable(wtable
, val
):
533 if wtable
[0][1] < val
:
534 wtable_out
.append(wtable
.pop(0))
535 elif wtable
[0][0] > val
:
538 (wt_lo
, wt_hi
, width
, width_cjk
) = wtable
.pop(0)
539 if wt_lo
== wt_hi
== val
:
542 wtable_out
.append((wt_lo
+1, wt_hi
, width
, width_cjk
))
544 wtable_out
.append((wt_lo
, wt_hi
-1, width
, width_cjk
))
546 wtable_out
.append((wt_lo
, val
-1, width
, width_cjk
))
547 wtable_out
.append((val
+1, wt_hi
, width
, width_cjk
))
549 wtable_out
.extend(wtable
)
554 def optimize_width_table(wtable
):
556 w_this
= wtable
.pop(0)
558 if w_this
[1] == wtable
[0][0] - 1 and w_this
[2:3] == wtable
[0][2:3]:
559 w_tmp
= wtable
.pop(0)
560 w_this
= (w_this
[0], w_tmp
[1], w_tmp
[2], w_tmp
[3])
562 wtable_out
.append(w_this
)
563 w_this
= wtable
.pop(0)
564 wtable_out
.append(w_this
)
567 if __name__
== "__main__":
569 if os
.path
.exists(r
):
571 with
open(r
, "w") as rf
:
572 # write the file's preamble
575 # download and parse all the data
577 with
open("ReadMe.txt") as readme
:
578 pattern
= "for Version (\d+)\.(\d+)\.(\d+) of the Unicode"
579 unicode_version
= re
.search(pattern
, readme
.read()).groups()
581 /// The version of [Unicode](http://www.unicode.org/)
582 /// that the unicode parts of `CharExt` and `UnicodeStrPrelude` traits are based on.
583 pub const UNICODE_VERSION: (u64, u64, u64) = (%s, %s, %s);
584 """ % unicode_version
)
585 (canon_decomp
, compat_decomp
, gencats
, combines
,
586 lowerupper
, upperlower
) = load_unicode_data("UnicodeData.txt")
587 want_derived
= ["XID_Start", "XID_Continue", "Alphabetic", "Lowercase", "Uppercase"]
588 derived
= load_properties("DerivedCoreProperties.txt", want_derived
)
589 scripts
= load_properties("Scripts.txt", [])
590 props
= load_properties("PropList.txt",
591 ["White_Space", "Join_Control", "Noncharacter_Code_Point"])
592 norm_props
= load_properties("DerivedNormalizationProps.txt",
593 ["Full_Composition_Exclusion"])
595 # bsearch_range_table is used in all the property modules below
596 emit_bsearch_range_table(rf
)
599 for (name
, cat
, pfuns
) in ("general_category", gencats
, ["N", "Cc"]), \
600 ("derived_property", derived
, want_derived
), \
601 ("property", props
, ["White_Space"]):
602 emit_property_module(rf
, name
, cat
, pfuns
)
604 # normalizations and conversions module
605 emit_norm_module(rf
, canon_decomp
, compat_decomp
, combines
, norm_props
)
606 emit_conversions_module(rf
, lowerupper
, upperlower
)
608 ### character width module
610 for zwcat
in ["Me", "Mn", "Cf"]:
611 width_table
.extend(map(lambda (lo
, hi
): (lo
, hi
, 0, 0), gencats
[zwcat
]))
612 width_table
.append((4448, 4607, 0, 0))
614 # get widths, except those that are explicitly marked zero-width above
615 ea_widths
= load_east_asian_width(["W", "F", "A"], ["Me", "Mn", "Cf"])
616 # these are doublewidth
617 for dwcat
in ["W", "F"]:
618 width_table
.extend(map(lambda (lo
, hi
): (lo
, hi
, 2, 2), ea_widths
[dwcat
]))
619 width_table
.extend(map(lambda (lo
, hi
): (lo
, hi
, 1, 2), ea_widths
["A"]))
621 width_table
.sort(key
=lambda w
: w
[0])
623 # soft hyphen is not zero width in preformatted text; it's used to indicate
624 # a hyphen inserted to facilitate a linebreak.
625 width_table
= remove_from_wtable(width_table
, 173)
627 # optimize the width table by collapsing adjacent entities when possible
628 width_table
= optimize_width_table(width_table
)
629 emit_charwidth_module(rf
, width_table
)
631 ### grapheme cluster module
632 # from http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Break_Property_Values
633 grapheme_cats
= load_properties("auxiliary/GraphemeBreakProperty.txt", [])
637 # This category also includes Cs (surrogate codepoints), but Rust's `char`s are
638 # Unicode Scalar Values only, and surrogates are thus invalid `char`s.
639 # Thus, we have to remove Cs from the Control category
641 # 0x0a and 0x0d (CR and LF) are not in the Control category for Graphemes.
642 # However, the Graphemes iterator treats these as a special case, so they
643 # should be included in grapheme_cats["Control"] for our implementation.
644 grapheme_cats
["Control"] = group_cat(list(
645 (set(ungroup_cat(grapheme_cats
["Control"]))
646 |
set(ungroup_cat(grapheme_cats
["CR"]))
647 |
set(ungroup_cat(grapheme_cats
["LF"])))
648 - set(ungroup_cat([surrogate_codepoints
]))))
649 del(grapheme_cats
["CR"])
650 del(grapheme_cats
["LF"])
653 for cat
in grapheme_cats
:
654 grapheme_table
.extend([(x
, y
, cat
) for (x
, y
) in grapheme_cats
[cat
]])
655 grapheme_table
.sort(key
=lambda w
: w
[0])
656 emit_grapheme_module(rf
, grapheme_table
, grapheme_cats
.keys())