react-nitro-hermes 0.0.1-alpha.8 → 0.0.1-alpha.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/hermes/CMakeLists.txt +874 -0
- package/hermes/android/HostObjectJniTest.cpp +178 -0
- package/hermes/android/build-logic/build.gradle.kts +31 -0
- package/hermes/android/build-logic/settings.gradle.kts +17 -0
- package/hermes/android/build-logic/src/main/kotlin/com/facebook/hermes/helpers/internal/SerializeHermesCompilerPackageJson.kt +33 -0
- package/hermes/android/build-logic/src/main/kotlin/com/facebook/hermes/plugins/internal/TestUtilsPlugin.kt +80 -0
- package/hermes/android/build-logic/src/main/kotlin/com/facebook/hermes/tasks/internal/CustomExecTask.kt +46 -0
- package/hermes/android/build-logic/src/main/kotlin/publish.gradle.kts +82 -0
- package/hermes/android/build.gradle.kts +332 -0
- package/hermes/android/cppruntime/build.gradle +72 -0
- package/hermes/android/cppruntime/src/main/AndroidManifest.xml +2 -0
- package/hermes/android/cppruntime/src/main/cpp/CMakeLists.txt +8 -0
- package/hermes/android/cppruntime/src/main/cpp/stub.cpp +12 -0
- package/hermes/android/cross-compile/swift-libicu.patch +13 -0
- package/hermes/android/cross-compile/toolchain-android-arm-api13-gnustl.cmake +13 -0
- package/hermes/android/cross-compile/toolchain-android-arm-api15-gnustl.cmake +14 -0
- package/hermes/android/gradle/libs.versions.toml +30 -0
- package/hermes/android/gradle/wrapper/gradle-wrapper.jar +0 -0
- package/hermes/android/gradle/wrapper/gradle-wrapper.properties +7 -0
- package/hermes/android/gradle.properties +3 -0
- package/hermes/android/gradlew +248 -0
- package/hermes/android/gradlew.bat +93 -0
- package/hermes/android/intltest/build.gradle +147 -0
- package/hermes/android/intltest/java/com/facebook/hermes/test/CMakeLists.txt +45 -0
- package/hermes/android/intltest/java/com/facebook/hermes/test/HermesEpilogue.cpp +68 -0
- package/hermes/android/intltest/java/com/facebook/hermes/test/HermesEpilogue.h +44 -0
- package/hermes/android/intltest/java/com/facebook/hermes/test/HermesEpilogue.java +45 -0
- package/hermes/android/intltest/java/com/facebook/hermes/test/HermesEpilogueTestData.java +32 -0
- package/hermes/android/intltest/java/com/facebook/hermes/test/HermesInstrumentationTest.java +150 -0
- package/hermes/android/intltest/java/com/facebook/hermes/test/HermesIntlAndroidTest.java +147 -0
- package/hermes/android/intltest/java/com/facebook/hermes/test/HermesIntlTest262.java +470 -0
- package/hermes/android/intltest/java/com/facebook/hermes/test/HermesRuntimeFactory.cpp +73 -0
- package/hermes/android/intltest/java/com/facebook/hermes/test/JSRuntime.cpp +90 -0
- package/hermes/android/intltest/java/com/facebook/hermes/test/JSRuntime.h +62 -0
- package/hermes/android/intltest/java/com/facebook/hermes/test/JSRuntime.java +155 -0
- package/hermes/android/intltest/java/com/facebook/hermes/test/MappedFileBuffer.cpp +48 -0
- package/hermes/android/intltest/java/com/facebook/hermes/test/MappedFileBuffer.h +36 -0
- package/hermes/android/intltest/java/com/facebook/hermes/test/OnLoad.cpp +13 -0
- package/hermes/android/intltest/java/com/facebook/hermes/test/OnLoadEpilogue.cpp +13 -0
- package/hermes/android/intltest/src/main/AndroidManifest.xml +2 -0
- package/hermes/android/ios-artifacts/build.gradle.kts +65 -0
- package/hermes/android/settings.gradle.kts +27 -0
- package/hermes/cmake/modules/Hermes.cmake +481 -0
- package/hermes/cmake/modules/Lit.cmake +96 -0
- package/hermes/doc/Branches.md +38 -0
- package/hermes/doc/BuildingAndRunning.md +121 -0
- package/hermes/doc/CodingStandards.md +112 -0
- package/hermes/doc/CrossCompilation.md +79 -0
- package/hermes/doc/Design.md +217 -0
- package/hermes/doc/Emscripten.md +156 -0
- package/hermes/doc/Features.md +143 -0
- package/hermes/doc/GCSafeCoding.md +563 -0
- package/hermes/doc/GenGC.md +300 -0
- package/hermes/doc/Hades.md +344 -0
- package/hermes/doc/HighLevelOptimizations.md +37 -0
- package/hermes/doc/IR.md +1306 -0
- package/hermes/doc/IntlAPIs.md +196 -0
- package/hermes/doc/JIT.md +999 -0
- package/hermes/doc/LazyEvalCompilation.md +84 -0
- package/hermes/doc/MemoryProfilers.md +316 -0
- package/hermes/doc/Modules.md +144 -0
- package/hermes/doc/Optimizer.md +83 -0
- package/hermes/doc/PerfProfiling.md +29 -0
- package/hermes/doc/ProhibitInvoke.md +329 -0
- package/hermes/doc/ReactNative.md +40 -0
- package/hermes/doc/ReactNativeIntegration.md +94 -0
- package/hermes/doc/RegExp.md +24 -0
- package/hermes/doc/SpecIncompat.md +85 -0
- package/hermes/doc/Strings.md +140 -0
- package/hermes/doc/TypedLanguage.md +432 -0
- package/hermes/doc/VM.md +174 -0
- package/hermes/doc/blog/2024-11-09-octane-benchmark-jit-progress.md +17 -0
- package/hermes/doc/blog/2024-12-19-static-hermes-update-dec-2024.md +47 -0
- package/hermes/doc/blog/2024-12-23-compiling-javascript-to-wasm.md +267 -0
- package/hermes/doc/blog/2025-06-09-jsi-runtime-data-apis.md +23 -0
- package/hermes/doc/blog/2025-07-15-static-h-performance-june-2025.md +18 -0
- package/hermes/doc/blog/2025-11-02-hermes-compilation-runtime-modes.md +23 -0
- package/hermes/doc/blog/2025-11-06-hermes-memory-modes.md +35 -0
- package/hermes/doc/blog/2025-11-24-json-parsing-performance.md +17 -0
- package/hermes/doc/blog/2025-12-02-iserialization.md +11 -0
- package/hermes/doc/blog/2025-12-12-new-way-to-contribute.md +68 -0
- package/hermes/doc/blog/2026-06-05-new-hermes-stable-release.md +51 -0
- package/hermes/doc/blog/README.md +25 -0
- package/hermes/doc/blog/images/2024-11-09-octane-pi3.jpeg +0 -0
- package/hermes/doc/blog/images/2024-11-09-octane-pi5.jpeg +0 -0
- package/hermes/doc/blog/images/2025-07-15-perf-hv32-interpreter.jpeg +0 -0
- package/hermes/doc/blog/images/2025-07-15-perf-hv32-jit.jpeg +0 -0
- package/hermes/doc/icu_license.txt +420 -0
- package/hermes/doc/img/heap_snapshot_retainers.png +0 -0
- package/hermes/doc/img/logo.svg +1 -0
- package/hermes/doc/img/object_captured_by_environment.png +0 -0
- package/hermes/doc/img/root_categories.png +0 -0
- package/hermes/doc/plans/ir-type/flow-type-system.md +324 -0
- package/hermes/doc/plans/ir-type/ir-type-system-v2-design.md +652 -0
- package/hermes/doc/plans/ir-type/ir-type-system.md +220 -0
- package/hermes/doc/plans/ir-type/ir-type-v2-implementation.md +1187 -0
- package/hermes/doc/plans/ir-type/memory.md +48 -0
- package/hermes/doc/plans/ir-type/phase1-steps.md +512 -0
- package/hermes/doc/plans/ir-type/progress.md +239 -0
- package/hermes/doc/plans/ir-type/typeinference-primitive-fastpath-design.md +203 -0
- package/hermes/doc/plans/ir-type/typeinference-primitive-fastpath-results.md +71 -0
- package/hermes/doc/superpowers/plans/2026-07-28-worker-arraybuffer-input.md +597 -0
- package/hermes/doc/superpowers/plans/2026-08-18-jitemitter-split.md +1149 -0
- package/hermes/doc/superpowers/plans/2026-08-20-jit-type-asserts.md +969 -0
- package/hermes/doc/superpowers/plans/2026-08-23-jit-shared-compiler-driver.md +478 -0
- package/hermes/doc/superpowers/plans/2026-08-23-x86-64-jit-skeleton.md +797 -0
- package/hermes/doc/superpowers/plans/2026-08-24-x86-64-jit-arith.md +444 -0
- package/hermes/doc/superpowers/plans/2026-08-24-x86-64-jit-calls.md +261 -0
- package/hermes/doc/superpowers/plans/2026-08-24-x86-64-jit-props.md +240 -0
- package/hermes/doc/superpowers/plans/2026-10-26-regexp-bytecode-sharing.md +2197 -0
- package/hermes/doc/superpowers/plans/2026-10-28-regexp-start-filter-and-exec-fast-paths.md +3981 -0
- package/hermes/doc/superpowers/specs/2026-07-28-worker-arraybuffer-input-design.md +206 -0
- package/hermes/doc/superpowers/specs/2026-08-18-jitemitter-split-design.md +530 -0
- package/hermes/doc/superpowers/specs/2026-08-20-jit-type-asserts-design.md +360 -0
- package/hermes/doc/superpowers/specs/2026-08-23-x86-64-jit-design.md +246 -0
- package/hermes/doc/superpowers/specs/2026-08-26-icu-free-normalize-design.md +355 -0
- package/hermes/doc/superpowers/specs/2026-08-27-icu-free-convert-to-case-design.md +305 -0
- package/hermes/doc/superpowers/specs/2026-08-27-icu-free-locale-compare-design.md +429 -0
- package/hermes/doc/superpowers/specs/2026-08-29-icu-free-date-format-design.md +297 -0
- package/hermes/doc/superpowers/specs/2026-10-26-regexp-bytecode-sharing-design.md +605 -0
- package/hermes/doc/superpowers/specs/2026-10-28-regexp-start-filter-and-exec-fast-paths-design.md +551 -0
- package/hermes/doc/typescript-stripping.md +90 -0
- package/hermes/external/CMakeLists.txt +20 -0
- package/hermes/utils/IntlGen/IntlGen.java +531 -0
- package/hermes/utils/bench_with_stats.py +827 -0
- package/hermes/utils/build-apple-framework.sh +323 -0
- package/hermes/utils/chrome_snapshot_parser.py +210 -0
- package/hermes/utils/cmake-dev-build.sh +18 -0
- package/hermes/utils/commons.sh +55 -0
- package/hermes/utils/dump-cpp-funcs.sh +3 -0
- package/hermes/utils/es5objects.js +198 -0
- package/hermes/utils/format.sh +145 -0
- package/hermes/utils/gen-promise-internal-bc.sh +66 -0
- package/hermes/utils/genUnicodeTable.py +2503 -0
- package/hermes/utils/hermes-lit/CMakeLists.txt +22 -0
- package/hermes/utils/hermes-lit/hermes-lit.in +15 -0
- package/hermes/utils/jit/README.md +134 -0
- package/hermes/utils/jit/jit-diff.sh +160 -0
- package/hermes/utils/jit/jit-dump.sh +193 -0
- package/hermes/utils/lit-expect-gen/generate.py +217 -0
- package/hermes/utils/promise/index.js +15 -0
- package/hermes/utils/promise/package.json +13 -0
- package/hermes/utils/promise/rollup.config.js +19 -0
- package/hermes/utils/promise/yarn.lock +247 -0
- package/hermes/utils/scripts/hermes/consts.js +26 -0
- package/hermes/utils/scripts/hermes/create-tarball.js +75 -0
- package/hermes/utils/scripts/hermes/get-hermes-version.js +57 -0
- package/hermes/utils/scripts/hermes/hermes-utils.js +122 -0
- package/hermes/utils/scripts/hermes/package.json +6 -0
- package/hermes/utils/scripts/hermes/prepare-artifacts.js +113 -0
- package/hermes/utils/scripts/hermes/publish-artifacts.js +109 -0
- package/hermes/utils/scripts/hermes/publish-npm.js +96 -0
- package/hermes/utils/scripts/hermes/scm-utils.js +41 -0
- package/hermes/utils/scripts/hermes/set-artifacts-version.js +64 -0
- package/hermes/utils/scripts/hermes/version-utils.js +98 -0
- package/hermes/utils/scripts/hermes/yarn.lock +240 -0
- package/hermes/utils/summarize_sizes.py +184 -0
- package/hermes/utils/symbolicate-nativecall-stats.py +112 -0
- package/hermes/utils/test_runner.py +13 -0
- package/hermes/utils/testsuite/README.facebook +3 -0
- package/hermes/utils/testsuite/README.md +69 -0
- package/hermes/utils/testsuite/cli.py +547 -0
- package/hermes/utils/testsuite/es_ast.py +337 -0
- package/hermes/utils/testsuite/external/LICENSE +28 -0
- package/hermes/utils/testsuite/external/README.facebook +8 -0
- package/hermes/utils/testsuite/external/__init__.py +0 -0
- package/hermes/utils/testsuite/external/_monkeyYaml.py +164 -0
- package/hermes/utils/testsuite/external/parse_test262.py +141 -0
- package/hermes/utils/testsuite/hermes.py +522 -0
- package/hermes/utils/testsuite/preprocess.py +365 -0
- package/hermes/utils/testsuite/progress.py +377 -0
- package/hermes/utils/testsuite/skiplist.json +4356 -0
- package/hermes/utils/testsuite/skiplist.py +270 -0
- package/hermes/utils/testsuite/test_run_defs.py +435 -0
- package/hermes/utils/testsuite/typing_defs.py +52 -0
- package/hermes/utils/testsuite/utils.py +214 -0
- package/hermes/utils/tidy.sh +22 -0
- package/hermes/utils/update-fbcode-hermes.sh +53 -0
- package/hermes/utils/updateErrorTest.py +193 -0
- package/hermes/utils/wasm-compile.sh +65 -0
- package/package.json +1 -1
|
@@ -0,0 +1,2503 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
|
3
|
+
#
|
|
4
|
+
# This source code is licensed under the MIT license found in the
|
|
5
|
+
# LICENSE file in the root directory of this source tree.
|
|
6
|
+
|
|
7
|
+
# -*- coding: utf-8 -*-
|
|
8
|
+
|
|
9
|
+
# Generates list of unicode ranges belonging to a set of categories, downloading
|
|
10
|
+
# Unicode data files as needed.
|
|
11
|
+
#
|
|
12
|
+
# Usage: genUnicodeTable.py
|
|
13
|
+
#
|
|
14
|
+
# To generate a new UnicodeData.inc file, the output of this script should be
|
|
15
|
+
# passed through clang-format, and then redirected:
|
|
16
|
+
#
|
|
17
|
+
# hermes/utils/genUnicodeTable.py | clang-format > hermes/lib/Platform/Unicode/UnicodeData.inc
|
|
18
|
+
|
|
19
|
+
import argparse
|
|
20
|
+
import datetime
|
|
21
|
+
import hashlib
|
|
22
|
+
import re
|
|
23
|
+
import sys
|
|
24
|
+
import urllib.request
|
|
25
|
+
from collections import defaultdict, OrderedDict
|
|
26
|
+
from functools import reduce
|
|
27
|
+
from itertools import islice
|
|
28
|
+
from string import Template
|
|
29
|
+
from textwrap import indent
|
|
30
|
+
from typing import Iterable, Optional, Tuple
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class UnicodeDataFiles:
|
|
34
|
+
# VERSION = "UCD/latest" # The bleeding edge version of Unicode.
|
|
35
|
+
VERSION = "17.0.0"
|
|
36
|
+
URLS = {
|
|
37
|
+
"UnicodeData.txt": f"http://unicode.org/Public/{VERSION}/ucd/UnicodeData.txt",
|
|
38
|
+
"SpecialCasing.txt": f"http://unicode.org/Public/{VERSION}/ucd/SpecialCasing.txt",
|
|
39
|
+
"CaseFolding.txt": f"http://unicode.org/Public/{VERSION}/ucd/CaseFolding.txt",
|
|
40
|
+
"DerivedGeneralCategory.txt": f"http://unicode.org/Public/{VERSION}/ucd/extracted/DerivedGeneralCategory.txt",
|
|
41
|
+
"Scripts.txt": f"http://unicode.org/Public/{VERSION}/ucd/Scripts.txt",
|
|
42
|
+
"ScriptExtensions.txt": f"http://unicode.org/Public/{VERSION}/ucd/ScriptExtensions.txt",
|
|
43
|
+
"DerivedCoreProperties.txt": f"http://unicode.org/Public/{VERSION}/ucd/DerivedCoreProperties.txt",
|
|
44
|
+
"DerivedNormalizationProps.txt": f"http://unicode.org/Public/{VERSION}/ucd/DerivedNormalizationProps.txt",
|
|
45
|
+
"DerivedBinaryProperties.txt": f"http://unicode.org/Public/{VERSION}/ucd/extracted/DerivedBinaryProperties.txt",
|
|
46
|
+
"PropertyValueAliases.txt": f"http://unicode.org/Public/{VERSION}/ucd/PropertyValueAliases.txt",
|
|
47
|
+
"PropertyAliases.txt": f"http://unicode.org/Public/{VERSION}/ucd/PropertyAliases.txt",
|
|
48
|
+
"PropList.txt": f"http://unicode.org/Public/{VERSION}/ucd/PropList.txt",
|
|
49
|
+
"emoji-data.txt": f"http://unicode.org/Public/{VERSION}/ucd/emoji/emoji-data.txt",
|
|
50
|
+
"NormalizationTest.txt": f"http://unicode.org/Public/{VERSION}/ucd/NormalizationTest.txt",
|
|
51
|
+
"allkeys.txt": f"http://unicode.org/Public/UCA/{VERSION}/allkeys.txt",
|
|
52
|
+
"CollationTest_NON_IGNORABLE_SHORT.txt": f"http://unicode.org/Public/UCA/{VERSION}/CollationTest/CollationTest_NON_IGNORABLE_SHORT.txt",
|
|
53
|
+
}
|
|
54
|
+
# Set to True to keep the downloaded files in the local directory.
|
|
55
|
+
KEEP_LOCAL_CACHE = False
|
|
56
|
+
|
|
57
|
+
__cache = {}
|
|
58
|
+
|
|
59
|
+
@classmethod
|
|
60
|
+
def get(cls, filename):
|
|
61
|
+
"""Retrieve a Unicode data file, fetching it if necessary."""
|
|
62
|
+
if filename not in cls.__cache:
|
|
63
|
+
data = cls.__local_or_fetch(cls.URLS[filename], filename)
|
|
64
|
+
cls.__cache[filename] = {
|
|
65
|
+
"sha1": hashlib.sha1(data).hexdigest(),
|
|
66
|
+
"lines": cls.__data_to_lines(data),
|
|
67
|
+
}
|
|
68
|
+
return cls.__cache[filename]
|
|
69
|
+
|
|
70
|
+
@classmethod
|
|
71
|
+
def __local_or_fetch(cls, url, filename) -> bytes:
|
|
72
|
+
"""Read a local file's contents or fetch them from a URL."""
|
|
73
|
+
try:
|
|
74
|
+
with open(filename, "rb") as f:
|
|
75
|
+
print(f"Found {filename} locally!", file=sys.stderr)
|
|
76
|
+
return f.read()
|
|
77
|
+
except IOError:
|
|
78
|
+
print(f"Fetching {url}...", file=sys.stderr)
|
|
79
|
+
with urllib.request.urlopen(url) as f:
|
|
80
|
+
data = f.read()
|
|
81
|
+
if cls.KEEP_LOCAL_CACHE:
|
|
82
|
+
print(f"Caching {filename} locally...", file=sys.stderr)
|
|
83
|
+
with open(filename, "wb") as f:
|
|
84
|
+
f.write(data)
|
|
85
|
+
return data
|
|
86
|
+
|
|
87
|
+
@classmethod
|
|
88
|
+
def __data_to_lines(cls, data) -> Iterable[str]:
|
|
89
|
+
return [
|
|
90
|
+
line
|
|
91
|
+
for line in data.decode("utf-8").splitlines()
|
|
92
|
+
if line and not line.startswith("#")
|
|
93
|
+
]
|
|
94
|
+
|
|
95
|
+
@classmethod
|
|
96
|
+
def get_lines(cls, filename) -> Iterable[str]:
|
|
97
|
+
return cls.get(filename)["lines"]
|
|
98
|
+
|
|
99
|
+
@classmethod
|
|
100
|
+
def get_sha1(cls, filename) -> str:
|
|
101
|
+
return cls.get(filename)["sha1"]
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
# Which UCD files each generated table derives from. Only these are hashed
|
|
105
|
+
# into a file's provenance header, and only these are downloaded, so adding a
|
|
106
|
+
# data file for one table cannot perturb another table's output.
|
|
107
|
+
PROPERTIES_FILES = [
|
|
108
|
+
f
|
|
109
|
+
for f in UnicodeDataFiles.URLS
|
|
110
|
+
if f
|
|
111
|
+
not in (
|
|
112
|
+
"NormalizationTest.txt",
|
|
113
|
+
"allkeys.txt",
|
|
114
|
+
"CollationTest_NON_IGNORABLE_SHORT.txt",
|
|
115
|
+
)
|
|
116
|
+
]
|
|
117
|
+
NORMALIZATION_FILES = ["UnicodeData.txt", "DerivedNormalizationProps.txt"]
|
|
118
|
+
NORMTEST_FILES = ["NormalizationTest.txt"]
|
|
119
|
+
CASING_FILES = [
|
|
120
|
+
"UnicodeData.txt",
|
|
121
|
+
"SpecialCasing.txt",
|
|
122
|
+
"DerivedCoreProperties.txt",
|
|
123
|
+
"PropList.txt",
|
|
124
|
+
]
|
|
125
|
+
CASETEST_FILES = ["UnicodeData.txt", "SpecialCasing.txt"]
|
|
126
|
+
COLLATION_FILES = ["allkeys.txt", "UnicodeData.txt", "PropList.txt"]
|
|
127
|
+
COLLATIONTEST_FILES = [
|
|
128
|
+
"CollationTest_NON_IGNORABLE_SHORT.txt",
|
|
129
|
+
"allkeys.txt",
|
|
130
|
+
"UnicodeData.txt",
|
|
131
|
+
]
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
# Unicode data field indexes. See UnicodeData.txt.
|
|
135
|
+
CODEPOINT_FIELD = 0
|
|
136
|
+
GENERAL_CATEGORY_FIELD = 2
|
|
137
|
+
DECOMPOSITION_FIELD = 5
|
|
138
|
+
UPPERCASE_FIELD = 12
|
|
139
|
+
LOWERCASE_FIELD = 13
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def print_template(s, **kwargs):
|
|
143
|
+
"""Substitute in the keyword arguments to the template string
|
|
144
|
+
(or direct template) s, and print the result, followed by a
|
|
145
|
+
newline.
|
|
146
|
+
"""
|
|
147
|
+
text = Template(s).substitute(**kwargs)
|
|
148
|
+
print(text.strip())
|
|
149
|
+
print("")
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
# A filename long enough to push its SHA1 line past the 80 column limit
|
|
153
|
+
# would otherwise be reflowed by clang-format, which wraps the hash onto the
|
|
154
|
+
# next line and leaves every hash attached to the wrong filename.
|
|
155
|
+
PROVENANCE_TEMPLATE = """
|
|
156
|
+
//
|
|
157
|
+
// File generated by genUnicodeTable.py
|
|
158
|
+
// using Unicode data files downloaded on ${today}
|
|
159
|
+
// for Unicode version ${version}
|
|
160
|
+
// clang-format off
|
|
161
|
+
${sha1s}
|
|
162
|
+
// clang-format on
|
|
163
|
+
// *** DO NOT EDIT BY HAND ***
|
|
164
|
+
"""
|
|
165
|
+
|
|
166
|
+
SHARED_STRUCTS = """
|
|
167
|
+
/// An inclusive range of Unicode characters.
|
|
168
|
+
struct UnicodeRange { uint32_t first; uint32_t second; };
|
|
169
|
+
|
|
170
|
+
/// A UnicodeTransformRange expresses a mapping such as case folding.
|
|
171
|
+
/// A character cp is mapped to cp + delta if cp is 0 for the given modulus.
|
|
172
|
+
struct UnicodeTransformRange {
|
|
173
|
+
/// The first codepoint of the range.
|
|
174
|
+
unsigned start:24;
|
|
175
|
+
|
|
176
|
+
/// The number of characters in the range.
|
|
177
|
+
unsigned count:8;
|
|
178
|
+
|
|
179
|
+
/// The signed delta amount.
|
|
180
|
+
int delta:24;
|
|
181
|
+
|
|
182
|
+
/// The modulo amount.
|
|
183
|
+
unsigned modulo:8;
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
/// A reference to a string pool entry.
|
|
187
|
+
struct StringPoolRef {
|
|
188
|
+
uint16_t offset;
|
|
189
|
+
uint16_t size;
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
/// A reference to a UnicodeRange pool entry.
|
|
193
|
+
struct UnicodeRangePoolRef {
|
|
194
|
+
uint16_t offset;
|
|
195
|
+
uint16_t size;
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
/// A reference to a string pool name that maps to a string pool canonical name.
|
|
199
|
+
struct NameMapEntry {
|
|
200
|
+
StringPoolRef name;
|
|
201
|
+
StringPoolRef canonical;
|
|
202
|
+
};
|
|
203
|
+
|
|
204
|
+
/// A reference to a string pool name that maps to a range array pool offset
|
|
205
|
+
/// and size.
|
|
206
|
+
struct RangeMapEntry {
|
|
207
|
+
StringPoolRef name;
|
|
208
|
+
uint16_t rangeArrayPoolOffset;
|
|
209
|
+
uint16_t rangeArraySize;
|
|
210
|
+
};
|
|
211
|
+
"""
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def print_header(files, structs=True):
|
|
215
|
+
"""Emit the provenance comment for a generated file, hashing only the UCD
|
|
216
|
+
files it derives from. Emit the shared struct definitions only for the
|
|
217
|
+
property tables, which are the ones that use them."""
|
|
218
|
+
print_template(
|
|
219
|
+
PROVENANCE_TEMPLATE,
|
|
220
|
+
today=str(datetime.date.today()),
|
|
221
|
+
sha1s="\n".join(
|
|
222
|
+
f"// {filename:<30} SHA1: {UnicodeDataFiles.get_sha1(filename)}"
|
|
223
|
+
for filename in files
|
|
224
|
+
),
|
|
225
|
+
version=UnicodeDataFiles.VERSION,
|
|
226
|
+
)
|
|
227
|
+
if structs:
|
|
228
|
+
print_template(SHARED_STRUCTS)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def run_interval(unicode_data_lines, args):
|
|
232
|
+
name = args[0]
|
|
233
|
+
categories = set(args[1:])
|
|
234
|
+
begin = 0
|
|
235
|
+
intervals = []
|
|
236
|
+
last_cp = 0
|
|
237
|
+
openi = False
|
|
238
|
+
for line in unicode_data_lines:
|
|
239
|
+
fields = line.split(";")
|
|
240
|
+
cp_str, category = fields[CODEPOINT_FIELD], fields[GENERAL_CATEGORY_FIELD]
|
|
241
|
+
cp = int(cp_str, 16)
|
|
242
|
+
if category in categories:
|
|
243
|
+
if not openi:
|
|
244
|
+
begin = cp
|
|
245
|
+
openi = True
|
|
246
|
+
else:
|
|
247
|
+
pass # do nothing we are still in interval
|
|
248
|
+
else:
|
|
249
|
+
if openi:
|
|
250
|
+
intervals.append((begin, last_cp))
|
|
251
|
+
openi = False
|
|
252
|
+
else:
|
|
253
|
+
pass # keep looking
|
|
254
|
+
last_cp = cp
|
|
255
|
+
|
|
256
|
+
if openi:
|
|
257
|
+
intervals.append((begin, last_cp))
|
|
258
|
+
|
|
259
|
+
print_template(
|
|
260
|
+
"""
|
|
261
|
+
// ${args}
|
|
262
|
+
// static constexpr uint32_t ${name}_SIZE = $interval_count;
|
|
263
|
+
static constexpr UnicodeRange ${name}[] = {
|
|
264
|
+
${intervals}
|
|
265
|
+
};
|
|
266
|
+
""",
|
|
267
|
+
args=" ".join(args),
|
|
268
|
+
name=name,
|
|
269
|
+
interval_count=len(intervals),
|
|
270
|
+
intervals="\n".join(
|
|
271
|
+
"{" + hex(i[0]) + ", " + hex(i[1]) + "}," for i in intervals
|
|
272
|
+
),
|
|
273
|
+
)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def print_categories(unicode_data_lines):
|
|
277
|
+
"""Output UnicodeRanges for Unicode General Categories."""
|
|
278
|
+
categories = [
|
|
279
|
+
"UNICODE_LETTERS Lu Ll Lt Lm Lo Nl",
|
|
280
|
+
"UNICODE_COMBINING_MARK Mn Mc",
|
|
281
|
+
"UNICODE_DIGIT Nd",
|
|
282
|
+
"UNICODE_CONNECTOR_PUNCTUATION Pc",
|
|
283
|
+
]
|
|
284
|
+
for cat in categories:
|
|
285
|
+
run_interval(unicode_data_lines, cat.split())
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def run_property_select(unicode_data_lines, args):
|
|
289
|
+
"""
|
|
290
|
+
Output UnicodeRanges for PropList.txt.
|
|
291
|
+
args[0] is the name of the variable.
|
|
292
|
+
|
|
293
|
+
Includes all codepoints that match any property name given,
|
|
294
|
+
and if any 2-character arg is given, it must match one of the specified
|
|
295
|
+
category.
|
|
296
|
+
"""
|
|
297
|
+
name = args[0]
|
|
298
|
+
include_prop = set()
|
|
299
|
+
include_cat = set()
|
|
300
|
+
for arg in args[1:]:
|
|
301
|
+
if len(arg) == 2:
|
|
302
|
+
include_cat.add(arg)
|
|
303
|
+
else:
|
|
304
|
+
include_prop.add(arg)
|
|
305
|
+
# Lines in the DerivedCoreProperties file look like:
|
|
306
|
+
# 0041..005A ; Alphabetic # L& [26]
|
|
307
|
+
# We want to extract the range, provided the property matches.
|
|
308
|
+
intervals = []
|
|
309
|
+
for line in unicode_data_lines:
|
|
310
|
+
fields = line.split()
|
|
311
|
+
# Skip lines that don't have the property.
|
|
312
|
+
prop = fields[2] if len(fields) > 2 else None
|
|
313
|
+
cat = fields[4] if len(fields) > 4 else None
|
|
314
|
+
if len(include_prop) > 0 and prop not in include_prop:
|
|
315
|
+
continue
|
|
316
|
+
if len(include_cat) > 0 and cat not in include_cat:
|
|
317
|
+
continue
|
|
318
|
+
# Parse the range, which comes before the ';'
|
|
319
|
+
range = parse_range(fields[0].strip())
|
|
320
|
+
intervals.append(range)
|
|
321
|
+
|
|
322
|
+
print_template(
|
|
323
|
+
"""
|
|
324
|
+
// static constexpr uint32_t ${name}_SIZE = $interval_count;
|
|
325
|
+
static constexpr std::array<UnicodeRange, ${interval_count}> ${name} = {
|
|
326
|
+
${intervals}
|
|
327
|
+
};
|
|
328
|
+
""",
|
|
329
|
+
name=name,
|
|
330
|
+
interval_count=len(intervals),
|
|
331
|
+
intervals="\n".join(
|
|
332
|
+
"{" + hex(i[0]) + ", " + hex(i[1]) + "}," for i in intervals
|
|
333
|
+
),
|
|
334
|
+
)
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def print_properties(unicode_data_lines):
|
|
338
|
+
"""Output UnicodeRanges for PropLists."""
|
|
339
|
+
categories = [
|
|
340
|
+
"UNICODE_OTHER_ID_START Other_ID_Start",
|
|
341
|
+
"UNICODE_OTHER_ID_CONTINUE Other_ID_Continue",
|
|
342
|
+
"UNICODE_PATTERN_LETTER Pattern_Syntax Pattern_White_Space L& Ll Lt Lu Lm Lo",
|
|
343
|
+
"UNICODE_PATTERN_CONTINUE Pattern_Syntax Pattern_White_Space Mn Mc Nd Pc",
|
|
344
|
+
]
|
|
345
|
+
for cat in categories:
|
|
346
|
+
run_property_select(unicode_data_lines, cat.split(" "))
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def get_assigned_codepoints(unicode_data_lines):
|
|
350
|
+
"""Gather intervals for all assigned Unicode codepoints."""
|
|
351
|
+
cp_begin = None
|
|
352
|
+
cp_end = None
|
|
353
|
+
|
|
354
|
+
def empty_buf():
|
|
355
|
+
if cp_begin is not None:
|
|
356
|
+
intervals.append((cp_begin, cp_begin if cp_end is None else cp_end))
|
|
357
|
+
|
|
358
|
+
intervals = []
|
|
359
|
+
lines = iter(unicode_data_lines)
|
|
360
|
+
last_cp = 0
|
|
361
|
+
|
|
362
|
+
while lines:
|
|
363
|
+
line = next(lines, None)
|
|
364
|
+
if line is None:
|
|
365
|
+
break
|
|
366
|
+
|
|
367
|
+
fields = split_fields(line)
|
|
368
|
+
cp = int(fields[0], 16)
|
|
369
|
+
# Handle UnicodeData.txt legacy codepoint ranges.
|
|
370
|
+
# <https://www.unicode.org/reports/tr44/#Code_Point_Ranges>
|
|
371
|
+
if fields[1].startswith("<") and fields[1].endswith("First>"):
|
|
372
|
+
empty_buf()
|
|
373
|
+
rng_begin = cp
|
|
374
|
+
rng_end = int(split_fields(next(lines))[0], 16)
|
|
375
|
+
intervals.append((rng_begin, rng_end))
|
|
376
|
+
cp_begin = cp_end = None
|
|
377
|
+
else:
|
|
378
|
+
if cp - last_cp == 1:
|
|
379
|
+
cp_end = cp
|
|
380
|
+
else:
|
|
381
|
+
if cp_begin is not None:
|
|
382
|
+
empty_buf()
|
|
383
|
+
cp_end = None
|
|
384
|
+
cp_begin = cp
|
|
385
|
+
|
|
386
|
+
last_cp = cp
|
|
387
|
+
|
|
388
|
+
return intervals
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def split_fields(line) -> list[str]:
|
|
392
|
+
"""
|
|
393
|
+
Split a semicolon-separated line into fields, ignoring comments.
|
|
394
|
+
"""
|
|
395
|
+
return [f.strip() for f in line.split("#")[0].split(";")]
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
# A Unicode codepoint range, represented as a tuple of (start, end).
|
|
399
|
+
range_tuple = tuple[int, int]
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def merge_adjacent_ranges(ranges: list[range_tuple]) -> list[range_tuple]:
|
|
403
|
+
"""Merge adjacent or overlapping ranges in a sorted list."""
|
|
404
|
+
if not ranges:
|
|
405
|
+
return ranges
|
|
406
|
+
merged = [ranges[0]]
|
|
407
|
+
for start, end in ranges[1:]:
|
|
408
|
+
prev_start, prev_end = merged[-1]
|
|
409
|
+
if start <= prev_end + 1:
|
|
410
|
+
merged[-1] = (prev_start, max(prev_end, end))
|
|
411
|
+
else:
|
|
412
|
+
merged.append((start, end))
|
|
413
|
+
return merged
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def parse_range(range_str) -> range_tuple:
|
|
417
|
+
"""
|
|
418
|
+
Parse the alternative codepoint range format, e.g. "1..10", or "1" into a
|
|
419
|
+
tuple of `(range_start, range_end)`.
|
|
420
|
+
"""
|
|
421
|
+
start, end = range_str.split("..") if ".." in range_str else (range_str, range_str)
|
|
422
|
+
return (int(start, 16), int(end, 16))
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def parse_codepoint_ranges(lines: Iterable[str], pred) -> dict[str, list[range_tuple]]:
|
|
426
|
+
"""
|
|
427
|
+
Create a mapping of canonical property names to lists of Unicode codepoint
|
|
428
|
+
ranges (start, end) for those properties, from the lines of a Unicode
|
|
429
|
+
Database data file.
|
|
430
|
+
|
|
431
|
+
Codepoint ranges will be merged if they are adjacent.
|
|
432
|
+
|
|
433
|
+
Example input:
|
|
434
|
+
|
|
435
|
+
0000..001F ; Cc # Cc [32] <control-0000>-<control-001F>
|
|
436
|
+
0020 ; Zs # Zs [1] SPACE
|
|
437
|
+
"""
|
|
438
|
+
ranges = defaultdict(list)
|
|
439
|
+
last_name = None
|
|
440
|
+
begin = 0
|
|
441
|
+
last_cp = 0
|
|
442
|
+
openi = False
|
|
443
|
+
for line in lines:
|
|
444
|
+
# Ignore empty lines and comment lines.
|
|
445
|
+
if not line or line.startswith("#"):
|
|
446
|
+
continue
|
|
447
|
+
|
|
448
|
+
fields = split_fields(line)
|
|
449
|
+
codepoint_range = fields[0]
|
|
450
|
+
canonical_name = fields[1]
|
|
451
|
+
if not pred(canonical_name):
|
|
452
|
+
continue
|
|
453
|
+
|
|
454
|
+
if last_name is None:
|
|
455
|
+
last_name = canonical_name
|
|
456
|
+
|
|
457
|
+
cp_start, cp_end = parse_range(codepoint_range)
|
|
458
|
+
if last_name != canonical_name:
|
|
459
|
+
# We have crossed over a property name boundary.
|
|
460
|
+
if openi:
|
|
461
|
+
ranges[last_name].append((begin, last_cp))
|
|
462
|
+
openi = True
|
|
463
|
+
last_name = canonical_name
|
|
464
|
+
begin = cp_start
|
|
465
|
+
else:
|
|
466
|
+
if openi:
|
|
467
|
+
if cp_start != last_cp + 1:
|
|
468
|
+
# We have crossed over an interval boundary.
|
|
469
|
+
ranges[last_name].append((begin, last_cp))
|
|
470
|
+
begin = cp_start
|
|
471
|
+
else:
|
|
472
|
+
begin = cp_start
|
|
473
|
+
openi = True
|
|
474
|
+
|
|
475
|
+
last_cp = cp_end
|
|
476
|
+
|
|
477
|
+
if openi:
|
|
478
|
+
ranges[last_name].append((begin, last_cp))
|
|
479
|
+
|
|
480
|
+
return ranges
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def binary_property_ranges(lines, prop):
|
|
484
|
+
"""Merged inclusive ranges of code points having binary property \\p prop."""
|
|
485
|
+
out = []
|
|
486
|
+
for line in lines:
|
|
487
|
+
f = split_fields(line)
|
|
488
|
+
if len(f) < 2 or f[1] != prop:
|
|
489
|
+
continue
|
|
490
|
+
out.append(parse_range(f[0]))
|
|
491
|
+
out.sort()
|
|
492
|
+
return merge_adjacent_ranges(out)
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
# One collation element: (variable, primary, secondary, tertiary).
|
|
496
|
+
CollationElement = Tuple[bool, int, int, int]
|
|
497
|
+
|
|
498
|
+
ALLKEYS_CE_RE = re.compile(
|
|
499
|
+
r"\[([.*])([0-9A-Fa-f]{4,6})\.([0-9A-Fa-f]{4,6})\.([0-9A-Fa-f]{4,6})\]"
|
|
500
|
+
)
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
def parse_allkeys(lines):
|
|
504
|
+
"""Parse allkeys.txt into (single, multi, contractions, implicit).
|
|
505
|
+
|
|
506
|
+
single: cp -> one collation element
|
|
507
|
+
multi: cp -> list of collation elements (an expansion)
|
|
508
|
+
contractions: tuple of cps -> list of collation elements
|
|
509
|
+
implicit: list of (first, last, base) from @implicitweights
|
|
510
|
+
|
|
511
|
+
Entries unreachable after NFD are dropped by the caller, not here, so
|
|
512
|
+
this function stays a faithful reading of the file."""
|
|
513
|
+
single, multi, contractions, implicit = {}, {}, {}, []
|
|
514
|
+
for line in lines:
|
|
515
|
+
text = line.split("#")[0].strip()
|
|
516
|
+
if not text:
|
|
517
|
+
continue
|
|
518
|
+
if text.startswith("@implicitweights"):
|
|
519
|
+
body = text.split(None, 1)[1]
|
|
520
|
+
rng, base = body.split(";")
|
|
521
|
+
first, last = rng.strip().split("..")
|
|
522
|
+
implicit.append((int(first, 16), int(last, 16), int(base, 16)))
|
|
523
|
+
continue
|
|
524
|
+
if text.startswith("@") or ";" not in text:
|
|
525
|
+
continue
|
|
526
|
+
lhs, rhs = text.split(";", 1)
|
|
527
|
+
cps = tuple(int(x, 16) for x in lhs.split())
|
|
528
|
+
ces = [
|
|
529
|
+
(
|
|
530
|
+
m.group(1) == "*",
|
|
531
|
+
int(m.group(2), 16),
|
|
532
|
+
int(m.group(3), 16),
|
|
533
|
+
int(m.group(4), 16),
|
|
534
|
+
)
|
|
535
|
+
for m in ALLKEYS_CE_RE.finditer(rhs)
|
|
536
|
+
]
|
|
537
|
+
assert ces, f"no collation elements parsed from: {text}"
|
|
538
|
+
if len(cps) > 1:
|
|
539
|
+
contractions[cps] = ces
|
|
540
|
+
elif len(ces) == 1:
|
|
541
|
+
single[cps[0]] = ces[0]
|
|
542
|
+
else:
|
|
543
|
+
multi[cps[0]] = ces
|
|
544
|
+
assert implicit, "no @implicitweights ranges found"
|
|
545
|
+
return single, multi, contractions, implicit
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def canonically_decomposable(unicode_data_lines):
|
|
549
|
+
"""\\return the set of code points that cannot survive NFD, so their
|
|
550
|
+
collation entries need never be generated.
|
|
551
|
+
|
|
552
|
+
Only *canonical* decompositions count: compatibility decompositions
|
|
553
|
+
survive NFD, so ligatures and compatibility forms stay in the table.
|
|
554
|
+
Hangul syllables decompose arithmetically and are not listed in
|
|
555
|
+
UnicodeData.txt, so they are added explicitly."""
|
|
556
|
+
result = set()
|
|
557
|
+
for line in unicode_data_lines:
|
|
558
|
+
fields = line.split(";")
|
|
559
|
+
decomp = fields[DECOMPOSITION_FIELD]
|
|
560
|
+
if decomp and not decomp.startswith("<"):
|
|
561
|
+
result.add(int(fields[CODEPOINT_FIELD], 16))
|
|
562
|
+
result.update(range(0xAC00, 0xD7A4))
|
|
563
|
+
return result
|
|
564
|
+
|
|
565
|
+
|
|
566
|
+
# A run's count is stored in 10 bits, so runs are split at this length.
|
|
567
|
+
MAX_COLL_RUN = 1023
|
|
568
|
+
|
|
569
|
+
# Primary weight bases for code points with no explicit entry, from UTS #10
|
|
570
|
+
# section 10.1.3. Emitted into the generated table and also used to check
|
|
571
|
+
# that no `@implicitweights` base collides with them.
|
|
572
|
+
HAN_CORE_BASE = 0xFB40
|
|
573
|
+
HAN_OTHER_BASE = 0xFB80
|
|
574
|
+
UNASSIGNED_BASE = 0xFBC0
|
|
575
|
+
|
|
576
|
+
|
|
577
|
+
def build_collation_runs(single, style_index):
|
|
578
|
+
"""Run-encode the single-element mappings.
|
|
579
|
+
|
|
580
|
+
Within a script block DUCET primary weights advance in step with the code
|
|
581
|
+
point, so 34,787 mappings collapse to roughly 6,660 runs. A run covers
|
|
582
|
+
consecutive code points that share a style and whose primary advances by a
|
|
583
|
+
constant step of 0 or 1."""
|
|
584
|
+
runs = []
|
|
585
|
+
items = sorted(single.items())
|
|
586
|
+
i = 0
|
|
587
|
+
while i < len(items):
|
|
588
|
+
cp, (var, prim, sec, ter) = items[i]
|
|
589
|
+
style = style_index[(var, sec, ter)]
|
|
590
|
+
step = None
|
|
591
|
+
j = i + 1
|
|
592
|
+
while j < len(items) and (j - i) < MAX_COLL_RUN:
|
|
593
|
+
cp2, (var2, prim2, sec2, ter2) = items[j]
|
|
594
|
+
if cp2 != cp + (j - i):
|
|
595
|
+
break
|
|
596
|
+
if style_index[(var2, sec2, ter2)] != style:
|
|
597
|
+
break
|
|
598
|
+
if step is None:
|
|
599
|
+
step = prim2 - prim
|
|
600
|
+
if step not in (0, 1):
|
|
601
|
+
break
|
|
602
|
+
elif prim2 != prim + (j - i) * step:
|
|
603
|
+
break
|
|
604
|
+
j += 1
|
|
605
|
+
# A run that failed to extend past its first code point can still
|
|
606
|
+
# have `step` set to the rejected (non-0/1) delta that caused the
|
|
607
|
+
# `break` above; a lone code point never uses `step`, so it must be
|
|
608
|
+
# forced back to 0 here rather than passed through.
|
|
609
|
+
runs.append((cp, j - i, prim, style, step if step in (0, 1) else 0))
|
|
610
|
+
i = j
|
|
611
|
+
return runs
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
def verify_collation_runs(runs, single, styles):
|
|
615
|
+
"""Assert the run encoding reproduces every input mapping exactly, and
|
|
616
|
+
that its fields fit the C++ struct's bit widths.
|
|
617
|
+
|
|
618
|
+
The encoder relies on primary weights advancing predictably; a data
|
|
619
|
+
change that broke that assumption would otherwise emit silently wrong
|
|
620
|
+
weights rather than failing."""
|
|
621
|
+
rebuilt = {}
|
|
622
|
+
for first, count, prim, style, step in runs:
|
|
623
|
+
assert step in (0, 1), f"run at {first:04X} has invalid step {step}"
|
|
624
|
+
last_prim = prim + (count - 1) * step
|
|
625
|
+
assert last_prim < 65536, (
|
|
626
|
+
f"run at {first:04X} overflows uint16_t primary: {last_prim}"
|
|
627
|
+
)
|
|
628
|
+
var, sec, ter = styles[style]
|
|
629
|
+
for k in range(count):
|
|
630
|
+
rebuilt[first + k] = (var, prim + k * step, sec, ter)
|
|
631
|
+
assert rebuilt == single, (
|
|
632
|
+
f"run encoding lost data: {len(rebuilt)} rebuilt vs {len(single)} input"
|
|
633
|
+
)
|
|
634
|
+
assert max(r[0] for r in runs) < (1 << 21), "code point must fit in 21 bits"
|
|
635
|
+
assert max(r[2] for r in runs) < 65536, "primary must fit in uint16_t"
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
def verify_style_sizes(styles):
|
|
639
|
+
"""Assert the pooled secondary/tertiary/variable styles fit the C++
|
|
640
|
+
struct's bit widths."""
|
|
641
|
+
assert len(styles) < 65536, "style index must fit in uint16_t"
|
|
642
|
+
assert max(s for _, s, _ in styles) < 65536, "secondary must fit in uint16_t"
|
|
643
|
+
assert max(t for _, _, t in styles) < 256, "tertiary must fit in uint8_t"
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
def implicit_anchors(implicit):
|
|
647
|
+
"""\\return a map from primary weight base to the code point its offsets
|
|
648
|
+
are measured from.
|
|
649
|
+
|
|
650
|
+
UTS #10 section 10.1.3 measures the second implicit weight of a code
|
|
651
|
+
point in an `@implicitweights` range from the start of the *first* range
|
|
652
|
+
that uses the range's base, not from the start of the range the code
|
|
653
|
+
point itself falls in. Two bases are shared by two ranges each, so the
|
|
654
|
+
distinction changes the weights of four of the six ranges."""
|
|
655
|
+
anchors = {}
|
|
656
|
+
for first, _, base in sorted(implicit):
|
|
657
|
+
anchors.setdefault(base, first)
|
|
658
|
+
return anchors
|
|
659
|
+
|
|
660
|
+
|
|
661
|
+
def verify_implicit_weights(implicit):
|
|
662
|
+
"""Assert the `@implicitweights` ranges satisfy the formula in UTS #10
|
|
663
|
+
section 10.1.3 rather than assuming they do.
|
|
664
|
+
|
|
665
|
+
A code point in such a range gets the two collation elements
|
|
666
|
+
AAAA = base and BBBB = (cp - anchor) | 0x8000. That yields distinct and
|
|
667
|
+
correctly ordered keys only if the ranges are disjoint, every offset
|
|
668
|
+
from the anchor fits in the 15 bits below the 0x8000 flag, and the
|
|
669
|
+
ranges that share a base stay disjoint after being shifted onto their
|
|
670
|
+
common anchor. Nothing in allkeys.txt guarantees any of that, so a
|
|
671
|
+
future data file that broke it must fail here rather than silently
|
|
672
|
+
emitting colliding weights."""
|
|
673
|
+
ranges = sorted(implicit)
|
|
674
|
+
for (first, last, _), (next_first, _, _) in zip(ranges, ranges[1:]):
|
|
675
|
+
assert first <= last, f"@implicitweights range U+{first:04X} is empty"
|
|
676
|
+
assert last < next_first, (
|
|
677
|
+
f"@implicitweights ranges U+{first:04X}..U+{last:04X} and "
|
|
678
|
+
f"U+{next_first:04X}.. overlap"
|
|
679
|
+
)
|
|
680
|
+
anchors = implicit_anchors(ranges)
|
|
681
|
+
spans = {}
|
|
682
|
+
for first, last, base in ranges:
|
|
683
|
+
assert base not in (HAN_CORE_BASE, HAN_OTHER_BASE, UNASSIGNED_BASE), (
|
|
684
|
+
f"@implicitweights base 0x{base:04X} collides with a base "
|
|
685
|
+
"reserved for Han and unassigned code points"
|
|
686
|
+
)
|
|
687
|
+
lo, hi = first - anchors[base], last - anchors[base]
|
|
688
|
+
assert 0 <= lo <= hi <= 0x7FFF, (
|
|
689
|
+
f"@implicitweights range U+{first:04X}..U+{last:04X} is "
|
|
690
|
+
f"0x{lo:X}..0x{hi:X} from the anchor of base 0x{base:04X}, which "
|
|
691
|
+
"does not fit the 15 bits UTS #10 section 10.1.3 allows"
|
|
692
|
+
)
|
|
693
|
+
for prev_lo, prev_hi in spans.setdefault(base, []):
|
|
694
|
+
assert hi < prev_lo or lo > prev_hi, (
|
|
695
|
+
f"@implicitweights range U+{first:04X}..U+{last:04X} shares "
|
|
696
|
+
f"base 0x{base:04X} with an earlier range and overlaps it "
|
|
697
|
+
"once both are measured from their common anchor"
|
|
698
|
+
)
|
|
699
|
+
spans[base].append((lo, hi))
|
|
700
|
+
|
|
701
|
+
|
|
702
|
+
def verify_no_implicit_overlap(single, multi, implicit):
|
|
703
|
+
"""Assert no code point in an `@implicitweights` range also has an
|
|
704
|
+
explicit `single`/`multi` entry, which would make the lookup order
|
|
705
|
+
between the two tables ambiguous."""
|
|
706
|
+
for first, last, _ in implicit:
|
|
707
|
+
for cp in range(first, last + 1):
|
|
708
|
+
assert cp not in single and cp not in multi, (
|
|
709
|
+
f"U+{cp:04X} is in an @implicitweights range but also has an "
|
|
710
|
+
"explicit entry; the lookup order would be ambiguous"
|
|
711
|
+
)
|
|
712
|
+
|
|
713
|
+
|
|
714
|
+
def verify_collation_pool(pool, expansions):
|
|
715
|
+
"""Assert the shared collation element pool and the expansions indexing
|
|
716
|
+
into it fit the C++ struct's bit widths."""
|
|
717
|
+
assert len(pool) < 65536, "pool offset must fit in uint16_t"
|
|
718
|
+
assert all(length < 256 for _, _, length in expansions), (
|
|
719
|
+
"expansion length must fit in uint8_t"
|
|
720
|
+
)
|
|
721
|
+
|
|
722
|
+
|
|
723
|
+
def verify_collation_invariants(single, contractions):
|
|
724
|
+
"""Check the properties of the DUCET data, as opposed to Unicode itself,
|
|
725
|
+
that the ASCII fast path in UnicodeCollation.cpp relies on, plus the
|
|
726
|
+
contraction key size its C++ matcher hardcodes.
|
|
727
|
+
|
|
728
|
+
ASCII's NFD-stability needs no check here: it is guaranteed by Unicode's
|
|
729
|
+
stability policy, not by this data. These three properties have no such
|
|
730
|
+
guarantee and could change with a future allkeys.txt, so the fast path
|
|
731
|
+
would otherwise be relying on an unstated assumption."""
|
|
732
|
+
max_contraction = max(len(cps) for cps in contractions)
|
|
733
|
+
assert max_contraction <= 3, (
|
|
734
|
+
f"contractions of {max_contraction} code points exceed the fixed "
|
|
735
|
+
"three-code-point key; the C++ matcher would truncate them"
|
|
736
|
+
)
|
|
737
|
+
assert not any(all(c < 0x80 for c in cps) for cps in contractions), (
|
|
738
|
+
"an all-ASCII contraction exists; the ASCII fast path in "
|
|
739
|
+
"UnicodeCollation.cpp assumes none does and would be wrong"
|
|
740
|
+
)
|
|
741
|
+
assert all(cp in single for cp in range(0x80)), (
|
|
742
|
+
"an ASCII code point has no single-element mapping in the DUCET "
|
|
743
|
+
"data (it may expand instead, or be missing entirely); the ASCII "
|
|
744
|
+
"fast path in UnicodeCollation.cpp would silently treat it as "
|
|
745
|
+
"completely ignorable instead of weighing it"
|
|
746
|
+
)
|
|
747
|
+
|
|
748
|
+
|
|
749
|
+
def print_collation_tables(
|
|
750
|
+
single, multi, contractions, implicit, decomposable, unified_ideographs
|
|
751
|
+
):
|
|
752
|
+
"""Emit CollationData.inc."""
|
|
753
|
+
# Entries a code point can never reach after NFD are omitted entirely.
|
|
754
|
+
single = {k: v for k, v in single.items() if k not in decomposable}
|
|
755
|
+
multi = {k: v for k, v in multi.items() if k not in decomposable}
|
|
756
|
+
contractions = {
|
|
757
|
+
k: v for k, v in contractions.items() if not any(c in decomposable for c in k)
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
# The secondary and tertiary weights come from a tiny alphabet, so they
|
|
761
|
+
# are pooled and referenced by index instead of stored per element.
|
|
762
|
+
styles = sorted(
|
|
763
|
+
{(v, s, t) for (v, p, s, t) in single.values()}
|
|
764
|
+
| {
|
|
765
|
+
(v, s, t)
|
|
766
|
+
for ces in list(multi.values()) + list(contractions.values())
|
|
767
|
+
for (v, p, s, t) in ces
|
|
768
|
+
}
|
|
769
|
+
)
|
|
770
|
+
style_index = {k: i for i, k in enumerate(styles)}
|
|
771
|
+
verify_style_sizes(styles)
|
|
772
|
+
|
|
773
|
+
runs = build_collation_runs(single, style_index)
|
|
774
|
+
verify_collation_runs(runs, single, styles)
|
|
775
|
+
|
|
776
|
+
verify_implicit_weights(implicit)
|
|
777
|
+
verify_no_implicit_overlap(single, multi, implicit)
|
|
778
|
+
|
|
779
|
+
print_template(
|
|
780
|
+
"""
|
|
781
|
+
/// The secondary weight, tertiary weight, and variable flag shared by many
|
|
782
|
+
/// collation elements. All of DUCET uses only a few hundred combinations, so
|
|
783
|
+
/// elements store an index into this table rather than the weights.
|
|
784
|
+
struct CollStyle {
|
|
785
|
+
uint16_t secondary;
|
|
786
|
+
uint8_t tertiary;
|
|
787
|
+
uint8_t variable;
|
|
788
|
+
};
|
|
789
|
+
|
|
790
|
+
/// A run of consecutive code points that share a style and whose primary
|
|
791
|
+
/// weight advances by \\c step per code point. Code point \\c cp in
|
|
792
|
+
/// [first, first + count) has primary weight
|
|
793
|
+
/// \\c primary + (cp - first) * step.
|
|
794
|
+
struct CollRun {
|
|
795
|
+
uint32_t first : 21;
|
|
796
|
+
uint32_t count : 10;
|
|
797
|
+
uint32_t step : 1;
|
|
798
|
+
uint16_t primary;
|
|
799
|
+
uint16_t style;
|
|
800
|
+
};
|
|
801
|
+
"""
|
|
802
|
+
)
|
|
803
|
+
|
|
804
|
+
print("static constexpr CollStyle COLL_STYLES[] = {")
|
|
805
|
+
for var, sec, ter in styles:
|
|
806
|
+
print(f" {{0x{sec:04X}, 0x{ter:02X}, {1 if var else 0}}},")
|
|
807
|
+
print("};")
|
|
808
|
+
print("")
|
|
809
|
+
|
|
810
|
+
print("/// Sorted by `first`, so lookup is a binary search.")
|
|
811
|
+
print("static constexpr CollRun COLL_RUNS[] = {")
|
|
812
|
+
for first, count, prim, style, step in runs:
|
|
813
|
+
print(f" {{0x{first:04X}, {count}, {step}, 0x{prim:04X}, {style}}},")
|
|
814
|
+
print("};")
|
|
815
|
+
print("")
|
|
816
|
+
|
|
817
|
+
# Expansions and contractions share one pool of collation elements, so a
|
|
818
|
+
# repeated element sequence costs nothing extra to reference twice.
|
|
819
|
+
pool = []
|
|
820
|
+
pool_offsets = {}
|
|
821
|
+
|
|
822
|
+
def intern(ces):
|
|
823
|
+
"""\\return the offset of \\p ces in the shared pool, appending it if
|
|
824
|
+
it is not already present. Sequences repeat often enough between
|
|
825
|
+
expansions and contractions to be worth deduplicating."""
|
|
826
|
+
key = tuple(ces)
|
|
827
|
+
if key not in pool_offsets:
|
|
828
|
+
pool_offsets[key] = len(pool)
|
|
829
|
+
pool.extend(ces)
|
|
830
|
+
return pool_offsets[key]
|
|
831
|
+
|
|
832
|
+
expansions = []
|
|
833
|
+
for cp in sorted(multi):
|
|
834
|
+
ces = multi[cp]
|
|
835
|
+
expansions.append((cp, intern(ces), len(ces)))
|
|
836
|
+
|
|
837
|
+
contraction_rows = []
|
|
838
|
+
for cps in sorted(contractions):
|
|
839
|
+
ces = contractions[cps]
|
|
840
|
+
contraction_rows.append((cps, intern(ces), len(ces)))
|
|
841
|
+
|
|
842
|
+
verify_collation_pool(pool, expansions)
|
|
843
|
+
max_contraction = max(len(cps) for cps, _, _ in contraction_rows)
|
|
844
|
+
verify_collation_invariants(single, contractions)
|
|
845
|
+
|
|
846
|
+
print_template(
|
|
847
|
+
"""
|
|
848
|
+
/// One collation element: a primary weight plus an index into COLL_STYLES for
|
|
849
|
+
/// its secondary weight, tertiary weight, and variable flag.
|
|
850
|
+
struct CollElem {
|
|
851
|
+
uint16_t primary;
|
|
852
|
+
uint16_t style;
|
|
853
|
+
};
|
|
854
|
+
|
|
855
|
+
/// A code point whose mapping is an expansion: \\c length collation elements
|
|
856
|
+
/// beginning at \\c offset in COLL_CE_POOL.
|
|
857
|
+
struct CollExpansion {
|
|
858
|
+
uint32_t cp;
|
|
859
|
+
uint16_t offset;
|
|
860
|
+
uint8_t length;
|
|
861
|
+
};
|
|
862
|
+
|
|
863
|
+
/// A contraction. The sequence cp0, cp1, cp2 maps to \\c length collation
|
|
864
|
+
/// elements beginning at \\c offset in COLL_CE_POOL. \\c cp2 is 0 for a
|
|
865
|
+
/// two-code-point contraction; 0 is never a contraction member.
|
|
866
|
+
struct CollContraction {
|
|
867
|
+
uint32_t cp0;
|
|
868
|
+
uint32_t cp1;
|
|
869
|
+
uint32_t cp2;
|
|
870
|
+
uint16_t offset;
|
|
871
|
+
uint8_t length;
|
|
872
|
+
};
|
|
873
|
+
|
|
874
|
+
/// An inclusive code point range.
|
|
875
|
+
struct CollRange {
|
|
876
|
+
uint32_t first;
|
|
877
|
+
uint32_t last;
|
|
878
|
+
};
|
|
879
|
+
|
|
880
|
+
/// An @implicitweights range, the primary weight base it uses, and the code
|
|
881
|
+
/// point its secondary implicit weight is measured from. Per UTS #10 section
|
|
882
|
+
/// 10.1.3 the anchor is the start of the first range that uses this base,
|
|
883
|
+
/// which is not this range's own start when two ranges share a base.
|
|
884
|
+
struct CollImplicitRange {
|
|
885
|
+
uint32_t first;
|
|
886
|
+
uint32_t last;
|
|
887
|
+
uint32_t anchor;
|
|
888
|
+
uint16_t base;
|
|
889
|
+
};
|
|
890
|
+
"""
|
|
891
|
+
)
|
|
892
|
+
|
|
893
|
+
print("/// Collation elements referenced by COLL_EXPANSIONS and")
|
|
894
|
+
print("/// COLL_CONTRACTIONS.")
|
|
895
|
+
print("static constexpr CollElem COLL_CE_POOL[] = {")
|
|
896
|
+
for var, prim, sec, ter in pool:
|
|
897
|
+
print(f" {{0x{prim:04X}, {style_index[(var, sec, ter)]}}},")
|
|
898
|
+
print("};")
|
|
899
|
+
print("")
|
|
900
|
+
|
|
901
|
+
print("/// Sorted by `cp`, so lookup is a binary search. Disjoint from")
|
|
902
|
+
print("/// COLL_RUNS: a code point appears in one or the other.")
|
|
903
|
+
print("static constexpr CollExpansion COLL_EXPANSIONS[] = {")
|
|
904
|
+
for cp, offset, length in expansions:
|
|
905
|
+
print(f" {{0x{cp:04X}, {offset}, {length}}},")
|
|
906
|
+
print("};")
|
|
907
|
+
print("")
|
|
908
|
+
|
|
909
|
+
print("/// Sorted lexicographically by (cp0, cp1, cp2).")
|
|
910
|
+
print("static constexpr CollContraction COLL_CONTRACTIONS[] = {")
|
|
911
|
+
for cps, offset, length in contraction_rows:
|
|
912
|
+
padded = list(cps) + [0] * (3 - len(cps))
|
|
913
|
+
cols = ", ".join(f"0x{c:04X}" for c in padded)
|
|
914
|
+
print(f" {{{cols}, {offset}, {length}}},")
|
|
915
|
+
print("};")
|
|
916
|
+
print("")
|
|
917
|
+
print("/// The longest contraction in the generated data.")
|
|
918
|
+
print(f"static constexpr size_t COLL_MAX_CONTRACTION_LENGTH = {max_contraction};")
|
|
919
|
+
print("")
|
|
920
|
+
|
|
921
|
+
print("/// Ranges given explicit primary weight bases by")
|
|
922
|
+
print("/// @implicitweights in allkeys.txt.")
|
|
923
|
+
print("static constexpr CollImplicitRange COLL_IMPLICIT_RANGES[] = {")
|
|
924
|
+
anchors = implicit_anchors(implicit)
|
|
925
|
+
for first, last, base in sorted(implicit):
|
|
926
|
+
print(
|
|
927
|
+
f" {{0x{first:04X}, 0x{last:04X}, 0x{anchors[base]:04X}, 0x{base:04X}}},"
|
|
928
|
+
)
|
|
929
|
+
print("};")
|
|
930
|
+
print("")
|
|
931
|
+
|
|
932
|
+
print("/// Code points with the Unified_Ideograph property, sorted.")
|
|
933
|
+
print("static constexpr CollRange COLL_UNIFIED_IDEOGRAPHS[] = {")
|
|
934
|
+
for first, last in unified_ideographs:
|
|
935
|
+
print(f" {{0x{first:04X}, 0x{last:04X}}},")
|
|
936
|
+
print("};")
|
|
937
|
+
print("")
|
|
938
|
+
|
|
939
|
+
print_template(
|
|
940
|
+
"""
|
|
941
|
+
/// Primary weight bases for code points with no table entry, from UTS #10
|
|
942
|
+
/// section 10.1.3. A Unified_Ideograph in the CJK Unified Ideographs or CJK
|
|
943
|
+
/// Compatibility Ideographs blocks uses the core base, any other
|
|
944
|
+
/// Unified_Ideograph uses the other base, and everything else, including
|
|
945
|
+
/// unassigned code points, uses the unassigned base.
|
|
946
|
+
static constexpr uint16_t COLL_HAN_CORE_BASE = 0x${han_core_base};
|
|
947
|
+
static constexpr uint16_t COLL_HAN_OTHER_BASE = 0x${han_other_base};
|
|
948
|
+
static constexpr uint16_t COLL_UNASSIGNED_BASE = 0x${unassigned_base};
|
|
949
|
+
|
|
950
|
+
/// The CJK Unified Ideographs and CJK Compatibility Ideographs blocks, which
|
|
951
|
+
/// select COLL_HAN_CORE_BASE. Block boundaries are stable, so they are
|
|
952
|
+
/// constants rather than generated.
|
|
953
|
+
static constexpr CollRange COLL_HAN_CORE_BLOCKS[] = {
|
|
954
|
+
{0x4E00, 0x9FFF},
|
|
955
|
+
{0xF900, 0xFAFF},
|
|
956
|
+
};
|
|
957
|
+
""",
|
|
958
|
+
han_core_base=f"{HAN_CORE_BASE:04X}",
|
|
959
|
+
han_other_base=f"{HAN_OTHER_BASE:04X}",
|
|
960
|
+
unassigned_base=f"{UNASSIGNED_BASE:04X}",
|
|
961
|
+
)
|
|
962
|
+
|
|
963
|
+
|
|
964
|
+
def print_collation_test_data(single, decomposable):
|
|
965
|
+
"""Emit CollationTestData.inc.
|
|
966
|
+
|
|
967
|
+
Rows are emitted as string literals in the upstream file's own format
|
|
968
|
+
rather than as pre-parsed arrays, matching what the normalization
|
|
969
|
+
conformance data does: it is far smaller, compiles faster, stays greppable
|
|
970
|
+
against the upstream file, and lets a failure print the row verbatim.
|
|
971
|
+
|
|
972
|
+
The table is const rather than constexpr; see MSVC_CONSTEXPR_LITERAL_NOTE."""
|
|
973
|
+
rows = []
|
|
974
|
+
for line in UnicodeDataFiles.get_lines("CollationTest_NON_IGNORABLE_SHORT.txt"):
|
|
975
|
+
# The full upstream file terminates every row with ';' where the
|
|
976
|
+
# short one does not, so the ';' is stripped as well as the comment.
|
|
977
|
+
# Leaving it in would emit a row the C++ parser cannot read.
|
|
978
|
+
text = line.split("#")[0].strip().rstrip(";").strip()
|
|
979
|
+
if not text or text.startswith("@"):
|
|
980
|
+
continue
|
|
981
|
+
rows.append(" ".join(text.split()))
|
|
982
|
+
assert len(rows) > 200000, f"only {len(rows)} conformance rows parsed"
|
|
983
|
+
|
|
984
|
+
print_template(
|
|
985
|
+
"""
|
|
986
|
+
/// One row of CollationTest_NON_IGNORABLE.txt: a space-separated list of hex
|
|
987
|
+
/// code points. Each row must sort at or after the row before it.
|
|
988
|
+
struct CollTestRow { const char *codePoints; };
|
|
989
|
+
"""
|
|
990
|
+
)
|
|
991
|
+
|
|
992
|
+
# clang-format splits long string literals across lines, which stops the
|
|
993
|
+
# rows from matching the upstream file when grepped.
|
|
994
|
+
print("// clang-format off")
|
|
995
|
+
print(MSVC_CONSTEXPR_LITERAL_NOTE)
|
|
996
|
+
print("static const CollTestRow COLL_TEST_ROWS[] = {")
|
|
997
|
+
for row in rows:
|
|
998
|
+
print(f' {{"{row}"}},')
|
|
999
|
+
print("};")
|
|
1000
|
+
print("// clang-format on")
|
|
1001
|
+
print("")
|
|
1002
|
+
|
|
1003
|
+
# An independent check on the compression: the expected weights are read
|
|
1004
|
+
# straight out of allkeys.txt here, so a bug in the run encoder shows up
|
|
1005
|
+
# as a mismatch rather than being reproduced identically on both sides.
|
|
1006
|
+
print_template(
|
|
1007
|
+
"""
|
|
1008
|
+
/// A code point and the single collation element allkeys.txt gives it, read
|
|
1009
|
+
/// directly from the file rather than through the compressed table, so this
|
|
1010
|
+
/// array is an independent check on the run encoding.
|
|
1011
|
+
struct CollWeightCheck {
|
|
1012
|
+
uint32_t cp;
|
|
1013
|
+
uint16_t primary;
|
|
1014
|
+
uint16_t secondary;
|
|
1015
|
+
uint8_t tertiary;
|
|
1016
|
+
};
|
|
1017
|
+
"""
|
|
1018
|
+
)
|
|
1019
|
+
checks = [(cp, v) for cp, v in sorted(single.items()) if cp not in decomposable]
|
|
1020
|
+
print("static constexpr CollWeightCheck COLL_WEIGHT_CHECKS[] = {")
|
|
1021
|
+
for cp, (_var, prim, sec, ter) in checks:
|
|
1022
|
+
print(f" {{0x{cp:04X}, 0x{prim:04X}, 0x{sec:04X}, 0x{ter:02X}}},")
|
|
1023
|
+
print("};")
|
|
1024
|
+
print("")
|
|
1025
|
+
|
|
1026
|
+
|
|
1027
|
+
def parse_property_aliases(
|
|
1028
|
+
lines: Iterable[str], get_canonical_name
|
|
1029
|
+
) -> dict[str, list[str]]:
|
|
1030
|
+
"""
|
|
1031
|
+
Create a mapping of canonical property names to lists of aliases, from the
|
|
1032
|
+
lines of a Unicode Database data file.
|
|
1033
|
+
|
|
1034
|
+
Example input:
|
|
1035
|
+
|
|
1036
|
+
gc ; Cc ; Control ; cntrl
|
|
1037
|
+
gc ; Cf ; Format
|
|
1038
|
+
|
|
1039
|
+
Example output:
|
|
1040
|
+
|
|
1041
|
+
{
|
|
1042
|
+
"Cc": ["Control", "cntrl"],
|
|
1043
|
+
"Cf": ["Format"],
|
|
1044
|
+
}
|
|
1045
|
+
"""
|
|
1046
|
+
property_aliases = {}
|
|
1047
|
+
for line in lines:
|
|
1048
|
+
fields = split_fields(line)
|
|
1049
|
+
canonical_name = get_canonical_name(fields)
|
|
1050
|
+
if canonical_name is not None:
|
|
1051
|
+
property_aliases[canonical_name] = fields[1:]
|
|
1052
|
+
return property_aliases
|
|
1053
|
+
|
|
1054
|
+
|
|
1055
|
+
# A range pool entry, represented as a tuple of `(offset, size)`.
|
|
1056
|
+
range_array_pool_entry = tuple[int, int]
|
|
1057
|
+
|
|
1058
|
+
|
|
1059
|
+
class UnicodePropertyCategory:
|
|
1060
|
+
"""
|
|
1061
|
+
A pool of property names and aliases, and codepoint range arrays, that exist
|
|
1062
|
+
with `UnicodeProperties` as the parent, and represent a specific category of
|
|
1063
|
+
Unicode properties, such as "General_Category" or "Script".
|
|
1064
|
+
"""
|
|
1065
|
+
|
|
1066
|
+
def __init__(self, parent=None):
|
|
1067
|
+
self.parent: UnicodeProperties = parent
|
|
1068
|
+
self._aliases: dict[str, list[str]] = {}
|
|
1069
|
+
self._range_array_pool: dict[str, range_array_pool_entry] = OrderedDict()
|
|
1070
|
+
|
|
1071
|
+
def all_names(self) -> list[tuple[str, str]]:
|
|
1072
|
+
"""
|
|
1073
|
+
Sorted list of `(alias, canonical_name)` tuples for all know property
|
|
1074
|
+
names in this pool.
|
|
1075
|
+
"""
|
|
1076
|
+
# This is sorted so the C++ code can use a binary search.
|
|
1077
|
+
return sorted(
|
|
1078
|
+
{
|
|
1079
|
+
(alias, name)
|
|
1080
|
+
for name, aliases in self._aliases.items()
|
|
1081
|
+
for alias in aliases
|
|
1082
|
+
}
|
|
1083
|
+
)
|
|
1084
|
+
|
|
1085
|
+
def range_array_pool(self):
|
|
1086
|
+
"""
|
|
1087
|
+
Sorted list of `(name, (offset, size))` tuples for the range array pool
|
|
1088
|
+
data.
|
|
1089
|
+
"""
|
|
1090
|
+
# This is sorted so the C++ code can use a binary search.
|
|
1091
|
+
return sorted(self._range_array_pool.items())
|
|
1092
|
+
|
|
1093
|
+
def add_aliases(self, name, aliases):
|
|
1094
|
+
"""
|
|
1095
|
+
See `UnicodeProperties.add_aliases`.
|
|
1096
|
+
"""
|
|
1097
|
+
if name in self._aliases:
|
|
1098
|
+
raise ValueError(f"Duplicate name {name}")
|
|
1099
|
+
elif name not in aliases:
|
|
1100
|
+
raise ValueError(f"Canonical name {name} not in aliases")
|
|
1101
|
+
self._aliases[name] = aliases
|
|
1102
|
+
|
|
1103
|
+
if self.parent is not None:
|
|
1104
|
+
self.parent.add_aliases(name, aliases)
|
|
1105
|
+
|
|
1106
|
+
def mark_range_pool(
|
|
1107
|
+
self, category: str, name: str, ranges=None, offset=None, size=None
|
|
1108
|
+
):
|
|
1109
|
+
"""
|
|
1110
|
+
See `UnicodeProperties.mark_range_pool`.
|
|
1111
|
+
"""
|
|
1112
|
+
if self.parent is not None:
|
|
1113
|
+
self.parent.mark_range_pool(category, name, ranges, offset, size)
|
|
1114
|
+
|
|
1115
|
+
def mark_range_array_pool(self, name: str, canonical_names: list[str]):
|
|
1116
|
+
"""
|
|
1117
|
+
For a compound property, mark the index and size of the compound
|
|
1118
|
+
property's ranges.
|
|
1119
|
+
|
|
1120
|
+
For example: "C" is a compound property that refers to the ranges of the
|
|
1121
|
+
"Cc", "Cf", "Cn", "Co", and "Cs" properties.
|
|
1122
|
+
|
|
1123
|
+
If all the canonical names are already in the range array pool, then
|
|
1124
|
+
this is an overlapping compound property, and the marked entry instead
|
|
1125
|
+
refers back to the existing pool entry, instead of adding a new one.
|
|
1126
|
+
"""
|
|
1127
|
+
if name in self._range_array_pool:
|
|
1128
|
+
raise ValueError(f"Duplicate name {name}")
|
|
1129
|
+
|
|
1130
|
+
size = len(canonical_names)
|
|
1131
|
+
|
|
1132
|
+
if all(
|
|
1133
|
+
canonical_name in self._range_array_pool
|
|
1134
|
+
for canonical_name in canonical_names
|
|
1135
|
+
):
|
|
1136
|
+
# This is an overlapping compound property, refer back to the first
|
|
1137
|
+
# existing pool entry, and do not increment the tracking index.
|
|
1138
|
+
offset = self._range_array_pool[canonical_names[0]][0]
|
|
1139
|
+
self._range_array_pool[name] = (
|
|
1140
|
+
offset,
|
|
1141
|
+
size,
|
|
1142
|
+
)
|
|
1143
|
+
return offset
|
|
1144
|
+
else:
|
|
1145
|
+
offset = self.parent._range_array_pool_index
|
|
1146
|
+
self._range_array_pool[name] = (offset, size)
|
|
1147
|
+
for canonical_name in canonical_names:
|
|
1148
|
+
self._range_array_pool[canonical_name] = (
|
|
1149
|
+
self.parent._range_array_pool_index,
|
|
1150
|
+
1,
|
|
1151
|
+
)
|
|
1152
|
+
self.parent._range_array_pool_index += 1
|
|
1153
|
+
return offset
|
|
1154
|
+
|
|
1155
|
+
def mark_range_array_pool_manual(self, name: str, offset: int, size: int):
|
|
1156
|
+
"""
|
|
1157
|
+
Like `mark_range_array_pool` but use manually provided offset and size.
|
|
1158
|
+
"""
|
|
1159
|
+
if name in self._range_array_pool:
|
|
1160
|
+
raise ValueError(f"Duplicate name {name}")
|
|
1161
|
+
|
|
1162
|
+
self._range_array_pool[name] = (offset, size)
|
|
1163
|
+
self.parent._range_array_pool_index += 1
|
|
1164
|
+
|
|
1165
|
+
def get_range(self, category: str, name: str) -> Optional[range_array_pool_entry]:
|
|
1166
|
+
return self.parent._range_pool.get((category, name))
|
|
1167
|
+
|
|
1168
|
+
|
|
1169
|
+
# Tuple of `(offset, (range_pool_index, ranges, size))` for a range pool entry.
|
|
1170
|
+
range_pool_entry = tuple[int, tuple[int, Optional[list[range_tuple]], Optional[int]]]
|
|
1171
|
+
|
|
1172
|
+
|
|
1173
|
+
class UnicodeProperties:
|
|
1174
|
+
"""
|
|
1175
|
+
The parent pool for all Unicode property categories, which share common
|
|
1176
|
+
string, range, and range array pools. The point of the pools is to
|
|
1177
|
+
generate code that is able to efficiently reference the large amount of
|
|
1178
|
+
Unicode property data, by using indexes into shared pools.
|
|
1179
|
+
|
|
1180
|
+
The string pool is a shared pool of all property names and aliases, which
|
|
1181
|
+
contains all canonical names and aliases.
|
|
1182
|
+
|
|
1183
|
+
The range pool is a shared pool of all codepoint ranges, which is referenced
|
|
1184
|
+
by a canonical name.
|
|
1185
|
+
|
|
1186
|
+
The range array pool is a shared pool of codepoint range arrays, which is
|
|
1187
|
+
referenced by a conical name, and refers to one or more ranges in the range
|
|
1188
|
+
pool.
|
|
1189
|
+
"""
|
|
1190
|
+
|
|
1191
|
+
INCLUDE_COMMENTS = True
|
|
1192
|
+
|
|
1193
|
+
def __init__(self):
|
|
1194
|
+
self.general_category_pool = UnicodePropertyCategory(parent=self)
|
|
1195
|
+
self.binary_property_pool = UnicodePropertyCategory(parent=self)
|
|
1196
|
+
self.script_property_pool = UnicodePropertyCategory(parent=self)
|
|
1197
|
+
self.script_extensions_property_pool = UnicodePropertyCategory(parent=self)
|
|
1198
|
+
|
|
1199
|
+
# All seen names, that comprise the shared string pool.
|
|
1200
|
+
self._names = set()
|
|
1201
|
+
|
|
1202
|
+
# Mapping of `(category, name)` to `(offset, ranges)` for the range
|
|
1203
|
+
# pool, which is shared across the other property pools.
|
|
1204
|
+
#
|
|
1205
|
+
# The offset is used by the individual range array pools, to refer back
|
|
1206
|
+
# to the shared range pool, and the individual ranges are used to build
|
|
1207
|
+
# the shared range pool data.
|
|
1208
|
+
self._range_pool: dict[str, range_pool_entry] = OrderedDict()
|
|
1209
|
+
|
|
1210
|
+
# Track the offset into the range pool, every time a new range is marked
|
|
1211
|
+
# the index is incremented by the size of the new range.
|
|
1212
|
+
self._range_pool_index = 0
|
|
1213
|
+
|
|
1214
|
+
# Track the offset into the shared range array pool, every time a new
|
|
1215
|
+
# range array is added to one of the property pools, this is incremented
|
|
1216
|
+
# by 1.
|
|
1217
|
+
self._range_array_pool_index = 0
|
|
1218
|
+
self._metrics = defaultdict(lambda: 0)
|
|
1219
|
+
|
|
1220
|
+
def log_metrics(self):
|
|
1221
|
+
print(
|
|
1222
|
+
f"""
|
|
1223
|
+
string_offset_bits: {self._metrics["string_offset"].bit_length()}
|
|
1224
|
+
string_size_bits: {self._metrics["string_size"].bit_length()}
|
|
1225
|
+
range_pool_offset_bits: {self._metrics["range_pool_offset"].bit_length()}
|
|
1226
|
+
range_pool_size_bits: {self._metrics["range_pool_size"].bit_length()}
|
|
1227
|
+
range_array_pool_offset_bits: {self._metrics["range_array_pool_offset"].bit_length()}
|
|
1228
|
+
range_array_pool_size_bits: {self._metrics["range_array_pool_size"].bit_length()}
|
|
1229
|
+
""",
|
|
1230
|
+
file=sys.stderr,
|
|
1231
|
+
)
|
|
1232
|
+
|
|
1233
|
+
def add_aliases(self, name: str, aliases: list[str]):
|
|
1234
|
+
"""
|
|
1235
|
+
Add a name and aliases to the shared string pool.
|
|
1236
|
+
"""
|
|
1237
|
+
self._names.add(name)
|
|
1238
|
+
self._names.update(aliases)
|
|
1239
|
+
|
|
1240
|
+
def mark_range_pool(
|
|
1241
|
+
self,
|
|
1242
|
+
category: str,
|
|
1243
|
+
name: str,
|
|
1244
|
+
ranges: list[int] = None,
|
|
1245
|
+
offset: int = None,
|
|
1246
|
+
size: int = None,
|
|
1247
|
+
):
|
|
1248
|
+
"""
|
|
1249
|
+
Mark a range pool entry, with optional codepoint ranges.
|
|
1250
|
+
|
|
1251
|
+
The category is necessary to disambiguate in cases where the name itself
|
|
1252
|
+
may not be unique across properties, such as `Scripts` and
|
|
1253
|
+
`Script_Extensions` where they share names.
|
|
1254
|
+
"""
|
|
1255
|
+
key = (category, name)
|
|
1256
|
+
if key in self._range_pool:
|
|
1257
|
+
raise ValueError(f"Duplicate key {key}")
|
|
1258
|
+
|
|
1259
|
+
pool_offset = self._range_pool_index if offset is None else offset
|
|
1260
|
+
self._range_pool[key] = (pool_offset, ranges, size)
|
|
1261
|
+
if ranges:
|
|
1262
|
+
self._range_pool_index += len(ranges)
|
|
1263
|
+
|
|
1264
|
+
def gather_general_category_properties(self):
|
|
1265
|
+
"""
|
|
1266
|
+
Gather the aliases and codepoint ranges for General_Category properties,
|
|
1267
|
+
into the shared string and range pools.
|
|
1268
|
+
|
|
1269
|
+
Example aliases input:
|
|
1270
|
+
|
|
1271
|
+
gc ; Cc ; Control ; cntrl
|
|
1272
|
+
gc ; Cf ; Format
|
|
1273
|
+
|
|
1274
|
+
Example codepoint input:
|
|
1275
|
+
|
|
1276
|
+
00D8..00DE ; Lu # [7] LATIN CAPITAL LETTER O WITH STROKE..LATIN CAPITAL LETTER THORN
|
|
1277
|
+
0100 ; Lu # LATIN CAPITAL LETTER A WITH MACRON
|
|
1278
|
+
"""
|
|
1279
|
+
gc_property_aliases = parse_property_aliases(
|
|
1280
|
+
UnicodeDataFiles.get_lines("PropertyValueAliases.txt"),
|
|
1281
|
+
get_canonical_name=lambda fields: fields[1] if fields[0] == "gc" else None,
|
|
1282
|
+
)
|
|
1283
|
+
gc_property_ranges = parse_codepoint_ranges(
|
|
1284
|
+
UnicodeDataFiles.get_lines("DerivedGeneralCategory.txt"),
|
|
1285
|
+
lambda canonical_name: canonical_name in gc_property_aliases.keys(),
|
|
1286
|
+
)
|
|
1287
|
+
|
|
1288
|
+
pool = self.general_category_pool
|
|
1289
|
+
|
|
1290
|
+
# Update the string pool with the General_Category property names and
|
|
1291
|
+
# aliases.
|
|
1292
|
+
for name, aliases in gc_property_aliases.items():
|
|
1293
|
+
pool.add_aliases(name, aliases)
|
|
1294
|
+
|
|
1295
|
+
# These General_Category properties are never directly associated with
|
|
1296
|
+
# codepoints, but exist conceptually as unions of other properties.
|
|
1297
|
+
#
|
|
1298
|
+
# NOTE: It's important that any ranges shared by compound groups overlap,
|
|
1299
|
+
# so that the offset+size can be contiguous for each of them.
|
|
1300
|
+
#
|
|
1301
|
+
# <https://www.unicode.org/reports/tr44/#General_Category_Values>
|
|
1302
|
+
COMPOUND_GC_PROPERTIES = {
|
|
1303
|
+
"C": ["Cc", "Cf", "Cn", "Co", "Cs"],
|
|
1304
|
+
"L": ["Ll", "Lt", "Lu", "Lm", "Lo"],
|
|
1305
|
+
"LC": ["Ll", "Lt", "Lu"],
|
|
1306
|
+
"M": ["Mc", "Me", "Mn"],
|
|
1307
|
+
"N": ["Nd", "Nl", "No"],
|
|
1308
|
+
"P": ["Pc", "Pd", "Pe", "Pf", "Pi", "Po", "Ps"],
|
|
1309
|
+
"S": ["Sc", "Sk", "Sm", "So"],
|
|
1310
|
+
"Z": ["Zl", "Zp", "Zs"],
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
cat = "General_Category"
|
|
1314
|
+
for compound_name, canonical_names in COMPOUND_GC_PROPERTIES.items():
|
|
1315
|
+
pool.mark_range_pool(cat, compound_name)
|
|
1316
|
+
|
|
1317
|
+
for canonical_name in canonical_names:
|
|
1318
|
+
ranges = gc_property_ranges[canonical_name]
|
|
1319
|
+
if pool.get_range(cat, canonical_name) is None:
|
|
1320
|
+
pool.mark_range_pool(cat, canonical_name, ranges)
|
|
1321
|
+
|
|
1322
|
+
pool.mark_range_array_pool(compound_name, canonical_names)
|
|
1323
|
+
|
|
1324
|
+
# Add any extra ranges that are not part of the compound groups.
|
|
1325
|
+
for canonical_name, ranges in gc_property_ranges.items():
|
|
1326
|
+
if pool.get_range(cat, canonical_name) is None:
|
|
1327
|
+
pool.mark_range_pool(cat, canonical_name, ranges)
|
|
1328
|
+
pool.mark_range_array_pool(canonical_name, [canonical_name])
|
|
1329
|
+
|
|
1330
|
+
def gather_binary_properties(self):
|
|
1331
|
+
"""
|
|
1332
|
+
Gather allowed binary (in the true/false sense) property aliases and
|
|
1333
|
+
codepoint ranges, explicitly given by ECMA262, into the shared string
|
|
1334
|
+
and range pools.
|
|
1335
|
+
|
|
1336
|
+
<https://tc39.es/ecma262/multipage/text-processing.html#table-binary-unicode-properties>
|
|
1337
|
+
|
|
1338
|
+
Example property aliases input:
|
|
1339
|
+
|
|
1340
|
+
# Alias ; Canonical name ; Additional alias
|
|
1341
|
+
|
|
1342
|
+
AHex ; ASCII_Hex_Digit
|
|
1343
|
+
Alpha ; Alphabetic
|
|
1344
|
+
WSpace ; White_Space ; space
|
|
1345
|
+
"""
|
|
1346
|
+
BINARY_PROPERTY_NAMES = [
|
|
1347
|
+
"ASCII",
|
|
1348
|
+
"ASCII_Hex_Digit",
|
|
1349
|
+
"Alphabetic",
|
|
1350
|
+
"Bidi_Control",
|
|
1351
|
+
"Bidi_Mirrored",
|
|
1352
|
+
"Case_Ignorable",
|
|
1353
|
+
"Cased",
|
|
1354
|
+
"Changes_When_Casefolded",
|
|
1355
|
+
"Changes_When_Casemapped",
|
|
1356
|
+
"Changes_When_Lowercased",
|
|
1357
|
+
"Changes_When_NFKC_Casefolded",
|
|
1358
|
+
"Changes_When_Titlecased",
|
|
1359
|
+
"Changes_When_Uppercased",
|
|
1360
|
+
"Dash",
|
|
1361
|
+
"Default_Ignorable_Code_Point",
|
|
1362
|
+
"Deprecated",
|
|
1363
|
+
"Diacritic",
|
|
1364
|
+
"Emoji",
|
|
1365
|
+
"Emoji_Component",
|
|
1366
|
+
"Emoji_Modifier",
|
|
1367
|
+
"Emoji_Modifier_Base",
|
|
1368
|
+
"Emoji_Presentation",
|
|
1369
|
+
"Extended_Pictographic",
|
|
1370
|
+
"Extender",
|
|
1371
|
+
"Grapheme_Base",
|
|
1372
|
+
"Grapheme_Extend",
|
|
1373
|
+
"Hex_Digit",
|
|
1374
|
+
"IDS_Binary_Operator",
|
|
1375
|
+
"IDS_Trinary_Operator",
|
|
1376
|
+
"ID_Continue",
|
|
1377
|
+
"ID_Start",
|
|
1378
|
+
"Ideographic",
|
|
1379
|
+
"Join_Control",
|
|
1380
|
+
"Logical_Order_Exception",
|
|
1381
|
+
"Lowercase",
|
|
1382
|
+
"Math",
|
|
1383
|
+
"Noncharacter_Code_Point",
|
|
1384
|
+
"Pattern_Syntax",
|
|
1385
|
+
"Pattern_White_Space",
|
|
1386
|
+
"Quotation_Mark",
|
|
1387
|
+
"Radical",
|
|
1388
|
+
"Regional_Indicator",
|
|
1389
|
+
"Sentence_Terminal",
|
|
1390
|
+
"Soft_Dotted",
|
|
1391
|
+
"Terminal_Punctuation",
|
|
1392
|
+
"Unified_Ideograph",
|
|
1393
|
+
"Uppercase",
|
|
1394
|
+
"Variation_Selector",
|
|
1395
|
+
"White_Space",
|
|
1396
|
+
"XID_Continue",
|
|
1397
|
+
"XID_Start",
|
|
1398
|
+
]
|
|
1399
|
+
|
|
1400
|
+
binary_property_aliases = {
|
|
1401
|
+
canonical_name: [] for canonical_name in BINARY_PROPERTY_NAMES
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
for line in UnicodeDataFiles.get_lines("PropertyAliases.txt"):
|
|
1405
|
+
fields = split_fields(line)
|
|
1406
|
+
canonical_name = fields[1]
|
|
1407
|
+
if canonical_name in binary_property_aliases:
|
|
1408
|
+
assert len(binary_property_aliases[canonical_name]) == 0, (
|
|
1409
|
+
"Duplicate canonical name"
|
|
1410
|
+
)
|
|
1411
|
+
binary_property_aliases[canonical_name] = list(set(fields))
|
|
1412
|
+
|
|
1413
|
+
is_known_name_or_alias = (
|
|
1414
|
+
lambda canonical_name: canonical_name in binary_property_aliases.keys()
|
|
1415
|
+
)
|
|
1416
|
+
binary_property_ranges = {
|
|
1417
|
+
# Used for binary properties such as `ASCII_Hex_Digit`.
|
|
1418
|
+
**parse_codepoint_ranges(
|
|
1419
|
+
UnicodeDataFiles.get_lines("PropList.txt"), is_known_name_or_alias
|
|
1420
|
+
),
|
|
1421
|
+
# Used for general category properties such as `Cased_Letter`.
|
|
1422
|
+
**parse_codepoint_ranges(
|
|
1423
|
+
UnicodeDataFiles.get_lines("DerivedCoreProperties.txt"),
|
|
1424
|
+
is_known_name_or_alias,
|
|
1425
|
+
),
|
|
1426
|
+
# Used for case folding properties such as `Changes_When_Casefolded`.
|
|
1427
|
+
**parse_codepoint_ranges(
|
|
1428
|
+
UnicodeDataFiles.get_lines("DerivedNormalizationProps.txt"),
|
|
1429
|
+
is_known_name_or_alias,
|
|
1430
|
+
),
|
|
1431
|
+
# Used for binary properties such as `Bidi_Mirrored`.
|
|
1432
|
+
**parse_codepoint_ranges(
|
|
1433
|
+
UnicodeDataFiles.get_lines("DerivedBinaryProperties.txt"),
|
|
1434
|
+
is_known_name_or_alias,
|
|
1435
|
+
),
|
|
1436
|
+
# Used for emoji-related binary properties such as
|
|
1437
|
+
# `Emoji_Presentation`.
|
|
1438
|
+
**parse_codepoint_ranges(
|
|
1439
|
+
UnicodeDataFiles.get_lines("emoji-data.txt"), is_known_name_or_alias
|
|
1440
|
+
),
|
|
1441
|
+
}
|
|
1442
|
+
|
|
1443
|
+
# Manually add cases that are not part of the enumerations.
|
|
1444
|
+
# <https://unicode.org/reports/tr18/#General_Category_Property>
|
|
1445
|
+
binary_property_aliases["ASCII"] = ["ASCII"]
|
|
1446
|
+
binary_property_ranges["ASCII"] = [(0x0, 0x7F)]
|
|
1447
|
+
|
|
1448
|
+
binary_property_aliases["Any"] = ["Any"]
|
|
1449
|
+
binary_property_ranges["Any"] = [(0x0, 0x10FFFF)]
|
|
1450
|
+
|
|
1451
|
+
binary_property_aliases["Assigned"] = ["Assigned"]
|
|
1452
|
+
binary_property_ranges["Assigned"] = get_assigned_codepoints(
|
|
1453
|
+
UnicodeDataFiles.get_lines("UnicodeData.txt")
|
|
1454
|
+
)
|
|
1455
|
+
|
|
1456
|
+
pool = self.binary_property_pool
|
|
1457
|
+
|
|
1458
|
+
# Update the string pool with the binary property names and aliases
|
|
1459
|
+
for name, aliases in binary_property_aliases.items():
|
|
1460
|
+
pool.add_aliases(name, aliases)
|
|
1461
|
+
|
|
1462
|
+
cat = "Binary"
|
|
1463
|
+
for canonical_name, ranges in binary_property_ranges.items():
|
|
1464
|
+
if pool.get_range(cat, canonical_name) is None:
|
|
1465
|
+
pool.mark_range_pool(cat, canonical_name, ranges)
|
|
1466
|
+
pool.mark_range_array_pool(canonical_name, [canonical_name])
|
|
1467
|
+
|
|
1468
|
+
def gather_script_properties(self):
|
|
1469
|
+
"""
|
|
1470
|
+
Gather script and script extensions property aliases and codepoint
|
|
1471
|
+
ranges, as they exist in the Unicode Database, into the string and range
|
|
1472
|
+
pools.
|
|
1473
|
+
|
|
1474
|
+
Script and script extensions are interleaved so that the ranges are
|
|
1475
|
+
contiguous.
|
|
1476
|
+
|
|
1477
|
+
NOTE: Script extensions don't have their own names, instead they re-use
|
|
1478
|
+
the Script property names. However, the ranges are referenced by the
|
|
1479
|
+
alias, not the canonical name, which differs from how scripts are
|
|
1480
|
+
handled.
|
|
1481
|
+
|
|
1482
|
+
Example property values aliases input:
|
|
1483
|
+
|
|
1484
|
+
# Category ; Alias ; Canonical name
|
|
1485
|
+
|
|
1486
|
+
sc ; Arab ; Arabic
|
|
1487
|
+
sc ; Latn ; Latin
|
|
1488
|
+
|
|
1489
|
+
Example scripts input:
|
|
1490
|
+
|
|
1491
|
+
0041..005A ; Latin # L& [26] LATIN CAPITAL LETTER A..LATIN CAPITAL LETTER Z
|
|
1492
|
+
0600..0604 ; Arabic # Cf [5] ARABIC NUMBER SIGN..ARABIC SIGN SAMVAT
|
|
1493
|
+
"""
|
|
1494
|
+
script_property_aliases = parse_property_aliases(
|
|
1495
|
+
UnicodeDataFiles.get_lines("PropertyValueAliases.txt"),
|
|
1496
|
+
get_canonical_name=lambda fields: fields[2] if fields[0] == "sc" else None,
|
|
1497
|
+
)
|
|
1498
|
+
|
|
1499
|
+
# This property is fictional, and is never directly referenced in the
|
|
1500
|
+
# codepoint data. Instead, Katakana (Kana) and Hiragana (Hira) are used
|
|
1501
|
+
# separately.
|
|
1502
|
+
#
|
|
1503
|
+
# <https://www.unicode.org/reports/tr44/#Allowed_Changes>
|
|
1504
|
+
del script_property_aliases["Katakana_Or_Hiragana"]
|
|
1505
|
+
|
|
1506
|
+
script_property_ranges = parse_codepoint_ranges(
|
|
1507
|
+
UnicodeDataFiles.get_lines("Scripts.txt"),
|
|
1508
|
+
lambda canonical_name: canonical_name in script_property_aliases,
|
|
1509
|
+
)
|
|
1510
|
+
|
|
1511
|
+
script_property_aliases_by_alias = parse_property_aliases(
|
|
1512
|
+
UnicodeDataFiles.get_lines("PropertyValueAliases.txt"),
|
|
1513
|
+
get_canonical_name=lambda fields: fields[1] if fields[0] == "sc" else None,
|
|
1514
|
+
)
|
|
1515
|
+
raw_property_ranges = parse_codepoint_ranges(
|
|
1516
|
+
UnicodeDataFiles.get_lines("ScriptExtensions.txt"), lambda _: True
|
|
1517
|
+
)
|
|
1518
|
+
# Because script extension codepoints are referenced by the script
|
|
1519
|
+
# property alias, not the canonical name, the ranges need to be manually
|
|
1520
|
+
# remapped.
|
|
1521
|
+
script_extensions_property_ranges = defaultdict(list)
|
|
1522
|
+
for key, ranges in raw_property_ranges.items():
|
|
1523
|
+
for short_key in key.split():
|
|
1524
|
+
# Script extension codepoints use the script property alias, not
|
|
1525
|
+
# the canonical name.
|
|
1526
|
+
canonical_name = script_property_aliases_by_alias[short_key][1]
|
|
1527
|
+
script_extensions_property_ranges[canonical_name].extend(ranges)
|
|
1528
|
+
|
|
1529
|
+
# Sort and merge ranges. The ranges were collected from multiple
|
|
1530
|
+
# multi-script lines in ScriptExtensions.txt, so they may be out of
|
|
1531
|
+
# order and adjacent ranges from different lines may not be merged.
|
|
1532
|
+
for name in script_extensions_property_ranges:
|
|
1533
|
+
script_extensions_property_ranges[name] = merge_adjacent_ranges(
|
|
1534
|
+
sorted(script_extensions_property_ranges[name])
|
|
1535
|
+
)
|
|
1536
|
+
|
|
1537
|
+
pool = self.script_property_pool
|
|
1538
|
+
ext_pool = self.script_extensions_property_pool
|
|
1539
|
+
# Update the string pool with the script property names and aliases
|
|
1540
|
+
for name, aliases in script_property_aliases.items():
|
|
1541
|
+
pool.add_aliases(name, aliases)
|
|
1542
|
+
|
|
1543
|
+
cat = "Script"
|
|
1544
|
+
ext_cat = "Script_Extensions"
|
|
1545
|
+
for canonical_name, ranges in script_property_ranges.items():
|
|
1546
|
+
if pool.get_range(cat, canonical_name) is None:
|
|
1547
|
+
pool.mark_range_pool(cat, canonical_name, ranges)
|
|
1548
|
+
script_range_array_offset = pool.mark_range_array_pool(
|
|
1549
|
+
canonical_name, [canonical_name]
|
|
1550
|
+
)
|
|
1551
|
+
|
|
1552
|
+
# Script extensions are a superset of the script property ranges,
|
|
1553
|
+
# they are added immediately after the corresponding script so that
|
|
1554
|
+
# the ranges are contiguous.
|
|
1555
|
+
ext_ranges = script_extensions_property_ranges[canonical_name]
|
|
1556
|
+
if ext_ranges and ext_pool.get_range(ext_cat, canonical_name) is None:
|
|
1557
|
+
script_range_offset = pool.get_range(cat, canonical_name)[0]
|
|
1558
|
+
ext_pool.mark_range_pool(
|
|
1559
|
+
ext_cat,
|
|
1560
|
+
canonical_name,
|
|
1561
|
+
ext_ranges,
|
|
1562
|
+
# Start the range pool offset at the same offset as the
|
|
1563
|
+
# corresponding script, and extend the size to include both
|
|
1564
|
+
# the script and script extension ranges.
|
|
1565
|
+
offset=script_range_offset,
|
|
1566
|
+
size=len(ranges) + len(ext_ranges),
|
|
1567
|
+
)
|
|
1568
|
+
# Point directly at the combined Script_Extensions pool ref,
|
|
1569
|
+
# which already includes both Script and Script_Extensions
|
|
1570
|
+
# ranges as a single entry.
|
|
1571
|
+
ext_pool.mark_range_array_pool_manual(
|
|
1572
|
+
canonical_name,
|
|
1573
|
+
script_range_array_offset + 1,
|
|
1574
|
+
1,
|
|
1575
|
+
)
|
|
1576
|
+
|
|
1577
|
+
# Manually map the "Zzzz" / "Unknown" script property to the "Cn" /
|
|
1578
|
+
# "Unassigned" range.
|
|
1579
|
+
pool._range_array_pool["Unknown"] = (
|
|
1580
|
+
self.general_category_pool._range_array_pool["Cn"]
|
|
1581
|
+
)
|
|
1582
|
+
|
|
1583
|
+
def print_template(self):
|
|
1584
|
+
"""
|
|
1585
|
+
Produce the generated C++ code for the gathered Unicode properties data.
|
|
1586
|
+
|
|
1587
|
+
This includes the string pool, range pool, and range array pool data.
|
|
1588
|
+
"""
|
|
1589
|
+
all_strings = sorted(
|
|
1590
|
+
self._names,
|
|
1591
|
+
key=lambda name: (len(name), name),
|
|
1592
|
+
reverse=True,
|
|
1593
|
+
)
|
|
1594
|
+
string_pool = reduce(
|
|
1595
|
+
lambda acc, item: acc if item in acc else acc + item,
|
|
1596
|
+
all_strings,
|
|
1597
|
+
"",
|
|
1598
|
+
)
|
|
1599
|
+
|
|
1600
|
+
def string_coord(name):
|
|
1601
|
+
"""
|
|
1602
|
+
Build a string pool lookup reference for a given name.
|
|
1603
|
+
|
|
1604
|
+
Example output:
|
|
1605
|
+
|
|
1606
|
+
{ offset, size }
|
|
1607
|
+
"""
|
|
1608
|
+
offset = string_pool.index(name)
|
|
1609
|
+
size = len(name)
|
|
1610
|
+
self._metrics["string_offset"] = max(self._metrics["string_offset"], offset)
|
|
1611
|
+
self._metrics["string_size"] = max(self._metrics["string_size"], size)
|
|
1612
|
+
assert offset + size < 0xFFFF, "String pool offset+size exceeds uint16_t"
|
|
1613
|
+
return f"{{ {offset}, {size} }}"
|
|
1614
|
+
|
|
1615
|
+
def _range_pool():
|
|
1616
|
+
"""
|
|
1617
|
+
Using the range pool, generate the UnicodeRange entries for the C++
|
|
1618
|
+
code, that reference the shared range pool.
|
|
1619
|
+
|
|
1620
|
+
Example output:
|
|
1621
|
+
|
|
1622
|
+
static constexpr UnicodeRange UNICODE_RANGE_POOL[] = {
|
|
1623
|
+
// General_Category: Cc
|
|
1624
|
+
{0x0000, 0x001F},
|
|
1625
|
+
{0x007F, 0x009F},
|
|
1626
|
+
};
|
|
1627
|
+
"""
|
|
1628
|
+
for (cat, name), (offset, ranges, range_size) in self._range_pool.items():
|
|
1629
|
+
if self.INCLUDE_COMMENTS:
|
|
1630
|
+
yield f"// {cat}: {name}"
|
|
1631
|
+
if ranges:
|
|
1632
|
+
# Manually batch the ranges into 3 per line, because
|
|
1633
|
+
# clang-format wants to format them to a single item per
|
|
1634
|
+
# line.
|
|
1635
|
+
for batch in batched(ranges, 3):
|
|
1636
|
+
yield "".join(
|
|
1637
|
+
f"{{{as_hex(start)}, {as_hex(end)}}},".ljust(20)
|
|
1638
|
+
for start, end in batch
|
|
1639
|
+
).strip()
|
|
1640
|
+
|
|
1641
|
+
def _range_array_pool():
|
|
1642
|
+
"""
|
|
1643
|
+
Using the range array pool, generate the UnicodeRangePoolRef entries
|
|
1644
|
+
for the C++ code, that reference the shared range pool.
|
|
1645
|
+
|
|
1646
|
+
Example output:
|
|
1647
|
+
|
|
1648
|
+
static constexpr UnicodeRangePoolRef UNICODE_RANGE_ARRAY_POOL[] {
|
|
1649
|
+
// General_Category: Cc
|
|
1650
|
+
{0, 2},
|
|
1651
|
+
// General_Category: Cf
|
|
1652
|
+
{2, 21},
|
|
1653
|
+
};
|
|
1654
|
+
"""
|
|
1655
|
+
for (cat, name), (offset, ranges, range_size) in self._range_pool.items():
|
|
1656
|
+
if self.INCLUDE_COMMENTS:
|
|
1657
|
+
yield f"// {cat}: {name}"
|
|
1658
|
+
if ranges is not None:
|
|
1659
|
+
size = len(ranges) if range_size is None else range_size
|
|
1660
|
+
assert offset + size < 0xFFFF, (
|
|
1661
|
+
"Range array offset+size exceeds uint16_t"
|
|
1662
|
+
)
|
|
1663
|
+
self._metrics["range_pool_offset"] = max(
|
|
1664
|
+
self._metrics["range_pool_offset"], offset
|
|
1665
|
+
)
|
|
1666
|
+
self._metrics["range_pool_size"] = max(
|
|
1667
|
+
self._metrics["range_pool_size"], size
|
|
1668
|
+
)
|
|
1669
|
+
yield f"{{ {offset}, {size} }},"
|
|
1670
|
+
|
|
1671
|
+
def _build_name_map(pool: UnicodePropertyCategory):
|
|
1672
|
+
"""
|
|
1673
|
+
For a given pool, build the NameMapEntry entries for the C++ code,
|
|
1674
|
+
that reference the shared string pool.
|
|
1675
|
+
|
|
1676
|
+
Example output:
|
|
1677
|
+
|
|
1678
|
+
static constexpr NameMapEntry canonicalPropertyNameMap_GeneralCategory[] = {
|
|
1679
|
+
// "C", "C"
|
|
1680
|
+
{{18, 1}, {18, 1}},
|
|
1681
|
+
// "Cased_Letter", "LC"
|
|
1682
|
+
{{1368, 12}, {3008, 2}},
|
|
1683
|
+
};
|
|
1684
|
+
"""
|
|
1685
|
+
for alias, name in pool.all_names():
|
|
1686
|
+
if self.INCLUDE_COMMENTS:
|
|
1687
|
+
yield f'// "{alias}", "{name}"'
|
|
1688
|
+
yield f"{{ {string_coord(alias)}, {string_coord(name)} }},"
|
|
1689
|
+
|
|
1690
|
+
def _build_range_map(pool: UnicodePropertyCategory):
|
|
1691
|
+
"""
|
|
1692
|
+
For a given pool, build the RangeMapEntry entries for the C++ code,
|
|
1693
|
+
that reference the shared range array pool.
|
|
1694
|
+
|
|
1695
|
+
Example output:
|
|
1696
|
+
|
|
1697
|
+
static constexpr RangeMapEntry unicodePropertyRangeMap_GeneralCategory[] = {
|
|
1698
|
+
// "C"
|
|
1699
|
+
{{18, 1}, 0, 5},
|
|
1700
|
+
// "Cc"
|
|
1701
|
+
{{3018, 2}, 0, 1},
|
|
1702
|
+
};
|
|
1703
|
+
"""
|
|
1704
|
+
for name, (offset, size) in pool.range_array_pool():
|
|
1705
|
+
if self.INCLUDE_COMMENTS:
|
|
1706
|
+
yield f'// "{name}"'
|
|
1707
|
+
assert offset + size < 0xFFFF, (
|
|
1708
|
+
"Range array map offset+size exceeds uint16_t"
|
|
1709
|
+
)
|
|
1710
|
+
self._metrics["range_array_pool_offset"] = max(
|
|
1711
|
+
self._metrics["range_array_pool_offset"], offset
|
|
1712
|
+
)
|
|
1713
|
+
self._metrics["range_array_pool_size"] = max(
|
|
1714
|
+
self._metrics["range_array_pool_size"], size
|
|
1715
|
+
)
|
|
1716
|
+
yield f"{{ {string_coord(name)}, {offset}, {size} }},"
|
|
1717
|
+
|
|
1718
|
+
print_template(
|
|
1719
|
+
"""
|
|
1720
|
+
#ifdef HERMES_ENABLE_UNICODE_REGEXP_PROPERTY_ESCAPES
|
|
1721
|
+
|
|
1722
|
+
static constexpr std::string_view UNICODE_DATA_STRING_POOL = "${string_pool}";
|
|
1723
|
+
|
|
1724
|
+
// clang-format off
|
|
1725
|
+
static constexpr UnicodeRange UNICODE_RANGE_POOL[] = {
|
|
1726
|
+
${range_pool}
|
|
1727
|
+
};
|
|
1728
|
+
// clang-format on
|
|
1729
|
+
|
|
1730
|
+
static constexpr UnicodeRangePoolRef UNICODE_RANGE_ARRAY_POOL[] {
|
|
1731
|
+
${range_array_pool}
|
|
1732
|
+
};
|
|
1733
|
+
|
|
1734
|
+
static constexpr NameMapEntry canonicalPropertyNameMap_GeneralCategory[] = {
|
|
1735
|
+
${name_map_general_category}
|
|
1736
|
+
};
|
|
1737
|
+
|
|
1738
|
+
static constexpr RangeMapEntry unicodePropertyRangeMap_GeneralCategory[] = {
|
|
1739
|
+
${range_map_general_category}
|
|
1740
|
+
};
|
|
1741
|
+
|
|
1742
|
+
static constexpr NameMapEntry canonicalPropertyNameMap_BinaryProperty[] = {
|
|
1743
|
+
${name_map_binary_property}
|
|
1744
|
+
};
|
|
1745
|
+
|
|
1746
|
+
static constexpr RangeMapEntry unicodePropertyRangeMap_BinaryProperty[] = {
|
|
1747
|
+
${range_map_binary_property}
|
|
1748
|
+
};
|
|
1749
|
+
|
|
1750
|
+
static constexpr NameMapEntry canonicalPropertyNameMap_Script[] = {
|
|
1751
|
+
${name_map_script_property}
|
|
1752
|
+
};
|
|
1753
|
+
|
|
1754
|
+
static constexpr RangeMapEntry unicodePropertyRangeMap_Script[] = {
|
|
1755
|
+
${range_map_script_property}
|
|
1756
|
+
};
|
|
1757
|
+
|
|
1758
|
+
static constexpr RangeMapEntry unicodePropertyRangeMap_ScriptExtensions[] = {
|
|
1759
|
+
${range_map_script_extensions_property}
|
|
1760
|
+
};
|
|
1761
|
+
|
|
1762
|
+
#endif
|
|
1763
|
+
""",
|
|
1764
|
+
string_pool=string_pool,
|
|
1765
|
+
range_pool=indent("\n".join(_range_pool()), " "),
|
|
1766
|
+
range_array_pool="\n".join(_range_array_pool()),
|
|
1767
|
+
name_map_general_category="\n".join(
|
|
1768
|
+
_build_name_map(self.general_category_pool)
|
|
1769
|
+
),
|
|
1770
|
+
range_map_general_category="\n".join(
|
|
1771
|
+
_build_range_map(self.general_category_pool)
|
|
1772
|
+
),
|
|
1773
|
+
name_map_binary_property="\n".join(
|
|
1774
|
+
_build_name_map(self.binary_property_pool)
|
|
1775
|
+
),
|
|
1776
|
+
range_map_binary_property="\n".join(
|
|
1777
|
+
_build_range_map(self.binary_property_pool)
|
|
1778
|
+
),
|
|
1779
|
+
name_map_script_property="\n".join(
|
|
1780
|
+
_build_name_map(self.script_property_pool)
|
|
1781
|
+
),
|
|
1782
|
+
range_map_script_property="\n".join(
|
|
1783
|
+
_build_range_map(self.script_property_pool)
|
|
1784
|
+
),
|
|
1785
|
+
# NOTE: There is no canonical name mapping for Script_Extensions,
|
|
1786
|
+
# instead the one for Script is reused.
|
|
1787
|
+
range_map_script_extensions_property="\n".join(
|
|
1788
|
+
_build_range_map(self.script_extensions_property_pool)
|
|
1789
|
+
),
|
|
1790
|
+
)
|
|
1791
|
+
|
|
1792
|
+
|
|
1793
|
+
def stride_from(p1, p2):
|
|
1794
|
+
return p2[0] - p1[0]
|
|
1795
|
+
|
|
1796
|
+
|
|
1797
|
+
def delta_within(p):
|
|
1798
|
+
return p[1] - p[0]
|
|
1799
|
+
|
|
1800
|
+
|
|
1801
|
+
def as_hex(cp):
|
|
1802
|
+
return "0x%.4X" % cp
|
|
1803
|
+
|
|
1804
|
+
|
|
1805
|
+
def batched(iterable, n):
|
|
1806
|
+
"""
|
|
1807
|
+
Roughly equivalent to `itertools.batched` from Python 3.12, according to the
|
|
1808
|
+
Python3 documentation for batched.
|
|
1809
|
+
|
|
1810
|
+
<https://docs.python.org/3/library/itertools.html#itertools.batched>
|
|
1811
|
+
|
|
1812
|
+
>>> batched('ABCDEFG', 3) # ['ABC', 'DEF', 'G']
|
|
1813
|
+
"""
|
|
1814
|
+
if n < 1:
|
|
1815
|
+
raise ValueError("n must be at least one")
|
|
1816
|
+
it = iter(iterable)
|
|
1817
|
+
while batch := tuple(islice(it, n)):
|
|
1818
|
+
yield batch
|
|
1819
|
+
|
|
1820
|
+
|
|
1821
|
+
class DeltaMapBlock:
|
|
1822
|
+
def __init__(self):
|
|
1823
|
+
self.pairs = []
|
|
1824
|
+
|
|
1825
|
+
def stride(self):
|
|
1826
|
+
return stride_from(self.pairs[0], self.pairs[1])
|
|
1827
|
+
|
|
1828
|
+
def delta(self):
|
|
1829
|
+
return delta_within(self.pairs[0])
|
|
1830
|
+
|
|
1831
|
+
def can_append(self, pair):
|
|
1832
|
+
if not self.pairs:
|
|
1833
|
+
return True
|
|
1834
|
+
if pair[0] - self.pairs[0][0] >= 256:
|
|
1835
|
+
return False
|
|
1836
|
+
if self.delta() != delta_within(pair):
|
|
1837
|
+
return False
|
|
1838
|
+
return len(self.pairs) < 2 or self.stride() == stride_from(self.pairs[-1], pair)
|
|
1839
|
+
|
|
1840
|
+
@staticmethod
|
|
1841
|
+
def append_to_list(blocks, p):
|
|
1842
|
+
if not blocks or not blocks[-1].can_append(p):
|
|
1843
|
+
blocks.append(DeltaMapBlock())
|
|
1844
|
+
blocks[-1].pairs.append(p)
|
|
1845
|
+
|
|
1846
|
+
def output(self):
|
|
1847
|
+
pairs = self.pairs
|
|
1848
|
+
if not pairs:
|
|
1849
|
+
return ""
|
|
1850
|
+
|
|
1851
|
+
first = pairs[0][0]
|
|
1852
|
+
last = pairs[-1][0]
|
|
1853
|
+
modulo = self.stride() if len(pairs) >= 2 else 1
|
|
1854
|
+
delta = self.delta()
|
|
1855
|
+
code = Template("{$first, $count, $delta, $modulo}").substitute(
|
|
1856
|
+
first=as_hex(first), count=last - first + 1, delta=delta, modulo=modulo
|
|
1857
|
+
)
|
|
1858
|
+
return code.strip()
|
|
1859
|
+
|
|
1860
|
+
|
|
1861
|
+
class FullCaseData:
|
|
1862
|
+
"""Full Unicode case mappings, including the multi-character mappings and
|
|
1863
|
+
the properties needed by the conditional rules. Distinct from CaseMap,
|
|
1864
|
+
which keeps only single-character locale-insensitive mappings for RegExp
|
|
1865
|
+
canonicalization."""
|
|
1866
|
+
|
|
1867
|
+
def __init__(self, unicode_data_lines, special_casing_lines):
|
|
1868
|
+
self.simple_upper = {} # cp -> cp
|
|
1869
|
+
self.simple_lower = {} # cp -> cp
|
|
1870
|
+
self.full_upper = {} # cp -> [cp, ...], only when longer than one
|
|
1871
|
+
self.full_lower = {}
|
|
1872
|
+
for line in unicode_data_lines:
|
|
1873
|
+
f = line.split(";")
|
|
1874
|
+
if len(f) < 14:
|
|
1875
|
+
continue
|
|
1876
|
+
cp = int(f[CODEPOINT_FIELD], 16)
|
|
1877
|
+
if f[UPPERCASE_FIELD].strip():
|
|
1878
|
+
self.simple_upper[cp] = int(f[UPPERCASE_FIELD], 16)
|
|
1879
|
+
if f[LOWERCASE_FIELD].strip():
|
|
1880
|
+
self.simple_lower[cp] = int(f[LOWERCASE_FIELD], 16)
|
|
1881
|
+
for line in special_casing_lines:
|
|
1882
|
+
f = [x.strip() for x in line.split("#")[0].split(";")]
|
|
1883
|
+
if len(f) < 5 or not f[0]:
|
|
1884
|
+
continue
|
|
1885
|
+
# Conditional entries are implemented in C++, not tabulated.
|
|
1886
|
+
if f[4]:
|
|
1887
|
+
continue
|
|
1888
|
+
cp = int(f[0], 16)
|
|
1889
|
+
lower = [int(x, 16) for x in f[1].split()]
|
|
1890
|
+
upper = [int(x, 16) for x in f[3].split()]
|
|
1891
|
+
if len(upper) > 1:
|
|
1892
|
+
self.full_upper[cp] = upper
|
|
1893
|
+
if len(lower) > 1:
|
|
1894
|
+
self.full_lower[cp] = lower
|
|
1895
|
+
|
|
1896
|
+
def delta_pairs(self, simple, full):
|
|
1897
|
+
"""(cp, mapped) pairs for the delta blocks, excluding code points that
|
|
1898
|
+
have a full mapping since those are handled by the side table."""
|
|
1899
|
+
return [
|
|
1900
|
+
(cp, m) for cp, m in sorted(simple.items()) if cp != m and cp not in full
|
|
1901
|
+
]
|
|
1902
|
+
|
|
1903
|
+
|
|
1904
|
+
class CaseMap:
|
|
1905
|
+
"""Unicode case mapping helper.
|
|
1906
|
+
|
|
1907
|
+
This class holds the list of codepoints, and their uppercase and
|
|
1908
|
+
lowercase mappings.
|
|
1909
|
+
|
|
1910
|
+
"""
|
|
1911
|
+
|
|
1912
|
+
def __init__(self, unicode_data_lines, special_casing_lines, casefolding_lines):
|
|
1913
|
+
"""Construct with the lines from UnicodeData and SpecialCasing."""
|
|
1914
|
+
self.toupper = {}
|
|
1915
|
+
self.tolower = {}
|
|
1916
|
+
self.codepoints = []
|
|
1917
|
+
for line in unicode_data_lines:
|
|
1918
|
+
fields = line.split(";")
|
|
1919
|
+
self.__set_casemap(
|
|
1920
|
+
fields[CODEPOINT_FIELD],
|
|
1921
|
+
upper=fields[UPPERCASE_FIELD],
|
|
1922
|
+
lower=fields[LOWERCASE_FIELD],
|
|
1923
|
+
)
|
|
1924
|
+
self.codepoints.extend(self.toupper.keys())
|
|
1925
|
+
|
|
1926
|
+
# Apply special cases. This is to support ES5.1 Canonicalize, which is
|
|
1927
|
+
# cast in terms of toUpperCase(). The desire here is to have a
|
|
1928
|
+
# locale-independent result. Thus we ignore SpecialCasing rules that
|
|
1929
|
+
# are locale specific. We can also get away with ignoring
|
|
1930
|
+
# context-sensitive rules because Canonicalize only considers one
|
|
1931
|
+
# character. Thus ignore any rules that have a condition.
|
|
1932
|
+
# Format is codepoint, lower, title, upper, condition
|
|
1933
|
+
for line in special_casing_lines:
|
|
1934
|
+
# Trim comments
|
|
1935
|
+
line = line.split("#")[0]
|
|
1936
|
+
fields = line.split(";")
|
|
1937
|
+
if len(fields) < 5:
|
|
1938
|
+
continue
|
|
1939
|
+
cps, lower, title, upper, condition = fields[:5]
|
|
1940
|
+
# Title is unused
|
|
1941
|
+
_ = title # noqa: F841
|
|
1942
|
+
if not condition.strip():
|
|
1943
|
+
self.__set_casemap(cps, upper=upper, lower=lower)
|
|
1944
|
+
|
|
1945
|
+
# Characters default to folding to themselves.
|
|
1946
|
+
self.folds = {cp: cp for cp in self.codepoints}
|
|
1947
|
+
|
|
1948
|
+
# Parse case folds.
|
|
1949
|
+
for line in casefolding_lines:
|
|
1950
|
+
fields = line.split("#")[0].split(";")
|
|
1951
|
+
if len(fields) != 4:
|
|
1952
|
+
continue
|
|
1953
|
+
orig, status, folded, _ = map(str.strip, fields)
|
|
1954
|
+
# We are only interested in common and simple case foldings.
|
|
1955
|
+
if status not in ["C", "S"]:
|
|
1956
|
+
continue
|
|
1957
|
+
self.folds[int(orig, 16)] = int(folded, 16)
|
|
1958
|
+
|
|
1959
|
+
def __set_casemap(self, cp, upper, lower):
|
|
1960
|
+
"""Set a case mapping.
|
|
1961
|
+
|
|
1962
|
+
Mark the upper and lower case forms of cp. If a form is empty,
|
|
1963
|
+
the character is its own case mapping.
|
|
1964
|
+
All parameters are code points encoded via hex into a string.
|
|
1965
|
+
|
|
1966
|
+
"""
|
|
1967
|
+
# Parse the codepoint from hex.
|
|
1968
|
+
cp = int(cp, 16)
|
|
1969
|
+
|
|
1970
|
+
# "The simple uppercase is omitted in the data file if the uppercase
|
|
1971
|
+
# is the same as the code point itself."
|
|
1972
|
+
# The same is true for the lowercase.
|
|
1973
|
+
# Skip eszett or anything else that maps to more than one character.
|
|
1974
|
+
self.toupper[cp] = int(upper, 16) if upper and len(upper.split()) == 1 else cp
|
|
1975
|
+
self.tolower[cp] = int(lower, 16) if lower and len(lower.split()) == 1 else cp
|
|
1976
|
+
|
|
1977
|
+
def canonicalize(self, ch, unicode):
|
|
1978
|
+
"""Canonicalize a character per ES9 21.2.2.8.2."""
|
|
1979
|
+
if unicode:
|
|
1980
|
+
return self.folds[ch]
|
|
1981
|
+
else:
|
|
1982
|
+
upper_ch = self.toupper[ch]
|
|
1983
|
+
# "If u does not consist of a single character, return ch"
|
|
1984
|
+
# We only store 1-1 mappings.
|
|
1985
|
+
# "If ch's code unit value is greater than or equal to decimal 128
|
|
1986
|
+
# and cu's code unit value is less than decimal 128, then return ch"
|
|
1987
|
+
# That is, only ASCII may canonicalize to ASCII.
|
|
1988
|
+
if upper_ch < 128 and ch >= 128:
|
|
1989
|
+
return ch
|
|
1990
|
+
return upper_ch
|
|
1991
|
+
|
|
1992
|
+
|
|
1993
|
+
def print_canonicalizations(casemap, unicode):
|
|
1994
|
+
blocks = []
|
|
1995
|
+
for cp in casemap.codepoints:
|
|
1996
|
+
# legacy does not decode surrogate pairs, so we can skip large code points.
|
|
1997
|
+
if not unicode and cp > 0xFFFF:
|
|
1998
|
+
continue
|
|
1999
|
+
canon_cp = casemap.canonicalize(cp, unicode)
|
|
2000
|
+
if cp != canon_cp:
|
|
2001
|
+
DeltaMapBlock.append_to_list(blocks, (cp, canon_cp))
|
|
2002
|
+
|
|
2003
|
+
print_template(
|
|
2004
|
+
"""
|
|
2005
|
+
// static constexpr uint32_t ${name}_SIZE = ${entry_count};
|
|
2006
|
+
static constexpr UnicodeTransformRange ${name}[] = {
|
|
2007
|
+
${entry_text}
|
|
2008
|
+
};
|
|
2009
|
+
""",
|
|
2010
|
+
name="UNICODE_FOLDS" if unicode else "LEGACY_CANONS",
|
|
2011
|
+
entry_count=len(blocks),
|
|
2012
|
+
entry_text=",\n".join(b.output() for b in blocks),
|
|
2013
|
+
)
|
|
2014
|
+
|
|
2015
|
+
|
|
2016
|
+
def print_case_tables(case, cased, case_ignorable, soft_dotted):
|
|
2017
|
+
"""Emit CaseData.inc."""
|
|
2018
|
+
print_template(
|
|
2019
|
+
"""
|
|
2020
|
+
/// A run of code points sharing a case-mapping delta, in the same encoding as
|
|
2021
|
+
/// UNICODE_FOLDS: cp maps to cp + delta when (cp - start) % modulo == 0.
|
|
2022
|
+
struct CaseDelta {
|
|
2023
|
+
unsigned start : 24;
|
|
2024
|
+
unsigned count : 8;
|
|
2025
|
+
int delta : 24;
|
|
2026
|
+
unsigned modulo : 8;
|
|
2027
|
+
};
|
|
2028
|
+
|
|
2029
|
+
/// A multi-character case mapping, as an offset and length into
|
|
2030
|
+
/// FULL_CASE_POOL.
|
|
2031
|
+
struct FullCaseEntry { uint32_t cp; uint32_t offset; uint8_t length; };
|
|
2032
|
+
|
|
2033
|
+
/// An inclusive range of code points sharing a binary property.
|
|
2034
|
+
struct CaseRange { uint32_t first; uint32_t last; };
|
|
2035
|
+
"""
|
|
2036
|
+
)
|
|
2037
|
+
|
|
2038
|
+
for name, pairs in (
|
|
2039
|
+
("TO_UPPER_DELTAS", case.delta_pairs(case.simple_upper, case.full_upper)),
|
|
2040
|
+
("TO_LOWER_DELTAS", case.delta_pairs(case.simple_lower, case.full_lower)),
|
|
2041
|
+
):
|
|
2042
|
+
blocks = []
|
|
2043
|
+
for p in pairs:
|
|
2044
|
+
DeltaMapBlock.append_to_list(blocks, p)
|
|
2045
|
+
print(f"static constexpr CaseDelta {name}[] = {{")
|
|
2046
|
+
for b in blocks:
|
|
2047
|
+
print(f" {b.output()},")
|
|
2048
|
+
print("};")
|
|
2049
|
+
print("")
|
|
2050
|
+
|
|
2051
|
+
pool = []
|
|
2052
|
+
pool_index = {}
|
|
2053
|
+
|
|
2054
|
+
def intern(seq):
|
|
2055
|
+
key = tuple(seq)
|
|
2056
|
+
if key not in pool_index:
|
|
2057
|
+
pool_index[key] = len(pool)
|
|
2058
|
+
pool.extend(seq)
|
|
2059
|
+
return pool_index[key]
|
|
2060
|
+
|
|
2061
|
+
tables = {}
|
|
2062
|
+
for name, mapping in (
|
|
2063
|
+
("FULL_UPPER", case.full_upper),
|
|
2064
|
+
("FULL_LOWER", case.full_lower),
|
|
2065
|
+
):
|
|
2066
|
+
entries = []
|
|
2067
|
+
for cp in sorted(mapping):
|
|
2068
|
+
seq = mapping[cp]
|
|
2069
|
+
assert all(c <= 0xFFFF for c in seq), f"{cp:04X} maps outside the BMP"
|
|
2070
|
+
entries.append((cp, intern(seq), len(seq)))
|
|
2071
|
+
tables[name] = entries
|
|
2072
|
+
|
|
2073
|
+
print_codepoint_array("FULL_CASE_POOL", "char16_t", pool)
|
|
2074
|
+
|
|
2075
|
+
for name, entries in tables.items():
|
|
2076
|
+
print(f"static constexpr FullCaseEntry {name}[] = {{")
|
|
2077
|
+
for cp, offset, length in entries:
|
|
2078
|
+
print(f" {{{as_hex(cp)}, {offset}, {length}}},")
|
|
2079
|
+
print("};")
|
|
2080
|
+
print("")
|
|
2081
|
+
|
|
2082
|
+
for name, ranges in (
|
|
2083
|
+
("CASED_RANGES", cased),
|
|
2084
|
+
("CASE_IGNORABLE_RANGES", case_ignorable),
|
|
2085
|
+
("SOFT_DOTTED_RANGES", soft_dotted),
|
|
2086
|
+
):
|
|
2087
|
+
print(f"static constexpr CaseRange {name}[] = {{")
|
|
2088
|
+
for first, last in ranges:
|
|
2089
|
+
print(f" {{{as_hex(first)}, {as_hex(last)}}},")
|
|
2090
|
+
print("};")
|
|
2091
|
+
print("")
|
|
2092
|
+
|
|
2093
|
+
|
|
2094
|
+
def print_case_test_data(case):
|
|
2095
|
+
"""Emit CaseMappingTestData.inc: expectations derived directly from the
|
|
2096
|
+
UCD dictionaries, so the test cross-checks the delta-block compression
|
|
2097
|
+
rather than restating it.
|
|
2098
|
+
|
|
2099
|
+
Emitted as two lists, one per direction, each excluding code points that
|
|
2100
|
+
have a multi-character mapping in THAT direction. Full mappings are
|
|
2101
|
+
asymmetric -- 102 code points have one only for uppercase and U+0130 only
|
|
2102
|
+
for lowercase -- so a single combined list would either lose coverage or
|
|
2103
|
+
force the test to guard its assertions, which would let it pass
|
|
2104
|
+
vacuously."""
|
|
2105
|
+
print_template(
|
|
2106
|
+
"""
|
|
2107
|
+
/// One code point's expected single-character mapping, taken straight from
|
|
2108
|
+
/// UnicodeData.txt rather than through the compressed tables.
|
|
2109
|
+
struct SimpleCaseExpectation { uint32_t cp; uint32_t mapped; };
|
|
2110
|
+
"""
|
|
2111
|
+
)
|
|
2112
|
+
for name, simple, full in (
|
|
2113
|
+
("SIMPLE_UPPER_EXPECTATIONS", case.simple_upper, case.full_upper),
|
|
2114
|
+
("SIMPLE_LOWER_EXPECTATIONS", case.simple_lower, case.full_lower),
|
|
2115
|
+
):
|
|
2116
|
+
print("// clang-format off")
|
|
2117
|
+
print(f"static constexpr SimpleCaseExpectation {name}[] = {{")
|
|
2118
|
+
for cp in sorted(simple):
|
|
2119
|
+
if cp in full:
|
|
2120
|
+
continue
|
|
2121
|
+
print(f" {{{as_hex(cp)}, {as_hex(simple[cp])}}},")
|
|
2122
|
+
print("};")
|
|
2123
|
+
print("// clang-format on")
|
|
2124
|
+
print("")
|
|
2125
|
+
|
|
2126
|
+
|
|
2127
|
+
class NormalizationData:
|
|
2128
|
+
"""Decomposition, combining class, composition and Quick_Check data
|
|
2129
|
+
extracted from the UCD, in the form needed by UnicodeNormalization.cpp."""
|
|
2130
|
+
|
|
2131
|
+
def __init__(self, unicode_data_lines, derived_norm_props_lines):
|
|
2132
|
+
self.ccc = {} # cp -> canonical combining class, omitted when 0
|
|
2133
|
+
self.canon = {} # cp -> primary canonical decomposition
|
|
2134
|
+
self.compat = {} # cp -> primary compatibility decomposition
|
|
2135
|
+
self.exclusions = set()
|
|
2136
|
+
self.qc = {"NFC": set(), "NFD": set(), "NFKC": set(), "NFKD": set()}
|
|
2137
|
+
self.comp = {} # (starter, combining) -> composite
|
|
2138
|
+
self._parse_unicode_data(unicode_data_lines)
|
|
2139
|
+
self._parse_derived(derived_norm_props_lines)
|
|
2140
|
+
self._build_compositions()
|
|
2141
|
+
|
|
2142
|
+
def _parse_unicode_data(self, lines):
|
|
2143
|
+
for line in lines:
|
|
2144
|
+
f = split_fields(line)
|
|
2145
|
+
if len(f) < 6:
|
|
2146
|
+
continue
|
|
2147
|
+
cp = int(f[0], 16)
|
|
2148
|
+
ccc = int(f[3])
|
|
2149
|
+
if ccc:
|
|
2150
|
+
self.ccc[cp] = ccc
|
|
2151
|
+
d = f[5]
|
|
2152
|
+
if not d:
|
|
2153
|
+
continue
|
|
2154
|
+
if d.startswith("<"):
|
|
2155
|
+
# Compatibility mapping, e.g. "<compat> 0020 0308".
|
|
2156
|
+
self.compat[cp] = [int(x, 16) for x in d.split(">")[1].split()]
|
|
2157
|
+
else:
|
|
2158
|
+
self.canon[cp] = [int(x, 16) for x in d.split()]
|
|
2159
|
+
|
|
2160
|
+
def _parse_derived(self, lines):
|
|
2161
|
+
for line in lines:
|
|
2162
|
+
f = split_fields(line)
|
|
2163
|
+
if len(f) < 2:
|
|
2164
|
+
continue
|
|
2165
|
+
first, last = parse_range(f[0])
|
|
2166
|
+
prop = f[1]
|
|
2167
|
+
if prop == "Full_Composition_Exclusion":
|
|
2168
|
+
self.exclusions.update(range(first, last + 1))
|
|
2169
|
+
elif prop in ("NFC_QC", "NFD_QC", "NFKC_QC", "NFKD_QC"):
|
|
2170
|
+
# Both No and Maybe mean the fast path cannot be taken.
|
|
2171
|
+
self.qc[prop[:-3]].update(range(first, last + 1))
|
|
2172
|
+
|
|
2173
|
+
def _build_compositions(self):
|
|
2174
|
+
for cp, m in self.canon.items():
|
|
2175
|
+
if len(m) != 2:
|
|
2176
|
+
continue # Singleton decompositions never compose.
|
|
2177
|
+
if cp in self.exclusions:
|
|
2178
|
+
continue
|
|
2179
|
+
if self.ccc.get(m[0], 0) != 0:
|
|
2180
|
+
continue # Non-starter decompositions never compose.
|
|
2181
|
+
self.comp[(m[0], m[1])] = cp
|
|
2182
|
+
|
|
2183
|
+
def full_canonical(self, cp):
|
|
2184
|
+
"""Recursively expanded canonical decomposition of cp, or [cp]."""
|
|
2185
|
+
m = self.canon.get(cp)
|
|
2186
|
+
if not m:
|
|
2187
|
+
return [cp]
|
|
2188
|
+
out = []
|
|
2189
|
+
for c in m:
|
|
2190
|
+
out.extend(self.full_canonical(c))
|
|
2191
|
+
return out
|
|
2192
|
+
|
|
2193
|
+
def full_compatibility(self, cp):
|
|
2194
|
+
"""Recursively expanded compatibility decomposition of cp, or [cp].
|
|
2195
|
+
Compatibility decomposition subsumes canonical, so NFKD is a superset
|
|
2196
|
+
of NFD."""
|
|
2197
|
+
m = self.compat.get(cp) or self.canon.get(cp)
|
|
2198
|
+
if not m:
|
|
2199
|
+
return [cp]
|
|
2200
|
+
out = []
|
|
2201
|
+
for c in m:
|
|
2202
|
+
out.extend(self.full_compatibility(c))
|
|
2203
|
+
return out
|
|
2204
|
+
|
|
2205
|
+
def ccc_ranges(self):
|
|
2206
|
+
"""Runs of consecutive code points sharing a non-zero CCC."""
|
|
2207
|
+
out = []
|
|
2208
|
+
for cp in sorted(self.ccc):
|
|
2209
|
+
ccc = self.ccc[cp]
|
|
2210
|
+
if out and out[-1][1] == cp - 1 and out[-1][2] == ccc:
|
|
2211
|
+
out[-1] = (out[-1][0], cp, ccc)
|
|
2212
|
+
else:
|
|
2213
|
+
out.append((cp, cp, ccc))
|
|
2214
|
+
return out
|
|
2215
|
+
|
|
2216
|
+
def qc_ranges(self, form):
|
|
2217
|
+
return merge_adjacent_ranges([(cp, cp) for cp in sorted(self.qc[form])])
|
|
2218
|
+
|
|
2219
|
+
|
|
2220
|
+
def print_normalization_structs():
|
|
2221
|
+
print_template(
|
|
2222
|
+
"""
|
|
2223
|
+
/// An inclusive range of code points.
|
|
2224
|
+
struct NormRange { uint32_t first; uint32_t last; };
|
|
2225
|
+
|
|
2226
|
+
/// An inclusive range of code points sharing a canonical combining class.
|
|
2227
|
+
struct CCCRange { uint32_t first; uint32_t last; uint8_t ccc; };
|
|
2228
|
+
|
|
2229
|
+
/// A decomposition mapping. The mapped-to code points live in DECOMP_POOL16,
|
|
2230
|
+
/// or in DECOMP_POOL32 when \\c wide is set because the sequence contains a
|
|
2231
|
+
/// supplementary-plane code point. Packed into 8 bytes rather than the
|
|
2232
|
+
/// natural 12 because these are the two largest tables.
|
|
2233
|
+
struct DecompEntry {
|
|
2234
|
+
uint32_t cp : 21;
|
|
2235
|
+
uint32_t length : 5;
|
|
2236
|
+
uint32_t wide : 1;
|
|
2237
|
+
uint32_t offset;
|
|
2238
|
+
};
|
|
2239
|
+
|
|
2240
|
+
/// A canonical composition of two code points into one.
|
|
2241
|
+
struct CompEntry { uint32_t starter; uint32_t combining; uint32_t composite; };
|
|
2242
|
+
"""
|
|
2243
|
+
)
|
|
2244
|
+
|
|
2245
|
+
|
|
2246
|
+
def print_codepoint_array(name, decl, values, per_line=8):
|
|
2247
|
+
print(f"static constexpr {decl} {name}[] = {{")
|
|
2248
|
+
for chunk in batched(values, per_line): # noqa: B911 (local shim, not itertools)
|
|
2249
|
+
print(" " + " ".join(f"{as_hex(c)}," for c in chunk))
|
|
2250
|
+
print("};")
|
|
2251
|
+
print("")
|
|
2252
|
+
|
|
2253
|
+
|
|
2254
|
+
def build_decomposition_tables(norm):
|
|
2255
|
+
"""Build the decomposition entries and their shared pools.
|
|
2256
|
+
|
|
2257
|
+
Sequences that fit in the BMP go in a char16_t pool and the rest in a
|
|
2258
|
+
char32_t one; most decompositions are BMP-only, so this nearly halves the
|
|
2259
|
+
pool. Identical sequences are shared between entries and between tables.
|
|
2260
|
+
|
|
2261
|
+
\\return (canon, compat, pool16, pool32), where each entry is a tuple of
|
|
2262
|
+
(code point, pool offset, length, wide)."""
|
|
2263
|
+
pool16, pool32 = [], []
|
|
2264
|
+
pool_index = {}
|
|
2265
|
+
|
|
2266
|
+
def intern(seq):
|
|
2267
|
+
key = tuple(seq)
|
|
2268
|
+
if key not in pool_index:
|
|
2269
|
+
wide = any(cp > 0xFFFF for cp in seq)
|
|
2270
|
+
pool = pool32 if wide else pool16
|
|
2271
|
+
pool_index[key] = (len(pool), wide)
|
|
2272
|
+
pool.extend(seq)
|
|
2273
|
+
return pool_index[key]
|
|
2274
|
+
|
|
2275
|
+
def entry(cp, seq):
|
|
2276
|
+
assert len(seq) < 32, f"decomposition of {cp:04X} exceeds the 5-bit length"
|
|
2277
|
+
assert cp <= 0x10FFFF, f"code point {cp:04X} exceeds 21 bits"
|
|
2278
|
+
offset, wide = intern(seq)
|
|
2279
|
+
return (cp, offset, len(seq), 1 if wide else 0)
|
|
2280
|
+
|
|
2281
|
+
canon = [
|
|
2282
|
+
entry(cp, seq)
|
|
2283
|
+
for cp in sorted(norm.canon)
|
|
2284
|
+
for seq in [norm.full_canonical(cp)]
|
|
2285
|
+
if seq != [cp]
|
|
2286
|
+
]
|
|
2287
|
+
# A compatibility mapping is stored only when it differs from the canonical
|
|
2288
|
+
# one; getDecomposition falls back to CANON_DECOMP otherwise. That drops
|
|
2289
|
+
# roughly a third of the entries.
|
|
2290
|
+
compat = [
|
|
2291
|
+
entry(cp, seq)
|
|
2292
|
+
for cp in sorted(set(norm.canon) | set(norm.compat))
|
|
2293
|
+
for seq in [norm.full_compatibility(cp)]
|
|
2294
|
+
if seq != [cp] and seq != norm.full_canonical(cp)
|
|
2295
|
+
]
|
|
2296
|
+
return canon, compat, pool16, pool32
|
|
2297
|
+
|
|
2298
|
+
|
|
2299
|
+
def print_normalization_tables(norm):
|
|
2300
|
+
"""Emit NormalizationData.inc."""
|
|
2301
|
+
canon, compat, pool16, pool32 = build_decomposition_tables(norm)
|
|
2302
|
+
|
|
2303
|
+
print_normalization_structs()
|
|
2304
|
+
|
|
2305
|
+
for form in ("NFC", "NFD", "NFKC", "NFKD"):
|
|
2306
|
+
print(f"// Code points whose {form}_QC is No or Maybe.")
|
|
2307
|
+
print(f"static constexpr NormRange {form}_QC_NOT_YES[] = {{")
|
|
2308
|
+
for first, last in norm.qc_ranges(form):
|
|
2309
|
+
print(f" {{{as_hex(first)}, {as_hex(last)}}},")
|
|
2310
|
+
print("};")
|
|
2311
|
+
print("")
|
|
2312
|
+
|
|
2313
|
+
print("static constexpr CCCRange CCC_RANGES[] = {")
|
|
2314
|
+
for first, last, ccc in norm.ccc_ranges():
|
|
2315
|
+
print(f" {{{as_hex(first)}, {as_hex(last)}, {ccc}}},")
|
|
2316
|
+
print("};")
|
|
2317
|
+
print("")
|
|
2318
|
+
|
|
2319
|
+
print_codepoint_array("DECOMP_POOL16", "char16_t", pool16)
|
|
2320
|
+
print_codepoint_array("DECOMP_POOL32", "char32_t", pool32)
|
|
2321
|
+
|
|
2322
|
+
for name, entries in (("CANON_DECOMP", canon), ("COMPAT_DECOMP", compat)):
|
|
2323
|
+
print(f"static constexpr DecompEntry {name}[] = {{")
|
|
2324
|
+
for cp, offset, length, wide in entries:
|
|
2325
|
+
print(f" {{{as_hex(cp)}, {length}, {wide}, {offset}}},")
|
|
2326
|
+
print("};")
|
|
2327
|
+
print("")
|
|
2328
|
+
|
|
2329
|
+
print("static constexpr CompEntry CANON_COMP[] = {")
|
|
2330
|
+
for (starter, combining), composite in sorted(norm.comp.items()):
|
|
2331
|
+
print(f" {{{as_hex(starter)}, {as_hex(combining)}, {as_hex(composite)}}},")
|
|
2332
|
+
print("};")
|
|
2333
|
+
print("")
|
|
2334
|
+
|
|
2335
|
+
|
|
2336
|
+
# Emitted above any table whose rows are string literals. Such a table must be
|
|
2337
|
+
# const, not constexpr: MSVC folds certain pairs of distinct string literals in
|
|
2338
|
+
# a constexpr initializer into a single literal, so a few rows silently hold
|
|
2339
|
+
# another row's text. It reproduces on every MSVC version tested, not just the
|
|
2340
|
+
# current one. Minimal reproduction:
|
|
2341
|
+
# constexpr const char *A = "0F19 003F";
|
|
2342
|
+
# constexpr const char *B = "296F 0021";
|
|
2343
|
+
# // strcmp(A, B) == 0
|
|
2344
|
+
MSVC_CONSTEXPR_LITERAL_NOTE = """\
|
|
2345
|
+
// const, not constexpr: MSVC folds distinct string literals in a constexpr
|
|
2346
|
+
// initializer (e.g. "0F19 003F" and "296F 0021") into one, silently giving a
|
|
2347
|
+
// few rows another row's text. A const table is unaffected."""
|
|
2348
|
+
|
|
2349
|
+
|
|
2350
|
+
def print_normalization_test_data():
|
|
2351
|
+
"""Emit NormalizationTestData.inc from NormalizationTest.txt.
|
|
2352
|
+
|
|
2353
|
+
The rows are emitted as string literals in the source file's own format
|
|
2354
|
+
rather than as pre-parsed tables. That is roughly four times smaller than
|
|
2355
|
+
an equivalent array of code points, compiles far faster than hundreds of
|
|
2356
|
+
thousands of integer tokens, keeps the data greppable against the upstream
|
|
2357
|
+
file, and lets a failing test print the row verbatim. Each literal is one
|
|
2358
|
+
short row, staying well under the 65535-character limit MSVC imposes on a
|
|
2359
|
+
single string literal."""
|
|
2360
|
+
rows = []
|
|
2361
|
+
part1 = []
|
|
2362
|
+
part = 0
|
|
2363
|
+
for line in UnicodeDataFiles.get_lines("NormalizationTest.txt"):
|
|
2364
|
+
if line.startswith("@Part"):
|
|
2365
|
+
part = int(line[5])
|
|
2366
|
+
continue
|
|
2367
|
+
f = split_fields(line)
|
|
2368
|
+
if len(f) < 5 or not f[0]:
|
|
2369
|
+
continue
|
|
2370
|
+
# Keep only the five data columns, normalizing away incidental spacing
|
|
2371
|
+
# so the literals stay compact and stable across UCD releases.
|
|
2372
|
+
cols = [" ".join(c.split()) for c in f[:5]]
|
|
2373
|
+
rows.append((";".join(cols), part))
|
|
2374
|
+
if part == 1:
|
|
2375
|
+
part1.append(int(f[0].split()[0], 16))
|
|
2376
|
+
|
|
2377
|
+
print_template(
|
|
2378
|
+
"""
|
|
2379
|
+
/// One row of NormalizationTest.txt, as "c1;c2;c3;c4;c5", where each column
|
|
2380
|
+
/// is a space-separated list of hex code points. Parsed by the conformance
|
|
2381
|
+
/// test rather than pre-expanded, to keep this file small.
|
|
2382
|
+
struct NormTestRow { const char *columns; uint8_t part; };
|
|
2383
|
+
"""
|
|
2384
|
+
)
|
|
2385
|
+
|
|
2386
|
+
# clang-format splits long string literals across lines, which triples the
|
|
2387
|
+
# file size and stops the rows from matching the upstream file when
|
|
2388
|
+
# grepped. The rows below are already one per line.
|
|
2389
|
+
print("// clang-format off")
|
|
2390
|
+
print(MSVC_CONSTEXPR_LITERAL_NOTE)
|
|
2391
|
+
print("static const NormTestRow NORM_TEST_ROWS[] = {")
|
|
2392
|
+
for row, part in rows:
|
|
2393
|
+
print(f' {{"{row}", {part}}},')
|
|
2394
|
+
print("};")
|
|
2395
|
+
print("// clang-format on")
|
|
2396
|
+
print("")
|
|
2397
|
+
|
|
2398
|
+
print("// Code points listed in Part 1. Every code point NOT in this list")
|
|
2399
|
+
print("// normalizes to itself under all four forms.")
|
|
2400
|
+
print_codepoint_array("NORM_TEST_PART1", "uint32_t", sorted(part1))
|
|
2401
|
+
|
|
2402
|
+
|
|
2403
|
+
def print_properties_tables():
|
|
2404
|
+
print_categories(UnicodeDataFiles.get_lines("UnicodeData.txt"))
|
|
2405
|
+
print_properties(UnicodeDataFiles.get_lines("PropList.txt"))
|
|
2406
|
+
|
|
2407
|
+
unicode_properties = UnicodeProperties()
|
|
2408
|
+
unicode_properties.gather_general_category_properties()
|
|
2409
|
+
unicode_properties.gather_binary_properties()
|
|
2410
|
+
unicode_properties.gather_script_properties()
|
|
2411
|
+
unicode_properties.print_template()
|
|
2412
|
+
# Show information about bit sizes for the string and range pools.
|
|
2413
|
+
# unicode_properties.log_metrics()
|
|
2414
|
+
|
|
2415
|
+
casemap = CaseMap(
|
|
2416
|
+
unicode_data_lines=UnicodeDataFiles.get_lines("UnicodeData.txt"),
|
|
2417
|
+
special_casing_lines=UnicodeDataFiles.get_lines("SpecialCasing.txt"),
|
|
2418
|
+
casefolding_lines=UnicodeDataFiles.get_lines("CaseFolding.txt"),
|
|
2419
|
+
)
|
|
2420
|
+
print_canonicalizations(casemap, unicode=True)
|
|
2421
|
+
print_canonicalizations(casemap, unicode=False)
|
|
2422
|
+
|
|
2423
|
+
|
|
2424
|
+
if __name__ == "__main__":
|
|
2425
|
+
parser = argparse.ArgumentParser(
|
|
2426
|
+
description="Generate Unicode tables for the Hermes VM."
|
|
2427
|
+
)
|
|
2428
|
+
parser.add_argument(
|
|
2429
|
+
"--table",
|
|
2430
|
+
choices=(
|
|
2431
|
+
"properties",
|
|
2432
|
+
"normalization",
|
|
2433
|
+
"normtest",
|
|
2434
|
+
"casing",
|
|
2435
|
+
"casetest",
|
|
2436
|
+
"collation",
|
|
2437
|
+
"collationtest",
|
|
2438
|
+
),
|
|
2439
|
+
default="properties",
|
|
2440
|
+
help="which generated file to emit (default: properties)",
|
|
2441
|
+
)
|
|
2442
|
+
args = parser.parse_args()
|
|
2443
|
+
|
|
2444
|
+
if args.table == "properties":
|
|
2445
|
+
print_header(PROPERTIES_FILES)
|
|
2446
|
+
print_properties_tables()
|
|
2447
|
+
elif args.table == "normalization":
|
|
2448
|
+
print_header(NORMALIZATION_FILES, structs=False)
|
|
2449
|
+
print_normalization_tables(
|
|
2450
|
+
NormalizationData(
|
|
2451
|
+
UnicodeDataFiles.get_lines("UnicodeData.txt"),
|
|
2452
|
+
UnicodeDataFiles.get_lines("DerivedNormalizationProps.txt"),
|
|
2453
|
+
)
|
|
2454
|
+
)
|
|
2455
|
+
elif args.table == "casing":
|
|
2456
|
+
print_header(CASING_FILES, structs=False)
|
|
2457
|
+
derived = UnicodeDataFiles.get_lines("DerivedCoreProperties.txt")
|
|
2458
|
+
print_case_tables(
|
|
2459
|
+
FullCaseData(
|
|
2460
|
+
UnicodeDataFiles.get_lines("UnicodeData.txt"),
|
|
2461
|
+
UnicodeDataFiles.get_lines("SpecialCasing.txt"),
|
|
2462
|
+
),
|
|
2463
|
+
binary_property_ranges(derived, "Cased"),
|
|
2464
|
+
binary_property_ranges(derived, "Case_Ignorable"),
|
|
2465
|
+
binary_property_ranges(
|
|
2466
|
+
UnicodeDataFiles.get_lines("PropList.txt"), "Soft_Dotted"
|
|
2467
|
+
),
|
|
2468
|
+
)
|
|
2469
|
+
elif args.table == "casetest":
|
|
2470
|
+
print_header(CASETEST_FILES, structs=False)
|
|
2471
|
+
print_case_test_data(
|
|
2472
|
+
FullCaseData(
|
|
2473
|
+
UnicodeDataFiles.get_lines("UnicodeData.txt"),
|
|
2474
|
+
UnicodeDataFiles.get_lines("SpecialCasing.txt"),
|
|
2475
|
+
)
|
|
2476
|
+
)
|
|
2477
|
+
elif args.table == "collation":
|
|
2478
|
+
print_header(COLLATION_FILES, structs=False)
|
|
2479
|
+
single, multi, contractions, implicit = parse_allkeys(
|
|
2480
|
+
UnicodeDataFiles.get_lines("allkeys.txt")
|
|
2481
|
+
)
|
|
2482
|
+
print_collation_tables(
|
|
2483
|
+
single,
|
|
2484
|
+
multi,
|
|
2485
|
+
contractions,
|
|
2486
|
+
implicit,
|
|
2487
|
+
canonically_decomposable(UnicodeDataFiles.get_lines("UnicodeData.txt")),
|
|
2488
|
+
binary_property_ranges(
|
|
2489
|
+
UnicodeDataFiles.get_lines("PropList.txt"), "Unified_Ideograph"
|
|
2490
|
+
),
|
|
2491
|
+
)
|
|
2492
|
+
elif args.table == "normtest":
|
|
2493
|
+
print_header(NORMTEST_FILES, structs=False)
|
|
2494
|
+
print_normalization_test_data()
|
|
2495
|
+
elif args.table == "collationtest":
|
|
2496
|
+
print_header(COLLATIONTEST_FILES, structs=False)
|
|
2497
|
+
single, _, _, _ = parse_allkeys(UnicodeDataFiles.get_lines("allkeys.txt"))
|
|
2498
|
+
print_collation_test_data(
|
|
2499
|
+
single,
|
|
2500
|
+
canonically_decomposable(UnicodeDataFiles.get_lines("UnicodeData.txt")),
|
|
2501
|
+
)
|
|
2502
|
+
else:
|
|
2503
|
+
raise AssertionError(f"unhandled --table {args.table}")
|