unicode.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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. # This script uses the following Unicode tables:
  13. # - DerivedCoreProperties.txt
  14. # - auxiliary/GraphemeBreakProperty.txt
  15. # - auxiliary/WordBreakProperty.txt
  16. # - ReadMe.txt
  17. # - UnicodeData.txt
  18. #
  19. # Since this should not require frequent updates, we just store this
  20. # out-of-line and check the unicode.rs file into git.
  21. import fileinput, re, os, sys
  22. preamble = '''// Copyright 2012-2018 The Rust Project Developers. See the COPYRIGHT
  23. // file at the top-level directory of this distribution and at
  24. // http://rust-lang.org/COPYRIGHT.
  25. //
  26. // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
  27. // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
  28. // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
  29. // option. This file may not be copied, modified, or distributed
  30. // except according to those terms.
  31. // NOTE: The following code was generated by "scripts/unicode.py", do not edit directly
  32. #![allow(missing_docs, non_upper_case_globals, non_snake_case)]
  33. '''
  34. # Mapping taken from Table 12 from:
  35. # http://www.unicode.org/reports/tr44/#General_Category_Values
  36. expanded_categories = {
  37. 'Lu': ['LC', 'L'], 'Ll': ['LC', 'L'], 'Lt': ['LC', 'L'],
  38. 'Lm': ['L'], 'Lo': ['L'],
  39. 'Mn': ['M'], 'Mc': ['M'], 'Me': ['M'],
  40. 'Nd': ['N'], 'Nl': ['N'], 'No': ['N'],
  41. 'Pc': ['P'], 'Pd': ['P'], 'Ps': ['P'], 'Pe': ['P'],
  42. 'Pi': ['P'], 'Pf': ['P'], 'Po': ['P'],
  43. 'Sm': ['S'], 'Sc': ['S'], 'Sk': ['S'], 'So': ['S'],
  44. 'Zs': ['Z'], 'Zl': ['Z'], 'Zp': ['Z'],
  45. 'Cc': ['C'], 'Cf': ['C'], 'Cs': ['C'], 'Co': ['C'], 'Cn': ['C'],
  46. }
  47. # these are the surrogate codepoints, which are not valid rust characters
  48. surrogate_codepoints = (0xd800, 0xdfff)
  49. UNICODE_VERSION = (14, 0, 0)
  50. UNICODE_VERSION_NUMBER = "%s.%s.%s" %UNICODE_VERSION
  51. def is_surrogate(n):
  52. return surrogate_codepoints[0] <= n <= surrogate_codepoints[1]
  53. def fetch(f):
  54. if not os.path.exists(os.path.basename(f)):
  55. if "emoji" in f:
  56. os.system("curl -O https://www.unicode.org/Public/%s/ucd/emoji/%s"
  57. % (UNICODE_VERSION_NUMBER, f))
  58. else:
  59. os.system("curl -O https://www.unicode.org/Public/%s/ucd/%s"
  60. % (UNICODE_VERSION_NUMBER, f))
  61. if not os.path.exists(os.path.basename(f)):
  62. sys.stderr.write("cannot load %s" % f)
  63. exit(1)
  64. def load_gencats(f):
  65. fetch(f)
  66. gencats = {}
  67. udict = {};
  68. range_start = -1;
  69. for line in fileinput.input(f):
  70. data = line.split(';');
  71. if len(data) != 15:
  72. continue
  73. cp = int(data[0], 16);
  74. if is_surrogate(cp):
  75. continue
  76. if range_start >= 0:
  77. for i in range(range_start, cp):
  78. udict[i] = data;
  79. range_start = -1;
  80. if data[1].endswith(", First>"):
  81. range_start = cp;
  82. continue;
  83. udict[cp] = data;
  84. for code in udict:
  85. [code_org, name, gencat, combine, bidi,
  86. decomp, deci, digit, num, mirror,
  87. old, iso, upcase, lowcase, titlecase ] = udict[code];
  88. # place letter in categories as appropriate
  89. for cat in [gencat, "Assigned"] + expanded_categories.get(gencat, []):
  90. if cat not in gencats:
  91. gencats[cat] = []
  92. gencats[cat].append(code)
  93. gencats = group_cats(gencats)
  94. return gencats
  95. def group_cats(cats):
  96. cats_out = {}
  97. for cat in cats:
  98. cats_out[cat] = group_cat(cats[cat])
  99. return cats_out
  100. def group_cat(cat):
  101. cat_out = []
  102. letters = sorted(set(cat))
  103. cur_start = letters.pop(0)
  104. cur_end = cur_start
  105. for letter in letters:
  106. assert letter > cur_end, \
  107. "cur_end: %s, letter: %s" % (hex(cur_end), hex(letter))
  108. if letter == cur_end + 1:
  109. cur_end = letter
  110. else:
  111. cat_out.append((cur_start, cur_end))
  112. cur_start = cur_end = letter
  113. cat_out.append((cur_start, cur_end))
  114. return cat_out
  115. def ungroup_cat(cat):
  116. cat_out = []
  117. for (lo, hi) in cat:
  118. while lo <= hi:
  119. cat_out.append(lo)
  120. lo += 1
  121. return cat_out
  122. def format_table_content(f, content, indent):
  123. line = " "*indent
  124. first = True
  125. for chunk in content.split(","):
  126. if len(line) + len(chunk) < 98:
  127. if first:
  128. line += chunk
  129. else:
  130. line += ", " + chunk
  131. first = False
  132. else:
  133. f.write(line + ",\n")
  134. line = " "*indent + chunk
  135. f.write(line)
  136. def load_properties(f, interestingprops):
  137. fetch(f)
  138. props = {}
  139. re1 = re.compile(r"^ *([0-9A-F]+) *; *(\w+)")
  140. re2 = re.compile(r"^ *([0-9A-F]+)\.\.([0-9A-F]+) *; *(\w+)")
  141. for line in fileinput.input(os.path.basename(f)):
  142. prop = None
  143. d_lo = 0
  144. d_hi = 0
  145. m = re1.match(line)
  146. if m:
  147. d_lo = m.group(1)
  148. d_hi = m.group(1)
  149. prop = m.group(2)
  150. else:
  151. m = re2.match(line)
  152. if m:
  153. d_lo = m.group(1)
  154. d_hi = m.group(2)
  155. prop = m.group(3)
  156. else:
  157. continue
  158. if interestingprops and prop not in interestingprops:
  159. continue
  160. d_lo = int(d_lo, 16)
  161. d_hi = int(d_hi, 16)
  162. if prop not in props:
  163. props[prop] = []
  164. props[prop].append((d_lo, d_hi))
  165. # optimize if possible
  166. for prop in props:
  167. props[prop] = group_cat(ungroup_cat(props[prop]))
  168. return props
  169. def escape_char(c):
  170. return "'\\u{%x}'" % c
  171. def emit_table(f, name, t_data, t_type = "&'static [(char, char)]", is_pub=True,
  172. pfun=lambda x: "(%s,%s)" % (escape_char(x[0]), escape_char(x[1])), is_const=True):
  173. pub_string = "const"
  174. if not is_const:
  175. pub_string = "let"
  176. if is_pub:
  177. pub_string = "pub " + pub_string
  178. f.write(" %s %s: %s = &[\n" % (pub_string, name, t_type))
  179. data = ""
  180. first = True
  181. for dat in t_data:
  182. if not first:
  183. data += ","
  184. first = False
  185. data += pfun(dat)
  186. format_table_content(f, data, 8)
  187. f.write("\n ];\n\n")
  188. def emit_util_mod(f):
  189. f.write("""
  190. pub mod util {
  191. #[inline]
  192. pub fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool {
  193. use core::cmp::Ordering::{Equal, Less, Greater};
  194. r.binary_search_by(|&(lo,hi)| {
  195. if lo <= c && c <= hi { Equal }
  196. else if hi < c { Less }
  197. else { Greater }
  198. }).is_ok()
  199. }
  200. #[inline]
  201. fn is_alphabetic(c: char) -> bool {
  202. match c {
  203. 'a' ..= 'z' | 'A' ..= 'Z' => true,
  204. c if c > '\x7f' => super::derived_property::Alphabetic(c),
  205. _ => false,
  206. }
  207. }
  208. #[inline]
  209. fn is_numeric(c: char) -> bool {
  210. match c {
  211. '0' ..= '9' => true,
  212. c if c > '\x7f' => super::general_category::N(c),
  213. _ => false,
  214. }
  215. }
  216. #[inline]
  217. pub fn is_alphanumeric(c: char) -> bool {
  218. is_alphabetic(c) || is_numeric(c)
  219. }
  220. }
  221. """)
  222. def emit_property_module(f, mod, tbl, emit):
  223. f.write("mod %s {\n" % mod)
  224. for cat in sorted(emit):
  225. emit_table(f, "%s_table" % cat, tbl[cat], is_pub=False)
  226. f.write(" #[inline]\n")
  227. f.write(" pub fn %s(c: char) -> bool {\n" % cat)
  228. f.write(" super::util::bsearch_range_table(c, %s_table)\n" % cat)
  229. f.write(" }\n\n")
  230. f.write("}\n\n")
  231. def emit_break_module(f, break_table, break_cats, name):
  232. Name = name.capitalize()
  233. f.write("""pub mod %s {
  234. use core::result::Result::{Ok, Err};
  235. pub use self::%sCat::*;
  236. #[allow(non_camel_case_types)]
  237. #[derive(Clone, Copy, PartialEq, Eq, Debug)]
  238. pub enum %sCat {
  239. """ % (name, Name, Name))
  240. break_cats.append("Any")
  241. break_cats.sort()
  242. for cat in break_cats:
  243. f.write((" %sC_" % Name[0]) + cat + ",\n")
  244. f.write(""" }
  245. fn bsearch_range_value_table(c: char, r: &'static [(char, char, %sCat)]) -> (u32, u32, %sCat) {
  246. use core::cmp::Ordering::{Equal, Less, Greater};
  247. match r.binary_search_by(|&(lo, hi, _)| {
  248. if lo <= c && c <= hi { Equal }
  249. else if hi < c { Less }
  250. else { Greater }
  251. }) {
  252. Ok(idx) => {
  253. let (lower, upper, cat) = r[idx];
  254. (lower as u32, upper as u32, cat)
  255. }
  256. Err(idx) => {
  257. (
  258. if idx > 0 { r[idx-1].1 as u32 + 1 } else { 0 },
  259. r.get(idx).map(|c|c.0 as u32 - 1).unwrap_or(core::u32::MAX),
  260. %sC_Any,
  261. )
  262. }
  263. }
  264. }
  265. pub fn %s_category(c: char) -> (u32, u32, %sCat) {
  266. bsearch_range_value_table(c, %s_cat_table)
  267. }
  268. """ % (Name, Name, Name[0], name, Name, name))
  269. emit_table(f, "%s_cat_table" % name, break_table, "&'static [(char, char, %sCat)]" % Name,
  270. pfun=lambda x: "(%s,%s,%sC_%s)" % (escape_char(x[0]), escape_char(x[1]), Name[0], x[2]),
  271. is_pub=False, is_const=True)
  272. f.write("}\n")
  273. if __name__ == "__main__":
  274. r = "tables.rs"
  275. if os.path.exists(r):
  276. os.remove(r)
  277. with open(r, "w") as rf:
  278. # write the file's preamble
  279. rf.write(preamble)
  280. rf.write("""
  281. /// The version of [Unicode](http://www.unicode.org/)
  282. /// that this version of unicode-segmentation is based on.
  283. pub const UNICODE_VERSION: (u64, u64, u64) = (%s, %s, %s);
  284. """ % UNICODE_VERSION)
  285. # download and parse all the data
  286. gencats = load_gencats("UnicodeData.txt")
  287. derived = load_properties("DerivedCoreProperties.txt", ["Alphabetic"])
  288. emit_util_mod(rf)
  289. for (name, cat, pfuns) in ("general_category", gencats, ["N"]), \
  290. ("derived_property", derived, ["Alphabetic"]):
  291. emit_property_module(rf, name, cat, pfuns)
  292. ### grapheme cluster module
  293. # from http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Break_Property_Values
  294. grapheme_cats = load_properties("auxiliary/GraphemeBreakProperty.txt", [])
  295. # Control
  296. # Note:
  297. # This category also includes Cs (surrogate codepoints), but Rust's `char`s are
  298. # Unicode Scalar Values only, and surrogates are thus invalid `char`s.
  299. # Thus, we have to remove Cs from the Control category
  300. grapheme_cats["Control"] = group_cat(list(
  301. set(ungroup_cat(grapheme_cats["Control"]))
  302. - set(ungroup_cat([surrogate_codepoints]))))
  303. grapheme_table = []
  304. for cat in grapheme_cats:
  305. grapheme_table.extend([(x, y, cat) for (x, y) in grapheme_cats[cat]])
  306. emoji_props = load_properties("emoji-data.txt", ["Extended_Pictographic"])
  307. grapheme_table.extend([(x, y, "Extended_Pictographic") for (x, y) in emoji_props["Extended_Pictographic"]])
  308. grapheme_table.sort(key=lambda w: w[0])
  309. last = -1
  310. for chars in grapheme_table:
  311. if chars[0] <= last:
  312. raise "Grapheme tables and Extended_Pictographic values overlap; need to store these separately!"
  313. last = chars[1]
  314. emit_break_module(rf, grapheme_table, list(grapheme_cats.keys()) + ["Extended_Pictographic"], "grapheme")
  315. rf.write("\n")
  316. word_cats = load_properties("auxiliary/WordBreakProperty.txt", [])
  317. word_table = []
  318. for cat in word_cats:
  319. word_table.extend([(x, y, cat) for (x, y) in word_cats[cat]])
  320. word_table.sort(key=lambda w: w[0])
  321. emit_break_module(rf, word_table, list(word_cats.keys()), "word")
  322. # There are some emoji which are also ALetter, so this needs to be stored separately
  323. # For efficiency, we could still merge the two tables and produce an ALetterEP state
  324. emoji_table = [(x, y, "Extended_Pictographic") for (x, y) in emoji_props["Extended_Pictographic"]]
  325. emit_break_module(rf, emoji_table, ["Extended_Pictographic"], "emoji")
  326. sentence_cats = load_properties("auxiliary/SentenceBreakProperty.txt", [])
  327. sentence_table = []
  328. for cat in sentence_cats:
  329. sentence_table.extend([(x, y, cat) for (x, y) in sentence_cats[cat]])
  330. sentence_table.sort(key=lambda w: w[0])
  331. emit_break_module(rf, sentence_table, list(sentence_cats.keys()), "sentence")