| 1 |
#!/usr/bin/env python |
| 2 |
# Based upon makeunicodedata.py |
| 3 |
# (http://hg.python.org/cpython/file/c8192197d23d/Tools/unicode/makeunicodedata.py) |
| 4 |
# written by Fredrik Lundh ([email protected]) |
| 5 |
# |
| 6 |
# Copyright (C) 2011 Tom Schuster <[email protected]> |
| 7 |
# |
| 8 |
# This program is free software: you can redistribute it and/or modify |
| 9 |
# it under the terms of the GNU General Public License as published by |
| 10 |
# the Free Software Foundation, either version 3 of the License, or |
| 11 |
# (at your option) any later version. |
| 12 |
# |
| 13 |
# This program is distributed in the hope that it will be useful, |
| 14 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 15 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 16 |
# GNU General Public License for more details. |
| 17 |
# |
| 18 |
# You should have received a copy of the GNU General Public License |
| 19 |
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 20 |
|
| 21 |
import csv |
| 22 |
import io |
| 23 |
import os |
| 24 |
import re |
| 25 |
import sys |
| 26 |
from contextlib import closing |
| 27 |
from functools import partial |
| 28 |
from itertools import chain, tee |
| 29 |
from operator import is_not, itemgetter |
| 30 |
from zipfile import ZipFile |
| 31 |
|
| 32 |
if sys.version_info.major == 2: |
| 33 |
from itertools import ifilter as filter |
| 34 |
from itertools import imap as map |
| 35 |
from itertools import izip_longest as zip_longest |
| 36 |
|
| 37 |
from urllib2 import urlopen |
| 38 |
|
| 39 |
range = xrange |
| 40 |
else: |
| 41 |
from itertools import zip_longest |
| 42 |
from urllib.request import urlopen |
| 43 |
|
| 44 |
|
| 45 |
class codepoint_dict(dict): |
| 46 |
def name(self, code_point): |
| 47 |
(_, _, name, alias) = self[code_point] |
| 48 |
return "{}{}".format(name, (" (" + alias + ")" if alias else "")) |
| 49 |
|
| 50 |
def full_name(self, code_point): |
| 51 |
(_, _, name, alias) = self[code_point] |
| 52 |
return "U+{:04X} {}{}".format( |
| 53 |
code_point, name, (" (" + alias + ")" if alias else "") |
| 54 |
) |
| 55 |
|
| 56 |
|
| 57 |
# ECMAScript 2016 |
| 58 |
# §11.2 White Space |
| 59 |
whitespace = [ |
| 60 |
# python doesn't support using control character names :( |
| 61 |
0x9, # CHARACTER TABULATION |
| 62 |
0xB, # LINE TABULATION |
| 63 |
0xC, # FORM FEED |
| 64 |
ord("\N{SPACE}"), |
| 65 |
ord("\N{NO-BREAK SPACE}"), |
| 66 |
ord("\N{ZERO WIDTH NO-BREAK SPACE}"), # also BOM |
| 67 |
] |
| 68 |
|
| 69 |
# §11.3 Line Terminators |
| 70 |
line_terminator = [ |
| 71 |
0xA, # LINE FEED |
| 72 |
0xD, # CARRIAGE RETURN |
| 73 |
ord("\N{LINE SEPARATOR}"), |
| 74 |
ord("\N{PARAGRAPH SEPARATOR}"), |
| 75 |
] |
| 76 |
|
| 77 |
# These are also part of IdentifierPart §11.6 Names and Keywords |
| 78 |
compatibility_identifier_part = [ |
| 79 |
ord("\N{ZERO WIDTH NON-JOINER}"), |
| 80 |
ord("\N{ZERO WIDTH JOINER}"), |
| 81 |
] |
| 82 |
|
| 83 |
FLAG_SPACE = 1 << 0 |
| 84 |
FLAG_UNICODE_ID_START = 1 << 1 |
| 85 |
FLAG_UNICODE_ID_CONTINUE_ONLY = 1 << 2 |
| 86 |
|
| 87 |
MAX_BMP = 0xFFFF |
| 88 |
|
| 89 |
public_domain = """ |
| 90 |
/* |
| 91 |
* Any copyright is dedicated to the Public Domain. |
| 92 |
* http://creativecommons.org/licenses/publicdomain/ |
| 93 |
*/ |
| 94 |
""" |
| 95 |
|
| 96 |
mpl_license = """\ |
| 97 |
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- |
| 98 |
* vim: set ts=8 sts=4 et sw=4 tw=99: |
| 99 |
* This Source Code Form is subject to the terms of the Mozilla Public |
| 100 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 101 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 102 |
""" |
| 103 |
|
| 104 |
warning_message = """\ |
| 105 |
/* Generated by make_unicode.py DO NOT MODIFY */ |
| 106 |
""" |
| 107 |
|
| 108 |
unicode_version_message = """\ |
| 109 |
/* Unicode version: {0} */ |
| 110 |
""" |
| 111 |
|
| 112 |
|
| 113 |
def read_unicode_data(unicode_data): |
| 114 |
""" |
| 115 |
If you want to understand how this wonderful file format works checkout |
| 116 |
Unicode Standard Annex #44 - Unicode Character Database |
| 117 |
http://www.unicode.org/reports/tr44/ |
| 118 |
""" |
| 119 |
|
| 120 |
reader = csv.reader(unicode_data, delimiter=";") |
| 121 |
|
| 122 |
while True: |
| 123 |
row = next(reader, None) |
| 124 |
if row is None: |
| 125 |
return |
| 126 |
name = row[1] |
| 127 |
|
| 128 |
# We need to expand the UAX #44 4.2.3 Code Point Range |
| 129 |
if name.startswith("<") and name.endswith("First>"): |
| 130 |
next_row = next(reader) |
| 131 |
|
| 132 |
for i in range(int(row[0], 16), int(next_row[0], 16) + 1): |
| 133 |
row[0] = i |
| 134 |
row[1] = name[1:-8] |
| 135 |
|
| 136 |
yield row |
| 137 |
else: |
| 138 |
row[0] = int(row[0], 16) |
| 139 |
yield row |
| 140 |
|
| 141 |
|
| 142 |
def read_case_folding(case_folding): |
| 143 |
""" |
| 144 |
File format is: |
| 145 |
<code>; <status>; <mapping>; # <name> |
| 146 |
""" |
| 147 |
|
| 148 |
for line in case_folding: |
| 149 |
if line == "\n" or line.startswith("#"): |
| 150 |
continue |
| 151 |
row = line.split("; ") |
| 152 |
if row[1] in ["F", "T"]: |
| 153 |
continue |
| 154 |
assert row[1] in ["C", "S"], "expect either (C)ommon or (S)imple case foldings" |
| 155 |
code = int(row[0], 16) |
| 156 |
mapping = int(row[2], 16) |
| 157 |
yield (code, mapping) |
| 158 |
|
| 159 |
|
| 160 |
def read_derived_core_properties(derived_core_properties): |
| 161 |
for line in derived_core_properties: |
| 162 |
if line == "\n" or line.startswith("#"): |
| 163 |
continue |
| 164 |
row = line.split("#")[0].split(";") |
| 165 |
char_range = row[0].strip() |
| 166 |
char_property = row[1].strip() |
| 167 |
if ".." not in char_range: |
| 168 |
yield (int(char_range, 16), char_property) |
| 169 |
else: |
| 170 |
[start, end] = char_range.split("..") |
| 171 |
for char in range(int(start, 16), int(end, 16) + 1): |
| 172 |
yield (char, char_property) |
| 173 |
|
| 174 |
|
| 175 |
def read_special_casing(special_casing): |
| 176 |
# Format: |
| 177 |
# <code>; <lower>; <title>; <upper>; (<condition_list>;)? # <comment> |
| 178 |
for line in special_casing: |
| 179 |
if line == "\n" or line.startswith("#"): |
| 180 |
continue |
| 181 |
row = line.split("#")[0].split(";") |
| 182 |
code = int(row[0].strip(), 16) |
| 183 |
lower = row[1].strip() |
| 184 |
lower = [int(c, 16) for c in lower.split(" ")] if lower else [] |
| 185 |
upper = row[3].strip() |
| 186 |
upper = [int(c, 16) for c in upper.split(" ")] if upper else [] |
| 187 |
languages = [] |
| 188 |
contexts = [] |
| 189 |
condition = row[4].strip() |
| 190 |
if condition: |
| 191 |
for cond in condition.split(" "): |
| 192 |
if cond[0].islower(): |
| 193 |
languages.append(cond) |
| 194 |
else: |
| 195 |
contexts.append(cond) |
| 196 |
pass |
| 197 |
yield (code, lower, upper, languages, contexts) |
| 198 |
|
| 199 |
|
| 200 |
def int_ranges(ints): |
| 201 |
"""Yields consecutive ranges (inclusive) from integer values.""" |
| 202 |
(a, b) = tee(sorted(ints)) |
| 203 |
start = next(b) |
| 204 |
for curr, succ in zip_longest(a, b): |
| 205 |
if curr + 1 != succ: |
| 206 |
yield (start, curr) |
| 207 |
start = succ |
| 208 |
|
| 209 |
|
| 210 |
def utf16_encode(code): |
| 211 |
NonBMPMin = 0x10000 |
| 212 |
LeadSurrogateMin = 0xD800 |
| 213 |
TrailSurrogateMin = 0xDC00 |
| 214 |
|
| 215 |
lead = (code - NonBMPMin) // 1024 + LeadSurrogateMin |
| 216 |
trail = ((code - NonBMPMin) % 1024) + TrailSurrogateMin |
| 217 |
|
| 218 |
return lead, trail |
| 219 |
|
| 220 |
|
| 221 |
def make_non_bmp_convert_macro(out_file, name, convert_map, codepoint_table): |
| 222 |
# Find continuous range in convert_map. |
| 223 |
convert_list = [] |
| 224 |
entry = None |
| 225 |
for code in sorted(convert_map.keys()): |
| 226 |
lead, trail = utf16_encode(code) |
| 227 |
converted = convert_map[code] |
| 228 |
diff = converted - code |
| 229 |
|
| 230 |
if ( |
| 231 |
entry |
| 232 |
and code == entry["code"] + entry["length"] |
| 233 |
and diff == entry["diff"] |
| 234 |
and lead == entry["lead"] |
| 235 |
): |
| 236 |
entry["length"] += 1 |
| 237 |
continue |
| 238 |
|
| 239 |
entry = { |
| 240 |
"code": code, |
| 241 |
"diff": diff, |
| 242 |
"length": 1, |
| 243 |
"lead": lead, |
| 244 |
"trail": trail, |
| 245 |
} |
| 246 |
convert_list.append(entry) |
| 247 |
|
| 248 |
# Generate macro call for each range. |
| 249 |
lines = [] |
| 250 |
comment = [] |
| 251 |
for entry in convert_list: |
| 252 |
from_code = entry["code"] |
| 253 |
to_code = entry["code"] + entry["length"] - 1 |
| 254 |
diff = entry["diff"] |
| 255 |
|
| 256 |
lead = entry["lead"] |
| 257 |
from_trail = entry["trail"] |
| 258 |
to_trail = entry["trail"] + entry["length"] - 1 |
| 259 |
|
| 260 |
lines.append( |
| 261 |
f" MACRO(0x{from_code:x}, 0x{to_code:x}, 0x{lead:x}, 0x{from_trail:x}, 0x{to_trail:x}, {diff:d})" |
| 262 |
) |
| 263 |
comment.append( |
| 264 |
f"// {codepoint_table.full_name(from_code)} .. {codepoint_table.full_name(to_code)}" |
| 265 |
) |
| 266 |
|
| 267 |
out_file.write("\n".join(comment)) |
| 268 |
out_file.write("\n") |
| 269 |
out_file.write(f"#define FOR_EACH_NON_BMP_{name}(MACRO) \\\n") |
| 270 |
out_file.write(" \\\n".join(lines)) |
| 271 |
out_file.write("\n") |
| 272 |
|
| 273 |
|
| 274 |
def process_derived_core_properties(derived_core_properties): |
| 275 |
id_start = set() |
| 276 |
id_continue = set() |
| 277 |
|
| 278 |
for char, prop in read_derived_core_properties(derived_core_properties): |
| 279 |
if prop == "ID_Start": |
| 280 |
id_start.add(char) |
| 281 |
if prop == "ID_Continue": |
| 282 |
id_continue.add(char) |
| 283 |
|
| 284 |
return (id_start, id_continue) |
| 285 |
|
| 286 |
|
| 287 |
def process_unicode_data(unicode_data, derived_core_properties): |
| 288 |
dummy = (0, 0, 0) |
| 289 |
table = [dummy] |
| 290 |
cache = {dummy: 0} |
| 291 |
index = [0] * (MAX_BMP + 1) |
| 292 |
|
| 293 |
codepoint_table = codepoint_dict() |
| 294 |
test_space_table = [] |
| 295 |
|
| 296 |
non_bmp_lower_map = {} |
| 297 |
non_bmp_upper_map = {} |
| 298 |
non_bmp_id_start_set = {} |
| 299 |
non_bmp_id_cont_set = {} |
| 300 |
non_bmp_space_set = {} |
| 301 |
|
| 302 |
(id_start, id_continue) = process_derived_core_properties(derived_core_properties) |
| 303 |
|
| 304 |
for row in read_unicode_data(unicode_data): |
| 305 |
code = row[0] |
| 306 |
name = row[1] |
| 307 |
category = row[2] |
| 308 |
alias = row[-5] |
| 309 |
uppercase = row[-3] |
| 310 |
lowercase = row[-2] |
| 311 |
|
| 312 |
if uppercase: |
| 313 |
upper = int(uppercase, 16) |
| 314 |
else: |
| 315 |
upper = code |
| 316 |
|
| 317 |
if lowercase: |
| 318 |
lower = int(lowercase, 16) |
| 319 |
else: |
| 320 |
lower = code |
| 321 |
|
| 322 |
codepoint_table[code] = (upper, lower, name, alias) |
| 323 |
|
| 324 |
if code > MAX_BMP: |
| 325 |
if code != lower: |
| 326 |
non_bmp_lower_map[code] = lower |
| 327 |
if code != upper: |
| 328 |
non_bmp_upper_map[code] = upper |
| 329 |
if category == "Zs": |
| 330 |
non_bmp_space_set[code] = 1 |
| 331 |
test_space_table.append(code) |
| 332 |
if code in id_start: |
| 333 |
non_bmp_id_start_set[code] = 1 |
| 334 |
if code in id_continue: |
| 335 |
non_bmp_id_cont_set[code] = 1 |
| 336 |
continue |
| 337 |
|
| 338 |
assert lower <= MAX_BMP and upper <= MAX_BMP |
| 339 |
|
| 340 |
flags = 0 |
| 341 |
|
| 342 |
# we combine whitespace and lineterminators because in pratice we don't need them separated |
| 343 |
if category == "Zs" or code in whitespace or code in line_terminator: |
| 344 |
flags |= FLAG_SPACE |
| 345 |
test_space_table.append(code) |
| 346 |
|
| 347 |
# §11.6 (IdentifierStart) |
| 348 |
if code in id_start: |
| 349 |
flags |= FLAG_UNICODE_ID_START |
| 350 |
|
| 351 |
# §11.6 (IdentifierPart) |
| 352 |
elif code in id_continue or code in compatibility_identifier_part: |
| 353 |
flags |= FLAG_UNICODE_ID_CONTINUE_ONLY |
| 354 |
|
| 355 |
up_d = upper - code |
| 356 |
low_d = lower - code |
| 357 |
|
| 358 |
assert up_d > -65535 and up_d < 65535 |
| 359 |
assert low_d > -65535 and low_d < 65535 |
| 360 |
|
| 361 |
upper = up_d & 0xFFFF |
| 362 |
lower = low_d & 0xFFFF |
| 363 |
|
| 364 |
item = (upper, lower, flags) |
| 365 |
|
| 366 |
i = cache.get(item) |
| 367 |
if i is None: |
| 368 |
assert item not in table |
| 369 |
cache[item] = i = len(table) |
| 370 |
table.append(item) |
| 371 |
index[code] = i |
| 372 |
|
| 373 |
return ( |
| 374 |
table, |
| 375 |
index, |
| 376 |
non_bmp_lower_map, |
| 377 |
non_bmp_upper_map, |
| 378 |
non_bmp_space_set, |
| 379 |
non_bmp_id_start_set, |
| 380 |
non_bmp_id_cont_set, |
| 381 |
codepoint_table, |
| 382 |
test_space_table, |
| 383 |
) |
| 384 |
|
| 385 |
|
| 386 |
def process_case_folding(case_folding): |
| 387 |
folding_map = {} |
| 388 |
rev_folding_map = {} |
| 389 |
folding_dummy = (0,) |
| 390 |
folding_table = [folding_dummy] |
| 391 |
folding_cache = {folding_dummy: 0} |
| 392 |
folding_index = [0] * (MAX_BMP + 1) |
| 393 |
|
| 394 |
folding_tests = [] |
| 395 |
folding_codes = set() |
| 396 |
|
| 397 |
for code, mapping in read_case_folding(case_folding): |
| 398 |
folding_map[code] = mapping |
| 399 |
|
| 400 |
if mapping not in rev_folding_map: |
| 401 |
rev_folding_map[mapping] = [code] |
| 402 |
else: |
| 403 |
rev_folding_map[mapping].append(code) |
| 404 |
|
| 405 |
folding_codes.add(code) |
| 406 |
folding_codes.add(mapping) |
| 407 |
|
| 408 |
for code in sorted(folding_codes): |
| 409 |
if code in folding_map: |
| 410 |
folding = folding_map[code] |
| 411 |
else: |
| 412 |
folding = code |
| 413 |
|
| 414 |
if code in rev_folding_map: |
| 415 |
rev_folding = rev_folding_map[code] |
| 416 |
elif folding in rev_folding_map: |
| 417 |
rev_folding = [c for c in rev_folding_map[folding] if c != code] |
| 418 |
else: |
| 419 |
rev_folding = [] |
| 420 |
|
| 421 |
if folding != code or len(rev_folding): |
| 422 |
item = [code] |
| 423 |
if folding != code: |
| 424 |
item.append(folding) |
| 425 |
folding_tests.append(item + rev_folding) |
| 426 |
|
| 427 |
if code > MAX_BMP: |
| 428 |
continue |
| 429 |
|
| 430 |
folding_d = folding - code |
| 431 |
|
| 432 |
assert folding_d > -65535 and folding_d < 65535 |
| 433 |
|
| 434 |
folding = folding_d & 0xFFFF |
| 435 |
|
| 436 |
item = (folding,) |
| 437 |
|
| 438 |
i = folding_cache.get(item) |
| 439 |
if i is None: |
| 440 |
assert item not in folding_table |
| 441 |
folding_cache[item] = i = len(folding_table) |
| 442 |
folding_table.append(item) |
| 443 |
folding_index[code] = i |
| 444 |
return (folding_table, folding_index, folding_tests) |
| 445 |
|
| 446 |
|
| 447 |
def process_special_casing(special_casing, table, index): |
| 448 |
# Unconditional special casing. |
| 449 |
unconditional_tolower = {} |
| 450 |
unconditional_toupper = {} |
| 451 |
|
| 452 |
# Conditional special casing, language independent. |
| 453 |
conditional_tolower = {} |
| 454 |
conditional_toupper = {} |
| 455 |
|
| 456 |
# Conditional special casing, language dependent. |
| 457 |
lang_conditional_tolower = {} |
| 458 |
lang_conditional_toupper = {} |
| 459 |
|
| 460 |
def caseInfo(code): |
| 461 |
(upper, lower, flags) = table[index[code]] |
| 462 |
return ((code + lower) & 0xFFFF, (code + upper) & 0xFFFF) |
| 463 |
|
| 464 |
for code, lower, upper, languages, contexts in read_special_casing(special_casing): |
| 465 |
assert code <= MAX_BMP, "Unexpected character outside of BMP: %s" % code |
| 466 |
assert len(languages) <= 1, "Expected zero or one language ids: %s" % languages |
| 467 |
assert len(contexts) <= 1, ( |
| 468 |
"Expected zero or one casing contexts: %s" % languages |
| 469 |
) |
| 470 |
|
| 471 |
(default_lower, default_upper) = caseInfo(code) |
| 472 |
special_lower = len(lower) != 1 or lower[0] != default_lower |
| 473 |
special_upper = len(upper) != 1 or upper[0] != default_upper |
| 474 |
|
| 475 |
# Invariant: If |code| has casing per UnicodeData.txt, then it also has |
| 476 |
# casing rules in SpecialCasing.txt. |
| 477 |
assert code == default_lower or len(lower) != 1 or code != lower[0] |
| 478 |
assert code == default_upper or len(upper) != 1 or code != upper[0] |
| 479 |
|
| 480 |
language = languages[0] if languages else None |
| 481 |
context = contexts[0] if contexts else None |
| 482 |
|
| 483 |
if not language and not context: |
| 484 |
if special_lower: |
| 485 |
unconditional_tolower[code] = lower |
| 486 |
if special_upper: |
| 487 |
unconditional_toupper[code] = upper |
| 488 |
elif not language and context: |
| 489 |
if special_lower: |
| 490 |
conditional_tolower[code] = (lower, context) |
| 491 |
if special_upper: |
| 492 |
conditional_toupper[code] = (upper, context) |
| 493 |
else: |
| 494 |
if language not in lang_conditional_tolower: |
| 495 |
lang_conditional_tolower[language] = {} |
| 496 |
lang_conditional_toupper[language] = {} |
| 497 |
if special_lower: |
| 498 |
lang_conditional_tolower[language][code] = (lower, context) |
| 499 |
if special_upper: |
| 500 |
lang_conditional_toupper[language][code] = (upper, context) |
| 501 |
|
| 502 |
# Certain special casing rules are inlined in jsstr.cpp, ensure these cases |
| 503 |
# still match the current SpecialCasing.txt file. |
| 504 |
def lowerCase(code): |
| 505 |
(lower, _) = caseInfo(code) |
| 506 |
return lower |
| 507 |
|
| 508 |
def upperCase(code): |
| 509 |
(_, upper) = caseInfo(code) |
| 510 |
return upper |
| 511 |
|
| 512 |
def ascii(char_dict): |
| 513 |
return (ch for ch in char_dict.keys() if ch <= 0x7F) |
| 514 |
|
| 515 |
def latin1(char_dict): |
| 516 |
return (ch for ch in char_dict.keys() if ch <= 0xFF) |
| 517 |
|
| 518 |
def is_empty(iterable): |
| 519 |
return not any(True for _ in iterable) |
| 520 |
|
| 521 |
def is_equals(iter1, iter2): |
| 522 |
return all(x == y for (x, y) in zip_longest(iter1, iter2)) |
| 523 |
|
| 524 |
# Ensure no ASCII characters have special case mappings. |
| 525 |
assert is_empty(ascii(unconditional_tolower)) |
| 526 |
assert is_empty(ascii(unconditional_toupper)) |
| 527 |
assert is_empty(ascii(conditional_tolower)) |
| 528 |
assert is_empty(ascii(conditional_toupper)) |
| 529 |
|
| 530 |
# Ensure no Latin1 characters have special lower case mappings. |
| 531 |
assert is_empty(latin1(unconditional_tolower)) |
| 532 |
assert is_empty(latin1(conditional_tolower)) |
| 533 |
|
| 534 |
# Ensure no Latin1 characters have conditional special upper case mappings. |
| 535 |
assert is_empty(latin1(conditional_toupper)) |
| 536 |
|
| 537 |
# Ensure U+00DF is the only Latin1 character with a special upper case mapping. |
| 538 |
assert is_equals([0x00DF], latin1(unconditional_toupper)) |
| 539 |
|
| 540 |
# Ensure U+0130 is the only character with a special lower case mapping. |
| 541 |
assert is_equals([0x0130], unconditional_tolower) |
| 542 |
|
| 543 |
# Ensure no characters have language independent conditional upper case mappings. |
| 544 |
assert is_empty(conditional_toupper) |
| 545 |
|
| 546 |
# Ensure U+03A3 is the only character with language independent conditional lower case mapping. |
| 547 |
assert is_equals([0x03A3], conditional_tolower) |
| 548 |
|
| 549 |
# Verify U+0130 and U+03A3 have simple lower case mappings. |
| 550 |
assert all(ch != lowerCase(ch) for ch in [0x0130, 0x03A3]) |
| 551 |
|
| 552 |
# Ensure Azeri, Lithuanian, and Turkish are the only languages with conditional case mappings. |
| 553 |
assert is_equals(["az", "lt", "tr"], sorted(lang_conditional_tolower.keys())) |
| 554 |
assert is_equals(["az", "lt", "tr"], sorted(lang_conditional_toupper.keys())) |
| 555 |
|
| 556 |
# Maximum case mapping length is three characters. |
| 557 |
assert ( |
| 558 |
max( |
| 559 |
map( |
| 560 |
len, |
| 561 |
chain( |
| 562 |
unconditional_tolower.values(), |
| 563 |
unconditional_toupper.values(), |
| 564 |
map(itemgetter(0), conditional_tolower.values()), |
| 565 |
map(itemgetter(0), conditional_toupper.values()), |
| 566 |
map( |
| 567 |
itemgetter(0), |
| 568 |
chain.from_iterable( |
| 569 |
d.values() for d in lang_conditional_tolower.values() |
| 570 |
), |
| 571 |
), |
| 572 |
map( |
| 573 |
itemgetter(0), |
| 574 |
chain.from_iterable( |
| 575 |
d.values() for d in lang_conditional_toupper.values() |
| 576 |
), |
| 577 |
), |
| 578 |
), |
| 579 |
) |
| 580 |
) |
| 581 |
<= 3 |
| 582 |
) |
| 583 |
|
| 584 |
# Ensure all case mapping contexts are known (see Unicode 9.0, §3.13 Default Case Algorithms). |
| 585 |
assert set( |
| 586 |
[ |
| 587 |
"After_I", |
| 588 |
"After_Soft_Dotted", |
| 589 |
"Final_Sigma", |
| 590 |
"More_Above", |
| 591 |
"Not_Before_Dot", |
| 592 |
] |
| 593 |
).issuperset( |
| 594 |
set( |
| 595 |
filter( |
| 596 |
partial(is_not, None), |
| 597 |
chain( |
| 598 |
map(itemgetter(1), conditional_tolower.values()), |
| 599 |
map(itemgetter(1), conditional_toupper.values()), |
| 600 |
map( |
| 601 |
itemgetter(1), |
| 602 |
chain.from_iterable( |
| 603 |
d.values() for d in lang_conditional_tolower.values() |
| 604 |
), |
| 605 |
), |
| 606 |
map( |
| 607 |
itemgetter(1), |
| 608 |
chain.from_iterable( |
| 609 |
d.values() for d in lang_conditional_toupper.values() |
| 610 |
), |
| 611 |
), |
| 612 |
), |
| 613 |
) |
| 614 |
) |
| 615 |
) |
| 616 |
|
| 617 |
# Special casing for U+00DF (LATIN SMALL LETTER SHARP S). |
| 618 |
assert upperCase(0x00DF) == 0x00DF and unconditional_toupper[0x00DF] == [ |
| 619 |
0x0053, |
| 620 |
0x0053, |
| 621 |
] |
| 622 |
|
| 623 |
# Special casing for U+0130 (LATIN CAPITAL LETTER I WITH DOT ABOVE). |
| 624 |
assert unconditional_tolower[0x0130] == [0x0069, 0x0307] |
| 625 |
|
| 626 |
# Special casing for U+03A3 (GREEK CAPITAL LETTER SIGMA). |
| 627 |
assert lowerCase(0x03A3) == 0x03C3 and conditional_tolower[0x03A3] == ( |
| 628 |
[0x03C2], |
| 629 |
"Final_Sigma", |
| 630 |
) |
| 631 |
|
| 632 |
return (unconditional_tolower, unconditional_toupper) |
| 633 |
|
| 634 |
|
| 635 |
def make_non_bmp_file(version, non_bmp_lower_map, non_bmp_upper_map, codepoint_table): |
| 636 |
file_name = "UnicodeNonBMP.h" |
| 637 |
with open(file_name, mode="w", encoding="utf-8") as non_bmp_file: |
| 638 |
non_bmp_file.write(mpl_license) |
| 639 |
non_bmp_file.write("\n") |
| 640 |
non_bmp_file.write(warning_message) |
| 641 |
non_bmp_file.write(unicode_version_message.format(version)) |
| 642 |
non_bmp_file.write( |
| 643 |
""" |
| 644 |
#ifndef util_UnicodeNonBMP_h |
| 645 |
#define util_UnicodeNonBMP_h |
| 646 |
|
| 647 |
// |MACRO| receives the following arguments |
| 648 |
// MACRO(FROM, TO, LEAD, TRAIL_FROM, TRAIL_TO, DIFF) |
| 649 |
// FROM: code point where the range starts |
| 650 |
// TO: code point where the range ends |
| 651 |
// LEAD: common lead surrogate of FROM and TO |
| 652 |
// TRAIL_FROM: trail surrogate of FROM |
| 653 |
// TRAIL_FROM: trail surrogate of TO |
| 654 |
// DIFF: the difference between the code point in the range and |
| 655 |
// converted code point |
| 656 |
|
| 657 |
""" |
| 658 |
) |
| 659 |
|
| 660 |
make_non_bmp_convert_macro( |
| 661 |
non_bmp_file, "LOWERCASE", non_bmp_lower_map, codepoint_table |
| 662 |
) |
| 663 |
non_bmp_file.write("\n") |
| 664 |
make_non_bmp_convert_macro( |
| 665 |
non_bmp_file, "UPPERCASE", non_bmp_upper_map, codepoint_table |
| 666 |
) |
| 667 |
|
| 668 |
non_bmp_file.write( |
| 669 |
""" |
| 670 |
#endif /* util_UnicodeNonBMP_h */ |
| 671 |
""" |
| 672 |
) |
| 673 |
|
| 674 |
|
| 675 |
def write_special_casing_methods(unconditional_toupper, codepoint_table, println): |
| 676 |
def hexlit(n): |
| 677 |
"""Returns C++ hex-literal for |n|.""" |
| 678 |
return f"0x{n:04X}" |
| 679 |
|
| 680 |
def describe_range(ranges, depth): |
| 681 |
indent = depth * " " |
| 682 |
for start, end in ranges: |
| 683 |
if start == end: |
| 684 |
println(indent, f"// {codepoint_table.full_name(start)}") |
| 685 |
else: |
| 686 |
println( |
| 687 |
indent, |
| 688 |
f"// {codepoint_table.full_name(start)} .. {codepoint_table.full_name(end)}", |
| 689 |
) |
| 690 |
|
| 691 |
def out_range(start, end): |
| 692 |
"""Tests if the input character isn't a member of the set {x | start <= x <= end}.""" |
| 693 |
if start == end: |
| 694 |
return f"ch != {hexlit(start)}" |
| 695 |
return f"ch < {hexlit(start)} || ch > {hexlit(end)}" |
| 696 |
|
| 697 |
def in_range(start, end, parenthesize=False): |
| 698 |
"""Tests if the input character is in the set {x | start <= x <= end}.""" |
| 699 |
if start == end: |
| 700 |
return f"ch == {hexlit(start)}" |
| 701 |
(left, right) = ("(", ")") if parenthesize else ("", "") |
| 702 |
return f"{left}ch >= {hexlit(start)} && ch <= {hexlit(end)}{right}" |
| 703 |
|
| 704 |
def in_any_range(ranges, spaces): |
| 705 |
"""Tests if the input character is included in any of the given ranges.""" |
| 706 |
lines = [[]] |
| 707 |
for start, end in ranges: |
| 708 |
expr = in_range(start, end, parenthesize=True) |
| 709 |
line = " || ".join(lines[-1] + [expr]) |
| 710 |
if len(line) < (100 - len(spaces) - len(" ||")): |
| 711 |
lines[-1].append(expr) |
| 712 |
else: |
| 713 |
lines.append([expr]) |
| 714 |
return f" ||\n{spaces}".join(" || ".join(t) for t in lines) |
| 715 |
|
| 716 |
def write_range_accept(parent_list, child_list, depth): |
| 717 |
"""Accepts the input character if it matches any code unit in |child_list|.""" |
| 718 |
(min_parent, max_parent) = (parent_list[0], parent_list[-1]) |
| 719 |
(min_child, max_child) = (child_list[0], child_list[-1]) |
| 720 |
assert min_child >= min_parent |
| 721 |
assert max_child <= max_parent |
| 722 |
indent = depth * " " |
| 723 |
|
| 724 |
child_ranges = list(int_ranges(child_list)) |
| 725 |
has_successor = max_child != max_parent |
| 726 |
|
| 727 |
# If |child_list| is a contiguous list of code units, emit a simple |
| 728 |
# range check: |min_child <= input <= max_child|. |
| 729 |
if len(child_ranges) == 1: |
| 730 |
describe_range(child_ranges, depth) |
| 731 |
if has_successor: |
| 732 |
println(indent, f"if (ch <= {hexlit(max_child)}) {{") |
| 733 |
println(indent, f" return ch >= {hexlit(min_child)};") |
| 734 |
println(indent, "}") |
| 735 |
else: |
| 736 |
println(indent, f"return {in_range(min_child, max_child)};") |
| 737 |
return |
| 738 |
|
| 739 |
# Otherwise create a disjunction over the subranges in |child_ranges|. |
| 740 |
if not has_successor: |
| 741 |
spaces = indent + len("return ") * " " |
| 742 |
else: |
| 743 |
spaces = indent + len(" return ") * " " |
| 744 |
range_test_expr = in_any_range(child_ranges, spaces) |
| 745 |
|
| 746 |
if min_child != min_parent: |
| 747 |
println(indent, f"if (ch < {hexlit(min_child)}) {{") |
| 748 |
println(indent, " return false;") |
| 749 |
println(indent, "}") |
| 750 |
|
| 751 |
# If there's no successor block, we can omit the |input <= max_child| check, |
| 752 |
# because it was already checked when we emitted the parent range test. |
| 753 |
if not has_successor: |
| 754 |
describe_range(child_ranges, depth) |
| 755 |
println(indent, f"return {range_test_expr};") |
| 756 |
else: |
| 757 |
println(indent, f"if (ch <= {hexlit(max_child)}) {{") |
| 758 |
describe_range(child_ranges, depth + 1) |
| 759 |
println(indent, f" return {range_test_expr};") |
| 760 |
println(indent, "}") |
| 761 |
|
| 762 |
def write_ChangesWhenUpperCasedSpecialCasing(): |
| 763 |
"""Checks if the input has a special upper case mapping.""" |
| 764 |
println("bool") |
| 765 |
println("js::unicode::ChangesWhenUpperCasedSpecialCasing(char16_t ch)") |
| 766 |
println("{") |
| 767 |
|
| 768 |
assert unconditional_toupper, "|unconditional_toupper| is not empty" |
| 769 |
|
| 770 |
# Sorted list of code units with special upper case mappings. |
| 771 |
code_list = sorted(unconditional_toupper.keys()) |
| 772 |
|
| 773 |
# Fail-fast if the input character isn't a special casing character. |
| 774 |
println(f" if ({out_range(code_list[0], code_list[-1])}) {{") |
| 775 |
println(" return false;") |
| 776 |
println(" }") |
| 777 |
|
| 778 |
for i in range(0, 16): |
| 779 |
# Check if the input characters is in the range: |
| 780 |
# |start_point <= input < end_point|. |
| 781 |
start_point = i << 12 |
| 782 |
end_point = (i + 1) << 12 |
| 783 |
matches = [cu for cu in code_list if start_point <= cu < end_point] |
| 784 |
|
| 785 |
# Skip empty ranges. |
| 786 |
if not matches: |
| 787 |
continue |
| 788 |
|
| 789 |
# If |matches| consists of only a few characters, directly check |
| 790 |
# the input against the characters in |matches|. |
| 791 |
if len(matches) <= 8: |
| 792 |
write_range_accept(code_list, matches, depth=1) |
| 793 |
continue |
| 794 |
|
| 795 |
# Otherwise split into further subranges. |
| 796 |
|
| 797 |
# Only enter the if-block if the input is less-or-equals to the |
| 798 |
# largest value in the current range. |
| 799 |
is_last_block = matches[-1] == code_list[-1] |
| 800 |
if not is_last_block: |
| 801 |
println(f" if (ch <= {hexlit(matches[-1])}) {{") |
| 802 |
else: |
| 803 |
println(f" if (ch < {hexlit(matches[0])}) {{") |
| 804 |
println(" return false;") |
| 805 |
println(" }") |
| 806 |
|
| 807 |
for j in range(0, 16): |
| 808 |
inner_start = start_point + (j << 8) |
| 809 |
inner_end = start_point + ((j + 1) << 8) |
| 810 |
inner_matches = [cu for cu in matches if inner_start <= cu < inner_end] |
| 811 |
|
| 812 |
if inner_matches: |
| 813 |
d = 1 if is_last_block else 2 |
| 814 |
write_range_accept(matches, inner_matches, depth=d) |
| 815 |
|
| 816 |
if not is_last_block: |
| 817 |
println(" }") |
| 818 |
|
| 819 |
println("}") |
| 820 |
|
| 821 |
def write_LengthUpperCaseSpecialCasing(): |
| 822 |
"""Slow case: Special casing character was found, returns its mapping length.""" |
| 823 |
println("size_t") |
| 824 |
println("js::unicode::LengthUpperCaseSpecialCasing(char16_t ch)") |
| 825 |
println("{") |
| 826 |
|
| 827 |
println(" switch(ch) {") |
| 828 |
for code, converted in sorted(unconditional_toupper.items(), key=itemgetter(0)): |
| 829 |
println( |
| 830 |
f" case {hexlit(code)}: return {len(converted)}; // {codepoint_table.name(code)}" |
| 831 |
) |
| 832 |
println(" }") |
| 833 |
println("") |
| 834 |
println(' MOZ_ASSERT_UNREACHABLE("Bad character input.");') |
| 835 |
println(" return 0;") |
| 836 |
|
| 837 |
println("}") |
| 838 |
|
| 839 |
def write_AppendUpperCaseSpecialCasing(): |
| 840 |
"""Slow case: Special casing character was found, append its mapping characters.""" |
| 841 |
println("void") |
| 842 |
println( |
| 843 |
"js::unicode::AppendUpperCaseSpecialCasing(char16_t ch, char16_t* elements, size_t* index)" # NOQA: E501 |
| 844 |
) |
| 845 |
println("{") |
| 846 |
|
| 847 |
println(" switch(ch) {") |
| 848 |
for code, converted in sorted(unconditional_toupper.items(), key=itemgetter(0)): |
| 849 |
println(f" case {hexlit(code)}: // {codepoint_table.name(code)}") |
| 850 |
for ch in converted: |
| 851 |
println( |
| 852 |
f" elements[(*index)++] = {hexlit(ch)}; // {codepoint_table.name(ch)}" |
| 853 |
) |
| 854 |
println(" return;") |
| 855 |
println(" }") |
| 856 |
println("") |
| 857 |
println(' MOZ_ASSERT_UNREACHABLE("Bad character input.");') |
| 858 |
|
| 859 |
println("}") |
| 860 |
|
| 861 |
write_ChangesWhenUpperCasedSpecialCasing() |
| 862 |
println("") |
| 863 |
write_LengthUpperCaseSpecialCasing() |
| 864 |
println("") |
| 865 |
write_AppendUpperCaseSpecialCasing() |
| 866 |
|
| 867 |
|
| 868 |
def write_ascii_lookup_tables(table, index, write, println): |
| 869 |
def is_id_compat(code): |
| 870 |
return code == ord("\N{DOLLAR SIGN}") or code == ord("\N{LOW LINE}") |
| 871 |
|
| 872 |
def is_id_start(code): |
| 873 |
(upper, lower, flags) = table[index[code]] |
| 874 |
return (flags & FLAG_UNICODE_ID_START) or is_id_compat(code) |
| 875 |
|
| 876 |
def is_id_continue(code): |
| 877 |
(upper, lower, flags) = table[index[code]] |
| 878 |
return (flags & FLAG_UNICODE_ID_CONTINUE_ONLY) or is_id_start(code) |
| 879 |
|
| 880 |
def is_space(code): |
| 881 |
(upper, lower, flags) = table[index[code]] |
| 882 |
return flags & FLAG_SPACE |
| 883 |
|
| 884 |
def write_entries(name, predicate): |
| 885 |
println(f"const bool unicode::{name}[] = {{") |
| 886 |
header = "".join(f"{x: <6}" for x in range(0, 10)).rstrip() |
| 887 |
println(f"/* {header} */") |
| 888 |
for i in range(0, 13): |
| 889 |
write(f"/* {i: >2} */") |
| 890 |
for j in range(0, 10): |
| 891 |
code = i * 10 + j |
| 892 |
if code <= 0x7F: |
| 893 |
write(" {},".format("true" if predicate(code) else "____")) |
| 894 |
println("") |
| 895 |
println("};") |
| 896 |
|
| 897 |
println("") |
| 898 |
println("#define ____ false") |
| 899 |
|
| 900 |
println( |
| 901 |
""" |
| 902 |
/* |
| 903 |
* Identifier start chars: |
| 904 |
* - 36: $ |
| 905 |
* - 65..90: A..Z |
| 906 |
* - 95: _ |
| 907 |
* - 97..122: a..z |
| 908 |
*/""" |
| 909 |
) |
| 910 |
write_entries("js_isidstart", is_id_start) |
| 911 |
|
| 912 |
println( |
| 913 |
""" |
| 914 |
/* |
| 915 |
* Identifier chars: |
| 916 |
* - 36: $ |
| 917 |
* - 48..57: 0..9 |
| 918 |
* - 65..90: A..Z |
| 919 |
* - 95: _ |
| 920 |
* - 97..122: a..z |
| 921 |
*/""" |
| 922 |
) |
| 923 |
write_entries("js_isident", is_id_continue) |
| 924 |
|
| 925 |
println( |
| 926 |
""" |
| 927 |
/* Whitespace chars: '\\t', '\\n', '\\v', '\\f', '\\r', ' '. */""" |
| 928 |
) |
| 929 |
write_entries("js_isspace", is_space) |
| 930 |
|
| 931 |
println("") |
| 932 |
println("#undef ____") |
| 933 |
|
| 934 |
|
| 935 |
def write_latin1_lookup_tables(table, index, write, println): |
| 936 |
def case_info(code): |
| 937 |
assert 0 <= code and code <= MAX_BMP |
| 938 |
(upper, lower, flags) = table[index[code]] |
| 939 |
return ((code + upper) & 0xFFFF, (code + lower) & 0xFFFF, flags) |
| 940 |
|
| 941 |
def toLowerCase(code): |
| 942 |
(_, lower, _) = case_info(code) |
| 943 |
assert lower <= 0xFF, "lower-case of Latin-1 is always Latin-1" |
| 944 |
return lower |
| 945 |
|
| 946 |
def write_entries(name, mapper): |
| 947 |
println(f"const JS::Latin1Char unicode::{name}[] = {{") |
| 948 |
header = "".join(f"{x: <6}" for x in range(0, 16)).rstrip() |
| 949 |
println(f"/* {header} */") |
| 950 |
for i in range(0, 16): |
| 951 |
write(f"/* {i: >2} */") |
| 952 |
for j in range(0, 16): |
| 953 |
code = i * 16 + j |
| 954 |
if code <= 0xFF: |
| 955 |
write(f" 0x{mapper(code):02X},") |
| 956 |
println("") |
| 957 |
println("};") |
| 958 |
|
| 959 |
println("") |
| 960 |
write_entries("latin1ToLowerCaseTable", toLowerCase) |
| 961 |
|
| 962 |
|
| 963 |
def make_bmp_mapping_test( |
| 964 |
version, codepoint_table, unconditional_tolower, unconditional_toupper |
| 965 |
): |
| 966 |
def unicodeEsc(n): |
| 967 |
return f"\\u{n:04X}" |
| 968 |
|
| 969 |
file_name = "../tests/non262/String/string-upper-lower-mapping.js" |
| 970 |
with open(file_name, mode="w", encoding="utf-8") as output: |
| 971 |
write = partial(print, file=output, sep="", end="") |
| 972 |
println = partial(print, file=output, sep="", end="\n") |
| 973 |
|
| 974 |
write(warning_message) |
| 975 |
write(unicode_version_message.format(version)) |
| 976 |
write(public_domain) |
| 977 |
println("var mapping = [") |
| 978 |
for code in range(0, MAX_BMP + 1): |
| 979 |
entry = codepoint_table.get(code) |
| 980 |
|
| 981 |
if entry: |
| 982 |
(upper, lower, _, _) = entry |
| 983 |
upper = ( |
| 984 |
unconditional_toupper[code] |
| 985 |
if code in unconditional_toupper |
| 986 |
else [upper] |
| 987 |
) |
| 988 |
lower = ( |
| 989 |
unconditional_tolower[code] |
| 990 |
if code in unconditional_tolower |
| 991 |
else [lower] |
| 992 |
) |
| 993 |
println( |
| 994 |
' ["{}", "{}"], /* {} */'.format( |
| 995 |
"".join(map(unicodeEsc, upper)), |
| 996 |
"".join(map(unicodeEsc, lower)), |
| 997 |
codepoint_table.name(code), |
| 998 |
) |
| 999 |
) |
| 1000 |
else: |
| 1001 |
println(' ["{0}", "{0}"],'.format(unicodeEsc(code))) |
| 1002 |
println("];") |
| 1003 |
write( |
| 1004 |
""" |
| 1005 |
assertEq(mapping.length, 0x10000); |
| 1006 |
for (var i = 0; i <= 0xffff; i++) { |
| 1007 |
var char = String.fromCharCode(i); |
| 1008 |
var info = mapping[i]; |
| 1009 |
|
| 1010 |
assertEq(char.toUpperCase(), info[0]); |
| 1011 |
assertEq(char.toLowerCase(), info[1]); |
| 1012 |
} |
| 1013 |
|
| 1014 |
if (typeof reportCompare === "function") |
| 1015 |
reportCompare(true, true); |
| 1016 |
""" |
| 1017 |
) |
| 1018 |
|
| 1019 |
|
| 1020 |
def make_non_bmp_mapping_test( |
| 1021 |
version, non_bmp_upper_map, non_bmp_lower_map, codepoint_table |
| 1022 |
): |
| 1023 |
file_name = "../tests/non262/String/string-code-point-upper-lower-mapping.js" |
| 1024 |
with open(file_name, mode="w", encoding="utf-8") as test_non_bmp_mapping: |
| 1025 |
test_non_bmp_mapping.write(warning_message) |
| 1026 |
test_non_bmp_mapping.write(unicode_version_message.format(version)) |
| 1027 |
test_non_bmp_mapping.write(public_domain) |
| 1028 |
|
| 1029 |
for code in sorted(non_bmp_upper_map.keys()): |
| 1030 |
test_non_bmp_mapping.write( |
| 1031 |
f"""\ |
| 1032 |
assertEq(String.fromCodePoint(0x{code:04X}).toUpperCase().codePointAt(0), 0x{non_bmp_upper_map[code]:04X}); // {codepoint_table.name(code)}, {codepoint_table.name(non_bmp_upper_map[code])} |
| 1033 |
""" |
| 1034 |
) |
| 1035 |
|
| 1036 |
for code in sorted(non_bmp_lower_map.keys()): |
| 1037 |
test_non_bmp_mapping.write( |
| 1038 |
f"""\ |
| 1039 |
assertEq(String.fromCodePoint(0x{code:04X}).toLowerCase().codePointAt(0), 0x{non_bmp_lower_map[code]:04X}); // {codepoint_table.name(code)}, {codepoint_table.name(non_bmp_lower_map[code])} |
| 1040 |
""" |
| 1041 |
) |
| 1042 |
|
| 1043 |
test_non_bmp_mapping.write( |
| 1044 |
""" |
| 1045 |
if (typeof reportCompare === "function") |
| 1046 |
reportCompare(true, true); |
| 1047 |
""" |
| 1048 |
) |
| 1049 |
|
| 1050 |
|
| 1051 |
def make_space_test(version, test_space_table, codepoint_table): |
| 1052 |
def hex_and_name(c): |
| 1053 |
return f" 0x{c:04X} /* {codepoint_table.name(c)} */" |
| 1054 |
|
| 1055 |
file_name = "../tests/non262/String/string-space-trim.js" |
| 1056 |
with open(file_name, mode="w", encoding="utf-8") as test_space: |
| 1057 |
test_space.write(warning_message) |
| 1058 |
test_space.write(unicode_version_message.format(version)) |
| 1059 |
test_space.write(public_domain) |
| 1060 |
test_space.write("var onlySpace = String.fromCharCode(\n") |
| 1061 |
test_space.write(",\n".join(map(hex_and_name, test_space_table))) |
| 1062 |
test_space.write("\n);\n") |
| 1063 |
test_space.write( |
| 1064 |
""" |
| 1065 |
assertEq(onlySpace.trim(), ""); |
| 1066 |
assertEq((onlySpace + 'aaaa').trim(), 'aaaa'); |
| 1067 |
assertEq(('aaaa' + onlySpace).trim(), 'aaaa'); |
| 1068 |
assertEq((onlySpace + 'aaaa' + onlySpace).trim(), 'aaaa'); |
| 1069 |
|
| 1070 |
if (typeof reportCompare === "function") |
| 1071 |
reportCompare(true, true); |
| 1072 |
""" |
| 1073 |
) |
| 1074 |
|
| 1075 |
|
| 1076 |
def make_regexp_space_test(version, test_space_table, codepoint_table): |
| 1077 |
def hex_and_name(c): |
| 1078 |
return f" 0x{c:04X} /* {codepoint_table.name(c)} */" |
| 1079 |
|
| 1080 |
file_name = "../tests/non262/RegExp/character-class-escape-s.js" |
| 1081 |
with open(file_name, mode="w", encoding="utf-8") as test_space: |
| 1082 |
test_space.write(warning_message) |
| 1083 |
test_space.write(unicode_version_message.format(version)) |
| 1084 |
test_space.write(public_domain) |
| 1085 |
test_space.write("var onlySpace = String.fromCodePoint(\n") |
| 1086 |
test_space.write(",\n".join(map(hex_and_name, test_space_table))) |
| 1087 |
test_space.write("\n);\n") |
| 1088 |
test_space.write( |
| 1089 |
r""" |
| 1090 |
assertEq(/^\s+$/.exec(onlySpace) !== null, true); |
| 1091 |
assertEq(/^[\s]+$/.exec(onlySpace) !== null, true); |
| 1092 |
assertEq(/^[^\s]+$/.exec(onlySpace) === null, true); |
| 1093 |
|
| 1094 |
assertEq(/^\S+$/.exec(onlySpace) === null, true); |
| 1095 |
assertEq(/^[\S]+$/.exec(onlySpace) === null, true); |
| 1096 |
assertEq(/^[^\S]+$/.exec(onlySpace) !== null, true); |
| 1097 |
|
| 1098 |
// Also test with Unicode RegExps. |
| 1099 |
assertEq(/^\s+$/u.exec(onlySpace) !== null, true); |
| 1100 |
assertEq(/^[\s]+$/u.exec(onlySpace) !== null, true); |
| 1101 |
assertEq(/^[^\s]+$/u.exec(onlySpace) === null, true); |
| 1102 |
|
| 1103 |
assertEq(/^\S+$/u.exec(onlySpace) === null, true); |
| 1104 |
assertEq(/^[\S]+$/u.exec(onlySpace) === null, true); |
| 1105 |
assertEq(/^[^\S]+$/u.exec(onlySpace) !== null, true); |
| 1106 |
|
| 1107 |
if (typeof reportCompare === "function") |
| 1108 |
reportCompare(true, true); |
| 1109 |
""" |
| 1110 |
) |
| 1111 |
|
| 1112 |
|
| 1113 |
def make_icase_test(version, folding_tests, codepoint_table): |
| 1114 |
def char_hex(c): |
| 1115 |
return f"0x{c:04X}" |
| 1116 |
|
| 1117 |
file_name = "../tests/non262/RegExp/unicode-ignoreCase.js" |
| 1118 |
with open(file_name, mode="w", encoding="utf-8") as test_icase: |
| 1119 |
test_icase.write("// |reftest| skip-if(!this.hasOwnProperty('Intl'))\n\n") |
| 1120 |
test_icase.write(warning_message) |
| 1121 |
test_icase.write(unicode_version_message.format(version)) |
| 1122 |
test_icase.write(public_domain) |
| 1123 |
test_icase.write( |
| 1124 |
""" |
| 1125 |
var BUGNUMBER = 1135377; |
| 1126 |
var summary = "Implement RegExp unicode flag -- ignoreCase flag."; |
| 1127 |
|
| 1128 |
print(BUGNUMBER + ": " + summary); |
| 1129 |
|
| 1130 |
function test(code, ...equivs) { |
| 1131 |
var codeRe = new RegExp(String.fromCodePoint(code) + "+", "iu"); |
| 1132 |
var ans = String.fromCodePoint(code) + equivs.map(c => String.fromCodePoint(c)).join(""); |
| 1133 |
assertEqArray(codeRe.exec("<" + ans + ">"), [ans]); |
| 1134 |
codeRe = new RegExp("[" + String.fromCodePoint(code) + "]+", "iu"); |
| 1135 |
assertEqArray(codeRe.exec("<" + ans + ">"), [ans]); |
| 1136 |
} |
| 1137 |
""" |
| 1138 |
) |
| 1139 |
for args in folding_tests: |
| 1140 |
test_icase.write( |
| 1141 |
"test({}); // {}\n".format( |
| 1142 |
", ".join(map(char_hex, args)), |
| 1143 |
", ".join(map(codepoint_table.name, args)), |
| 1144 |
) |
| 1145 |
) |
| 1146 |
test_icase.write( |
| 1147 |
""" |
| 1148 |
if (typeof reportCompare === "function") |
| 1149 |
reportCompare(true, true); |
| 1150 |
""" |
| 1151 |
) |
| 1152 |
|
| 1153 |
|
| 1154 |
def make_unicode_file( |
| 1155 |
version, |
| 1156 |
table, |
| 1157 |
index, |
| 1158 |
folding_table, |
| 1159 |
folding_index, |
| 1160 |
non_bmp_space_set, |
| 1161 |
non_bmp_id_start_set, |
| 1162 |
non_bmp_id_cont_set, |
| 1163 |
unconditional_toupper, |
| 1164 |
codepoint_table, |
| 1165 |
): |
| 1166 |
index1, index2, shift = splitbins(index) |
| 1167 |
|
| 1168 |
# Don't forget to update CharInfo in Unicode.h if you need to change this |
| 1169 |
assert shift == 6 |
| 1170 |
|
| 1171 |
folding_index1, folding_index2, folding_shift = splitbins(folding_index) |
| 1172 |
|
| 1173 |
# Don't forget to update CaseFoldInfo in Unicode.h if you need to change this |
| 1174 |
assert folding_shift == 5 |
| 1175 |
|
| 1176 |
# verify correctness |
| 1177 |
for char in index: |
| 1178 |
test = table[index[char]] |
| 1179 |
|
| 1180 |
idx = index1[char >> shift] |
| 1181 |
idx = index2[(idx << shift) + (char & ((1 << shift) - 1))] |
| 1182 |
|
| 1183 |
assert test == table[idx] |
| 1184 |
|
| 1185 |
# verify correctness |
| 1186 |
for char in folding_index: |
| 1187 |
test = folding_table[folding_index[char]] |
| 1188 |
|
| 1189 |
idx = folding_index1[char >> folding_shift] |
| 1190 |
idx = folding_index2[ |
| 1191 |
(idx << folding_shift) + (char & ((1 << folding_shift) - 1)) |
| 1192 |
] |
| 1193 |
|
| 1194 |
assert test == folding_table[idx] |
| 1195 |
|
| 1196 |
comment = """ |
| 1197 |
/* |
| 1198 |
* So how does indexing work? |
| 1199 |
* First let's have a look at a char16_t, 16-bits: |
| 1200 |
* [................] |
| 1201 |
* Step 1: |
| 1202 |
* Extracting the upper 11 bits from the char16_t. |
| 1203 |
* upper = char >> 5 ([***********.....]) |
| 1204 |
* Step 2: |
| 1205 |
* Using these bits to get an reduced index from index1. |
| 1206 |
* index = index1[upper] |
| 1207 |
* Step 3: |
| 1208 |
* Combining the index and the bottom 5 bits of the original char16_t. |
| 1209 |
* real_index = index2[(index << 5) + (char & ((1 << 5) - 1))] ([...********+++++]) |
| 1210 |
* |
| 1211 |
* The advantage here is that the biggest number in index1 doesn't need 10 bits, |
| 1212 |
* but 7 and we save some memory. |
| 1213 |
* |
| 1214 |
* Step 4: |
| 1215 |
* Get the character informations by looking up real_index in js_charinfo. |
| 1216 |
* |
| 1217 |
* Pseudocode of generation: |
| 1218 |
* |
| 1219 |
* let table be the mapping of char16_t => js_charinfo_index |
| 1220 |
* let index1 be an empty array |
| 1221 |
* let index2 be an empty array |
| 1222 |
* let cache be a hash map |
| 1223 |
* |
| 1224 |
* while shift is less then maximal amount you can shift 0xffff before it's 0 |
| 1225 |
* let chunks be table split in chunks of size 2**shift |
| 1226 |
* |
| 1227 |
* for every chunk in chunks |
| 1228 |
* if chunk is in cache |
| 1229 |
* let index be cache[chunk] |
| 1230 |
* else |
| 1231 |
* let index be the max key of index2 + 1 |
| 1232 |
* for element in chunk |
| 1233 |
* push element to index2 |
| 1234 |
* put index as chunk in cache |
| 1235 |
* |
| 1236 |
* push index >> shift to index1 |
| 1237 |
* |
| 1238 |
* increase shift |
| 1239 |
* stop if you found the best shift |
| 1240 |
*/ |
| 1241 |
""" |
| 1242 |
|
| 1243 |
def dump(data, name, println): |
| 1244 |
println(f"const uint8_t unicode::{name}[] = {{") |
| 1245 |
|
| 1246 |
line = pad = " " * 4 |
| 1247 |
lines = [] |
| 1248 |
for entry in data: |
| 1249 |
assert entry < 256 |
| 1250 |
s = str(entry) |
| 1251 |
s = s.rjust(3) |
| 1252 |
|
| 1253 |
if len(line + s) + 5 > 99: |
| 1254 |
lines.append(line.rstrip()) |
| 1255 |
line = pad + s + ", " |
| 1256 |
else: |
| 1257 |
line = line + s + ", " |
| 1258 |
lines.append(line.rstrip()) |
| 1259 |
|
| 1260 |
println("\n".join(lines)) |
| 1261 |
println("};") |
| 1262 |
|
| 1263 |
def write_table(data_type, name, tbl, idx1_name, idx1, idx2_name, idx2, println): |
| 1264 |
println(f"const {data_type} unicode::{name}[] = {{") |
| 1265 |
for d in tbl: |
| 1266 |
println(" {{ {} }},".format(", ".join(str(e) for e in d))) |
| 1267 |
println("};") |
| 1268 |
println("") |
| 1269 |
|
| 1270 |
dump(idx1, idx1_name, println) |
| 1271 |
println("") |
| 1272 |
dump(idx2, idx2_name, println) |
| 1273 |
println("") |
| 1274 |
|
| 1275 |
def write_supplemental_identifier_method(name, group_set, println): |
| 1276 |
println("bool") |
| 1277 |
println(f"js::unicode::{name}(char32_t codePoint)") |
| 1278 |
println("{") |
| 1279 |
for from_code, to_code in int_ranges(group_set.keys()): |
| 1280 |
println( |
| 1281 |
f" if (codePoint >= 0x{from_code:X} && codePoint <= 0x{to_code:X}) {{ // {codepoint_table.name(from_code)} .. {codepoint_table.name(to_code)}" |
| 1282 |
) |
| 1283 |
println(" return true;") |
| 1284 |
println(" }") |
| 1285 |
println(" return false;") |
| 1286 |
println("}") |
| 1287 |
println("") |
| 1288 |
|
| 1289 |
file_name = "Unicode.cpp" |
| 1290 |
with open(file_name, "w", encoding="utf-8") as data_file: |
| 1291 |
write = partial(print, file=data_file, sep="", end="") |
| 1292 |
println = partial(print, file=data_file, sep="", end="\n") |
| 1293 |
|
| 1294 |
write(warning_message) |
| 1295 |
write(unicode_version_message.format(version)) |
| 1296 |
write(public_domain) |
| 1297 |
println('#include "util/Unicode.h"') |
| 1298 |
println("") |
| 1299 |
println("using namespace js;") |
| 1300 |
println("using namespace js::unicode;") |
| 1301 |
write(comment) |
| 1302 |
|
| 1303 |
write_table( |
| 1304 |
"CharacterInfo", |
| 1305 |
"js_charinfo", |
| 1306 |
table, |
| 1307 |
"index1", |
| 1308 |
index1, |
| 1309 |
"index2", |
| 1310 |
index2, |
| 1311 |
println, |
| 1312 |
) |
| 1313 |
|
| 1314 |
write_table( |
| 1315 |
"FoldingInfo", |
| 1316 |
"js_foldinfo", |
| 1317 |
folding_table, |
| 1318 |
"folding_index1", |
| 1319 |
folding_index1, |
| 1320 |
"folding_index2", |
| 1321 |
folding_index2, |
| 1322 |
println, |
| 1323 |
) |
| 1324 |
|
| 1325 |
# If the following assert fails, it means space character is added to |
| 1326 |
# non-BMP area. In that case the following code should be uncommented |
| 1327 |
# and the corresponding code should be added to frontend. (At least |
| 1328 |
# unicode::IsSpace will require updating to handle this.) |
| 1329 |
assert len(non_bmp_space_set.keys()) == 0 |
| 1330 |
|
| 1331 |
write_supplemental_identifier_method( |
| 1332 |
"IsIdentifierStartNonBMP", non_bmp_id_start_set, println |
| 1333 |
) |
| 1334 |
|
| 1335 |
write_supplemental_identifier_method( |
| 1336 |
"IsIdentifierPartNonBMP", non_bmp_id_cont_set, println |
| 1337 |
) |
| 1338 |
|
| 1339 |
write_special_casing_methods(unconditional_toupper, codepoint_table, println) |
| 1340 |
|
| 1341 |
write_ascii_lookup_tables(table, index, write, println) |
| 1342 |
|
| 1343 |
write_latin1_lookup_tables(table, index, write, println) |
| 1344 |
|
| 1345 |
|
| 1346 |
def getsize(data): |
| 1347 |
"""return smallest possible integer size for the given array""" |
| 1348 |
maxdata = max(data) |
| 1349 |
assert maxdata < 2**32 |
| 1350 |
|
| 1351 |
if maxdata < 256: |
| 1352 |
return 1 |
| 1353 |
elif maxdata < 65536: |
| 1354 |
return 2 |
| 1355 |
else: |
| 1356 |
return 4 |
| 1357 |
|
| 1358 |
|
| 1359 |
def splitbins(t): |
| 1360 |
"""t -> (t1, t2, shift). Split a table to save space. |
| 1361 |
|
| 1362 |
t is a sequence of ints. This function can be useful to save space if |
| 1363 |
many of the ints are the same. t1 and t2 are lists of ints, and shift |
| 1364 |
is an int, chosen to minimize the combined size of t1 and t2 (in C |
| 1365 |
code), and where for each i in range(len(t)), |
| 1366 |
t[i] == t2[(t1[i >> shift] << shift) + (i & mask)] |
| 1367 |
where mask is a bitmask isolating the last "shift" bits. |
| 1368 |
""" |
| 1369 |
|
| 1370 |
def dump(t1, t2, shift, bytes): |
| 1371 |
print( |
| 1372 |
"%d+%d bins at shift %d; %d bytes" % (len(t1), len(t2), shift, bytes), |
| 1373 |
file=sys.stderr, |
| 1374 |
) |
| 1375 |
print("Size of original table:", len(t) * getsize(t), "bytes", file=sys.stderr) |
| 1376 |
|
| 1377 |
n = len(t) - 1 # last valid index |
| 1378 |
maxshift = 0 # the most we can shift n and still have something left |
| 1379 |
if n > 0: |
| 1380 |
while n >> 1: |
| 1381 |
n >>= 1 |
| 1382 |
maxshift += 1 |
| 1383 |
del n |
| 1384 |
bytes = sys.maxsize # smallest total size so far |
| 1385 |
t = tuple(t) # so slices can be dict keys |
| 1386 |
for shift in range(maxshift + 1): |
| 1387 |
t1 = [] |
| 1388 |
t2 = [] |
| 1389 |
size = 2**shift |
| 1390 |
bincache = {} |
| 1391 |
|
| 1392 |
for i in range(0, len(t), size): |
| 1393 |
bin = t[i : i + size] |
| 1394 |
|
| 1395 |
index = bincache.get(bin) |
| 1396 |
if index is None: |
| 1397 |
index = len(t2) |
| 1398 |
bincache[bin] = index |
| 1399 |
t2.extend(bin) |
| 1400 |
t1.append(index >> shift) |
| 1401 |
|
| 1402 |
# determine memory size |
| 1403 |
b = len(t1) * getsize(t1) + len(t2) * getsize(t2) |
| 1404 |
if b < bytes: |
| 1405 |
best = t1, t2, shift |
| 1406 |
bytes = b |
| 1407 |
t1, t2, shift = best |
| 1408 |
|
| 1409 |
print("Best:", end=" ", file=sys.stderr) |
| 1410 |
dump(t1, t2, shift, bytes) |
| 1411 |
|
| 1412 |
# exhaustively verify that the decomposition is correct |
| 1413 |
mask = 2**shift - 1 |
| 1414 |
for i in range(len(t)): |
| 1415 |
assert t[i] == t2[(t1[i >> shift] << shift) + (i & mask)] |
| 1416 |
return best |
| 1417 |
|
| 1418 |
|
| 1419 |
def update_unicode(args): |
| 1420 |
base_path = os.getcwd() |
| 1421 |
|
| 1422 |
version = args.version |
| 1423 |
if version is not None: |
| 1424 |
baseurl = "https://unicode.org/Public" |
| 1425 |
if version == "UNIDATA": |
| 1426 |
url = "%s/%s" % (baseurl, version) |
| 1427 |
else: |
| 1428 |
url = "%s/%s/ucd" % (baseurl, version) |
| 1429 |
|
| 1430 |
print("Arguments:") |
| 1431 |
if version is not None: |
| 1432 |
print("\tVersion: %s" % version) |
| 1433 |
print("\tDownload url: %s" % url) |
| 1434 |
|
| 1435 |
request_url = f"{url}/UCD.zip" |
| 1436 |
with closing(urlopen(request_url)) as downloaded_file: |
| 1437 |
downloaded_data = io.BytesIO(downloaded_file.read()) |
| 1438 |
|
| 1439 |
with ZipFile(downloaded_data) as zip_file: |
| 1440 |
for fname in [ |
| 1441 |
"UnicodeData.txt", |
| 1442 |
"CaseFolding.txt", |
| 1443 |
"DerivedCoreProperties.txt", |
| 1444 |
"SpecialCasing.txt", |
| 1445 |
]: |
| 1446 |
zip_file.extract(fname, path=base_path) |
| 1447 |
else: |
| 1448 |
print("\tUsing local files.") |
| 1449 |
print("\tAlways make sure you have the newest Unicode files!") |
| 1450 |
print("") |
| 1451 |
|
| 1452 |
def version_from_file(f, fname): |
| 1453 |
pat_version = re.compile(r"# %s-(?P<version>\d+\.\d+\.\d+).txt" % fname) |
| 1454 |
return pat_version.match(f.readline()).group("version") |
| 1455 |
|
| 1456 |
with open( |
| 1457 |
os.path.join(base_path, "UnicodeData.txt"), encoding="utf-8" |
| 1458 |
) as unicode_data, open( |
| 1459 |
os.path.join(base_path, "CaseFolding.txt"), encoding="utf-8" |
| 1460 |
) as case_folding, open( |
| 1461 |
os.path.join(base_path, "DerivedCoreProperties.txt"), encoding="utf-8" |
| 1462 |
) as derived_core_properties, open( |
| 1463 |
os.path.join(base_path, "SpecialCasing.txt"), encoding="utf-8" |
| 1464 |
) as special_casing: |
| 1465 |
unicode_version = version_from_file( |
| 1466 |
derived_core_properties, "DerivedCoreProperties" |
| 1467 |
) |
| 1468 |
|
| 1469 |
print("Processing...") |
| 1470 |
( |
| 1471 |
table, |
| 1472 |
index, |
| 1473 |
non_bmp_lower_map, |
| 1474 |
non_bmp_upper_map, |
| 1475 |
non_bmp_space_set, |
| 1476 |
non_bmp_id_start_set, |
| 1477 |
non_bmp_id_cont_set, |
| 1478 |
codepoint_table, |
| 1479 |
test_space_table, |
| 1480 |
) = process_unicode_data(unicode_data, derived_core_properties) |
| 1481 |
(folding_table, folding_index, folding_tests) = process_case_folding( |
| 1482 |
case_folding |
| 1483 |
) |
| 1484 |
(unconditional_tolower, unconditional_toupper) = process_special_casing( |
| 1485 |
special_casing, table, index |
| 1486 |
) |
| 1487 |
|
| 1488 |
print("Generating...") |
| 1489 |
make_unicode_file( |
| 1490 |
unicode_version, |
| 1491 |
table, |
| 1492 |
index, |
| 1493 |
folding_table, |
| 1494 |
folding_index, |
| 1495 |
non_bmp_space_set, |
| 1496 |
non_bmp_id_start_set, |
| 1497 |
non_bmp_id_cont_set, |
| 1498 |
unconditional_toupper, |
| 1499 |
codepoint_table, |
| 1500 |
) |
| 1501 |
make_non_bmp_file( |
| 1502 |
unicode_version, non_bmp_lower_map, non_bmp_upper_map, codepoint_table |
| 1503 |
) |
| 1504 |
|
| 1505 |
make_bmp_mapping_test( |
| 1506 |
unicode_version, codepoint_table, unconditional_tolower, unconditional_toupper |
| 1507 |
) |
| 1508 |
make_non_bmp_mapping_test( |
| 1509 |
unicode_version, non_bmp_upper_map, non_bmp_lower_map, codepoint_table |
| 1510 |
) |
| 1511 |
make_space_test(unicode_version, test_space_table, codepoint_table) |
| 1512 |
make_regexp_space_test(unicode_version, test_space_table, codepoint_table) |
| 1513 |
make_icase_test(unicode_version, folding_tests, codepoint_table) |
| 1514 |
|
| 1515 |
|
| 1516 |
if __name__ == "__main__": |
| 1517 |
import argparse |
| 1518 |
|
| 1519 |
# This script must be run from js/src/util to work correctly. |
| 1520 |
if "/".join(os.path.normpath(os.getcwd()).split(os.sep)[-3:]) != "js/src/util": |
| 1521 |
raise RuntimeError("%s must be run from js/src/util" % sys.argv[0]) |
| 1522 |
|
| 1523 |
parser = argparse.ArgumentParser(description="Update Unicode data.") |
| 1524 |
|
| 1525 |
parser.add_argument( |
| 1526 |
"--version", |
| 1527 |
help='Optional Unicode version number. If specified, downloads the\ |
| 1528 |
selected version from <https://unicode.org/Public>. If not specified\ |
| 1529 |
uses the existing local files to generate the Unicode data. The\ |
| 1530 |
number must match a published Unicode version, e.g. use\ |
| 1531 |
"--version=8.0.0" to download Unicode 8 files. Alternatively use\ |
| 1532 |
"--version=UNIDATA" to download the latest published version.', |
| 1533 |
) |
| 1534 |
|
| 1535 |
parser.set_defaults(func=update_unicode) |
| 1536 |
|
| 1537 |
args = parser.parse_args() |
| 1538 |
args.func(args) |