Repository navigation
Expand file tree
/
Copy pathpreparseucd.py
More file actions
executable file
·2222 lines (2018 loc) · 78.4 KB
/
Copy pathpreparseucd.py
File metadata and controls
executable file
·2222 lines (2018 loc) · 78.4 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/python -B
# -*- coding: utf-8 -*-
# © 2016 and later: Unicode, Inc. and others.
# License & terms of use: http://www.unicode.org/copyright.html
# Copyright (c) 2009-2016 International Business Machines
# Corporation and others. All Rights Reserved.
#
# file name: preparseucd.py
# encoding: US-ASCII
# tab size: 8 (not used)
# indentation:4
#
# created on: 2011nov03 (forked from ucdcopy.py)
# created by: Markus W. Scherer
#
# Copies Unicode Character Database (UCD) files from a tree
# of files downloaded from (for example) ftp://www.unicode.org/Public/6.1.0/
# to ICU's source/data/unidata/ and source/test/testdata/
# and modifies some of the files to make them more compact.
# Parses them and writes unidata/ppucd.txt (PreParsed UCD) with simple syntax.
#
# Invoke with two command-line parameters:
# 1. source folder with UCD & idna files
# 2. ICU source root folder (ICU 59+ combined trunk with icu4c, icu4j, tools)
#
# Sample invocation:
# ~/svn.icu/tools/trunk/src/unicode$ py/preparseucd.py ~/uni61/20120118 ~/svn.icu/trunk/src
import array
import bisect
import codecs
import os
import os.path
import re
import shutil
import sys
# Unicode version ---------------------------------------------------------- ***
_ucd_version = "?"
# ISO 15924 script codes --------------------------------------------------- ***
# Script codes from ISO 15924 http://www.unicode.org/iso15924/codechanges.html
# that are not yet in the UCD.
_scripts_only_in_iso15924 = (
"Afak", "Blis", "Cirt", "Cyrs",
"Egyd", "Egyh", "Geok",
"Hanb", "Hans", "Hant",
"Inds", "Jamo", "Jpan", "Jurc", "Kore", "Kpel", "Latf", "Latg", "Loma",
"Maya", "Moon", "Nkgb", "Phlv", "Roro",
"Sara", "Syre", "Syrj", "Syrn",
"Teng", "Visp", "Wole", "Zmth", "Zsye", "Zsym", "Zxxx"
)
# Properties --------------------------------------------------------------- ***
# Properties that we do not want to store in ppucd.txt.
# Not a frozenset so that we can add aliases for simpler subsequent testing.
_ignored_properties = set((
# Other_Xyz only contribute to Xyz, store only the latter.
"OAlpha",
"ODI",
"OGr_Ext",
"OIDC",
"OIDS",
"OLower",
"OMath",
"OUpper",
# Further properties that just contribute to others.
"CE", # Composition_Exclusion just contributes to Full_Composition_Exclusion.
"JSN",
# These properties just don't seem useful.
# They are deprecated since Unicode 6.0.
"XO_NFC",
"XO_NFD",
"XO_NFKC",
"XO_NFKD",
# ICU does not use Unihan properties.
"cjkAccountingNumeric",
"cjkOtherNumeric",
"cjkPrimaryNumeric",
"cjkCompatibilityVariant",
"cjkIICore",
"cjkIRG_GSource",
"cjkIRG_HSource",
"cjkIRG_JSource",
"cjkIRG_KPSource",
"cjkIRG_KSource",
"cjkIRG_MSource",
"cjkIRG_SSource",
"cjkIRG_TSource",
"cjkIRG_UKSource",
"cjkIRG_USource",
"cjkIRG_VSource",
"cjkRSUnicode"
))
# These properties (short names) map code points to
# strings or other unusual values (property types String or Miscellaneous)
# that cannot be block-compressed (or would be confusing).
_uncompressible_props = frozenset((
"bmg", "bpb", "cf", "Conditional_Case_Mappings", "dm", "FC_NFKC",
"isc", "lc", "na", "na1", "Name_Alias", "NFKC_CF",
# scx is block-compressible.
"scf", "slc", "stc", "suc", "tc", "Turkic_Case_Folding", "uc"
))
# Dictionary of properties.
# Keyed by normalized property names and aliases.
# Each value is a tuple with
# 0: Type of property (binary, enum, ...)
# 1: List of aliases; short & long name followed by other aliases.
# The short name is "" if it is listed as "n/a" in PropertyValueAliases.txt.
# 2: Set of short property value names.
# 3: Dictionary of property values.
# For Catalog & Enumerated properties,
# maps each value name to a list of aliases.
# Empty for other types of properties.
_properties = {}
# Dictionary of binary-property values which we store as False/True.
# Same as the values dictionary of one of the binary properties.
_binary_values = {}
# Dictionary of null values.
# Keyed by short property names.
# These are type-specific values for properties that occur in the data.
# They are overridden by _defaults, block and code point properties.
_null_values = {}
# Property value names for null values.
# We do not store these in _defaults.
_null_names = frozenset(("<none>", "NaN"))
# Dictionary of explicit default property values.
# Keyed by short property names.
_defaults = {"gc": "Cn"}
# _null_values overridden by explicit _defaults.
# Initialized after parsing is done.
_null_or_defaults = {}
# List of properties with an ICU UProperty enum.
# Each item is an (enum, pname, values) tuple.
# - enum: the ICU enum UProperty constant string
# - pname: the UCD short property name
# - values: list of (enum, vname) pairs per property value
# - enum: the ICU property value's enum constant string
# - vname: the UCD short property value name
_icu_properties = []
# Dictionary of short property names mapped to _icu_properties items.
_pname_to_icu_prop = {}
_non_alnum_re = re.compile("[^a-zA-Z0-9]")
def NormPropName(pname):
"""Returns a normalized form of pname.
Removes non-ASCII-alphanumeric characters and lowercases letters."""
return _non_alnum_re.sub("", pname).lower()
def GetProperty(pname):
"""Returns the _properties value for the pname.
Returns null if the property is ignored.
Caches alternate spellings of the property name."""
# Try the input name.
prop = _properties.get(pname)
if prop != None: return prop
if pname in _ignored_properties: return None
# Try the normalized input name.
norm_name = NormPropName(pname)
prop = _properties.get(norm_name)
if prop != None:
_properties[pname] = prop # Cache prop under this new name spelling.
return prop
elif pname in _ignored_properties:
_ignored_properties.add(pname) # Remember to ignore this new name spelling.
return None
else:
raise NameError("unknown property %s\n" % pname)
def GetShortPropertyName(pname):
if pname in _null_values: return pname # pname is already the short name.
prop = GetProperty(pname)
if not prop: return "" # For ignored properties.
return prop[1][0] or prop[1][1] # Long name if no short name.
def GetShortPropertyValueName(prop, vname):
if vname in prop[2]: return vname
values = prop[3]
aliases = values.get(vname)
if aliases == None:
norm_name = NormPropName(vname)
aliases = values.get(norm_name)
if aliases == None:
raise NameError("unknown value name %s for property %s\n" %
(vname, prop[1][0]))
values[vname] = aliases
return aliases[0] or aliases[1] # Long name if no short name.
def NormalizePropertyValue(prop, vname):
if prop[2]: # Binary/Catalog/Enumerated property.
value = GetShortPropertyValueName(prop, vname)
if prop[0] == "Binary":
value = value == "Y"
if prop[1][0].endswith("ccc"):
value = int(value)
else:
value = vname
return value
# Character data ----------------------------------------------------------- ***
# Lists of NamesList h1 and h2 headings.
# Each h1 value is a (start, end, comment) tuple.
# Each h2 value is a (cp, comment) tuple.
_h1 = []
_h2 = []
# List of Unicode blocks.
# Each item is a tuple of start & end code point integers
# and a dictionary of default property values.
_blocks = []
# List of ranges with algorithmic names.
# Each value is a list of [start, end, type, prefix]
# where prefix is optional.
_alg_names_ranges = []
# List of Unicode character ranges and their properties,
# stored as an inversion map with range_start & props dictionary.
# Starts with one range for all of Unicode without any properties.
# Setting values subdivides ranges.
_starts = array.array('l', [0, 0x110000]) # array of int32_t
_props = [{}, {}] # props for 0 and 110000
def FindRange(x):
""" Binary search for x in the inversion map.
Returns the smallest i where x < _starts[i]"""
return bisect.bisect(_starts, x) - 1
def GetProps(c):
i = FindRange(c)
return _props[i]
def UpdateProps(start, end, update):
assert 0 <= start <= end <= 0x10ffff
(need_to_update, do_update, u) = (update[0], update[1], update[2])
# Find the index i of the range in _starts that contains start.
i = FindRange(start)
limit = end + 1
# Intersect [start, limit[ with ranges in _starts.
c_start = _starts[i]
c_limit = _starts[i + 1]
c_props = _props[i]
# c_start <= start < c_limit
if c_start < start:
update_limit = c_limit if c_limit <= limit else limit
if need_to_update(u, start, update_limit - 1, c_props):
# Split off [c_start, start[ with a copy of c_props.
i += 1
c_props = c_props.copy()
_starts.insert(i, start)
_props.insert(i, c_props)
c_start = start
# Modify all ranges that are fully inside [start, limit[.
while c_limit <= limit:
# start <= c_start < c_limit <= limit
if need_to_update(u, c_start, c_limit - 1, c_props):
do_update(u, c_start, c_limit - 1, c_props)
if c_limit == 0x110000: return
i += 1
c_start = c_limit
c_limit = _starts[i + 1]
c_props = _props[i]
if c_start < limit and need_to_update(u, c_start, limit - 1, c_props):
# Split off [limit, c_limit[ with a copy of c_props.
_starts.insert(i + 1, limit)
_props.insert(i + 1, c_props.copy())
# Modify [c_start, limit[ c_props.
do_update(u, c_start, limit - 1, c_props)
def NeedToSetProps(props, start, end, c_props):
"""Returns True if props is not a sub-dict of c_props."""
for (pname, value) in props.iteritems():
if pname not in c_props or value != c_props[pname]: return True
return False
def DoSetProps(props, start, end, c_props):
c_props.update(props)
def SetProps(start, end, props):
UpdateProps(start, end, (NeedToSetProps, DoSetProps, props))
def NeedToSetAlways(nv, start, end, c_props):
return True
# For restoring boundaries after merging adjacent same-props ranges.
def AddBoundary(x):
"""Ensure that there is a range start/limit at x."""
assert 0 <= x <= 0x10ffff
i = FindRange(x)
if _starts[i] == x: return
# Split the range at x.
c_start = _starts[i]
c_limit = _starts[i + 1]
c_props = _props[i]
# c_start < x < c_limit
i += 1
_starts.insert(i, x)
_props.insert(i, c_props.copy())
def SetDefaultValue(pname, value):
"""Sets the property's default value. Ignores null values."""
prop = GetProperty(pname)
if prop and value not in _null_names:
value = NormalizePropertyValue(prop, value)
if value != _null_values[prop[1][0]]:
_defaults[prop[1][0]] = value
SetProps(0, 0x10ffff, {prop[1][0]: value})
def SetBinaryPropertyToTrue(pname, start, end):
prop = GetProperty(pname)
if prop:
assert prop[0] == "Binary"
SetProps(start, end, {prop[1][0]: True})
def SetPropValue(prop, vname, start, end):
value = NormalizePropertyValue(prop, vname)
SetProps(start, end, {prop[1][0]: value})
def SetPropertyValue(pname, vname, start, end):
prop = GetProperty(pname)
if prop: SetPropValue(prop, vname, start, end)
# Parsing ------------------------------------------------------------------ ***
_stripped_cp_re = re.compile("([0-9a-fA-F]+)$")
_stripped_range_re = re.compile("([0-9a-fA-F]+)\.\.([0-9a-fA-F]+)$")
_missing_re = re.compile("# *@missing: *0000\.\.10FFFF *; *(.+)$")
def ReadUCDLines(in_file, want_ranges=True, want_other=False,
want_comments=False, want_missing=False):
"""Parses lines from a semicolon-delimited UCD text file.
Strips comments, ignores empty and all-comment lines.
Returns a tuple (type, line, ...).
"""
for line in in_file:
line = line.strip()
if not line: continue
if line.startswith("#"): # whole-line comment
if want_missing:
match = _missing_re.match(line)
if match:
fields = match.group(1).split(";")
for i in xrange(len(fields)): fields[i] = fields[i].strip()
yield ("missing", line, fields)
continue
if want_comments: yield ("comment", line)
continue
comment_start = line.find("#") # inline comment
if comment_start >= 0:
line = line[:comment_start].rstrip()
if not line: continue
fields = line.split(";")
for i in xrange(len(fields)): fields[i] = fields[i].strip()
if want_ranges:
first = fields[0]
match = _stripped_range_re.match(first)
if match:
start = int(match.group(1), 16)
end = int(match.group(2), 16)
yield ("range", line, start, end, fields)
continue
match = _stripped_cp_re.match(first)
if match:
c = int(match.group(1), 16)
yield ("range", line, c, c, fields)
continue
if want_other:
yield ("other", line, fields)
else:
raise SyntaxError("unable to parse line\n %s\n" % line)
def AddBinaryProperty(short_name, long_name):
_null_values[short_name] = False
bin_prop = _properties["Math"]
prop = ("Binary", [short_name, long_name], bin_prop[2], bin_prop[3])
_properties[short_name] = prop
_properties[long_name] = prop
_properties[NormPropName(short_name)] = prop
_properties[NormPropName(long_name)] = prop
def AddPOSIXBinaryProperty(name):
# We only define a long name for ICU-specific (non-UCD) POSIX properties.
_null_values[name] = False
bin_prop = _properties["Math"]
prop = ("Binary", ["", name], bin_prop[2], bin_prop[3])
_properties[name] = prop
_properties[NormPropName(name)] = prop
# This is to match UProperty UCHAR_POSIX_ALNUM etc.
_properties["posix" + NormPropName(name)] = prop
# Match a comment line like
# PropertyAliases-6.1.0.txt
# and extract the Unicode version.
_ucd_version_re = re.compile("# *PropertyAliases" +
"-([0-9]+(?:\\.[0-9]+)*)(?:d[0-9]+)?" +
"\\.txt")
def ParsePropertyAliases(in_file):
global _ucd_version
prop_type_nulls = {
"Binary": False,
"Catalog": "??", # Must be specified, e.g., in @missing line.
"Enumerated": "??", # Must be specified.
"Numeric": "NaN",
"String": "",
"Miscellaneous": ""
}
for data in ReadUCDLines(in_file, want_ranges=False,
want_other=True, want_comments=True):
if data[0] == "comment":
line = data[1]
match = _ucd_version_re.match(line)
if match:
_ucd_version = match.group(1)
else:
words = line[1:].lstrip().split()
if len(words) == 2 and words[1] == "Properties":
prop_type = words[0]
null_value = prop_type_nulls[prop_type]
else:
# type == "other"
aliases = data[2]
name = aliases[0]
if name in _ignored_properties:
for alias in aliases:
_ignored_properties.add(alias)
_ignored_properties.add(NormPropName(alias))
else:
if name.endswith("ccc"):
_null_values[name] = 0
else:
_null_values[name] = null_value
prop = (prop_type, aliases, set(), {})
for alias in aliases:
_properties[alias] = prop
_properties[NormPropName(alias)] = prop
# Add provisional and ICU-specific properties we need.
# We add some in support of runtime API, even if we do not write
# data for them to ppucd.txt (e.g., lccc & tccc).
# We add others just to represent UCD data that contributes to
# some functionality, although Unicode has not "blessed" them
# as separate properties (e.g., Turkic_Case_Folding).
# Turkic_Case_Folding: The 'T' mappings in CaseFolding.txt.
name = "Turkic_Case_Folding"
_null_values[name] = ""
prop = ("String", [name, name], set(), {})
_properties[name] = prop
_properties[NormPropName(name)] = prop
# Conditional_Case_Mappings: SpecialCasing.txt lines with conditions.
name = "Conditional_Case_Mappings"
_null_values[name] = ""
prop = ("Miscellaneous", [name, name], set(), {})
_properties[name] = prop
_properties[NormPropName(name)] = prop
# lccc = ccc of first cp in canonical decomposition.
_null_values["lccc"] = 0
ccc_prop = list(_properties["ccc"])
ccc_prop[1] = ["lccc", "Lead_Canonical_Combining_Class"]
prop = tuple(ccc_prop)
_properties["lccc"] = prop
_properties["Lead_Canonical_Combining_Class"] = prop
_properties["leadcanonicalcombiningclass"] = prop
# tccc = ccc of last cp in canonical decomposition.
_null_values["tccc"] = 0
ccc_prop[1] = ["tccc", "Trail_Canonical_Combining_Class"]
prop = tuple(ccc_prop)
_properties["tccc"] = prop
_properties["Trail_Canonical_Combining_Class"] = prop
_properties["trailcanonicalcombiningclass"] = prop
# Script_Extensions
if "scx" not in _properties:
_null_values["scx"] = ""
prop = ("Miscellaneous", ["scx", "Script_Extensions"], set(), {})
_properties["scx"] = prop
_properties["Script_Extensions"] = prop
_properties["scriptextensions"] = prop
# General Category as a bit mask.
_null_values["gcm"] = "??"
gc_prop = _properties["gc"]
prop = ("Bitmask", ["gcm", "General_Category_Mask"], gc_prop[2], gc_prop[3])
_properties["gcm"] = prop
_properties["General_Category_Mask"] = prop
_properties["generalcategorymask"] = prop
# Various binary properties.
AddBinaryProperty("Sensitive", "Case_Sensitive")
AddBinaryProperty("nfdinert", "NFD_Inert")
AddBinaryProperty("nfkdinert", "NFKD_Inert")
AddBinaryProperty("nfcinert", "NFC_Inert")
AddBinaryProperty("nfkcinert", "NFKC_Inert")
AddBinaryProperty("segstart", "Segment_Starter")
# http://www.unicode.org/reports/tr51/#Emoji_Properties
AddBinaryProperty("Emoji", "Emoji")
AddBinaryProperty("EPres", "Emoji_Presentation")
AddBinaryProperty("EMod", "Emoji_Modifier")
AddBinaryProperty("EBase", "Emoji_Modifier_Base")
AddBinaryProperty("EComp", "Emoji_Component")
AddBinaryProperty("ExtPict", "Extended_Pictographic")
# C/POSIX character classes that do not have Unicode property [value] aliases.
# See uchar.h.
AddPOSIXBinaryProperty("alnum")
AddPOSIXBinaryProperty("blank")
AddPOSIXBinaryProperty("graph")
AddPOSIXBinaryProperty("print")
AddPOSIXBinaryProperty("xdigit")
def ParsePropertyValueAliases(in_file):
global _binary_values
for data in ReadUCDLines(in_file, want_ranges=False,
want_other=True, want_missing=True):
if data[0] == "missing":
SetDefaultValue(data[2][0], data[2][1])
else:
# type == "other"
fields = data[2]
pname = fields[0]
prop = GetProperty(pname)
if prop:
del fields[0] # Only the list of aliases remains.
short_name = fields[0]
if short_name == "n/a": # no short name
fields[0] = ""
short_name = fields[1]
prop[2].add(short_name)
values = prop[3]
for alias in fields:
if alias:
values[alias] = fields
values[NormPropName(alias)] = fields
if prop[0] == "Binary" and not _binary_values:
_binary_values = values
# Some of the @missing lines with non-null default property values
# are in files that we do not parse;
# either because the data for that property is easily
# (i.e., the @missing line would be the only reason to parse such a file)
# or because we compute the property at runtime,
# such as the Hangul_Syllable_Type.
if "dt" not in _defaults: # DerivedDecompositionType.txt
_defaults["dt"] = "None"
if "nt" not in _defaults: # DerivedNumericType.txt
_defaults["nt"] = "None"
if "hst" not in _defaults: # HangulSyllableType.txt
_defaults["hst"] = "NA"
if "gc" not in _defaults: # No @missing line in any .txt file?
_defaults["gc"] = "Cn"
# Copy the gc default value to gcm.
_defaults["gcm"] = _defaults["gc"]
# Add ISO 15924-only script codes.
# Only for the ICU script code API, not necessary for parsing the UCD.
script_prop = _properties["sc"]
short_script_names = script_prop[2] # set
script_values = script_prop[3] # dict
remove_scripts = []
for script in _scripts_only_in_iso15924:
if script in short_script_names:
remove_scripts.append(script)
else:
short_script_names.add(script)
# Do not invent a Unicode long script name before the UCD adds the script.
script_list = [script, script] # [short, long]
script_values[script] = script_list
# Probably not necessary because
# we will not parse these scripts from the UCD:
script_values[NormPropName(script)] = script_list
if remove_scripts:
raise ValueError(
"remove %s from _scripts_only_in_iso15924" % remove_scripts)
def ParseBlocks(in_file):
for data in ReadUCDLines(in_file, want_missing=True):
if data[0] == "missing":
SetDefaultValue("blk", data[2][0])
else:
# type == "range"
(start, end, name) = (data[2], data[3], data[4][1])
_blocks.append((start, end, {"blk": name}))
SetPropertyValue("blk", name, start, end)
_blocks.sort()
# Check for overlapping blocks.
prev_end = -1
for b in _blocks:
start = b[0]
end = b[1]
if prev_end >= start:
raise ValueError(
"block %04lX..%04lX %s overlaps with another " +
"ending at %04lX\n %s\n" %
(start, end, b[2]["blk"], prev_end))
prev_end = end
def ParseUnicodeData(in_file):
dt_prop = GetProperty("dt")
range_first_line = ""
range_first = -1
for data in ReadUCDLines(in_file, want_missing=True):
# type == "range"
(line, c, end, fields) = (data[1], data[2], data[3], data[4])
assert c == end
name = fields[1]
if name.startswith("<"):
if name.endswith(", First>"):
if range_first >= 0:
raise SyntaxError(
"error: unterminated range started at\n %s\n" %
range_first_line)
range_first = c
range_first_line = line
continue
elif name.endswith(", Last>"):
if range_first < 0:
raise SyntaxError(
"error: range end without start at\n %s\n" %
line)
elif range_first > c:
raise SyntaxError(
"error: range start/end out of order at\n %s\n %s\n" %
(range_first_line, line))
first_name = range_first_line.split(";")[1][1:-8]
name = name[1:-7]
if first_name != name:
raise SyntaxError(
"error: range start/end name mismatch at\n %s\n %s\n" %
(range_first_line, line))
end = c
c = range_first
range_first = -1
# Remember algorithmic name ranges.
if "Ideograph" in name:
prefix = "CJK UNIFIED IDEOGRAPH-"
if c == 0x17000 or c == 0x18D00: prefix = "TANGUT IDEOGRAPH-"
_alg_names_ranges.append([c, end, "han", prefix])
elif name == "Hangul Syllable":
_alg_names_ranges.append([c, end, "hangul"])
name = ""
else:
# Ignore non-names like <control>.
name = ""
props = {}
if name: props["na"] = name
props["gc"] = fields[2]
ccc = int(fields[3])
if ccc: props["ccc"] = ccc
props["bc"] = fields[4]
# Decomposition type & mapping.
dm = fields[5]
if dm:
if dm.startswith("<"):
dt_limit = dm.index(">")
dt = NormalizePropertyValue(dt_prop, dm[1:dt_limit])
dm = dm[dt_limit + 1:].lstrip()
else:
dt = "Can"
props["dt"] = dt
props["dm"] = dm
# Numeric type & value.
decimal = fields[6]
digit = fields[7]
nv = fields[8]
if (decimal and decimal != nv) or (digit and digit != nv):
raise SyntaxError("error: numeric values differ at\n %s\n" % line)
if nv:
# Map improper fractions to proper ones.
# U+109F7 MEROITIC CURSIVE FRACTION TWO TWELFTHS
# .. U+109FF MEROITIC CURSIVE FRACTION TEN TWELFTHS
if nv == "2/12":
nv = "1/6"
elif nv == "3/12":
nv = "1/4"
elif nv == "4/12":
nv = "1/3"
elif nv == "6/12":
nv = "1/2"
elif nv == "8/12":
nv = "2/3"
elif nv == "9/12":
nv = "3/4"
elif nv == "10/12":
nv = "5/6"
props["nv"] = nv
props["nt"] = "De" if decimal else "Di" if digit else "Nu"
if fields[9] == "Y": props["Bidi_M"] = True
# ICU 49 and above does not support Unicode_1_Name any more.
# See ticket #9013.
# na1 = fields[10]
# if na1: props["na1"] = na1
# ISO_Comment is deprecated and has no values.
# isc = fields[11]
# if isc: props["isc"] = isc
# Simple case mappings.
suc = fields[12]
slc = fields[13]
stc = fields[14]
if suc: props["suc"] = suc
if slc: props["slc"] = slc
if stc: props["stc"] = stc
SetProps(c, end, props)
if range_first >= 0:
raise SyntaxError(
"error: unterminated range started at\n %s\n" %
range_first_line)
# Hangul syllables have canonical decompositions which are not listed in UnicodeData.txt.
SetPropertyValue("dt", "Can", 0xac00, 0xd7a3)
_alg_names_ranges.sort()
_names_h1_re = re.compile("@@\t([0-9a-fA-F]+)\t(.+?)\t([0-9a-fA-F]+)$")
_names_h2_re = re.compile("@\t\t(.+)")
_names_char_re = re.compile("([0-9a-fA-F]+)\t.+")
def ParseNamesList(in_file):
pending_h2 = ""
for line in in_file:
line = line.strip()
if not line: continue
match = _names_h1_re.match(line)
if match:
pending_h2 = "" # Drop a pending h2 when we get to an h1.
start = int(match.group(1), 16)
end = int(match.group(3), 16)
comment = match.group(2).replace(u"\xa0", " ")
_h1.append((start, end, comment))
continue
match = _names_h2_re.match(line)
if match:
pending_h2 = match.group(1).replace(u"\xa0", " ")
continue
if pending_h2:
match = _names_char_re.match(line)
if match:
c = int(match.group(1), 16)
_h2.append((c, pending_h2))
pending_h2 = ""
_h1.sort()
_h2.sort()
def ParseNamedProperties(in_file):
"""Parses a .txt file where the first column is a code point range
and the second column is a property name.
Sets binary properties to True,
and other properties to the values in the third column."""
for data in ReadUCDLines(in_file, want_missing=True):
if data[0] == "missing":
SetDefaultValue(data[2][0], data[2][1])
else:
# type == "range"
if len(data[4]) == 2:
SetBinaryPropertyToTrue(data[4][1], data[2], data[3])
else:
SetPropertyValue(data[4][1], data[4][2], data[2], data[3])
def ParseOneProperty(in_file, pname):
"""Parses a .txt file where the first column is a code point range
and the second column is the value of a known property."""
prop = GetProperty(pname)
for data in ReadUCDLines(in_file, want_missing=True):
if data[0] == "missing":
SetDefaultValue(pname, data[2][0])
else:
# type == "range"
SetPropValue(prop, data[4][1], data[2], data[3])
def ParseBidiMirroring(in_file): ParseOneProperty(in_file, "bmg")
def ParseDerivedAge(in_file): ParseOneProperty(in_file, "age")
def ParseDerivedBidiClass(in_file): ParseOneProperty(in_file, "bc")
def ParseDerivedJoiningGroup(in_file): ParseOneProperty(in_file, "jg")
def ParseDerivedJoiningType(in_file): ParseOneProperty(in_file, "jt")
def ParseEastAsianWidth(in_file): ParseOneProperty(in_file, "ea")
def ParseGraphemeBreakProperty(in_file): ParseOneProperty(in_file, "GCB")
def ParseIndicPositionalCategory(in_file): ParseOneProperty(in_file, "InPC")
def ParseIndicSyllabicCategory(in_file): ParseOneProperty(in_file, "InSC")
def ParseLineBreak(in_file): ParseOneProperty(in_file, "lb")
def ParseScripts(in_file): ParseOneProperty(in_file, "sc")
def ParseScriptExtensions(in_file): ParseOneProperty(in_file, "scx")
def ParseSentenceBreak(in_file): ParseOneProperty(in_file, "SB")
def ParseVerticalOrientation(in_file): ParseOneProperty(in_file, "vo")
def ParseWordBreak(in_file): ParseOneProperty(in_file, "WB")
def DoSetNameAlias(alias, start, end, c_props):
if "Name_Alias" in c_props:
c_props["Name_Alias"] += ',' + alias
else:
c_props["Name_Alias"] = alias
def ParseNameAliases(in_file):
"""Parses Name_Alias from NameAliases.txt.
A character can have multiple aliases.
In Unicode 6.0, there are two columns,
with a name correction in the second column.
In Unicode 6.1, there are three columns.
The second contains an alias, the third its type.
The documented types are:
correction, control, alternate, figment, abbreviation
This function does not sort the types, assuming they appear in this order."""
for data in ReadUCDLines(in_file):
start = data[2]
end = data[3]
if start != end:
raise ValueError("NameAliases.txt has an alias for a range %04lX..%04lX" %
(start, end))
fields = data[4]
if len(fields) == 2:
alias = "correction=" + fields[1]
else:
alias = fields[2] + '=' + fields[1]
update = (NeedToSetAlways, DoSetNameAlias, alias)
UpdateProps(start, end, update)
def NeedToSetNumericValue(nv, start, end, c_props):
c_nv = c_props.get("nv")
if c_nv == None:
# DerivedNumericValues.txt adds a Numeric_Value.
assert "nt" not in c_props
return True
if nv != c_nv:
raise ValueError(("UnicodeData.txt has nv=%s for %04lX..%04lX " +
"but DerivedNumericValues.txt has nv=%s") %
(c_nv, start, end, nv))
return False
def DoSetNumericValue(nv, start, end, c_props):
c_props.update({"nt": "Nu", "nv": nv})
def ParseDerivedNumericValues(in_file):
"""Parses DerivedNumericValues.txt.
For most characters, the numeric type & value were parsed previously
from UnicodeData.txt but that does not show the values for Han characters.
Here we check that values match those from UnicodeData.txt
and add new ones."""
# Ignore the @missing line which has an incorrect number of fields,
# and the "NaN" in the wrong field (at least in Unicode 5.1..6.1).
# Also, "NaN" is just the Numeric null value anyway.
for data in ReadUCDLines(in_file):
# Conditional update to the numeric value in the 4th field.
update = (NeedToSetNumericValue, DoSetNumericValue, data[4][3])
UpdateProps(data[2], data[3], update)
def ParseCaseFolding(in_file):
for data in ReadUCDLines(in_file, want_missing=True):
if data[0] == "missing":
assert data[2][0] == "C" # common to scf & cf
SetDefaultValue("scf", data[2][1])
SetDefaultValue("cf", data[2][1])
else:
# type == "range"
start = data[2]
end = data[3]
status = data[4][1]
mapping = data[4][2]
assert status in "CSFT"
if status == "C":
SetProps(start, end, {"scf": mapping, "cf": mapping})
elif status == "S":
SetPropertyValue("scf", mapping, start, end)
elif status == "F":
SetPropertyValue("cf", mapping, start, end)
else: # status == "T"
SetPropertyValue("Turkic_Case_Folding", mapping, start, end)
def DoSetConditionalCaseMappings(ccm, start, end, c_props):
if "Conditional_Case_Mappings" in c_props:
c_props["Conditional_Case_Mappings"] += ',' + ccm
else:
c_props["Conditional_Case_Mappings"] = ccm
def ParseSpecialCasing(in_file):
for data in ReadUCDLines(in_file, want_missing=True):
if data[0] == "missing":
SetDefaultValue("lc", data[2][0])
SetDefaultValue("tc", data[2][1])
SetDefaultValue("uc", data[2][2])
else:
# type == "range"
start = data[2]
end = data[3]
fields = data[4]
if len(fields) < 5 or not fields[4]:
# Unconditional mappings.
SetProps(start, end, {"lc": fields[1], "tc": fields[2], "uc": fields[3]})
else:
# Conditional_Case_Mappings
ccm = (fields[4] + ":lc=" + fields[1] +
"&tc=" + fields[2] + "&uc=" + fields[3])
update = (NeedToSetAlways, DoSetConditionalCaseMappings, ccm)
UpdateProps(start, end, update)
def ParseBidiBrackets(in_file):
for data in ReadUCDLines(in_file, want_missing=True):
if data[0] == "missing":
SetDefaultValue("bpt", data[2][1])
else:
# type == "range"
start = data[2]
end = data[3]
assert start == end
mapping = data[4][1]
bracket_type = data[4][2]
SetProps(start, end, {"bpb": mapping, "bpt": bracket_type})
# Postprocessing ----------------------------------------------------------- ***
def PrintedSize(pname, value):
if isinstance(value, bool):
if value:
return len(pname) + 1 # ";pname"
else:
return len(pname) + 2 # ";-pname"
else:
return len(pname) + len(str(value)) + 2 # ";pname=value"
def CompactBlock(b, i):
assert b[0] == _starts[i]
b_props = b[2] # Normally just blk from Blocks.txt.
# b_props["blk"] has not been canonicalized yet.
b_props["blk"] = _props[i]["blk"]
orig_i = i
# Count the number of occurrences of each property's value in this block.
# To minimize the output, count the number of assigned ranges,
# not the number of code points.
num_ranges = 0
prop_counters = {}
if "gc" in b_props:
b_is_unassigned = b_props["gc"] == "Cn" # Unreachable with normal data.
else:
b_is_unassigned = _defaults["gc"] == "Cn" # This is expected to be true.
while True:
start = _starts[i]
if start > b[1]: break
props = _props[i]
if "gc" in props:
is_unassigned = props["gc"] == "Cn"
else:
is_unassigned = b_is_unassigned
if is_unassigned:
# Compact an unassigned range inside the block and
# mark it to be written with "unassigned".
# It falls back to default properties, not block properties,
# except for the blk=Block property.
assert props["blk"] == b_props["blk"]
del props["blk"]
for pname in props.keys(): # .keys() is a copy so we can del props[pname].
if props[pname] == _null_or_defaults[pname]: del props[pname]
# What remains are unusual default values for unassigned code points.
# For example, bc=R or lb=ID.
# See http://www.unicode.org/reports/tr44/#Default_Values_Table
props["unassigned"] = True
else:
for (pname, value) in props.iteritems():
if pname in prop_counters:
counter = prop_counters[pname]