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::cmp::Ordering::{Equal, Less, Greater};
285        match r.binary_search_by(|&(lo, hi, _)| {
286            if lo <= c && c <= hi { Equal }
287            else if hi < c { Less }
288            else { Greater }
289        }) {
290            Ok(idx) => {
291                let (lower, upper, cat) = r[idx];
292                (lower as u32, upper as u32, cat)
293            }
294            Err(idx) => {
295                (
296                    if idx > 0 { r[idx-1].1 as u32 + 1 } else { 0 },
297                    r.get(idx).map(|c|c.0 as u32 - 1).unwrap_or(core::u32::MAX),
298                    %sC_Any,
299                )
300            }
301        }
302    }
303
304    pub fn %s_category(c: char) -> (u32, u32, %sCat) {
305        bsearch_range_value_table(c, %s_cat_table)
306    }
307
308""" % (Name, Name, Name[0], name, Name, name))
309
310    emit_table(f, "%s_cat_table" % name, break_table, "&'static [(char, char, %sCat)]" % Name,
311        pfun=lambda x: "(%s,%s,%sC_%s)" % (escape_char(x[0]), escape_char(x[1]), Name[0], x[2]),
312        is_pub=False, is_const=True)
313    f.write("}\n")
314
315if __name__ == "__main__":
316    r = "tables.rs"
317    if os.path.exists(r):
318        os.remove(r)
319    with open(r, "w") as rf:
320        # write the file's preamble
321        rf.write(preamble)
322        rf.write("""
323/// The version of [Unicode](http://www.unicode.org/)
324/// that this version of unicode-segmentation is based on.
325pub const UNICODE_VERSION: (u64, u64, u64) = (%s, %s, %s);
326""" % UNICODE_VERSION)
327
328        # download and parse all the data
329        gencats = load_gencats("UnicodeData.txt")
330        derived = load_properties("DerivedCoreProperties.txt", ["Alphabetic"])
331
332        emit_util_mod(rf)
333        for (name, cat, pfuns) in ("general_category", gencats, ["N"]), \
334                                  ("derived_property", derived, ["Alphabetic"]):
335            emit_property_module(rf, name, cat, pfuns)
336
337        ### grapheme cluster module
338        # from http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Break_Property_Values
339        grapheme_cats = load_properties("auxiliary/GraphemeBreakProperty.txt", [])
340
341        # Control
342        #  Note:
343        # This category also includes Cs (surrogate codepoints), but Rust's `char`s are
344        # Unicode Scalar Values only, and surrogates are thus invalid `char`s.
345        # Thus, we have to remove Cs from the Control category
346        grapheme_cats["Control"] = group_cat(list(
347            set(ungroup_cat(grapheme_cats["Control"]))
348            - set(ungroup_cat([surrogate_codepoints]))))
349
350        grapheme_table = []
351        for cat in grapheme_cats:
352            grapheme_table.extend([(x, y, cat) for (x, y) in grapheme_cats[cat]])
353        emoji_props = load_properties("emoji-data.txt", ["Extended_Pictographic"])
354        grapheme_table.extend([(x, y, "Extended_Pictographic") for (x, y) in emoji_props["Extended_Pictographic"]])
355        grapheme_table.sort(key=lambda w: w[0])
356        last = -1
357        for chars in grapheme_table:
358            if chars[0] <= last:
359                raise "Grapheme tables and Extended_Pictographic values overlap; need to store these separately!"
360            last = chars[1]
361        emit_break_module(rf, grapheme_table, list(grapheme_cats.keys()) + ["Extended_Pictographic"], "grapheme")
362        rf.write("\n")
363
364        word_cats = load_properties("auxiliary/WordBreakProperty.txt", [])
365        word_table = []
366        for cat in word_cats:
367            word_table.extend([(x, y, cat) for (x, y) in word_cats[cat]])
368        word_table.sort(key=lambda w: w[0])
369        emit_break_module(rf, word_table, list(word_cats.keys()), "word")
370
371        # There are some emoji which are also ALetter, so this needs to be stored separately
372        # For efficiency, we could still merge the two tables and produce an ALetterEP state
373        emoji_table = [(x, y, "Extended_Pictographic") for (x, y) in emoji_props["Extended_Pictographic"]]
374        emit_break_module(rf, emoji_table, ["Extended_Pictographic"], "emoji")
375
376        sentence_cats = load_properties("auxiliary/SentenceBreakProperty.txt", [])
377        sentence_table = []
378        for cat in sentence_cats:
379            sentence_table.extend([(x, y, cat) for (x, y) in sentence_cats[cat]])
380        sentence_table.sort(key=lambda w: w[0])
381        emit_break_module(rf, sentence_table, list(sentence_cats.keys()), "sentence")
382