forked from unicode-rs/unicode-width
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunicode.py
More file actions
executable file
·2249 lines (1901 loc) · 79.9 KB
/
unicode.py
File metadata and controls
executable file
·2249 lines (1901 loc) · 79.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#
# Copyright 2011-2025 The Rust Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution and at
# http://rust-lang.org/COPYRIGHT.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
# option. This file may not be copied, modified, or distributed
# except according to those terms.
# This script uses the following Unicode tables:
#
# - DerivedCoreProperties.txt
# - EastAsianWidth.txt
# - HangulSyllableType.txt
# - LineBreak.txt
# - NormalizationTest.txt (for tests only)
# - PropList.txt
# - ReadMe.txt
# - UnicodeData.txt
# - auxiliary/GraphemeBreakProperty.txt
# - emoji/emoji-data.txt
# - emoji/emoji-test.txt (for tests only)
# - emoji/emoji-variation-sequences.txt
# - extracted/DerivedCombiningClass.txt
# - extracted/DerivedGeneralCategory.txt
# - extracted/DerivedJoiningGroup.txt
# - extracted/DerivedJoiningType.txt
#
# Since this should not require frequent updates, we just store this
# out-of-line and check the generated module into git.
import enum
import math
import operator
import os
import re
import sys
import urllib.request
from collections import defaultdict
from itertools import batched
from typing import Callable, Iterable
UNICODE_VERSION = "17.0.0"
"""The version of the Unicode data files to download."""
NUM_CODEPOINTS = 0x110000
"""An upper bound for which `range(0, NUM_CODEPOINTS)` contains Unicode's codespace."""
MAX_CODEPOINT_BITS = math.ceil(math.log2(NUM_CODEPOINTS - 1))
"""The maximum number of bits required to represent a Unicode codepoint."""
class OffsetType(enum.IntEnum):
"""Represents the data type of a lookup table's offsets. Each variant's value represents the
number of bits required to represent that variant's type."""
U2 = 2
"""Offsets are 2-bit unsigned integers, packed four-per-byte."""
U4 = 4
"""Offsets are 4-bit unsigned integers, packed two-per-byte."""
U8 = 8
"""Each offset is a single byte (u8)."""
MODULE_PATH = "../src/tables.rs"
"""The path of the emitted Rust module (relative to the working directory)"""
TABLE_SPLITS = [7, 13]
"""The splits between the bits of the codepoint used to index each subtable.
Adjust these values to change the sizes of the subtables"""
Codepoint = int
BitPos = int
def fetch_open(filename: str, local_prefix: str = "", emoji: bool = False):
"""Opens `filename` and return its corresponding file object. If `filename` isn't on disk,
fetches it from `https://www.unicode.org/Public/`. Exits with code 1 on failure.
"""
basename = os.path.basename(filename)
localname = os.path.join(local_prefix, basename)
if not os.path.exists(localname):
if emoji:
prefix = "emoji"
else:
prefix = "ucd"
urllib.request.urlretrieve(
f"https://www.unicode.org/Public/{UNICODE_VERSION}/{prefix}/{filename}",
localname,
)
try:
return open(localname, encoding="utf-8")
except OSError:
sys.stderr.write(f"cannot load {localname}")
sys.exit(1)
def load_unicode_version() -> tuple[int, int, int]:
"""Returns the current Unicode version by fetching and processing `ReadMe.txt`."""
with fetch_open("ReadMe.txt") as readme:
pattern = r"for Version (\d+)\.(\d+)\.(\d+) of the Unicode"
return tuple(map(int, re.search(pattern, readme.read()).groups())) # type: ignore
def load_property(filename: str, pattern: str, action: Callable[[int], None]):
with fetch_open(filename) as properties:
single = re.compile(rf"^([0-9A-F]+)\s*;\s*{pattern}\s+")
multiple = re.compile(rf"^([0-9A-F]+)\.\.([0-9A-F]+)\s*;\s*{pattern}\s+")
for line in properties.readlines():
raw_data = None # (low, high)
if match := single.match(line):
raw_data = (match.group(1), match.group(1))
elif match := multiple.match(line):
raw_data = (match.group(1), match.group(2))
else:
continue
low = int(raw_data[0], 16)
high = int(raw_data[1], 16)
for cp in range(low, high + 1):
action(cp)
def to_sorted_ranges(iter: Iterable[Codepoint]) -> list[tuple[Codepoint, Codepoint]]:
"Creates a sorted list of ranges from an iterable of codepoints"
lst = [c for c in iter]
lst.sort()
ret = []
for cp in lst:
if len(ret) > 0 and ret[-1][1] == cp - 1:
ret[-1] = (ret[-1][0], cp)
else:
ret.append((cp, cp))
return ret
class EastAsianWidth(enum.IntEnum):
"""Represents the width of a Unicode character according to UAX 16.
All East Asian Width classes resolve into either
`EffectiveWidth.NARROW`, `EffectiveWidth.WIDE`, or `EffectiveWidth.AMBIGUOUS`.
"""
NARROW = 1
""" One column wide. """
WIDE = 2
""" Two columns wide. """
AMBIGUOUS = 3
""" Two columns wide in a CJK context. One column wide in all other contexts. """
class CharWidthInTable(enum.IntEnum):
"""Represents the width of a Unicode character
as stored in the tables."""
ZERO = 0
ONE = 1
TWO = 2
SPECIAL = 3
class WidthState(enum.IntEnum):
"""
Width calculation proceeds according to a state machine.
We iterate over the characters of the string from back to front;
the next character encountered determines the transition to take.
The integer values of these variants have special meaning:
- Top bit: whether this is Vs16
- 2nd from top: whether this is Vs15
- 3rd bit from top: whether this is transparent to emoji/text presentation
(if set, should also set 4th)
- 4th bit: whether to set top bit on emoji presentation.
If this is set but 3rd is not, the width mode is related to zwj sequences
- 5th from top: whether this is unaffected by ligature-transparent
(if set, should also set 3rd and 4th)
- 6th bit: if 4th is set but this one is not, then this is a ZWJ ligature state
where no ZWJ has been encountered yet; encountering one flips this on
- Seventh bit:
- CJK mode: is VS1 or VS3
- Not CJK: is VS2
"""
# BASIC WIDTHS
ZERO = 0x1_0000
"Zero columns wide."
NARROW = 0x1_0001
"One column wide."
WIDE = 0x1_0002
"Two columns wide."
THREE = 0x1_0003
"Three columns wide."
# \r\n
LINE_FEED = 0b0000_0000_0000_0001
"\\n (CRLF has width 1)"
# EMOJI
# Emoji skintone modifiers
EMOJI_MODIFIER = 0b0000_0000_0000_0010
"`Emoji_Modifier`"
# Emoji ZWJ sequences
REGIONAL_INDICATOR = 0b0000_0000_0000_0011
"`Regional_Indicator`"
SEVERAL_REGIONAL_INDICATOR = 0b0000_0000_0000_0100
"At least two `Regional_Indicator`in sequence"
EMOJI_PRESENTATION = 0b0000_0000_0000_0101
"`Emoji_Presentation`"
ZWJ_EMOJI_PRESENTATION = 0b0001_0000_0000_0110
"\\u200D `Emoji_Presentation`"
VS16_ZWJ_EMOJI_PRESENTATION = 0b1001_0000_0000_0110
"\\uFE0F \\u200D `Emoji_Presentation`"
KEYCAP_ZWJ_EMOJI_PRESENTATION = 0b0001_0000_0000_0111
"\\u20E3 \\u200D `Emoji_Presentation`"
VS16_KEYCAP_ZWJ_EMOJI_PRESENTATION = 0b1001_0000_0000_0111
"\\uFE0F \\u20E3 \\u200D `Emoji_Presentation`"
REGIONAL_INDICATOR_ZWJ_PRESENTATION = 0b0000_0000_0000_1001
"`Regional_Indicator` \\u200D `Emoji_Presentation`"
EVEN_REGIONAL_INDICATOR_ZWJ_PRESENTATION = 0b0000_0000_0000_1010
"(`Regional_Indicator` `Regional_Indicator`)+ \\u200D `Emoji_Presentation`"
ODD_REGIONAL_INDICATOR_ZWJ_PRESENTATION = 0b0000_0000_0000_1011
"(`Regional_Indicator` `Regional_Indicator`)+ `Regional_Indicator` \\u200D `Emoji_Presentation`"
TAG_END_ZWJ_EMOJI_PRESENTATION = 0b0000_0000_0001_0000
"\\uE007F \\u200D `Emoji_Presentation`"
TAG_D1_END_ZWJ_EMOJI_PRESENTATION = 0b0000_0000_0001_0001
"\\uE0030..=\\uE0039 \\uE007F \\u200D `Emoji_Presentation`"
TAG_D2_END_ZWJ_EMOJI_PRESENTATION = 0b0000_0000_0001_0010
"(\\uE0030..=\\uE0039){2} \\uE007F \\u200D `Emoji_Presentation`"
TAG_D3_END_ZWJ_EMOJI_PRESENTATION = 0b0000_0000_0001_0011
"(\\uE0030..=\\uE0039){3} \\uE007F \\u200D `Emoji_Presentation`"
TAG_A1_END_ZWJ_EMOJI_PRESENTATION = 0b0000_0000_0001_1001
"\\uE0061..=\\uE007A \\uE007F \\u200D `Emoji_Presentation`"
TAG_A2_END_ZWJ_EMOJI_PRESENTATION = 0b0000_0000_0001_1010
"(\\uE0061..=\\uE007A){2} \\uE007F \\u200D `Emoji_Presentation`"
TAG_A3_END_ZWJ_EMOJI_PRESENTATION = 0b0000_0000_0001_1011
"(\\uE0061..=\\uE007A){3} \\uE007F \\u200D `Emoji_Presentation`"
TAG_A4_END_ZWJ_EMOJI_PRESENTATION = 0b0000_0000_0001_1100
"(\\uE0061..=\\uE007A){4} \\uE007F \\u200D `Emoji_Presentation`"
TAG_A5_END_ZWJ_EMOJI_PRESENTATION = 0b0000_0000_0001_1101
"(\\uE0061..=\\uE007A){35} \\uE007F \\u200D `Emoji_Presentation`"
TAG_A6_END_ZWJ_EMOJI_PRESENTATION = 0b0000_0000_0001_1110
"(\\uE0061..=\\uE007A){6} \\uE007F \\u200D `Emoji_Presentation`"
# Kirat Rai
KIRAT_RAI_VOWEL_SIGN_E = 0b0000_0000_0010_0000
"\\u16D67 (\\u16D67 \\u16D67)+ and canonical equivalents"
KIRAT_RAI_VOWEL_SIGN_AI = 0b0000_0000_0010_0001
"(\\u16D68)+ and canonical equivalents"
# VARIATION SELECTORS
VARIATION_SELECTOR_1_2_OR_3 = 0b0000_0010_0000_0000
"\\uFE00 or \\uFE02 if CJK, or \\uFE01 otherwise"
# Text presentation sequences (not CJK)
VARIATION_SELECTOR_15 = 0b0100_0000_0000_0000
"\\uFE0E (text presentation sequences)"
# Emoji presentation sequences
VARIATION_SELECTOR_16 = 0b1000_0000_0000_0000
"\\uFE0F (emoji presentation sequences)"
# ARABIC LAM ALEF
JOINING_GROUP_ALEF = 0b0011_0000_1111_1111
"Joining_Group=Alef (Arabic Lam-Alef ligature)"
# COMBINING SOLIDUS (CJK only)
COMBINING_LONG_SOLIDUS_OVERLAY = 0b0011_1100_1111_1111
"\\u0338 (CJK only, makes <, =, > width 2)"
# SOLIDUS + ALEF (solidus is Joining_Type=Transparent)
SOLIDUS_OVERLAY_ALEF = 0b0011_1000_1111_1111
"\\u0338 followed by Joining_Group=Alef"
# SCRIPT ZWJ LIGATURES
# Hebrew alef lamed
HEBREW_LETTER_LAMED = 0b0011_1000_0000_0000
"\\u05DC (Alef-ZWJ-Lamed ligature)"
ZWJ_HEBREW_LETTER_LAMED = 0b0011_1100_0000_0000
"\\u200D\\u05DC (Alef-ZWJ-Lamed ligature)"
# Buginese <a -i> ya
BUGINESE_LETTER_YA = 0b0011_1000_0000_0001
"\\u1A10 (<a, -i> + ya ligature)"
ZWJ_BUGINESE_LETTER_YA = 0b0011_1100_0000_0001
"\\u200D\\u1A10 (<a, -i> + ya ligature)"
BUGINESE_VOWEL_SIGN_I_ZWJ_LETTER_YA = 0b0011_1100_0000_0010
"\\u1A17\\u200D\\u1A10 (<a, -i> + ya ligature)"
# Tifinagh bi-consonants
TIFINAGH_CONSONANT = 0b0011_1000_0000_0011
"\\u2D31..=\\u2D65 or \\u2D6F (joined by ZWJ or \\u2D7F TIFINAGH CONSONANT JOINER)"
ZWJ_TIFINAGH_CONSONANT = 0b0011_1100_0000_0011
"ZWJ then \\u2D31..=\\u2D65 or \\u2D6F"
TIFINAGH_JOINER_CONSONANT = 0b0011_1100_0000_0100
"\\u2D7F then \\u2D31..=\\u2D65 or \\u2D6F"
# Lisu tone letters
LISU_TONE_LETTER_MYA_NA_JEU = 0b0011_1100_0000_0101
"\\uA4FC or \\uA4FD (https://www.unicode.org/versions/Unicode15.0.0/ch18.pdf#G42078)"
# Old Turkic orkhon ec - orkhon i
OLD_TURKIC_LETTER_ORKHON_I = 0b0011_1000_0000_0110
"\\u10C03 (ORKHON EC-ZWJ-ORKHON I ligature)"
ZWJ_OLD_TURKIC_LETTER_ORKHON_I = 0b0011_1100_0000_0110
"\\u10C03 (ORKHON EC-ZWJ-ORKHON I ligature)"
# Khmer coeng signs
KHMER_COENG_ELIGIBLE_LETTER = 0b0011_1100_0000_0111
"\\u1780..=\\u17A2 | \\u17A7 | \\u17AB | \\u17AC | \\u17AF"
def table_width(self) -> CharWidthInTable:
"The width of a character as stored in the lookup tables."
match self:
case WidthState.ZERO:
return CharWidthInTable.ZERO
case WidthState.NARROW:
return CharWidthInTable.ONE
case WidthState.WIDE:
return CharWidthInTable.TWO
case _:
return CharWidthInTable.SPECIAL
def is_carried(self) -> bool:
"Whether this corresponds to a non-default `WidthInfo`."
return int(self) <= 0xFFFF
def width_alone(self) -> int:
"The width of a character with this type when it appears alone."
match self:
case (
WidthState.ZERO
| WidthState.COMBINING_LONG_SOLIDUS_OVERLAY
| WidthState.VARIATION_SELECTOR_15
| WidthState.VARIATION_SELECTOR_16
| WidthState.VARIATION_SELECTOR_1_2_OR_3
):
return 0
case (
WidthState.WIDE
| WidthState.EMOJI_MODIFIER
| WidthState.EMOJI_PRESENTATION
):
return 2
case WidthState.THREE:
return 3
case _:
return 1
def is_cjk_only(self) -> bool:
return self in [
WidthState.COMBINING_LONG_SOLIDUS_OVERLAY,
WidthState.SOLIDUS_OVERLAY_ALEF,
]
def is_non_cjk_only(self) -> bool:
return self == WidthState.VARIATION_SELECTOR_15
assert len(set([v.value for v in WidthState])) == len([v.value for v in WidthState])
def load_east_asian_widths() -> list[EastAsianWidth]:
"""Return a list of effective widths, indexed by codepoint.
Widths are determined by fetching and parsing `EastAsianWidth.txt`.
`Neutral`, `Narrow`, and `Halfwidth` characters are assigned `EffectiveWidth.NARROW`.
`Wide` and `Fullwidth` characters are assigned `EffectiveWidth.WIDE`.
`Ambiguous` characters are assigned `EffectiveWidth.AMBIGUOUS`."""
with fetch_open("EastAsianWidth.txt") as eaw:
# matches a width assignment for a single codepoint, i.e. "1F336;N # ..."
single = re.compile(r"^([0-9A-F]+)\s*;\s*(\w+) +# (\w+)")
# matches a width assignment for a range of codepoints, i.e. "3001..3003;W # ..."
multiple = re.compile(r"^([0-9A-F]+)\.\.([0-9A-F]+)\s*;\s*(\w+) +# (\w+)")
# map between width category code and condensed width
width_codes = {
**{c: EastAsianWidth.NARROW for c in ["N", "Na", "H"]},
**{c: EastAsianWidth.WIDE for c in ["W", "F"]},
"A": EastAsianWidth.AMBIGUOUS,
}
width_map = []
current = 0
for line in eaw.readlines():
raw_data = None # (low, high, width)
if match := single.match(line):
raw_data = (match.group(1), match.group(1), match.group(2))
elif match := multiple.match(line):
raw_data = (match.group(1), match.group(2), match.group(3))
else:
continue
low = int(raw_data[0], 16)
high = int(raw_data[1], 16)
width = width_codes[raw_data[2]]
assert current <= high
while current <= high:
# Some codepoints don't fall into any of the ranges in EastAsianWidth.txt.
# All such codepoints are implicitly given Neural width (resolves to narrow)
width_map.append(EastAsianWidth.NARROW if current < low else width)
current += 1
while len(width_map) < NUM_CODEPOINTS:
# Catch any leftover codepoints and assign them implicit Neutral/narrow width.
width_map.append(EastAsianWidth.NARROW)
# Characters with ambiguous line breaking are ambiguous
load_property(
"LineBreak.txt",
"AI",
lambda cp: (operator.setitem(width_map, cp, EastAsianWidth.AMBIGUOUS)),
)
# Ambiguous `Letter`s and `Modifier_Symbol`s are narrow
load_property(
"extracted/DerivedGeneralCategory.txt",
r"(:?Lu|Ll|Lt|Lm|Lo|Sk)",
lambda cp: (
operator.setitem(width_map, cp, EastAsianWidth.NARROW)
if width_map[cp] == EastAsianWidth.AMBIGUOUS
else None
),
)
# GREEK ANO TELEIA: NFC decomposes to U+00B7 MIDDLE DOT
width_map[0x0387] = EastAsianWidth.AMBIGUOUS
# Canonical equivalence for symbols with stroke
with fetch_open("UnicodeData.txt") as udata:
single = re.compile(r"([0-9A-Z]+);.*?;.*?;.*?;.*?;([0-9A-Z]+) 0338;")
for line in udata.readlines():
if match := single.match(line):
composed = int(match.group(1), 16)
decomposed = int(match.group(2), 16)
if width_map[decomposed] == EastAsianWidth.AMBIGUOUS:
width_map[composed] = EastAsianWidth.AMBIGUOUS
return width_map
def load_zero_widths() -> list[bool]:
"""Returns a list `l` where `l[c]` is true if codepoint `c` is considered a zero-width
character. `c` is considered a zero-width character if
- it has the `Default_Ignorable_Code_Point` property (determined from `DerivedCoreProperties.txt`),
- or if it has the `Grapheme_Extend` property (determined from `DerivedCoreProperties.txt`),
- or if it one of eight characters that should be `Grapheme_Extend` but aren't due to a Unicode spec bug,
- or if it has a `Hangul_Syllable_Type` of `Vowel_Jamo` or `Trailing_Jamo` (determined from `HangulSyllableType.txt`).
"""
zw_map = [False] * NUM_CODEPOINTS
# `Default_Ignorable_Code_Point`s also have 0 width:
# https://www.unicode.org/faq/unsup_char.html#3
# https://www.unicode.org/versions/Unicode15.1.0/ch05.pdf#G40095
#
# `Grapheme_Extend` includes characters with general category `Mn` or `Me`,
# as well as a few `Mc` characters that need to be included so that
# canonically equivalent sequences have the same width.
load_property(
"DerivedCoreProperties.txt",
r"(?:Default_Ignorable_Code_Point|Grapheme_Extend)",
lambda cp: operator.setitem(zw_map, cp, True),
)
# Treat `Hangul_Syllable_Type`s of `Vowel_Jamo` and `Trailing_Jamo`
# as zero-width. This matches the behavior of glibc `wcwidth`.
#
# Decomposed Hangul characters consist of 3 parts: a `Leading_Jamo`,
# a `Vowel_Jamo`, and an optional `Trailing_Jamo`. Together these combine
# into a single wide grapheme. So we treat vowel and trailing jamo as
# 0-width, such that only the width of the leading jamo is counted
# and the resulting grapheme has width 2.
#
# (See the Unicode Standard sections 3.12 and 18.6 for more on Hangul)
load_property(
"HangulSyllableType.txt",
r"(?:V|T)",
lambda cp: operator.setitem(zw_map, cp, True),
)
# Syriac abbreviation mark:
# Zero-width `Prepended_Concatenation_Mark`
zw_map[0x070F] = True
# Some Arabic Prepended_Concatenation_Mark`s
# https://www.unicode.org/versions/Unicode15.0.0/ch09.pdf#G27820
zw_map[0x0605] = True
zw_map[0x0890] = True
zw_map[0x0891] = True
zw_map[0x08E2] = True
# `[:Grapheme_Cluster_Break=Prepend:]-[:Prepended_Concatenation_Mark:]`
gcb_prepend = set()
load_property(
"auxiliary/GraphemeBreakProperty.txt",
"Prepend",
lambda cp: gcb_prepend.add(cp),
)
load_property(
"PropList.txt",
"Prepended_Concatenation_Mark",
lambda cp: gcb_prepend.remove(cp),
)
for cp in gcb_prepend:
zw_map[cp] = True
# HANGUL CHOSEONG FILLER
# U+115F is a `Default_Ignorable_Code_Point`, and therefore would normally have
# zero width. However, the expected usage is to combine it with vowel or trailing jamo
# (which are considered 0-width on their own) to form a composed Hangul syllable with
# width 2. Therefore, we treat it as having width 2.
zw_map[0x115F] = False
# TIFINAGH CONSONANT JOINER
# (invisible only when used to join two Tifinagh consonants
zw_map[0x2D7F] = False
# DEVANAGARI CARET
# https://www.unicode.org/versions/Unicode15.0.0/ch12.pdf#G667447
zw_map[0xA8FA] = True
return zw_map
def load_width_maps() -> tuple[list[WidthState], list[WidthState]]:
"""Load complete width table, including characters needing special handling.
(Returns 2 tables, one for East Asian and one for not.)"""
eaws = load_east_asian_widths()
zws = load_zero_widths()
not_ea = []
ea = []
for eaw, zw in zip(eaws, zws):
if zw:
not_ea.append(WidthState.ZERO)
ea.append(WidthState.ZERO)
else:
if eaw == EastAsianWidth.WIDE:
not_ea.append(WidthState.WIDE)
else:
not_ea.append(WidthState.NARROW)
if eaw == EastAsianWidth.NARROW:
ea.append(WidthState.NARROW)
else:
ea.append(WidthState.WIDE)
# Joining_Group=Alef (Arabic Lam-Alef ligature)
alef_joining = []
load_property(
"extracted/DerivedJoiningGroup.txt",
"Alef",
lambda cp: alef_joining.append(cp),
)
# Regional indicators
regional_indicators = []
load_property(
"PropList.txt",
"Regional_Indicator",
lambda cp: regional_indicators.append(cp),
)
# Emoji modifiers
emoji_modifiers = []
load_property(
"emoji/emoji-data.txt",
"Emoji_Modifier",
lambda cp: emoji_modifiers.append(cp),
)
# Default emoji presentation (for ZWJ sequences)
emoji_presentation = []
load_property(
"emoji/emoji-data.txt",
"Emoji_Presentation",
lambda cp: emoji_presentation.append(cp),
)
for cps, width in [
([0x0A], WidthState.LINE_FEED),
([0x05DC], WidthState.HEBREW_LETTER_LAMED),
(alef_joining, WidthState.JOINING_GROUP_ALEF),
(range(0x1780, 0x1783), WidthState.KHMER_COENG_ELIGIBLE_LETTER),
(range(0x1784, 0x1788), WidthState.KHMER_COENG_ELIGIBLE_LETTER),
(range(0x1789, 0x178D), WidthState.KHMER_COENG_ELIGIBLE_LETTER),
(range(0x178E, 0x1794), WidthState.KHMER_COENG_ELIGIBLE_LETTER),
(range(0x1795, 0x1799), WidthState.KHMER_COENG_ELIGIBLE_LETTER),
(range(0x179B, 0x179E), WidthState.KHMER_COENG_ELIGIBLE_LETTER),
(
[0x17A0, 0x17A2, 0x17A7, 0x17AB, 0x17AC, 0x17AF],
WidthState.KHMER_COENG_ELIGIBLE_LETTER,
),
([0x17A4], WidthState.WIDE),
([0x17D8], WidthState.THREE),
([0x1A10], WidthState.BUGINESE_LETTER_YA),
(range(0x2D31, 0x2D66), WidthState.TIFINAGH_CONSONANT),
([0x2D6F], WidthState.TIFINAGH_CONSONANT),
([0xA4FC], WidthState.LISU_TONE_LETTER_MYA_NA_JEU),
([0xA4FD], WidthState.LISU_TONE_LETTER_MYA_NA_JEU),
([0xFE0F], WidthState.VARIATION_SELECTOR_16),
([0x10C03], WidthState.OLD_TURKIC_LETTER_ORKHON_I),
([0x16D67], WidthState.KIRAT_RAI_VOWEL_SIGN_E),
([0x16D68], WidthState.KIRAT_RAI_VOWEL_SIGN_AI),
(emoji_presentation, WidthState.EMOJI_PRESENTATION),
(emoji_modifiers, WidthState.EMOJI_MODIFIER),
(regional_indicators, WidthState.REGIONAL_INDICATOR),
]:
for cp in cps:
not_ea[cp] = width
ea[cp] = width
# East-Asian only
ea[0x0338] = WidthState.COMBINING_LONG_SOLIDUS_OVERLAY
ea[0xFE00] = WidthState.VARIATION_SELECTOR_1_2_OR_3
ea[0xFE02] = WidthState.VARIATION_SELECTOR_1_2_OR_3
# Not East Asian only
not_ea[0xFE01] = WidthState.VARIATION_SELECTOR_1_2_OR_3
not_ea[0xFE0E] = WidthState.VARIATION_SELECTOR_15
return (not_ea, ea)
def load_joining_group_lam() -> list[tuple[Codepoint, Codepoint]]:
"Returns a list of character ranges with Joining_Group=Lam"
lam_joining = []
load_property(
"extracted/DerivedJoiningGroup.txt",
"Lam",
lambda cp: lam_joining.append(cp),
)
return to_sorted_ranges(lam_joining)
def load_non_transparent_zero_widths(
width_map: list[WidthState],
) -> list[tuple[Codepoint, Codepoint]]:
"Returns a list of characters with zero width but not 'Joining_Type=Transparent'"
zero_widths = set()
for cp, width in enumerate(width_map):
if width.width_alone() == 0:
zero_widths.add(cp)
transparent = set()
load_property(
"extracted/DerivedJoiningType.txt",
"T",
lambda cp: transparent.add(cp),
)
return to_sorted_ranges(zero_widths - transparent)
def load_ligature_transparent() -> list[tuple[Codepoint, Codepoint]]:
"""Returns a list of character ranges corresponding to all combining marks that are also
`Default_Ignorable_Code_Point`s, plus ZWJ. This is the set of characters that won't interrupt
a ligature."""
default_ignorables = set()
load_property(
"DerivedCoreProperties.txt",
"Default_Ignorable_Code_Point",
lambda cp: default_ignorables.add(cp),
)
combining_marks = set()
load_property(
"extracted/DerivedGeneralCategory.txt",
"(?:Mc|Mn|Me)",
lambda cp: combining_marks.add(cp),
)
default_ignorable_combinings = default_ignorables.intersection(combining_marks)
default_ignorable_combinings.add(0x200D) # ZWJ
return to_sorted_ranges(default_ignorable_combinings)
def load_solidus_transparent(
ligature_transparents: list[tuple[Codepoint, Codepoint]],
cjk_width_map: list[WidthState],
) -> list[tuple[Codepoint, Codepoint]]:
"""Characters expanding to a canonical combining class above 1, plus `ligature_transparent`s from above.
Ranges matching ones in `ligature_transparent` exactly are excluded (for compression), so it needs to be checked also.
"""
ccc_above_1 = set()
load_property(
"extracted/DerivedCombiningClass.txt",
"(?:[2-9]|(?:[1-9][0-9]+))",
lambda cp: ccc_above_1.add(cp),
)
for lo, hi in ligature_transparents:
for cp in range(lo, hi + 1):
ccc_above_1.add(cp)
num_chars = len(ccc_above_1)
# Recursive decompositions
while True:
with fetch_open("UnicodeData.txt") as udata:
single = re.compile(r"([0-9A-Z]+);.*?;.*?;.*?;.*?;([0-9A-F ]+);")
for line in udata.readlines():
if match := single.match(line):
composed = int(match.group(1), 16)
decomposed = [int(c, 16) for c in match.group(2).split(" ")]
if all([c in ccc_above_1 for c in decomposed]):
ccc_above_1.add(composed)
if len(ccc_above_1) == num_chars:
break
else:
num_chars = len(ccc_above_1)
for cp in ccc_above_1:
if cp not in [0xFE00, 0xFE02, 0xFE0F]:
assert (
cjk_width_map[cp].table_width() != CharWidthInTable.SPECIAL
), f"U+{cp:X}"
sorted = to_sorted_ranges(ccc_above_1)
return list(filter(lambda range: range not in ligature_transparents, sorted))
def load_normalization_tests() -> list[tuple[str, str, str, str, str]]:
def parse_codepoints(cps: str) -> str:
return "".join(map(lambda cp: chr(int(cp, 16)), cps.split(" ")))
with fetch_open("NormalizationTest.txt") as normtests:
ret = []
single = re.compile(
r"^([0-9A-F ]+);([0-9A-F ]+);([0-9A-F ]+);([0-9A-F ]+);([0-9A-F ]+);"
)
for line in normtests.readlines():
if match := single.match(line):
ret.append(
(
parse_codepoints(match.group(1)),
parse_codepoints(match.group(2)),
parse_codepoints(match.group(3)),
parse_codepoints(match.group(4)),
parse_codepoints(match.group(5)),
)
)
return ret
def make_special_ranges(
width_map: list[WidthState],
) -> list[tuple[tuple[Codepoint, Codepoint], WidthState]]:
"Assign ranges of characters to their special behavior (used in match)"
ret = []
can_merge_with_prev = False
for cp, width in enumerate(width_map):
if width == WidthState.EMOJI_PRESENTATION:
can_merge_with_prev = False
elif width.table_width() == CharWidthInTable.SPECIAL:
if can_merge_with_prev and ret[-1][1] == width:
ret[-1] = ((ret[-1][0][0], cp), width)
else:
ret.append(((cp, cp), width))
can_merge_with_prev = True
return ret
class Bucket:
"""A bucket contains a group of codepoints and an ordered width list. If one bucket's width
list overlaps with another's width list, those buckets can be merged via `try_extend`.
"""
def __init__(self):
"""Creates an empty bucket."""
self.entry_set = set()
self.widths = []
def append(self, codepoint: Codepoint, width: CharWidthInTable):
"""Adds a codepoint/width pair to the bucket, and appends `width` to the width list."""
self.entry_set.add((codepoint, width))
self.widths.append(width)
def try_extend(self, attempt: "Bucket") -> bool:
"""If either `self` or `attempt`'s width list starts with the other bucket's width list,
set `self`'s width list to the longer of the two, add all of `attempt`'s codepoints
into `self`, and return `True`. Otherwise, return `False`."""
(less, more) = (self.widths, attempt.widths)
if len(self.widths) > len(attempt.widths):
(less, more) = (attempt.widths, self.widths)
if less != more[: len(less)]:
return False
self.entry_set |= attempt.entry_set
self.widths = more
return True
def entries(self) -> list[tuple[Codepoint, CharWidthInTable]]:
"""Return a list of the codepoint/width pairs in this bucket, sorted by codepoint."""
result = list(self.entry_set)
result.sort()
return result
def width(self) -> CharWidthInTable | None:
"""If all codepoints in this bucket have the same width, return that width; otherwise,
return `None`."""
if len(self.widths) == 0:
return None
potential_width = self.widths[0]
for width in self.widths[1:]:
if potential_width != width:
return None
return potential_width
def make_buckets(
entries: Iterable[tuple[int, CharWidthInTable]], low_bit: BitPos, cap_bit: BitPos
) -> list[Bucket]:
"""Partitions the `(Codepoint, EffectiveWidth)` tuples in `entries` into `Bucket`s. All
codepoints with identical bits from `low_bit` to `cap_bit` (exclusive) are placed in the
same bucket. Returns a list of the buckets in increasing order of those bits."""
num_bits = cap_bit - low_bit
assert num_bits > 0
buckets = [Bucket() for _ in range(0, 2**num_bits)]
mask = (1 << num_bits) - 1
for codepoint, width in entries:
buckets[(codepoint >> low_bit) & mask].append(codepoint, width)
return buckets
class Table:
"""Represents a lookup table. Each table contains a certain number of subtables; each
subtable is indexed by a contiguous bit range of the codepoint and contains a list
of `2**(number of bits in bit range)` entries. (The bit range is the same for all subtables.)
Typically, tables contain a list of buckets of codepoints. Bucket `i`'s codepoints should
be indexed by sub-table `i` in the next-level lookup table. The entries of this table are
indexes into the bucket list (~= indexes into the sub-tables of the next-level table.) The
key to compression is that two different buckets in two different sub-tables may have the
same width list, which means that they can be merged into the same bucket.
If no bucket contains two codepoints with different widths, calling `indices_to_widths` will
discard the buckets and convert the entries into `EffectiveWidth` values."""
def __init__(
self,
name: str,
entry_groups: Iterable[Iterable[tuple[int, CharWidthInTable]]],
secondary_entry_groups: Iterable[Iterable[tuple[int, CharWidthInTable]]],
low_bit: BitPos,
cap_bit: BitPos,
offset_type: OffsetType,
align: int,
bytes_per_row: int | None = None,
starting_indexed: list[Bucket] = [],
cfged: bool = False,
):
"""Create a lookup table with a sub-table for each `(Codepoint, EffectiveWidth)` iterator
in `entry_groups`. Each sub-table is indexed by codepoint bits in `low_bit..cap_bit`,
and each table entry is represented in the format specified by `offset_type`. Asserts
that this table is actually representable with `offset_type`."""
starting_indexed_len = len(starting_indexed)
self.name = name
self.low_bit = low_bit
self.cap_bit = cap_bit
self.offset_type = offset_type
self.entries: list[int] = []
self.indexed: list[Bucket] = list(starting_indexed)
self.align = align
self.bytes_per_row = bytes_per_row
self.cfged = cfged
buckets: list[Bucket] = []
for entries in entry_groups:
buckets.extend(make_buckets(entries, self.low_bit, self.cap_bit))
for bucket in buckets:
for i, existing in enumerate(self.indexed):
if existing.try_extend(bucket):
self.entries.append(i)
break
else:
self.entries.append(len(self.indexed))
self.indexed.append(bucket)
self.primary_len = len(self.entries)
self.primary_bucket_len = len(self.indexed)
buckets = []
for entries in secondary_entry_groups:
buckets.extend(make_buckets(entries, self.low_bit, self.cap_bit))
for bucket in buckets:
for i, existing in enumerate(self.indexed):
if existing.try_extend(bucket):
self.entries.append(i)
break
else:
self.entries.append(len(self.indexed))
self.indexed.append(bucket)
# Validate offset type
max_index = 1 << int(self.offset_type)
for index in self.entries:
assert index < max_index, f"{index} <= {max_index}"
self.indexed = self.indexed[starting_indexed_len:]
def indices_to_widths(self):
"""Destructively converts the indices in this table to the `EffectiveWidth` values of
their buckets. Assumes that no bucket contains codepoints with different widths.
"""
self.entries = list(map(lambda i: int(self.indexed[i].width()), self.entries)) # type: ignore
del self.indexed
def buckets(self):
"""Returns an iterator over this table's buckets."""
return self.indexed
def to_bytes(self) -> list[int]:
"""Returns this table's entries as a list of bytes. The bytes are formatted according to
the `OffsetType` which the table was created with, converting any `EffectiveWidth` entries
to their enum variant's integer value. For example, with `OffsetType.U2`, each byte will
contain four packed 2-bit entries."""
entries_per_byte = 8 // int(self.offset_type)
byte_array = []
for i in range(0, len(self.entries), entries_per_byte):
byte = 0
for j in range(0, entries_per_byte):
byte |= self.entries[i + j] << (j * int(self.offset_type))
byte_array.append(byte)
return byte_array
def make_tables(
width_map: list[WidthState],
cjk_width_map: list[WidthState],
) -> list[Table]:
"""Creates a table for each configuration in `table_cfgs`, with the first config corresponding
to the top-level lookup table, the second config corresponding to the second-level lookup
table, and so forth. `entries` is an iterator over the `(Codepoint, EffectiveWidth)` pairs
to include in the top-level table."""
entries = enumerate([w.table_width() for w in width_map])
cjk_entries = enumerate([w.table_width() for w in cjk_width_map])
root_table = Table(
"WIDTH_ROOT",
[entries],
[],
TABLE_SPLITS[1],
MAX_CODEPOINT_BITS,
OffsetType.U8,
128,
)