#!/usr/bin/env python3 # # Copyright 2011-2015 The Rust Project Developers. See the COPYRIGHT # file at the top-level directory of this distribution and at # http://rust-lang.org/COPYRIGHT. # # Licensed under the Apache License, Version 2.0 or the MIT license # , at your # option. This file may not be copied, modified, or distributed # except according to those terms. # This script uses the following Unicode security tables: # - IdentifierStatus.txt # - ReadMe.txt # # Since this should not require frequent updates, we just store this # out-of-line and check the unicode.rs file into git. import fileinput, re, os, sys, operator preamble = '''// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. // NOTE: The following code was generated by "scripts/unicode.py", do not edit directly #![allow(missing_docs, non_upper_case_globals, non_snake_case)] ''' UNICODE_VERSION = (12, 1, 0) UNICODE_VERSION_NUMBER = "%s.%s.%s" %UNICODE_VERSION def fetch(f): if not os.path.exists(os.path.basename(f)): os.system("curl -O http://www.unicode.org/Public/security/%s/%s" % (UNICODE_VERSION_NUMBER, f)) if not os.path.exists(os.path.basename(f)): sys.stderr.write("cannot load %s\n" % f) exit(1) # Implementation from unicode-segmentation def load_properties(f, interestingprops = None): fetch(f) props = {} re1 = re.compile(r"^ *([0-9A-F]+) *; *(\w+)") re2 = re.compile(r"^ *([0-9A-F]+)\.\.([0-9A-F]+) *; *(\w+)") for line in fileinput.input(os.path.basename(f)): prop = None d_lo = 0 d_hi = 0 m = re1.match(line) if m: d_lo = m.group(1) d_hi = m.group(1) prop = m.group(2).strip() else: m = re2.match(line) if m: d_lo = m.group(1) d_hi = m.group(2) prop = m.group(3).strip() else: continue if interestingprops and prop not in interestingprops: continue d_lo = int(d_lo, 16) d_hi = int(d_hi, 16) if prop not in props: props[prop] = [] props[prop].append((d_lo, d_hi)) return props def format_table_content(f, content, indent): line = " "*indent first = True for chunk in content.split(","): if len(line) + len(chunk) < 98: if first: line += chunk else: line += ", " + chunk first = False else: f.write(line + ",\n") line = " "*indent + chunk f.write(line) def escape_char(c): return "'\\u{%x}'" % c def emit_table(f, name, t_data, t_type = "&'static [(char, char)]", is_pub=True, pfun=lambda x: "(%s,%s)" % (escape_char(x[0]), escape_char(x[1])), is_const=True): pub_string = "const" if not is_const: pub_string = "let" if is_pub: pub_string = "pub " + pub_string f.write(" %s %s: %s = &[\n" % (pub_string, name, t_type)) data = "" first = True for dat in t_data: if not first: data += "," first = False data += pfun(dat) format_table_content(f, data, 8) f.write("\n ];\n\n") def emit_identifier_module(f): f.write("pub mod identifier {") f.write(""" #[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd, Debug)] #[allow(non_camel_case_types)] /// https://www.unicode.org/reports/tr39/#Identifier_Status_and_Type pub enum IdentifierType { // Restricted Not_Character, Deprecated, Default_Ignorable, Not_NFKC, Not_XID, Exclusion, Obsolete, Technical, Uncommon_Use, Limited_Use, // Allowed Inclusion, Recommended } #[inline] pub fn identifier_status_allowed(c: char) -> bool { // FIXME: do we want to special case ASCII here? match c as usize { _ => super::util::bsearch_range_table(c, IDENTIFIER_STATUS) } } #[inline] pub fn identifier_type(c: char) -> Option { // FIXME: do we want to special case ASCII here? match c as usize { _ => super::util::bsearch_range_value_table(c, IDENTIFIER_TYPE) } } """) f.write(" // Identifier status table:\n") identifier_status_table = load_properties("IdentifierStatus.txt") emit_table(f, "IDENTIFIER_STATUS", identifier_status_table['Allowed'], "&'static [(char, char)]", is_pub=False, pfun=lambda x: "(%s,%s)" % (escape_char(x[0]), escape_char(x[1]))) identifier_type = load_properties("IdentifierType.txt") type_table = [] for ty in identifier_type: type_table.extend([(x, y, ty) for (x, y) in identifier_type[ty]]) type_table.sort(key=lambda w: w[0]) emit_table(f, "IDENTIFIER_TYPE", type_table, "&'static [(char, char, IdentifierType)]", is_pub=False, pfun=lambda x: "(%s,%s, IdentifierType::%s)" % (escape_char(x[0]), escape_char(x[1]), x[2])) f.write("}\n\n") def emit_util_mod(f): f.write(""" pub mod util { use core::result::Result::{Ok, Err}; #[inline] pub fn bsearch_range_table(c: char, r: &'static [(char,char)]) -> bool { use core::cmp::Ordering::{Equal, Less, Greater}; r.binary_search_by(|&(lo,hi)| { if lo <= c && c <= hi { Equal } else if hi < c { Less } else { Greater } }).is_ok() } pub fn bsearch_range_value_table(c: char, r: &'static [(char, char, T)]) -> Option { use core::cmp::Ordering::{Equal, Less, Greater}; match r.binary_search_by(|&(lo, hi, _)| { if lo <= c && c <= hi { Equal } else if hi < c { Less } else { Greater } }) { Ok(idx) => { let (_, _, cat) = r[idx]; Some(cat) } Err(_) => None } } } """) if __name__ == "__main__": r = "tables.rs" if os.path.exists(r): os.remove(r) with open(r, "w") as rf: # write the file's preamble rf.write(preamble) rf.write(""" /// The version of [Unicode](http://www.unicode.org/) /// that this version of unicode-security is based on. pub const UNICODE_VERSION: (u64, u64, u64) = (%s, %s, %s); """ % UNICODE_VERSION) emit_util_mod(rf) ### identifier module emit_identifier_module(rf)