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 = (16, 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: "list[str | tuple[str, str]] | None" = None): 159 fetch(f) 160 props = {} 161 re1 = re.compile(r"^\s*([0-9A-F]+)\s*;\s*(\w+)(?:\s*;\s*(\w+))?") 162 re2 = re.compile(r"^\s*([0-9A-F]+)\.\.([0-9A-F]+)\s*;\s*(\w+)(?:\s*;\s*(\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 = d_lo 172 prop = m.group(2) 173 value = m.group(3) 174 else: 175 m = re2.match(line) 176 if m: 177 d_lo = m.group(1) 178 d_hi = m.group(2) 179 prop = m.group(3) 180 value = m.group(4) 181 else: 182 continue 183 if value is not None: 184 prop = (prop, value) 185 if interestingprops is not None and prop not in interestingprops: 186 continue 187 d_lo = int(d_lo, 16) 188 d_hi = int(d_hi, 16) 189 if prop not in props: 190 props[prop] = [] 191 props[prop].append((d_lo, d_hi)) 192 193 # optimize if possible 194 for prop in props: 195 props[prop] = group_cat(ungroup_cat(props[prop])) 196 197 return props 198 199def escape_char(c): 200 return "'\\u{%x}'" % c 201 202def emit_table(f, name, t_data, t_type = "&[(char, char)]", is_pub=True, 203 pfun=lambda x: "(%s,%s)" % (escape_char(x[0]), escape_char(x[1])), is_const=True): 204 pub_string = "const" 205 if not is_const: 206 pub_string = "let" 207 if is_pub: 208 pub_string = "pub " + pub_string 209 f.write(" %s %s: %s = &[\n" % (pub_string, name, t_type)) 210 data = "" 211 first = True 212 for dat in t_data: 213 if not first: 214 data += "," 215 first = False 216 data += pfun(dat) 217 format_table_content(f, data, 8) 218 f.write("\n ];\n\n") 219 220def emit_util_mod(f): 221 f.write(""" 222pub mod util { 223 #[inline] 224 pub fn bsearch_range_table(c: char, r: &[(char,char)]) -> bool { 225 use core::cmp::Ordering::{Equal, Less, Greater}; 226 r.binary_search_by(|&(lo,hi)| { 227 if lo <= c && c <= hi { Equal } 228 else if hi < c { Less } 229 else { Greater } 230 }).is_ok() 231 } 232 233 #[inline] 234 fn is_alphabetic(c: char) -> bool { 235 if super::UNICODE_VERSION_U8 == char::UNICODE_VERSION { 236 c.is_alphabetic() 237 } else { 238 match c { 239 'a' ..= 'z' | 'A' ..= 'Z' => true, 240 c if c > '\\x7f' => super::derived_property::Alphabetic(c), 241 _ => false, 242 } 243 } 244 } 245 246 #[inline] 247 fn is_numeric(c: char) -> bool { 248 if super::UNICODE_VERSION_U8 == char::UNICODE_VERSION { 249 c.is_numeric() 250 } else { 251 match c { 252 '0' ..= '9' => true, 253 c if c > '\\x7f' => super::general_category::N(c), 254 _ => false, 255 } 256 } 257 } 258 259 #[inline] 260 pub fn is_alphanumeric(c: char) -> bool { 261 is_alphabetic(c) || is_numeric(c) 262 } 263} 264 265""") 266 267def emit_property_module(f, mod, tbl, emit: "list[str | tuple[str, str]]"): 268 f.write("pub mod %s {\n" % mod) 269 270 cats = [] 271 for cat in emit: 272 if type(cat) is tuple: 273 cats.append((f"{cat[0]}_{cat[1]}", cat)) 274 else: 275 cats.append((cat, cat)) 276 cats.sort(key=lambda x: x[0]) 277 278 for cat_str, cat in cats: 279 emit_table(f, "%s_table" % cat_str, tbl[cat], is_pub=False) 280 f.write(" #[inline]\n") 281 f.write(" pub fn %s(c: char) -> bool {\n" % cat_str) 282 f.write(" super::util::bsearch_range_table(c, %s_table)\n" % cat_str) 283 f.write(" }\n\n") 284 f.write("}\n\n") 285 286def emit_break_module(f, break_table, break_cats, name): 287 Name = name.capitalize() 288 f.write("""pub mod %s { 289 use core::result::Result::{Ok, Err}; 290 291 pub use self::%sCat::*; 292 293 #[allow(non_camel_case_types)] 294 #[derive(Clone, Copy, PartialEq, Eq, Debug)] 295 pub enum %sCat { 296""" % (name, Name, Name)) 297 298 # We don't want the lookup table to be too large so choose a reasonable 299 # cutoff. 0x20000 is selected because most of the range table entries are 300 # within the interval of [0x0, 0x20000] 301 lookup_value_cutoff = 0x20000 302 303 # Length of lookup table. It has to be a divisor of `lookup_value_cutoff`. 304 lookup_table_len = 0x400 305 306 lookup_interval = round(lookup_value_cutoff / lookup_table_len) 307 308 # Lookup table is a mapping from `character code / lookup_interval` to 309 # the index in the range table that covers the `character code`. 310 lookup_table = [0] * lookup_table_len 311 j = 0 312 for i in range(0, lookup_table_len): 313 lookup_from = i * lookup_interval 314 while j < len(break_table): 315 (_, entry_to, _) = break_table[j] 316 if entry_to >= lookup_from: 317 break 318 j += 1 319 lookup_table[i] = j 320 321 break_cats.append("Any") 322 break_cats.sort() 323 for cat in break_cats: 324 f.write((" %sC_" % Name[0]) + cat + ",\n") 325 f.write(""" } 326 327 fn bsearch_range_value_table(c: char, r: &[(char, char, %sCat)], default_lower: u32, default_upper: u32) -> (u32, u32, %sCat) { 328 use core::cmp::Ordering::{Equal, Less, Greater}; 329 match r.binary_search_by(|&(lo, hi, _)| { 330 if lo <= c && c <= hi { Equal } 331 else if hi < c { Less } 332 else { Greater } 333 }) { 334 Ok(idx) => { 335 let (lower, upper, cat) = r[idx]; 336 (lower as u32, upper as u32, cat) 337 } 338 Err(idx) => { 339 ( 340 if idx > 0 { r[idx-1].1 as u32 + 1 } else { default_lower }, 341 r.get(idx).map(|c|c.0 as u32 - 1).unwrap_or(default_upper), 342 %sC_Any, 343 ) 344 } 345 } 346 } 347 348 pub fn %s_category(c: char) -> (u32, u32, %sCat) { 349 // Perform a quick O(1) lookup in a precomputed table to determine 350 // the slice of the range table to search in. 351 let lookup_interval = 0x%x; 352 let idx = (c as u32 / lookup_interval) as usize; 353 let range = %s_cat_lookup.get(idx..(idx + 2)).map_or( 354 // If the `idx` is outside of the precomputed table - use the slice 355 // starting from the last covered index in the precomputed table and 356 // ending with the length of the range table. 357 %d..%d, 358 |r| (r[0] as usize)..((r[1] + 1) as usize) 359 ); 360 361 // Compute pessimistic default lower and upper bounds on the category. 362 // If character doesn't map to any range and there is no adjacent range 363 // in the table slice - these bounds has to apply. 364 let lower = idx as u32 * lookup_interval; 365 let upper = lower + lookup_interval - 1; 366 bsearch_range_value_table(c, &%s_cat_table[range], lower, upper) 367 } 368 369""" % (Name, Name, Name[0], name, Name, lookup_interval, name, j, len(break_table), name)) 370 371 372 if len(break_table) <= 0xff: 373 lookup_type = "u8" 374 elif len(break_table) <= 0xffff: 375 lookup_type = "u16" 376 else: 377 lookup_type = "u32" 378 379 emit_table(f, "%s_cat_lookup" % name, lookup_table, "&[%s]" % lookup_type, 380 pfun=lambda x: "%d" % x, 381 is_pub=False, is_const=True) 382 383 emit_table(f, "%s_cat_table" % name, break_table, "&[(char, char, %sCat)]" % Name, 384 pfun=lambda x: "(%s,%s,%sC_%s)" % (escape_char(x[0]), escape_char(x[1]), Name[0], x[2]), 385 is_pub=False, is_const=True) 386 f.write("}\n") 387 388if __name__ == "__main__": 389 r = "tables.rs" 390 if os.path.exists(r): 391 os.remove(r) 392 with open(r, "w") as rf: 393 # write the file's preamble 394 rf.write(preamble) 395 rf.write(""" 396/// The version of [Unicode](http://www.unicode.org/) 397/// that this version of unicode-segmentation is based on. 398pub const UNICODE_VERSION: (u64, u64, u64) = (%s, %s, %s); 399""" % UNICODE_VERSION) 400 401 rf.write(""" 402const UNICODE_VERSION_U8: (u8, u8, u8) = (%s, %s, %s); 403""" % UNICODE_VERSION) 404 405 # download and parse all the data 406 gencats = load_gencats("UnicodeData.txt") 407 derived = load_properties("DerivedCoreProperties.txt", ["Alphabetic", ("InCB", "Consonant"), ("InCB", "Extend"), ("InCB", "Linker")]) 408 409 emit_util_mod(rf) 410 for (name, cat, pfuns) in ("general_category", gencats, ["N"]), \ 411 ("derived_property", derived, ["Alphabetic", ("InCB", "Extend")]): 412 emit_property_module(rf, name, cat, pfuns) 413 414 rf.write("""pub fn is_incb_linker(c: char) -> bool { 415 matches!(c,""") 416 417 for (lo, hi) in derived[("InCB", "Linker")]: 418 rf.write(f" | '\\u{{{lo:X}}}'") 419 if lo != hi: 420 rf.write(f"..'\\u{{{lo:X}}}'") 421 422 rf.write(")\n}\n\n") 423 424 ### grapheme cluster module 425 # from http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Break_Property_Values 426 grapheme_cats = load_properties("auxiliary/GraphemeBreakProperty.txt") 427 # Control 428 # Note: 429 # This category also includes Cs (surrogate codepoints), but Rust's `char`s are 430 # Unicode Scalar Values only, and surrogates are thus invalid `char`s. 431 # Thus, we have to remove Cs from the Control category 432 grapheme_cats["Control"] = group_cat(list( 433 set(ungroup_cat(grapheme_cats["Control"])) 434 - set(ungroup_cat([surrogate_codepoints])))) 435 grapheme_cats["InCB_Consonant"] = derived[("InCB", "Consonant")] 436 emoji_props = load_properties("emoji-data.txt", ["Extended_Pictographic"]) 437 grapheme_cats["Extended_Pictographic"] = emoji_props["Extended_Pictographic"] 438 grapheme_table = [] 439 for cat in grapheme_cats: 440 grapheme_table.extend([(x, y, cat) for (x, y) in grapheme_cats[cat]]) 441 grapheme_table.sort(key=lambda w: w[0]) 442 last = -1 443 for chars in grapheme_table: 444 if chars[0] <= last: 445 raise "Grapheme tables and Extended_Pictographic values overlap; need to store these separately!" 446 last = chars[1] 447 emit_break_module(rf, grapheme_table, list(grapheme_cats.keys()), "grapheme") 448 rf.write("\n") 449 450 word_cats = load_properties("auxiliary/WordBreakProperty.txt") 451 word_table = [] 452 for cat in word_cats: 453 word_table.extend([(x, y, cat) for (x, y) in word_cats[cat]]) 454 word_table.sort(key=lambda w: w[0]) 455 emit_break_module(rf, word_table, list(word_cats.keys()), "word") 456 457 # There are some emoji which are also ALetter, so this needs to be stored separately 458 # For efficiency, we could still merge the two tables and produce an ALetterEP state 459 emoji_table = [(x, y, "Extended_Pictographic") for (x, y) in emoji_props["Extended_Pictographic"]] 460 emit_break_module(rf, emoji_table, ["Extended_Pictographic"], "emoji") 461 462 sentence_cats = load_properties("auxiliary/SentenceBreakProperty.txt") 463 sentence_table = [] 464 for cat in sentence_cats: 465 sentence_table.extend([(x, y, cat) for (x, y) in sentence_cats[cat]]) 466 sentence_table.sort(key=lambda w: w[0]) 467 emit_break_module(rf, sentence_table, list(sentence_cats.keys()), "sentence") 468