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 = (15, 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 # We don't want the lookup table to be too large so choose a reasonable 278 # cutoff. 0x20000 is selected because most of the range table entries are 279 # within the interval of [0x0, 0x20000] 280 lookup_value_cutoff = 0x20000 281 282 # Length of lookup table. It has to be a divisor of `lookup_value_cutoff`. 283 lookup_table_len = 0x400 284 285 lookup_interval = round(lookup_value_cutoff / lookup_table_len) 286 287 # Lookup table is a mapping from `character code / lookup_interval` to 288 # the index in the range table that covers the `character code`. 289 lookup_table = [0] * lookup_table_len 290 j = 0 291 for i in range(0, lookup_table_len): 292 lookup_from = i * lookup_interval 293 while j < len(break_table): 294 (_, entry_to, _) = break_table[j] 295 if entry_to >= lookup_from: 296 break 297 j += 1 298 lookup_table[i] = j 299 300 break_cats.append("Any") 301 break_cats.sort() 302 for cat in break_cats: 303 f.write((" %sC_" % Name[0]) + cat + ",\n") 304 f.write(""" } 305 306 fn bsearch_range_value_table(c: char, r: &'static [(char, char, %sCat)], default_lower: u32, default_upper: u32) -> (u32, u32, %sCat) { 307 use core::cmp::Ordering::{Equal, Less, Greater}; 308 match r.binary_search_by(|&(lo, hi, _)| { 309 if lo <= c && c <= hi { Equal } 310 else if hi < c { Less } 311 else { Greater } 312 }) { 313 Ok(idx) => { 314 let (lower, upper, cat) = r[idx]; 315 (lower as u32, upper as u32, cat) 316 } 317 Err(idx) => { 318 ( 319 if idx > 0 { r[idx-1].1 as u32 + 1 } else { default_lower }, 320 r.get(idx).map(|c|c.0 as u32 - 1).unwrap_or(default_upper), 321 %sC_Any, 322 ) 323 } 324 } 325 } 326 327 pub fn %s_category(c: char) -> (u32, u32, %sCat) { 328 // Perform a quick O(1) lookup in a precomputed table to determine 329 // the slice of the range table to search in. 330 let lookup_interval = 0x%x; 331 let idx = (c as u32 / lookup_interval) as usize; 332 let range = %s_cat_lookup.get(idx..(idx + 2)).map_or( 333 // If the `idx` is outside of the precomputed table - use the slice 334 // starting from the last covered index in the precomputed table and 335 // ending with the length of the range table. 336 %d..%d, 337 |r| (r[0] as usize)..((r[1] + 1) as usize) 338 ); 339 340 // Compute pessimistic default lower and upper bounds on the category. 341 // If character doesn't map to any range and there is no adjacent range 342 // in the table slice - these bounds has to apply. 343 let lower = idx as u32 * lookup_interval; 344 let upper = lower + lookup_interval - 1; 345 bsearch_range_value_table(c, &%s_cat_table[range], lower, upper) 346 } 347 348""" % (Name, Name, Name[0], name, Name, lookup_interval, name, j, len(break_table), name)) 349 350 351 if len(break_table) <= 0xff: 352 lookup_type = "u8" 353 elif len(break_table) <= 0xffff: 354 lookup_type = "u16" 355 else: 356 lookup_type = "u32" 357 358 emit_table(f, "%s_cat_lookup" % name, lookup_table, "&'static [%s]" % lookup_type, 359 pfun=lambda x: "%d" % x, 360 is_pub=False, is_const=True) 361 362 emit_table(f, "%s_cat_table" % name, break_table, "&'static [(char, char, %sCat)]" % Name, 363 pfun=lambda x: "(%s,%s,%sC_%s)" % (escape_char(x[0]), escape_char(x[1]), Name[0], x[2]), 364 is_pub=False, is_const=True) 365 f.write("}\n") 366 367if __name__ == "__main__": 368 r = "tables.rs" 369 if os.path.exists(r): 370 os.remove(r) 371 with open(r, "w") as rf: 372 # write the file's preamble 373 rf.write(preamble) 374 rf.write(""" 375/// The version of [Unicode](http://www.unicode.org/) 376/// that this version of unicode-segmentation is based on. 377pub const UNICODE_VERSION: (u64, u64, u64) = (%s, %s, %s); 378""" % UNICODE_VERSION) 379 380 # download and parse all the data 381 gencats = load_gencats("UnicodeData.txt") 382 derived = load_properties("DerivedCoreProperties.txt", ["Alphabetic"]) 383 384 emit_util_mod(rf) 385 for (name, cat, pfuns) in ("general_category", gencats, ["N"]), \ 386 ("derived_property", derived, ["Alphabetic"]): 387 emit_property_module(rf, name, cat, pfuns) 388 389 ### grapheme cluster module 390 # from http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Break_Property_Values 391 grapheme_cats = load_properties("auxiliary/GraphemeBreakProperty.txt", []) 392 393 # Control 394 # Note: 395 # This category also includes Cs (surrogate codepoints), but Rust's `char`s are 396 # Unicode Scalar Values only, and surrogates are thus invalid `char`s. 397 # Thus, we have to remove Cs from the Control category 398 grapheme_cats["Control"] = group_cat(list( 399 set(ungroup_cat(grapheme_cats["Control"])) 400 - set(ungroup_cat([surrogate_codepoints])))) 401 402 grapheme_table = [] 403 for cat in grapheme_cats: 404 grapheme_table.extend([(x, y, cat) for (x, y) in grapheme_cats[cat]]) 405 emoji_props = load_properties("emoji-data.txt", ["Extended_Pictographic"]) 406 grapheme_table.extend([(x, y, "Extended_Pictographic") for (x, y) in emoji_props["Extended_Pictographic"]]) 407 grapheme_table.sort(key=lambda w: w[0]) 408 last = -1 409 for chars in grapheme_table: 410 if chars[0] <= last: 411 raise "Grapheme tables and Extended_Pictographic values overlap; need to store these separately!" 412 last = chars[1] 413 emit_break_module(rf, grapheme_table, list(grapheme_cats.keys()) + ["Extended_Pictographic"], "grapheme") 414 rf.write("\n") 415 416 word_cats = load_properties("auxiliary/WordBreakProperty.txt", []) 417 word_table = [] 418 for cat in word_cats: 419 word_table.extend([(x, y, cat) for (x, y) in word_cats[cat]]) 420 word_table.sort(key=lambda w: w[0]) 421 emit_break_module(rf, word_table, list(word_cats.keys()), "word") 422 423 # There are some emoji which are also ALetter, so this needs to be stored separately 424 # For efficiency, we could still merge the two tables and produce an ALetterEP state 425 emoji_table = [(x, y, "Extended_Pictographic") for (x, y) in emoji_props["Extended_Pictographic"]] 426 emit_break_module(rf, emoji_table, ["Extended_Pictographic"], "emoji") 427 428 sentence_cats = load_properties("auxiliary/SentenceBreakProperty.txt", []) 429 sentence_table = [] 430 for cat in sentence_cats: 431 sentence_table.extend([(x, y, cat) for (x, y) in sentence_cats[cat]]) 432 sentence_table.sort(key=lambda w: w[0]) 433 emit_break_module(rf, sentence_table, list(sentence_cats.keys()), "sentence") 434