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 23import fileinput, re, os, sys 24 25preamble = '''// Copyright 2012-2018 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 42expanded_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': ['N'], 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 55surrogate_codepoints = (0xd800, 0xdfff) 56 57UNICODE_VERSION = (13, 0, 0) 58 59UNICODE_VERSION_NUMBER = "%s.%s.%s" %UNICODE_VERSION 60 61def is_surrogate(n): 62 return surrogate_codepoints[0] <= n <= surrogate_codepoints[1] 63 64def fetch(f): 65 if not os.path.exists(os.path.basename(f)): 66 if "emoji" in f: 67 os.system("curl -O https://www.unicode.org/Public/%s/ucd/emoji/%s" 68 % (UNICODE_VERSION_NUMBER, f)) 69 else: 70 os.system("curl -O https://www.unicode.org/Public/%s/ucd/%s" 71 % (UNICODE_VERSION_NUMBER, f)) 72 73 if not os.path.exists(os.path.basename(f)): 74 sys.stderr.write("cannot load %s" % f) 75 exit(1) 76 77def load_gencats(f): 78 fetch(f) 79 gencats = {} 80 81 udict = {}; 82 range_start = -1; 83 for line in fileinput.input(f): 84 data = line.split(';'); 85 if len(data) != 15: 86 continue 87 cp = int(data[0], 16); 88 if is_surrogate(cp): 89 continue 90 if range_start >= 0: 91 for i in range(range_start, cp): 92 udict[i] = data; 93 range_start = -1; 94 if data[1].endswith(", First>"): 95 range_start = cp; 96 continue; 97 udict[cp] = data; 98 99 for code in udict: 100 [code_org, name, gencat, combine, bidi, 101 decomp, deci, digit, num, mirror, 102 old, iso, upcase, lowcase, titlecase ] = udict[code]; 103 104 # place letter in categories as appropriate 105 for cat in [gencat, "Assigned"] + expanded_categories.get(gencat, []): 106 if cat not in gencats: 107 gencats[cat] = [] 108 gencats[cat].append(code) 109 110 gencats = group_cats(gencats) 111 return gencats 112 113def group_cats(cats): 114 cats_out = {} 115 for cat in cats: 116 cats_out[cat] = group_cat(cats[cat]) 117 return cats_out 118 119def group_cat(cat): 120 cat_out = [] 121 letters = sorted(set(cat)) 122 cur_start = letters.pop(0) 123 cur_end = cur_start 124 for letter in letters: 125 assert letter > cur_end, \ 126 "cur_end: %s, letter: %s" % (hex(cur_end), hex(letter)) 127 if letter == cur_end + 1: 128 cur_end = letter 129 else: 130 cat_out.append((cur_start, cur_end)) 131 cur_start = cur_end = letter 132 cat_out.append((cur_start, cur_end)) 133 return cat_out 134 135def ungroup_cat(cat): 136 cat_out = [] 137 for (lo, hi) in cat: 138 while lo <= hi: 139 cat_out.append(lo) 140 lo += 1 141 return cat_out 142 143def format_table_content(f, content, indent): 144 line = " "*indent 145 first = True 146 for chunk in content.split(","): 147 if len(line) + len(chunk) < 98: 148 if first: 149 line += chunk 150 else: 151 line += ", " + chunk 152 first = False 153 else: 154 f.write(line + ",\n") 155 line = " "*indent + chunk 156 f.write(line) 157 158def load_properties(f, interestingprops): 159 fetch(f) 160 props = {} 161 re1 = re.compile(r"^ *([0-9A-F]+) *; *(\w+)") 162 re2 = re.compile(r"^ *([0-9A-F]+)\.\.([0-9A-F]+) *; *(\w+)") 163 164 for line in fileinput.input(os.path.basename(f)): 165 prop = None 166 d_lo = 0 167 d_hi = 0 168 m = re1.match(line) 169 if m: 170 d_lo = m.group(1) 171 d_hi = m.group(1) 172 prop = m.group(2) 173 else: 174 m = re2.match(line) 175 if m: 176 d_lo = m.group(1) 177 d_hi = m.group(2) 178 prop = m.group(3) 179 else: 180 continue 181 if interestingprops and prop not in interestingprops: 182 continue 183 d_lo = int(d_lo, 16) 184 d_hi = int(d_hi, 16) 185 if prop not in props: 186 props[prop] = [] 187 props[prop].append((d_lo, d_hi)) 188 189 # optimize if possible 190 for prop in props: 191 props[prop] = group_cat(ungroup_cat(props[prop])) 192 193 return props 194 195def escape_char(c): 196 return "'\\u{%x}'" % c 197 198def emit_table(f, name, t_data, t_type = "&'static [(char, char)]", is_pub=True, 199 pfun=lambda x: "(%s,%s)" % (escape_char(x[0]), escape_char(x[1])), is_const=True): 200 pub_string = "const" 201 if not is_const: 202 pub_string = "let" 203 if is_pub: 204 pub_string = "pub " + pub_string 205 f.write(" %s %s: %s = &[\n" % (pub_string, name, t_type)) 206 data = "" 207 first = True 208 for dat in t_data: 209 if not first: 210 data += "," 211 first = False 212 data += pfun(dat) 213 format_table_content(f, data, 8) 214 f.write("\n ];\n\n") 215 216def emit_util_mod(f): 217 f.write(""" 218pub mod util { 219 #[inline] 220 pub fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool { 221 use core::cmp::Ordering::{Equal, Less, Greater}; 222 r.binary_search_by(|&(lo,hi)| { 223 if lo <= c && c <= hi { Equal } 224 else if hi < c { Less } 225 else { Greater } 226 }).is_ok() 227 } 228 229 #[inline] 230 fn is_alphabetic(c: char) -> bool { 231 match c { 232 'a' ... 'z' | 'A' ... 'Z' => true, 233 c if c > '\x7f' => super::derived_property::Alphabetic(c), 234 _ => false, 235 } 236 } 237 238 #[inline] 239 fn is_numeric(c: char) -> bool { 240 match c { 241 '0' ... '9' => true, 242 c if c > '\x7f' => super::general_category::N(c), 243 _ => false, 244 } 245 } 246 247 #[inline] 248 pub fn is_alphanumeric(c: char) -> bool { 249 is_alphabetic(c) || is_numeric(c) 250 } 251} 252 253""") 254 255def emit_property_module(f, mod, tbl, emit): 256 f.write("mod %s {\n" % mod) 257 for cat in sorted(emit): 258 emit_table(f, "%s_table" % cat, tbl[cat], is_pub=False) 259 f.write(" #[inline]\n") 260 f.write(" pub fn %s(c: char) -> bool {\n" % cat) 261 f.write(" super::util::bsearch_range_table(c, %s_table)\n" % cat) 262 f.write(" }\n\n") 263 f.write("}\n\n") 264 265def emit_break_module(f, break_table, break_cats, name): 266 Name = name.capitalize() 267 f.write("""pub mod %s { 268 use core::result::Result::{Ok, Err}; 269 270 pub use self::%sCat::*; 271 272 #[allow(non_camel_case_types)] 273 #[derive(Clone, Copy, PartialEq, Eq, Debug)] 274 pub enum %sCat { 275""" % (name, Name, Name)) 276 277 break_cats.append("Any") 278 break_cats.sort() 279 for cat in break_cats: 280 f.write((" %sC_" % Name[0]) + cat + ",\n") 281 f.write(""" } 282 283 fn bsearch_range_value_table(c: char, r: &'static [(char, char, %sCat)]) -> (u32, u32, %sCat) { 284 use core; 285 use core::cmp::Ordering::{Equal, Less, Greater}; 286 match r.binary_search_by(|&(lo, hi, _)| { 287 if lo <= c && c <= hi { Equal } 288 else if hi < c { Less } 289 else { Greater } 290 }) { 291 Ok(idx) => { 292 let (lower, upper, cat) = r[idx]; 293 (lower as u32, upper as u32, cat) 294 } 295 Err(idx) => { 296 ( 297 if idx > 0 { r[idx-1].1 as u32 + 1 } else { 0 }, 298 r.get(idx).map(|c|c.0 as u32 - 1).unwrap_or(core::u32::MAX), 299 %sC_Any, 300 ) 301 } 302 } 303 } 304 305 pub fn %s_category(c: char) -> (u32, u32, %sCat) { 306 bsearch_range_value_table(c, %s_cat_table) 307 } 308 309""" % (Name, Name, Name[0], name, Name, name)) 310 311 emit_table(f, "%s_cat_table" % name, break_table, "&'static [(char, char, %sCat)]" % Name, 312 pfun=lambda x: "(%s,%s,%sC_%s)" % (escape_char(x[0]), escape_char(x[1]), Name[0], x[2]), 313 is_pub=False, is_const=True) 314 f.write("}\n") 315 316if __name__ == "__main__": 317 r = "tables.rs" 318 if os.path.exists(r): 319 os.remove(r) 320 with open(r, "w") as rf: 321 # write the file's preamble 322 rf.write(preamble) 323 rf.write(""" 324/// The version of [Unicode](http://www.unicode.org/) 325/// that this version of unicode-segmentation is based on. 326pub const UNICODE_VERSION: (u64, u64, u64) = (%s, %s, %s); 327""" % UNICODE_VERSION) 328 329 # download and parse all the data 330 gencats = load_gencats("UnicodeData.txt") 331 derived = load_properties("DerivedCoreProperties.txt", ["Alphabetic"]) 332 333 emit_util_mod(rf) 334 for (name, cat, pfuns) in ("general_category", gencats, ["N"]), \ 335 ("derived_property", derived, ["Alphabetic"]): 336 emit_property_module(rf, name, cat, pfuns) 337 338 ### grapheme cluster module 339 # from http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Break_Property_Values 340 grapheme_cats = load_properties("auxiliary/GraphemeBreakProperty.txt", []) 341 342 # Control 343 # Note: 344 # This category also includes Cs (surrogate codepoints), but Rust's `char`s are 345 # Unicode Scalar Values only, and surrogates are thus invalid `char`s. 346 # Thus, we have to remove Cs from the Control category 347 grapheme_cats["Control"] = group_cat(list( 348 set(ungroup_cat(grapheme_cats["Control"])) 349 - set(ungroup_cat([surrogate_codepoints])))) 350 351 grapheme_table = [] 352 for cat in grapheme_cats: 353 grapheme_table.extend([(x, y, cat) for (x, y) in grapheme_cats[cat]]) 354 emoji_props = load_properties("emoji-data.txt", ["Extended_Pictographic"]) 355 grapheme_table.extend([(x, y, "Extended_Pictographic") for (x, y) in emoji_props["Extended_Pictographic"]]) 356 grapheme_table.sort(key=lambda w: w[0]) 357 last = -1 358 for chars in grapheme_table: 359 if chars[0] <= last: 360 raise "Grapheme tables and Extended_Pictographic values overlap; need to store these separately!" 361 last = chars[1] 362 emit_break_module(rf, grapheme_table, list(grapheme_cats.keys()) + ["Extended_Pictographic"], "grapheme") 363 rf.write("\n") 364 365 word_cats = load_properties("auxiliary/WordBreakProperty.txt", []) 366 word_table = [] 367 for cat in word_cats: 368 word_table.extend([(x, y, cat) for (x, y) in word_cats[cat]]) 369 word_table.sort(key=lambda w: w[0]) 370 emit_break_module(rf, word_table, list(word_cats.keys()), "word") 371 372 # There are some emoji which are also ALetter, so this needs to be stored separately 373 # For efficiency, we could still merge the two tables and produce an ALetterEP state 374 emoji_table = [(x, y, "Extended_Pictographic") for (x, y) in emoji_props["Extended_Pictographic"]] 375 emit_break_module(rf, emoji_table, ["Extended_Pictographic"], "emoji") 376 377 sentence_cats = load_properties("auxiliary/SentenceBreakProperty.txt", []) 378 sentence_table = [] 379 for cat in sentence_cats: 380 sentence_table.extend([(x, y, cat) for (x, y) in sentence_cats[cat]]) 381 sentence_table.sort(key=lambda w: w[0]) 382 emit_break_module(rf, sentence_table, list(sentence_cats.keys()), "sentence") 383