/
build_regex_unicode.py
1777 lines (1296 loc) · 53.3 KB
/
build_regex_unicode.py
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
#! python3.9
# -*- coding: utf-8 -*-
#
# This Python script parses the Unicode data files and generates the C files
# for the regex module.
#
# Written by MRAB.
#
from contextlib import suppress
from itertools import chain
from os import listdir, mkdir
from os.path import basename, dirname, exists, join, normpath
from urllib.parse import urljoin
from urllib.request import urlretrieve
from time import time
import codecs
import sys
sys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach())
class Timed:
def __init__(self, message=None):
self._message = message
def __enter__(self):
self._start = time()
def __exit__(self, exc_type, exc_val, exc_tb):
finish = time()
elapsed = finish - self._start
if self._message is None:
print(f'Took {elapsed:0.2f} secs')
else:
print(f'{self._message} took {elapsed:0.2f} secs')
return False
def unique(iterable, key=None):
if key is None:
def key(item):
return item
seen = set()
for item in iterable:
k = key(item)
if k not in seen:
seen.add(k)
yield item
class IterRanges:
def __init__(self, ranges):
self._ranges = ranges
self._pos = 0
self._update()
def next(self):
if self._pos >= len(self._ranges):
return
self._pos += 1
self._update()
def _update(self):
if self._pos < len(self._ranges):
self.lower, self.upper = self._ranges[self._pos]
else:
self.lower = self.upper = NUM_CODEPOINTS
class Ranges:
def __init__(self, initial=None):
self._ranges = []
if initial is not None:
self._ranges.extend(initial)
self._is_normalised = initial is None
def add(self, lower, upper=None):
if upper is None:
self._ranges.append((lower, lower))
else:
self._ranges.append((lower, upper))
self._is_normalised = False
def __or__(self, other):
return Ranges(self._ranges + other._ranges)
def __sub__(self, other):
self._normalise()
other._normalise()
include = IterRanges(self._ranges)
exclude = IterRanges(other._ranges)
new_ranges = []
lower = include.lower
while lower < NUM_CODEPOINTS:
if lower < include.lower:
# We're below the current include range.
# Advance into the range.
lower = include.lower
elif lower > include.upper:
# We're above the current include range.
# Advance into the next include range.
include.next()
lower = max(lower, include.lower)
elif lower < exclude.lower:
# We're below the current exclude range.
# Accept codepoints as far as the end of the include range.
upper = min(include.upper, exclude.lower - 1)
new_ranges.append((lower, upper))
lower = upper + 1
elif lower > exclude.upper:
# We're above the current exclude range.
exclude.next()
else:
# We're within both the include and exclude ranges.
# Advance out of the overlap.
upper = min(include.upper, exclude.upper)
lower = upper + 1
return Ranges(new_ranges)
def __iter__(self):
self._normalise()
return iter(self._ranges)
def __len__(self):
self._normalise()
return len(self._ranges)
def lowest(self):
self._normalise()
return self._ranges[0][0]
def __repr__(self):
self._normalise()
return 'Ranges({!r})'.format(self._ranges)
def _normalise(self):
if self._is_normalised:
return
if len(self._ranges) >= 2:
self._ranges.sort()
new_ranges = []
lower, upper = self._ranges[0]
for l, u in self._ranges[1 : ]:
if l - upper > 1:
new_ranges.append((lower, upper))
lower, upper = l, u
else:
lower = min(lower, l)
upper = max(upper, u)
new_ranges.append((lower, upper))
self._ranges = new_ranges
self._is_normalised = True
munge_dict = str.maketrans({'-': '', '_': '', ' ': ''})
def munge(value):
munged_value = value.translate(munge_dict).upper()
if value.startswith('-'):
munged_value = '-' + munged_value
return munged_value
def download_unicode_files(unicode_data_base, data_files, data_folder):
for section in data_files.values():
for rel_path in section:
path = normpath(join(data_folder, basename(rel_path)))
if not exists(path):
url = urljoin(unicode_data_base, rel_path)
print('Downloading {} from {}'.format(rel_path, url),
flush=True)
urlretrieve(url, path)
def parse_property_aliases(data_folder):
properties = {}
path = join(data_folder, 'PropertyAliases.txt')
with open(path, encoding='utf-8') as file:
for line in file:
line = line.strip()
if not line or line.startswith('#'):
continue
fields = [field.strip() for field in line.split(';')]
prop_name = fields.pop(1)
property = {'names': list(unique([prop_name] + fields, key=munge))}
for name in property['names']:
properties[munge(name)] = property
return properties
def parse_value_aliases(data_folder, properties):
path = join(data_folder, 'PropertyValueAliases.txt')
with open(path, encoding='utf-8') as file:
for line in file:
line = line.strip()
if not line or line.startswith('#'):
continue
line = line.partition('#')[0]
fields = [field.strip() for field in line.split(';')]
prop_name = fields.pop(0)
val_name = fields.pop(2 if prop_name == 'ccc' else 1)
property = properties[munge(prop_name)]
value = {'names': list(unique([val_name] + fields, key=munge))}
values = property.setdefault('values', {})
for name in value['names']:
values[munge(name)] = value
def parse_binary(properties, path):
with open(path, encoding='utf-8') as file:
for line in file:
line = line.strip()
if not line or line.startswith('#'):
continue
line = line.partition('#')[0]
fields = [field.strip() for field in line.split(';')]
codepoints = [int(part, 16) for part in fields[0].split('..')]
prop_name = fields[1]
property = properties[munge(prop_name)]
property.setdefault('default', munge('No'))
value = property['values'][munge('Yes')]
value.setdefault('codepoints', Ranges()).add(codepoints[0],
codepoints[-1])
def parse_emoji(properties, path):
with open(path, encoding='utf-8') as file:
for line in file:
line = line.strip()
if not line:
continue
if line.startswith('# @missing:'):
fields = line.split()
prop_name = fields[-3]
try:
property = properties[munge(prop_name)]
except KeyError:
property = {'names': [prop_name], 'values': {}}
value = {'names': ['No', 'N']}
property['values'][munge(value['names'][0])] = value
value = {'names': ['Yes', 'Y']}
property['values'][munge(value['names'][0])] = value
properties[munge(prop_name)] = property
default = fields[-1]
property['default'] = munge(default)
elif not line.startswith('#'):
line = line.partition('#')[0]
fields = [field.strip() for field in line.split(';')]
codepoints = [int(part, 16) for part in fields[0].split('..')]
prop_name = fields[1]
property = properties[munge(prop_name)]
property.setdefault('default', munge('No'))
try:
value = property['values'][munge('Yes')]
except KeyError:
value = {'names': ['Yes']}
property['values'][munge('Yes')] = value
value.setdefault('codepoints', Ranges()).add(codepoints[0],
codepoints[-1])
def parse_multivalue(properties, path):
with open(path, encoding='utf-8') as file:
for line in file:
line = line.strip()
if not line:
continue
if line.startswith('# Property:'):
prop_name = line.split()[-1]
property = properties[munge(prop_name)]
elif line.startswith('# All code points not explicitly listed for'):
prop_name = line.split()[-1]
property = properties[munge(prop_name)]
elif line.startswith('# @missing:'):
default = line.split()[-1]
property['default'] = munge(default)
elif not line.startswith('#'):
line = line.partition('#')[0]
fields = [field.strip() for field in line.split(';')]
codepoints = [int(part, 16) for part in fields[0].split('..')]
val_name = fields[1]
value = property['values'][munge(val_name)]
value.setdefault('codepoints', Ranges()).add(codepoints[0],
codepoints[-1])
def parse_normalisation(properties, path):
property = None
with open(path, encoding='utf-8') as file:
for line in file:
line = line.strip()
if not line:
continue
if line.startswith('# Derived Property:'):
property = None
elif line.startswith('# Property:'):
prop_name = line.split()[-1]
property = properties[munge(prop_name)]
elif property:
if line.startswith('# @missing:'):
default = line.split()[-1]
property['default'] = munge(default)
elif not line.startswith('#'):
line = line.partition('#')[0]
fields = [field.strip() for field in line.split(';')]
codepoints = [int(part, 16) for part in
fields[0].split('..')]
val_name = fields[2]
value = property['values'][munge(val_name)]
value.setdefault('codepoints', Ranges()).add(codepoints[0],
codepoints[-1])
def parse_numeric_values(properties, path):
with open(path, encoding='utf-8') as file:
for line in file:
line = line.strip()
if not line:
continue
if line.startswith('# Derived Property:'):
prop_name = line.split()[-1]
property = properties[munge(prop_name)]
default = {'names': ['NaN']}
property['values'] = {munge('NaN'): default}
property['default'] = munge('NaN')
elif line.startswith('# @missing:'):
default = line.split()[-1]
property['default'] = munge(default)
elif not line.startswith('#'):
line = line.partition('#')[0]
fields = [field.strip() for field in line.split(';')]
codepoints = [int(part, 16) for part in fields[0].split('..')]
val_name = fields[3]
try:
value = property['values'][munge(val_name)]
except KeyError:
value = {'names': [val_name]}
property['values'][munge(val_name)] = value
value.setdefault('codepoints', Ranges()).add(codepoints[0],
codepoints[-1])
def parse_script_extensions(properties, path):
with open(path, encoding='utf-8') as file:
for line in file:
line = line.strip()
if not line:
continue
if line.startswith('# Property:'):
prop_name = line.split()[-1]
property = properties[munge(prop_name)]
property['values'] = {}
elif not line.startswith('#'):
line = line.partition('#')[0]
fields = [field.strip() for field in line.split(';')]
codepoints = [int(part, 16) for part in fields[0].split('..')]
key = tuple(sorted(fields[1].split(), key=str.lower))
try:
value = property['values'][key]
except KeyError:
value = {'codepoints': Ranges()}
property['values'][key] = value
value['codepoints'].add(codepoints[0], codepoints[-1])
def parse_case_folding(properties, path):
simple_folding = {}
full_folding = {}
turkic_set = set()
with open(path, encoding='utf-8') as file:
for line in file:
line = line.strip()
if not line or line.startswith('#'):
continue
line = line.partition('#')[0]
fields = line.split(';')
codepoint = int(fields[0], 16)
kind = fields[1].strip()
folded = [int(part, 16) for part in fields[2].split()]
delta = folded[0] ^ codepoint
if kind in {'S', 'C', 'T'}:
simple_folding.setdefault(delta, Ranges()).add(codepoint,
codepoint)
if kind in {'F', 'C', 'T'}:
key = tuple([delta] + folded[1 : ])
full_folding.setdefault(key, Ranges()).add(codepoint,
codepoint)
if kind == 'T':
turkic_set.add((codepoint, tuple(folded)))
# Is the Turkic set what we expected?
if turkic_set != {(0x49, (0x131, )), (0x130, (0x69, ))}:
raise ValueError('Turkic set has changed')
properties['simple_folding'] = simple_folding
properties['full_folding'] = full_folding
def parse_unicode_files(data_files, data_folder):
properties = parse_property_aliases(data_folder)
parse_value_aliases(data_folder, properties)
def ignore(*args):
pass
parsers = {
'aliases': ignore,
'binary': parse_binary,
'emoji': parse_emoji,
'multivalue': parse_multivalue,
'normalisation': parse_normalisation,
'numeric_values': parse_numeric_values,
'script_extensions': parse_script_extensions,
'case_folding': parse_case_folding,
}
for section, rel_paths in data_files.items():
parse = parsers[section]
for rel_path in rel_paths:
data_file = basename(rel_path)
print('Parsing {}'.format(data_file), flush=True)
parse(properties, join(data_folder, data_file))
unicode_data = {'properties': {}}
for prop_name, property in properties.items():
if has_codepoints(property):
unicode_data['properties'][prop_name] = property
elif prop_name in {'simple_folding', 'full_folding'}:
unicode_data[prop_name] = property
properties = unicode_data['properties']
property = properties[munge('General_Category')]
property['default'] = munge('Unassigned')
values = property['values']
for val_name, value in list(values.items()):
if len(val_name) == 1:
new_name = val_name.upper() + '&'
values[munge(new_name)] = value
value['names'].append(new_name)
return unicode_data
def make_binary_property(properties, names, codepoints):
no_value = {'names': ['No', 'N', 'F', 'False']}
yes_value = {'names': ['Yes', 'Y', 'T', 'True'], 'codepoints': codepoints}
values = {}
for value in [no_value, yes_value]:
for name in value['names']:
values[munge(name)] = value
property = {'names': names, 'values': values, 'default': munge('No')}
for name in names:
properties[munge(name)] = property
def make_additional_properties(unicode_data):
def get_values(prop_name):
return properties[munge(prop_name)]['values']
def get_codepoints(prop_name, val_name):
return get_values(prop_name)[munge(val_name)]['codepoints']
properties = unicode_data['properties']
# Make the 'Alphanumeric' property.
alphabetic = get_codepoints('Alphabetic', 'Yes')
decimal_number = get_codepoints('General_Category', 'Decimal_Number')
make_binary_property(properties, ['Alphanumeric', 'AlNum'], alphabetic |
decimal_number)
# Make the 'Any' property.
make_binary_property(properties, ['Any'], Ranges([(0, NUM_CODEPOINTS -
1)]))
# General_Category has a compound value called 'Assigned'.
assigned = Ranges()
for value in unique(get_values('General_Category').values(), key=id):
if value['names'][0] != 'Unassigned':
try:
assigned |= value['codepoints']
except KeyError:
pass
value = {'names': ['Assigned']}
properties[munge('General_Category')]['values'][munge('Assigned')] = value
# Make the 'Blank' property.
space_separator = get_codepoints('General_Category', 'Space_Separator')
blank = Ranges([(0x09, 0x09)]) | space_separator
make_binary_property(properties, ['Blank'], blank)
# Make the 'Graph' property.
whitespace = get_codepoints('White_Space', 'Yes')
control = get_codepoints('General_Category', 'Control')
surrogate = get_codepoints('General_Category', 'Surrogate')
graph = assigned - (whitespace | control | surrogate)
make_binary_property(properties, ['Graph'], graph)
# Make the 'Print' property.
print_ = (graph | blank) - control
make_binary_property(properties, ['Print'], print_)
# Make the 'Word' property.
enclosing_mark = get_codepoints('General_Category', 'Enclosing_Mark')
nonspacing_mark = get_codepoints('General_Category', 'Nonspacing_Mark')
spacing_mark = get_codepoints('General_Category', 'Spacing_Mark')
connector_punctuation = get_codepoints('General_Category',
'Connector_Punctuation')
join_control = get_codepoints('Join_Control', 'Yes')
word = (alphabetic | enclosing_mark | nonspacing_mark | spacing_mark |
decimal_number | connector_punctuation | join_control)
make_binary_property(properties, ['Word'], word)
# Make the 'XDigit' property.
hex_digit = get_codepoints('Hex_Digit', 'Yes')
xdigit = decimal_number | hex_digit
make_binary_property(properties, ['XDigit'], xdigit)
# Make the 'Posix_Digit' property.
posix_digit = Ranges([(ord('0'), ord('9'))])
make_binary_property(properties, ['Posix_Digit'], posix_digit)
# Make the 'Posix_AlNum' property.
posix_alnum = alphabetic | posix_digit
make_binary_property(properties, ['Posix_AlNum'], posix_alnum)
# Make the 'Posix_Punct' property.
punctuation = Ranges()
for name in 'Pd Ps Pe Pc Po Pi Pf'.split():
punctuation |= get_codepoints('General_Category', name)
symbol = Ranges()
for name in 'Sm Sc Sk So '.split():
symbol |= get_codepoints('General_Category', name)
posix_punct = (punctuation | symbol) - alphabetic
make_binary_property(properties, ['Posix_Punct'], posix_punct)
# Make the 'Posix_XDigit' property.
posix_xdigit = Ranges([(ord('0'), ord('9')), (ord('A'), ord('F')),
(ord('a'), ord('f'))])
make_binary_property(properties, ['Posix_XDigit'], posix_xdigit)
def preferred(d):
return munge(d['names'][0])
def has_codepoints(property):
if 'values' not in property:
return False
return any('codepoints' in value for value in property['values'].values())
def write_summary(unicode_data, tools_folder):
print('Writing summary')
properties = unicode_data['properties']
path = join(tools_folder, 'Unicode.txt')
with open(path, 'w', encoding='ascii') as file:
file.write('Version {}\n'.format(UNICODE_VERSION))
for property in sorted(unique(properties.values(), key=id),
key=preferred):
if not has_codepoints(property):
print(property['names'][0])
continue
file.write('Property {}\n'.format(' '.join(property['names'])))
values = property['values']
if property['names'][0] == 'Script_Extensions':
for key in sorted(values):
value = values[key]
file.write('Value {}\n'.format(' '.join(key)))
for lower, upper in value.get('codepoints', []):
if lower == upper:
file.write('{:04X}\n'.format(lower))
else:
file.write('{:04X}..{:04X}\n'.format(lower, upper))
else:
if 'default' in property:
default = values[property['default']]
file.write('DefaultValue {}\n'.format(default['names'][0]))
for value in sorted(unique(values.values(), key=id),
key=preferred):
file.write('Value {}\n'.format(' '.join(value['names'])))
for lower, upper in value.get('codepoints', []):
if lower == upper:
file.write('{:04X}\n'.format(lower))
else:
file.write('{:04X}..{:04X}\n'.format(lower, upper))
file.write('SimpleFolding\n')
for delta, ranges in unicode_data['simple_folding'].items():
file.write('Value {:04X}\n'.format(delta))
for lower, upper in ranges:
if lower == upper:
file.write('{:04X}\n'.format(lower))
else:
file.write('{:04X}..{:04X}\n'.format(lower, upper))
file.write('FullFolding\n')
for key, ranges in unicode_data['full_folding'].items():
file.write('Value {}\n'.format(' '.join('{:04X}'.format(value) for
value in key)))
for lower, upper in ranges:
if lower == upper:
file.write('{:04X}\n'.format(lower))
else:
file.write('{:04X}..{:04X}\n'.format(lower, upper))
def make_binary_dict():
binary_dict = {}
for n in range(0x100):
key = tuple(map(int, format(n, '08b')[ : : -1]))
binary_dict[key] = n
return binary_dict
def collect_strings(properties):
strings = []
for property in properties.values():
try:
strings.extend(property['names'])
for value in property['values'].values():
strings.extend(value['names'])
except KeyError:
pass
return sorted(set(munge(string) for string in strings))
def chunked(iterable, chunk_size):
sequence = iterable
count = len(sequence)
for start in range(0, count, chunk_size):
chunk = sequence[start : start + chunk_size]
yield chunk
def determine_entry_type(iterable):
lower, upper = min(iterable), max(iterable)
if 0 <= lower <= upper <= 0xFF:
return 'RE_UINT8'
if 0 <= lower <= upper <= 0xFFFF:
return 'RE_UINT16'
raise ValueError('cannot determine C type for {}..{}'.format(lower, upper))
def is_binary(property):
return sum(1 for val in val_list if val['id'] != 0) == 1
def count_ranges(property):
count = 0
default_id = property['values'][munge(property['default'])]['id']
for value in unique(property['values'].values(), key=id):
if value['id'] != default_id:
count += len(value.get('codepoints', []))
return count
def generate_small_lookup(property, c_file):
c_file.write('''
/* {}. */
RE_UINT32 re_get_{}(RE_UINT32 codepoint) {{
'''.format(property['names'][0], property['names'][0].lower()))
default_id = property['values'][munge(property['default'])]['id']
ranges = []
for value in unique(property['values'].values(), key=id):
if value['id'] != default_id:
val_id = value['id']
for lower, upper in value.get('codepoints', []):
ranges.append((lower, upper, val_id))
if len(ranges) == 1 and ranges[0][ : 2] == (0, NUM_CODEPOINTS - 1):
c_file.write(' return {};\n}}\n'.format(ranges[0][2]))
else:
for lower, upper, val_id in ranges:
width = 2 if upper <= 0xFF else 4 if upper <= 0xFFFF else 6
if lower == upper:
c_file.write('''\
if (codepoint == 0x{:0{width}X})
return {};
'''.format(lower, val_id, width=width))
else:
c_file.write('''\
if (0x{:0{width}X} <= codepoint && codepoint <= 0x{:0{width}X})
return {};
'''.format(lower, upper, val_id, width=width))
c_file.write('\n return {};\n}}\n'.format(default_id))
def generate_table(table_name, values, c_file, max_columns=16, public=False):
entry_type = determine_entry_type(values)
if public:
c_file.write('{} {}[] = {{\n'.format(entry_type, table_name))
else:
c_file.write('static {} {}[] = {{\n'.format(entry_type, table_name))
entries = [str(value) for value in values]
max_width = max(len(entry) for entry in entries)
entries = [entry.rjust(max_width) + ',' for entry in entries]
entries[-1] = entries[-1].rstrip(',')
for chunk in chunked(entries, max_columns):
c_file.write(' %s\n' % ' '.join(chunk))
c_file.write('};\n')
def generate_lookup(property, c_file):
val_list = list(unique(property['values'].values(), key=id))
if count_ranges(property) <= 8:
generate_small_lookup(property, c_file)
return
default_id = property['values'][munge(property['default'])]['id']
entries = [default_id] * NUM_CODEPOINTS
for value in val_list:
val_id = value['id']
for lower, upper in value.get('codepoints', []):
entries[lower : upper + 1] = [val_id] * (upper - lower + 1)
CHUNK_SIZE = 32
indexes = []
chunks = {}
for chunk in chunked(tuple(entries), CHUNK_SIZE):
indexes.append(chunks.setdefault(chunk, len(chunks)))
table_2 = list(chain(*sorted(chunks, key=chunks.get)))
entries = indexes
indexes = []
chunks = {}
for start in range(0, len(entries), CHUNK_SIZE):
chunk = tuple(entries[start : start + CHUNK_SIZE])
indexes.append(chunks.setdefault(chunk, len(chunks)))
table_1 = list(chain(*sorted(chunks, key=chunks.get)))
table_0 = indexes
c_file.write('\n/* {}. */\n'.format(property['names'][0]))
prop_name = property['names'][0].lower()
binary = set(table_2) == {0, 1}
for i, table in enumerate([table_0, table_1, table_2]):
if i == 2 and binary:
binary = True
entries = []
for start in range(0, len(table), 8):
entries.append(binary_dict[tuple(table[start : start + 8])])
table = entries
if i > 0:
c_file.write('\n')
generate_table('re_{}_table_{}'.format(prop_name, 1 + i), table,
c_file)
if binary:
c_file.write('''
RE_UINT32 re_get_{0}(RE_UINT32 codepoint) {{
RE_UINT32 field_2;
RE_UINT32 field_1;
RE_UINT32 field_0;
RE_UINT32 offset;
RE_UINT32 v;
field_2 = codepoint >> 10;
field_1 = (codepoint >> 5) & 0x1F;
field_0 = (codepoint >> 3) & 0x3;
offset = codepoint & 0x7;
v = re_{0}_table_1[field_2];
v = re_{0}_table_2[(v << 5) | field_1];
v = re_{0}_table_3[(v << 2) | field_0];
return (v >> offset) & 0x1;
}}
'''.format(prop_name))
else:
c_file.write('''
RE_UINT32 re_get_{0}(RE_UINT32 codepoint) {{
RE_UINT32 field_2;
RE_UINT32 field_1;
RE_UINT32 field_0;
RE_UINT32 v;
field_2 = codepoint >> 10;
field_1 = (codepoint >> 5) & 0x1F;
field_0 = codepoint & 0x1F;
v = re_{0}_table_1[field_2];
v = re_{0}_table_2[(v << 5) | field_1];
v = re_{0}_table_3[(v << 5) | field_0];
return v;
}}
'''.format(prop_name))
def generate_script_extensions_lookup(properties, property, c_file):
entries = [0] * NUM_CODEPOINTS
# Initialise with script.
val_list = unique(properties[munge('Script')]['values'].values(), key=id)
for value in val_list:
val_id = value['id']
for lower, upper in value.get('codepoints', []):
entries[lower : upper + 1] = [val_id] * (upper - lower + 1)
script_count = 1 + max(value['id'] for value in
properties[munge('Script')]['values'].values())
val_list = unique(property['values'].values(), key=id)
for value in val_list:
val_id = value['id']
for lower, upper in value.get('codepoints', []):
entries[lower : upper + 1] = [val_id] * (upper - lower + 1)
CHUNK_SIZE = 32
indexes = []
chunks = {}
for chunk in chunked(entries, CHUNK_SIZE):
indexes.append(chunks.setdefault(tuple(chunk), len(chunks)))
table_2 = list(chain(*sorted(chunks, key=chunks.get)))
entries = indexes
indexes = []
chunks = {}
for start in range(0, len(entries), CHUNK_SIZE):
chunk = tuple(entries[start : start + CHUNK_SIZE])
indexes.append(chunks.setdefault(chunk, len(chunks)))
table_1 = list(chain(*sorted(chunks, key=chunks.get)))
table_0 = indexes
c_file.write('\n/* {}. */\n'.format(property['names'][0]))
prop_name = property['names'][0].lower()
for i, table in enumerate([table_0, table_1, table_2]):
generate_table('{}_table_{}'.format(prop_name, 1 + i), table, c_file)
script_values = properties[munge('Script')]['values']
ext_dict = {}
for key, value in property['values'].items():
ext_dict[value['id']] = [script_values[munge(name)]['id'] for name in
key]
offsets = []
entries = []
for key, value in sorted(ext_dict.items()):
offsets.append(len(entries))
entries.extend(value + [0])
generate_table('{}_table_4'.format(prop_name), offsets, c_file)
generate_table('{}_table_5'.format(prop_name), entries, c_file)
c_file.write('''
int re_get_{0}(RE_UINT32 codepoint, RE_UINT8* scripts) {{
RE_UINT32 field_2;
RE_UINT32 field_1;
RE_UINT32 field_0;
RE_UINT32 v;
int offset;
int count;
field_2 = codepoint >> 10;
field_1 = (codepoint >> 5) & 0x1F;
field_0 = codepoint & 0x1F;
v = {0}_table_1[field_2];
v = {0}_table_2[(v << 5) | field_1];
v = {0}_table_3[(v << 5) | field_0];
if (v < {1}) {{
scripts[0] = v;
return 1;
}}
offset = {0}_table_4[v - {1}];
count = 0;
do {{