Debian Codegraph @

tools/build_regex_unicode.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 #
4 # This Python script parses the Unicode data files in the UCD.zip file and
5 # generates the C files for the regex module.
6 #
7 # Written by MRAB.
8 #
9 from contextlib import contextmanager, suppress
10 from io import TextIOWrapper
11 from itertools import chain
12 from os import listdir, mkdir
13 from os.path import basename, dirname, exists, join, normpath
14 from time import time
15 from urllib.parse import urljoin
16 from urllib.request import urlretrieve
17 from zipfile import ZipFile
18 import re
19
20 import codecs
21 import sys
22 sys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach())
23
24 @contextmanager
25 def UCDSubfile(zip_path, subfile_name):
26 with ZipFile(ucd_zip_path) as ucd_zip_file:
27 with ucd_zip_file.open(subfile_name) as bin_file:
28 with TextIOWrapper(bin_file, encoding='utf-8') as file:
29 yield file
30
31 def have_ucd_version(ucd_zip_path, desired_version):
32 with UCDSubfile(ucd_zip_path, 'ReadMe.txt') as file:
33 for line in file:
34 m = re.search(r'(?i)Version (\d+\.\d+\.\d+)', line)
35
36 if m and m[1] == desired_version:
37 return True
38
39 return False
40
41 def unique(iterable, key=None):
42
43 if key is None:
44 def key(item):
45 return item
46
47 seen = set()
48
49 for item in iterable:
50 k = key(item)
51
52 if k not in seen:
53 seen.add(k)
54 yield item
55
56 class IterRanges:
57 def __init__(self, ranges):
58 self._ranges = ranges
59 self._pos = 0
60 self._update()
61
62 def next(self):
63 if self._pos >= len(self._ranges):
64 return
65
66 self._pos += 1
67 self._update()
68
69 def _update(self):
70 if self._pos < len(self._ranges):
71 self.lower, self.upper = self._ranges[self._pos]
72 else:
73 self.lower = self.upper = NUM_CODEPOINTS
74
75 class Ranges:
76 def __init__(self, initial=None):
77 self._ranges = []
78
79 if initial is not None:
80 self._ranges.extend(initial)
81
82 self._is_normalised = initial is None
83
84 def add(self, lower, upper=None):
85 if upper is None:
86 self._ranges.append((lower, lower))
87 else:
88 self._ranges.append((lower, upper))
89
90 self._is_normalised = False
91
92 def __or__(self, other):
93 return Ranges(self._ranges + other._ranges)
94
95 def __sub__(self, other):
96 self._normalise()
97 other._normalise()
98
99 include = IterRanges(self._ranges)
100 exclude = IterRanges(other._ranges)
101 new_ranges = []
102
103 lower = include.lower
104
105 while lower < NUM_CODEPOINTS:
106 if lower < include.lower:
107 # We're below the current include range.
108 # Advance into the range.
109 lower = include.lower
110 elif lower > include.upper:
111 # We're above the current include range.
112 # Advance into the next include range.
113 include.next()
114 lower = max(lower, include.lower)
115 elif lower < exclude.lower:
116 # We're below the current exclude range.
117 # Accept codepoints as far as the end of the include range.
118 upper = min(include.upper, exclude.lower - 1)
119 new_ranges.append((lower, upper))
120 lower = upper + 1
121 elif lower > exclude.upper:
122 # We're above the current exclude range.
123 exclude.next()
124 else:
125 # We're within both the include and exclude ranges.
126 # Advance out of the overlap.
127 upper = min(include.upper, exclude.upper)
128 lower = upper + 1
129
130 return Ranges(new_ranges)
131
132 def __iter__(self):
133 self._normalise()
134
135 return iter(self._ranges)
136
137 def __len__(self):
138 self._normalise()
139
140 return len(self._ranges)
141
142 def lowest(self):
143 self._normalise()
144
145 return self._ranges[0][0]
146
147 def __repr__(self):
148 self._normalise()
149
150 return 'Ranges({!r})'.format(self._ranges)
151
152 def _normalise(self):
153 if self._is_normalised:
154 return
155
156 if len(self._ranges) >= 2:
157 self._ranges.sort()
158
159 new_ranges = []
160 lower, upper = self._ranges[0]
161
162 for l, u in self._ranges[1 : ]:
163 if l - upper > 1:
164 new_ranges.append((lower, upper))
165 lower, upper = l, u
166 else:
167 lower = min(lower, l)
168 upper = max(upper, u)
169
170 new_ranges.append((lower, upper))
171
172 self._ranges = new_ranges
173
174 self._is_normalised = True
175
176 munge_dict = str.maketrans({'-': '', '_': '', ' ': ''})
177
178 def munge(value):
179 munged_value = value.translate(munge_dict).upper()
180
181 if value.startswith('-'):
182 munged_value = '-' + munged_value
183
184 return munged_value
185
186 def download_unicode_files(unicode_data_base, data_files, data_folder):
187 for section in data_files.values():
188 for rel_path in section:
189 path = normpath(join(data_folder, basename(rel_path)))
190
191 if not exists(path):
192 url = urljoin(unicode_data_base, rel_path)
193 print('Downloading {} from {}'.format(rel_path, url),
194 flush=True)
195 urlretrieve(url, path)
196
197 def parse_property_aliases(ucd_zip_path):
198 properties = {}
199
200 with UCDSubfile(ucd_zip_path, 'PropertyAliases.txt') as file:
201 for line in file:
202 line = line.strip()
203
204 if not line or line.startswith('#'):
205 continue
206
207 fields = [field.strip() for field in line.split(';')]
208 prop_name = fields.pop(1)
209
210 property = {'names': list(unique([prop_name] + fields, key=munge))}
211
212 for name in property['names']:
213 properties[munge(name)] = property
214
215 return properties
216
217 def parse_value_aliases(ucd_zip_path, properties):
218 with UCDSubfile(ucd_zip_path, 'PropertyValueAliases.txt') as file:
219 for line in file:
220 line = line.strip()
221
222 if not line or line.startswith('#'):
223 continue
224
225 line = line.partition('#')[0]
226 fields = [field.strip() for field in line.split(';')]
227 prop_name = fields.pop(0)
228 val_name = fields.pop(2 if prop_name == 'ccc' else 1)
229
230 property = properties[munge(prop_name)]
231 value = {'names': list(unique([val_name] + fields, key=munge))}
232 values = property.setdefault('values', {})
233
234 for name in value['names']:
235 values[munge(name)] = value
236
237 binary_values = {'N', 'YES', 'TRUE', 'FALSE', 'T', 'Y', 'NO', 'F'}
238
239 for property in properties.values():
240 property['is_binary'] = set(property.get('values', [])) == binary_values
241
242 def parse_binary(properties, subpath):
243 print('Parsing %s' % subpath, flush=True)
244
245 with UCDSubfile(ucd_zip_path, subpath) as file:
246 for line in file:
247 line = line.strip()
248
249 if line.startswith('# @missing:'):
250 default = line.split(';')[-1].strip()
251
252 if not line or line.startswith('#'):
253 continue
254
255 line = line.partition('#')[0]
256 fields = [field.strip() for field in line.split(';')]
257 codepoints = [int(part, 16) for part in fields[0].split('..')]
258 prop_name = fields[1]
259 property = properties[munge(prop_name)]
260
261 if property['is_binary']:
262 property.setdefault('default', munge('No'))
263 value = property['values'][munge('Yes')]
264 value.setdefault('codepoints', Ranges()).add(codepoints[0],
265 codepoints[-1])
266 else:
267 # Not a binary property!
268 property.setdefault('default', munge(default))
269 val_name = fields[2]
270 value = property['values'][munge(val_name)]
271 value.setdefault('codepoints', Ranges()).add(codepoints[0],
272 codepoints[-1])
273
274 def parse_emoji(properties, subpath):
275 print('Parsing %s' % subpath, flush=True)
276
277 with UCDSubfile(ucd_zip_path, subpath) as file:
278 for line in file:
279 line = line.strip()
280
281 if not line:
282 continue
283
284 if line.startswith('# @missing:'):
285 fields = line.split()
286 prop_name = fields[-3]
287
288 try:
289 property = properties[munge(prop_name)]
290 except KeyError:
291 property = {'names': [prop_name], 'values': {}}
292 value = {'names': ['No', 'N']}
293 property['values'][munge(value['names'][0])] = value
294 value = {'names': ['Yes', 'Y']}
295 property['values'][munge(value['names'][0])] = value
296 properties[munge(prop_name)] = property
297
298 default = fields[-1]
299 property['default'] = munge(default)
300 elif not line.startswith('#'):
301 line = line.partition('#')[0]
302 fields = [field.strip() for field in line.split(';')]
303 codepoints = [int(part, 16) for part in fields[0].split('..')]
304 prop_name = fields[1]
305 property = properties[munge(prop_name)]
306 property.setdefault('default', munge('No'))
307
308 try:
309 value = property['values'][munge('Yes')]
310 except KeyError:
311 value = {'names': ['Yes']}
312 property['values'][munge('Yes')] = value
313
314 value.setdefault('codepoints', Ranges()).add(codepoints[0],
315 codepoints[-1])
316
317 def parse_multivalue(properties, subpath):
318 print('Parsing %s' % subpath, flush=True)
319
320 with UCDSubfile(ucd_zip_path, subpath) as file:
321 for line in file:
322 line = line.strip()
323
324 if not line:
325 continue
326
327 if line.startswith('# Property:'):
328 prop_name = line.split()[-1]
329 property = properties[munge(prop_name)]
330 elif line.startswith('# All code points not explicitly listed for'):
331 prop_name = line.split()[-1]
332 property = properties[munge(prop_name)]
333 elif len(line.split()) == 3 and line.endswith(' Property'):
334 prop_name = line.split()[1]
335 property = properties[munge(prop_name)]
336 elif line.startswith('# @missing:'):
337 default = line.split()[-1]
338 property['default'] = munge(default)
339 elif not line.startswith('#'):
340 line = line.partition('#')[0]
341 fields = [field.strip() for field in line.split(';')]
342 codepoints = [int(part, 16) for part in fields[0].split('..')]
343 val_name = fields[1]
344 value = property['values'][munge(val_name)]
345 value.setdefault('codepoints', Ranges()).add(codepoints[0],
346 codepoints[-1])
347
348 def parse_normalisation(properties, subpath):
349 print('Parsing %s' % subpath, flush=True)
350
351 property = None
352
353 with UCDSubfile(ucd_zip_path, subpath) as file:
354 for line in file:
355 line = line.strip()
356
357 if not line:
358 continue
359
360 if line.startswith('# Derived Property:'):
361 property = None
362 elif line.startswith('# Property:'):
363 prop_name = line.split()[-1]
364 property = properties[munge(prop_name)]
365 elif property:
366 if line.startswith('# @missing:'):
367 default = line.split()[-1]
368 property['default'] = munge(default)
369 elif not line.startswith('#'):
370 line = line.partition('#')[0]
371 fields = [field.strip() for field in line.split(';')]
372 codepoints = [int(part, 16) for part in
373 fields[0].split('..')]
374 val_name = fields[2]
375
376 value = property['values'][munge(val_name)]
377 value.setdefault('codepoints', Ranges()).add(codepoints[0],
378 codepoints[-1])
379
380 def parse_numeric_values(properties, subpath):
381 print('Parsing %s' % subpath, flush=True)
382
383 with UCDSubfile(ucd_zip_path, subpath) as file:
384 for line in file:
385 line = line.strip()
386
387 if not line:
388 continue
389
390 if line.startswith('# Derived Property:'):
391 prop_name = line.split()[-1]
392 property = properties[munge(prop_name)]
393 default = {'names': ['NaN']}
394 property['values'] = {munge('NaN'): default}
395 property['default'] = munge('NaN')
396 elif line.startswith('# @missing:'):
397 default = line.split()[-1]
398 property['default'] = munge(default)
399 elif not line.startswith('#'):
400 line = line.partition('#')[0]
401 fields = [field.strip() for field in line.split(';')]
402 codepoints = [int(part, 16) for part in fields[0].split('..')]
403 val_name = fields[3]
404
405 try:
406 value = property['values'][munge(val_name)]
407 except KeyError:
408 value = {'names': [val_name]}
409 property['values'][munge(val_name)] = value
410
411 value.setdefault('codepoints', Ranges()).add(codepoints[0],
412 codepoints[-1])
413
414 def parse_script_extensions(properties, subpath):
415 print('Parsing %s' % subpath, flush=True)
416
417 with UCDSubfile(ucd_zip_path, subpath) as file:
418 for line in file:
419 line = line.strip()
420
421 if not line:
422 continue
423
424 if line.startswith('# Property:'):
425 prop_name = line.split()[-1]
426 property = properties[munge(prop_name)]
427 property['values'] = {}
428 elif line.startswith('# All code points not explicitly listed for '):
429 prop_name = line.split()[-1]
430 property = properties[munge(prop_name)]
431 property['values'] = {}
432 elif not line.startswith('#'):
433 line = line.partition('#')[0]
434 fields = [field.strip() for field in line.split(';')]
435 codepoints = [int(part, 16) for part in fields[0].split('..')]
436
437 key = tuple(sorted(fields[1].split(), key=str.lower))
438
439 try:
440 value = property['values'][key]
441 except KeyError:
442 value = {'codepoints': Ranges()}
443 property['values'][key] = value
444
445 value['codepoints'].add(codepoints[0], codepoints[-1])
446
447 def parse_case_folding(properties, subpath):
448 print('Parsing %s' % subpath, flush=True)
449
450 simple_folding = {}
451 full_folding = {}
452 turkic_set = set()
453
454 with UCDSubfile(ucd_zip_path, subpath) as file:
455 for line in file:
456 line = line.strip()
457
458 if not line or line.startswith('#'):
459 continue
460
461 line = line.partition('#')[0]
462 fields = line.split(';')
463 codepoint = int(fields[0], 16)
464 kind = fields[1].strip()
465 folded = [int(part, 16) for part in fields[2].split()]
466 delta = folded[0] ^ codepoint
467
468 if kind in {'S', 'C', 'T'}:
469 simple_folding.setdefault(delta, Ranges()).add(codepoint,
470 codepoint)
471
472 if kind in {'F', 'C', 'T'}:
473 key = tuple([delta] + folded[1 : ])
474 full_folding.setdefault(key, Ranges()).add(codepoint,
475 codepoint)
476
477 if kind == 'T':
478 turkic_set.add((codepoint, tuple(folded)))
479
480 # Is the Turkic set what we expected?
481 if turkic_set != {(0x49, (0x131, )), (0x130, (0x69, ))}:
482 raise ValueError('Turkic set has changed')
483
484 properties['simple_folding'] = simple_folding
485 properties['full_folding'] = full_folding
486
487 def parse_unicode_data_files(ucd_zip_path):
488 properties = parse_property_aliases(ucd_zip_path)
489 parse_value_aliases(ucd_zip_path, properties)
490
491 parse_binary(properties, 'PropList.txt')
492 parse_binary(properties, 'extracted/DerivedBinaryProperties.txt')
493 parse_binary(properties, 'DerivedCoreProperties.txt')
494
495 parse_emoji(properties, 'emoji/emoji-data.txt')
496
497 parse_normalisation(properties, 'DerivedNormalizationProps.txt')
498
499 parse_multivalue(properties, 'auxiliary/GraphemeBreakProperty.txt')
500 parse_multivalue(properties, 'auxiliary/SentenceBreakProperty.txt')
501 parse_multivalue(properties, 'auxiliary/WordBreakProperty.txt')
502 parse_multivalue(properties, 'Blocks.txt')
503 parse_multivalue(properties, 'extracted/DerivedBidiClass.txt')
504 parse_multivalue(properties, 'extracted/DerivedCombiningClass.txt')
505 parse_multivalue(properties, 'extracted/DerivedDecompositionType.txt')
506 parse_multivalue(properties, 'extracted/DerivedEastAsianWidth.txt')
507 parse_multivalue(properties, 'extracted/DerivedGeneralCategory.txt')
508 parse_multivalue(properties, 'extracted/DerivedJoiningGroup.txt')
509 parse_multivalue(properties, 'extracted/DerivedJoiningType.txt')
510 parse_multivalue(properties, 'LineBreak.txt')
511 parse_multivalue(properties, 'extracted/DerivedNumericType.txt')
512 parse_multivalue(properties, 'HangulSyllableType.txt')
513 parse_multivalue(properties, 'IndicPositionalCategory.txt')
514 parse_multivalue(properties, 'IndicSyllabicCategory.txt')
515 parse_multivalue(properties, 'Scripts.txt')
516
517 parse_numeric_values(properties, 'extracted/DerivedNumericValues.txt')
518
519 parse_script_extensions(properties, 'ScriptExtensions.txt')
520
521 parse_case_folding(properties, 'CaseFolding.txt')
522
523 unicode_data = {'properties': {}}
524
525 for prop_name, property in properties.items():
526 if has_codepoints(property):
527 unicode_data['properties'][prop_name] = property
528 elif prop_name in {'simple_folding', 'full_folding'}:
529 unicode_data[prop_name] = property
530
531 properties = unicode_data['properties']
532 property = properties[munge('General_Category')]
533 property['default'] = munge('Unassigned')
534
535 values = property['values']
536
537 for val_name, value in list(values.items()):
538 if len(val_name) == 1:
539 new_name = val_name.upper() + '&'
540 values[munge(new_name)] = value
541 value['names'].append(new_name)
542
543 return unicode_data
544
545 def make_binary_property(properties, names, codepoints):
546 no_value = {'names': ['No', 'N', 'F', 'False']}
547 yes_value = {'names': ['Yes', 'Y', 'T', 'True'], 'codepoints': codepoints}
548 values = {}
549
550 for value in [no_value, yes_value]:
551 for name in value['names']:
552 values[munge(name)] = value
553
554 property = {'names': names, 'values': values, 'default': munge('No')}
555
556 for name in names:
557 properties[munge(name)] = property
558
559 def make_ranges(*values):
560 return Ranges((value, value) for value in values)
561
562 def make_additional_properties(unicode_data):
563
564 def get_values(prop_name):
565 return properties[munge(prop_name)]['values']
566
567 def get_codepoints(prop_name, val_name):
568 return get_values(prop_name)[munge(val_name)]['codepoints']
569
570 properties = unicode_data['properties']
571
572 # Make the 'Alphanumeric' property.
573 alphabetic = get_codepoints('Alphabetic', 'Yes')
574 decimal_number = get_codepoints('General_Category', 'Decimal_Number')
575
576 make_binary_property(properties, ['Alphanumeric', 'AlNum'], alphabetic |
577 decimal_number)
578
579 # Make the 'Any' property.
580 make_binary_property(properties, ['Any'], Ranges([(0, NUM_CODEPOINTS -
581 1)]))
582
583 # General_Category has a compound value called 'Assigned'.
584 assigned = Ranges()
585
586 for value in unique(get_values('General_Category').values(), key=id):
587 if value['names'][0] != 'Unassigned':
588 try:
589 assigned |= value['codepoints']
590 except KeyError:
591 pass
592
593 value = {'names': ['Assigned']}
594 properties[munge('General_Category')]['values'][munge('Assigned')] = value
595
596 # Make the 'Blank' property.
597 space_separator = get_codepoints('General_Category', 'Space_Separator')
598 blank = Ranges([(0x09, 0x09)]) | space_separator
599
600 make_binary_property(properties, ['Blank'], blank)
601
602 # Make the 'Graph' property.
603 whitespace = get_codepoints('White_Space', 'Yes')
604 control = get_codepoints('General_Category', 'Control')
605 surrogate = get_codepoints('General_Category', 'Surrogate')
606
607 graph = assigned - (whitespace | control | surrogate)
608
609 make_binary_property(properties, ['Graph'], graph)
610
611 # Make the 'Print' property.
612 print_ = (graph | blank) - control
613
614 make_binary_property(properties, ['Print'], print_)
615
616 # Make the 'Word' property.
617 enclosing_mark = get_codepoints('General_Category', 'Enclosing_Mark')
618 nonspacing_mark = get_codepoints('General_Category', 'Nonspacing_Mark')
619 spacing_mark = get_codepoints('General_Category', 'Spacing_Mark')
620 connector_punctuation = get_codepoints('General_Category',
621 'Connector_Punctuation')
622 join_control = get_codepoints('Join_Control', 'Yes')
623
624 word = (alphabetic | enclosing_mark | nonspacing_mark | spacing_mark |
625 decimal_number | connector_punctuation | join_control)
626
627 make_binary_property(properties, ['Word'], word)
628
629 # Make the 'XDigit' property.
630 hex_digit = get_codepoints('Hex_Digit', 'Yes')
631
632 xdigit = decimal_number | hex_digit
633
634 make_binary_property(properties, ['XDigit'], xdigit)
635
636 # Make the 'Posix_Digit' property.
637 posix_digit = Ranges([(ord('0'), ord('9'))])
638
639 make_binary_property(properties, ['Posix_Digit'], posix_digit)
640
641 # Make the 'Posix_AlNum' property.
642 posix_alnum = alphabetic | posix_digit
643
644 make_binary_property(properties, ['Posix_AlNum'], posix_alnum)
645
646 # Make the 'Posix_Punct' property.
647 punctuation = Ranges()
648
649 for name in 'Pd Ps Pe Pc Po Pi Pf'.split():
650 punctuation |= get_codepoints('General_Category', name)
651
652 symbol = Ranges()
653
654 for name in 'Sm Sc Sk So '.split():
655 symbol |= get_codepoints('General_Category', name)
656
657 posix_punct = (punctuation | symbol) - alphabetic
658
659 make_binary_property(properties, ['Posix_Punct'], posix_punct)
660
661 # Make the 'Posix_XDigit' property.
662 posix_xdigit = Ranges([(ord('0'), ord('9')), (ord('A'), ord('F')),
663 (ord('a'), ord('f'))])
664
665 make_binary_property(properties, ['Posix_XDigit'], posix_xdigit)
666
667 # Make the 'Horiz_Space' property.
668 horiz_space = make_ranges(0x09, 0x20, 0xA0, 0x1680, 0x180E) | Ranges([(0x2000, 0x200A)]) | make_ranges(0x202F, 0x205F, 0x3000)
669
670 make_binary_property(properties, ['Horiz_Space', 'H'], horiz_space)
671
672 # Make the 'Vert_Space' property.
673 vert_space = Ranges([(0x0A, 0x0D)]) | make_ranges(0x85, 0x2028, 0x2029)
674
675 make_binary_property(properties, ['Vert_Space', 'V'], vert_space)
676
677 def preferred(d):
678 return munge(d['names'][0])
679
680 def has_codepoints(property):
681 if 'values' not in property:
682 return False
683
684 return any('codepoints' in value for value in property['values'].values())
685
686 def write_summary(unicode_data, unicode_version, tools_folder):
687 print('Writing summary')
688
689 properties = unicode_data['properties']
690
691 path = join(tools_folder, 'Unicode %s.txt' % unicode_version)
692
693 with open(path, 'w', encoding='ascii') as file:
694 file.write('Version {}\n'.format(unicode_version))
695
696 for property in sorted(unique(properties.values(), key=id),
697 key=preferred):
698 if not has_codepoints(property):
699 print(property['names'][0])
700 continue
701
702 file.write('Property {}\n'.format(' '.join(property['names'])))
703
704 values = property['values']
705
706 if property['names'][0] == 'Script_Extensions':
707 for key in sorted(values):
708 value = values[key]
709 file.write('Value {}\n'.format(' '.join(key)))
710
711 for lower, upper in value.get('codepoints', []):
712 if lower == upper:
713 file.write('{:04X}\n'.format(lower))
714 else:
715 file.write('{:04X}..{:04X}\n'.format(lower, upper))
716 else:
717 if 'default' in property:
718 default = values[property['default']]
719 file.write('DefaultValue {}\n'.format(default['names'][0]))
720
721 for value in sorted(unique(values.values(), key=id),
722 key=preferred):
723 file.write('Value {}\n'.format(' '.join(value['names'])))
724
725 for lower, upper in value.get('codepoints', []):
726 if lower == upper:
727 file.write('{:04X}\n'.format(lower))
728 else:
729 file.write('{:04X}..{:04X}\n'.format(lower, upper))
730
731 file.write('SimpleFolding\n')
732
733 for delta, ranges in unicode_data['simple_folding'].items():
734 file.write('Value {:04X}\n'.format(delta))
735
736 for lower, upper in ranges:
737 if lower == upper:
738 file.write('{:04X}\n'.format(lower))
739 else:
740 file.write('{:04X}..{:04X}\n'.format(lower, upper))
741
742 file.write('FullFolding\n')
743
744 for key, ranges in unicode_data['full_folding'].items():
745 file.write('Value {}\n'.format(' '.join('{:04X}'.format(value) for
746 value in key)))
747
748 for lower, upper in ranges:
749 if lower == upper:
750 file.write('{:04X}\n'.format(lower))
751 else:
752 file.write('{:04X}..{:04X}\n'.format(lower, upper))
753
754 def make_binary_dict():
755 binary_dict = {}
756
757 for n in range(0x100):
758 key = tuple(map(int, format(n, '08b')[ : : -1]))
759 binary_dict[key] = n
760
761 return binary_dict
762
763 def collect_strings(properties):
764 strings = []
765
766 for property in properties.values():
767 try:
768 strings.extend(property['names'])
769
770 for value in property['values'].values():
771 strings.extend(value['names'])
772 except KeyError:
773 pass
774
775 return sorted(set(munge(string) for string in strings))
776
777 def chunked(iterable, chunk_size):
778 sequence = iterable
779 count = len(sequence)
780
781 for start in range(0, count, chunk_size):
782 chunk = sequence[start : start + chunk_size]
783 yield chunk
784
785 def determine_entry_type(iterable):
786 lower, upper = min(iterable), max(iterable)
787
788 if 0 <= lower <= upper <= 0xFF:
789 return 'RE_UINT8'
790
791 if 0 <= lower <= upper <= 0xFFFF:
792 return 'RE_UINT16'
793
794 raise ValueError('cannot determine C type for {}..{}'.format(lower, upper))
795
796 def count_ranges(property):
797 count = 0
798 default_id = property['values'][munge(property['default'])]['id']
799
800 for value in unique(property['values'].values(), key=id):
801 if value['id'] != default_id:
802 count += len(value.get('codepoints', []))
803
804 return count
805
806 def generate_small_lookup(property, c_file):
807 c_file.write('''
808 /* {}. */
809 RE_UINT32 re_get_{}(RE_UINT32 codepoint) {{
810 '''.format(property['names'][0], property['names'][0].lower()))
811
812 default_id = property['values'][munge(property['default'])]['id']
813 ranges = []
814
815 for value in unique(property['values'].values(), key=id):
816 if value['id'] != default_id:
817 val_id = value['id']
818
819 for lower, upper in value.get('codepoints', []):
820 ranges.append((lower, upper, val_id))
821
822 if len(ranges) == 1 and ranges[0][ : 2] == (0, NUM_CODEPOINTS - 1):
823 c_file.write(' return {};\n}}\n'.format(ranges[0][2]))
824 else:
825 for lower, upper, val_id in ranges:
826 width = 2 if upper <= 0xFF else 4 if upper <= 0xFFFF else 6
827
828 if lower == upper:
829 c_file.write('''\
830 if (codepoint == 0x{:0{width}X})
831 return {};
832 '''.format(lower, val_id, width=width))
833 else:
834 c_file.write('''\
835 if (0x{:0{width}X} <= codepoint && codepoint <= 0x{:0{width}X})
836 return {};
837 '''.format(lower, upper, val_id, width=width))
838
839 c_file.write('\n return {};\n}}\n'.format(default_id))
840
841 def generate_table(table_name, values, c_file, max_columns=16, public=False):
842 entry_type = determine_entry_type(values)
843
844 if public:
845 c_file.write('{} {}[] = {{\n'.format(entry_type, table_name))
846 else:
847 c_file.write('static {} {}[] = {{\n'.format(entry_type, table_name))
848
849 entries = [str(value) for value in values]
850 max_width = max(len(entry) for entry in entries)
851 entries = [entry.rjust(max_width) + ',' for entry in entries]
852 entries[-1] = entries[-1].rstrip(',')
853
854 for chunk in chunked(entries, max_columns):
855 c_file.write(' %s\n' % ' '.join(chunk))
856
857 c_file.write('};\n')
858
859 def generate_lookup(property, c_file):
860 val_list = list(unique(property['values'].values(), key=id))
861
862 if count_ranges(property) <= 8:
863 generate_small_lookup(property, c_file)
864 return
865
866 default_id = property['values'][munge(property['default'])]['id']
867 entries = [default_id] * NUM_CODEPOINTS
868
869 for value in val_list:
870 val_id = value['id']
871
872 for lower, upper in value.get('codepoints', []):
873 entries[lower : upper + 1] = [val_id] * (upper - lower + 1)
874
875 CHUNK_SIZE = 32
876
877 indexes = []
878 chunks = {}
879
880 for chunk in chunked(tuple(entries), CHUNK_SIZE):
881 indexes.append(chunks.setdefault(chunk, len(chunks)))
882
883 table_2 = list(chain(*sorted(chunks, key=chunks.get)))
884
885 entries = indexes
886 indexes = []
887 chunks = {}
888
889 for start in range(0, len(entries), CHUNK_SIZE):
890 chunk = tuple(entries[start : start + CHUNK_SIZE])
891 indexes.append(chunks.setdefault(chunk, len(chunks)))
892
893 table_1 = list(chain(*sorted(chunks, key=chunks.get)))
894
895 table_0 = indexes
896
897 c_file.write('\n/* {}. */\n'.format(property['names'][0]))
898
899 prop_name = property['names'][0].lower()
900 binary = set(table_2) == {0, 1}
901
902 for i, table in enumerate([table_0, table_1, table_2]):
903 if i == 2 and binary:
904 binary = True
905 entries = []
906
907 for start in range(0, len(table), 8):
908 entries.append(binary_dict[tuple(table[start : start + 8])])
909
910 table = entries
911
912 if i > 0:
913 c_file.write('\n')
914
915 generate_table('re_{}_table_{}'.format(prop_name, 1 + i), table,
916 c_file)
917
918 if binary:
919 c_file.write('''
920 RE_UINT32 re_get_{0}(RE_UINT32 codepoint) {{
921 RE_UINT32 field_2;
922 RE_UINT32 field_1;
923 RE_UINT32 field_0;
924 RE_UINT32 offset;
925 RE_UINT32 v;
926
927 field_2 = codepoint >> 10;
928 field_1 = (codepoint >> 5) & 0x1F;
929 field_0 = (codepoint >> 3) & 0x3;
930 offset = codepoint & 0x7;
931
932 v = re_{0}_table_1[field_2];
933 v = re_{0}_table_2[(v << 5) | field_1];
934 v = re_{0}_table_3[(v << 2) | field_0];
935
936 return (v >> offset) & 0x1;
937 }}
938 '''.format(prop_name))
939 else:
940 c_file.write('''
941 RE_UINT32 re_get_{0}(RE_UINT32 codepoint) {{
942 RE_UINT32 field_2;
943 RE_UINT32 field_1;
944 RE_UINT32 field_0;
945 RE_UINT32 v;
946
947 field_2 = codepoint >> 10;
948 field_1 = (codepoint >> 5) & 0x1F;
949 field_0 = codepoint & 0x1F;
950
951 v = re_{0}_table_1[field_2];
952 v = re_{0}_table_2[(v << 5) | field_1];
953 v = re_{0}_table_3[(v << 5) | field_0];
954
955 return v;
956 }}
957 '''.format(prop_name))
958
959 def generate_script_extensions_lookup(properties, property, c_file):
960 entries = [0] * NUM_CODEPOINTS
961
962 # Initialise with script.
963 val_list = unique(properties[munge('Script')]['values'].values(), key=id)
964
965 for value in val_list:
966 val_id = value['id']
967
968 for lower, upper in value.get('codepoints', []):
969 entries[lower : upper + 1] = [val_id] * (upper - lower + 1)
970
971 script_count = 1 + max(value['id'] for value in
972 properties[munge('Script')]['values'].values())
973
974 val_list = unique(property['values'].values(), key=id)
975
976 for value in val_list:
977 val_id = value['id']
978
979 for lower, upper in value.get('codepoints', []):
980 entries[lower : upper + 1] = [val_id] * (upper - lower + 1)
981
982 CHUNK_SIZE = 32
983
984 indexes = []
985 chunks = {}
986
987 for chunk in chunked(entries, CHUNK_SIZE):
988 indexes.append(chunks.setdefault(tuple(chunk), len(chunks)))
989
990 table_2 = list(chain(*sorted(chunks, key=chunks.get)))
991
992 entries = indexes
993 indexes = []
994 chunks = {}
995
996 for start in range(0, len(entries), CHUNK_SIZE):
997 chunk = tuple(entries[start : start + CHUNK_SIZE])
998 indexes.append(chunks.setdefault(chunk, len(chunks)))
999
1000 table_1 = list(chain(*sorted(chunks, key=chunks.get)))
1001
1002 table_0 = indexes
1003
1004 c_file.write('\n/* {}. */\n'.format(property['names'][0]))
1005
1006 prop_name = property['names'][0].lower()
1007
1008 for i, table in enumerate([table_0, table_1, table_2]):
1009 generate_table('{}_table_{}'.format(prop_name, 1 + i), table, c_file)
1010
1011 script_values = properties[munge('Script')]['values']
1012 ext_dict = {}
1013
1014 for key, value in property['values'].items():
1015 ext_dict[value['id']] = [script_values[munge(name)]['id'] for name in
1016 key]
1017
1018 offsets = []
1019 entries = []
1020
1021 for key, value in sorted(ext_dict.items()):
1022 offsets.append(len(entries))
1023 entries.extend(value + [0])
1024
1025 generate_table('{}_table_4'.format(prop_name), offsets, c_file)
1026
1027 generate_table('{}_table_5'.format(prop_name), entries, c_file)
1028
1029 c_file.write('''
1030 int re_get_{0}(RE_UINT32 codepoint, RE_UINT8* scripts) {{
1031 RE_UINT32 field_2;
1032 RE_UINT32 field_1;
1033 RE_UINT32 field_0;
1034 RE_UINT32 v;
1035 int offset;
1036 int count;
1037
1038 field_2 = codepoint >> 10;
1039 field_1 = (codepoint >> 5) & 0x1F;
1040 field_0 = codepoint & 0x1F;
1041
1042 v = {0}_table_1[field_2];
1043 v = {0}_table_2[(v << 5) | field_1];
1044 v = {0}_table_3[(v << 5) | field_0];
1045
1046 if (v < {1}) {{
1047 scripts[0] = v;
1048
1049 return 1;
1050 }}
1051
1052 offset = {0}_table_4[v - {1}];
1053 count = 0;
1054
1055 do {{
1056 scripts[count] = {0}_table_5[offset + count];
1057 ++count;
1058 }} while ({0}_table_5[offset + count] != 0);
1059
1060 return count;
1061 }}
1062 '''.format(prop_name, script_count))
1063
1064 def generate_all_cases(unicode_data, c_file):
1065 simple_folding = unicode_data['simple_folding']
1066
1067 all_cases = {}
1068
1069 for delta, ranges in simple_folding.items():
1070 for lower, upper in ranges:
1071 for codepoint in range(lower, upper + 1):
1072 folded = codepoint ^ delta
1073 all_cases.setdefault(folded, set()).update({codepoint, folded})
1074
1075 for codepoint in list(all_cases):
1076 cases = {codepoint} | all_cases.get(codepoint, set())
1077
1078 for c in list(cases):
1079 cases |= all_cases.get(c, set())
1080
1081 for c in cases:
1082 all_cases[c] = cases
1083
1084 all_cases[0x49] = {0x49, 0x69, 0x131} # Dotless capital I.
1085 all_cases[0x69] = {0x69, 0x49, 0x130} # Dotted small I.
1086 all_cases[0x130] = {0x130, 0x69} # Dotted capital I.
1087 all_cases[0x131] = {0x131, 0x49} # Dotless small I.
1088
1089 entries = [0] * NUM_CODEPOINTS
1090 others_dict = {(0, ): 0}
1091
1092 for codepoint, cases in all_cases.items():
1093 others = sorted(cases - {codepoint})
1094 key = tuple([others[0] ^ codepoint] + others[1 : ])
1095 entries[codepoint] = others_dict.setdefault(key, len(others_dict))
1096
1097 CHUNK_SIZE = 32
1098
1099 indexes = []
1100 chunks = {}
1101
1102 for chunk in chunked(entries, CHUNK_SIZE):
1103 indexes.append(chunks.setdefault(tuple(chunk), len(chunks)))
1104
1105 table_2 = list(chain(*sorted(chunks, key=chunks.get)))
1106
1107 entries = indexes
1108 indexes = []
1109 chunks = {}
1110
1111 for start in range(0, len(entries), CHUNK_SIZE):
1112 chunk = tuple(entries[start : start + CHUNK_SIZE])
1113 indexes.append(chunks.setdefault(chunk, len(chunks)))
1114
1115 table_1 = list(chain(*sorted(chunks, key=chunks.get)))
1116
1117 table_0 = indexes
1118
1119 c_file.write('\n/* All cases. */\n')
1120
1121 for i, table in enumerate([table_0, table_1, table_2]):
1122 if i > 0:
1123 c_file.write('\n')
1124
1125 generate_table('re_all_cases_table_{}'.format(1 + i), table, c_file)
1126
1127 c_file.write('\nstatic RE_AllCases re_all_cases_table_4[] = {\n')
1128
1129 max_columns = max(len(value) for value in others_dict)
1130
1131 max_width = max(len(str(item)) for value in others_dict for item in value)
1132 fmt = ' {{{:%d}, {{' % max_width + ', '.join(['{:%d}' % max_width] *
1133 (max_columns -1)) + '}}}},\n'
1134
1135 lines = []
1136
1137 for values in sorted(others_dict, key=others_dict.get):
1138 values = list(values) + [0] * max_columns
1139 lines.append(fmt.format(*values))
1140
1141 lines[-1] = lines[-1].rstrip(',\n') + '\n'
1142
1143 c_file.writelines(lines)
1144
1145 c_file.write('};\n')
1146
1147 c_file.write('''
1148 int re_get_all_cases(RE_UINT32 codepoint, RE_UINT32* cases) {
1149 RE_UINT32 field_2;
1150 RE_UINT32 field_1;
1151 RE_UINT32 field_0;
1152 RE_UINT32 v;
1153
1154 field_2 = codepoint >> 10;
1155 field_1 = (codepoint >> 5) & 0x1F;
1156 field_0 = codepoint & 0x1F;
1157
1158 v = re_all_cases_table_1[field_2];
1159 v = re_all_cases_table_2[(v << 5) | field_1];
1160 v = re_all_cases_table_3[(v << 5) | field_0];
1161
1162 cases[0] = codepoint;
1163
1164 if (re_all_cases_table_4[v].delta == 0)
1165 return 1;
1166
1167 cases[1] = codepoint ^ re_all_cases_table_4[v].delta;
1168
1169 if (re_all_cases_table_4[v].others[0] == 0)
1170 return 2;
1171
1172 cases[2] = re_all_cases_table_4[v].others[0];
1173
1174 if (re_all_cases_table_4[v].others[1] == 0)
1175 return 3;
1176
1177 cases[3] = re_all_cases_table_4[v].others[1];
1178
1179 return 4;
1180 }
1181 ''')
1182
1183 def generate_simple_case_folding(unicode_data, c_file):
1184 simple_folding = unicode_data['simple_folding']
1185
1186 entries = [0] * NUM_CODEPOINTS
1187 value_dict = {0: 0}
1188
1189 for delta, ranges in sorted(simple_folding.items()):
1190 val_id = value_dict.setdefault(delta, len(value_dict))
1191
1192 for lower, upper in ranges:
1193 entries[lower : upper + 1] = [val_id] * (upper - lower + 1)
1194
1195 CHUNK_SIZE = 32
1196
1197 indexes = []
1198 chunks = {}
1199
1200 for chunk in chunked(entries, CHUNK_SIZE):
1201 indexes.append(chunks.setdefault(tuple(chunk), len(chunks)))
1202
1203 table_2 = list(chain(*sorted(chunks, key=chunks.get)))
1204
1205 entries = indexes
1206 indexes = []
1207 chunks = {}
1208
1209 for start in range(0, len(entries), CHUNK_SIZE):
1210 chunk = tuple(entries[start : start + CHUNK_SIZE])
1211 indexes.append(chunks.setdefault(chunk, len(chunks)))
1212
1213 table_1 = list(chain(*sorted(chunks, key=chunks.get)))
1214
1215 table_0 = indexes
1216
1217 c_file.write('\n/* Simple case folding. */\n')
1218
1219 for i, table in enumerate([table_0, table_1, table_2]):
1220 if i > 0:
1221 c_file.write('\n')
1222
1223 generate_table('re_simple_folding_table_{}'.format(1 + i), table, c_file)
1224
1225 c_file.write('\nstatic RE_UINT16 re_simple_folding_table_4[] = {\n')
1226
1227 entries = [str(value) for value in sorted(value_dict, key=value_dict.get)]
1228 max_width = max(len(entry) for entry in entries)
1229 entries = [entry.rjust(max_width) + ',' for entry in entries]
1230 entries[-1] = entries[-1].rstrip(',')
1231
1232 for chunk in chunked(entries, 8):
1233 c_file.write(' %s\n' % ' '.join(chunk))
1234
1235 c_file.write('};\n')
1236
1237 c_file.write('''
1238 RE_UINT32 re_get_simple_case_folding(RE_UINT32 codepoint) {
1239 RE_UINT32 field_2;
1240 RE_UINT32 field_1;
1241 RE_UINT32 field_0;
1242 RE_UINT32 v;
1243
1244 field_2 = codepoint >> 10;
1245 field_1 = (codepoint >> 5) & 0x1F;
1246 field_0 = codepoint & 0x1F;
1247
1248 v = re_simple_folding_table_1[field_2];
1249 v = re_simple_folding_table_2[(v << 5) | field_1];
1250 v = re_simple_folding_table_3[(v << 5) | field_0];
1251
1252 return codepoint ^ re_simple_folding_table_4[v];
1253 }
1254 ''')
1255
1256 def generate_full_case_folding(unicode_data, c_file):
1257 full_folding = unicode_data['full_folding']
1258
1259 entries = [0] * NUM_CODEPOINTS
1260 value_dict = {(0, ): 0}
1261
1262 for delta, ranges in sorted(full_folding.items()):
1263 val_id = value_dict.setdefault(delta, len(value_dict))
1264
1265 for lower, upper in ranges:
1266 entries[lower : upper + 1] = [val_id] * (upper - lower + 1)
1267
1268 CHUNK_SIZE = 32
1269
1270 indexes = []
1271 chunks = {}
1272
1273 for chunk in chunked(entries, CHUNK_SIZE):
1274 indexes.append(chunks.setdefault(tuple(chunk), len(chunks)))
1275
1276 table_2 = list(chain(*sorted(chunks, key=chunks.get)))
1277
1278 entries = indexes
1279 indexes = []
1280 chunks = {}
1281
1282 for start in range(0, len(entries), CHUNK_SIZE):
1283 chunk = tuple(entries[start : start + CHUNK_SIZE])
1284 indexes.append(chunks.setdefault(chunk, len(chunks)))
1285
1286 table_1 = list(chain(*sorted(chunks, key=chunks.get)))
1287
1288 table_0 = indexes
1289
1290 c_file.write('\n/* Full case folding. */\n')
1291
1292 for i, table in enumerate([table_0, table_1, table_2]):
1293 if i > 0:
1294 c_file.write('\n')
1295
1296 generate_table('re_full_folding_table_{}'.format(1 + i), table, c_file)
1297
1298 c_file.write('\nstatic RE_FullCaseFolding re_full_folding_table_4[] = {\n')
1299
1300 max_folded = max(len(value) for value in value_dict)
1301 max_width = max(len(str(item)) for value in value_dict for item in value)
1302 rows = [(value + (0, ) * max_folded)[ : max_folded] for value in
1303 sorted(value_dict, key=value_dict.get)]
1304 fmt = (' {{{{' + ', '.join(['{:%d}' % max_width] * max_folded) +
1305 '}}}},\n').format
1306 lines = []
1307
1308 for row in rows:
1309 lines.append(fmt(*row))
1310
1311 lines[-1] = lines[-1].rstrip(',\n') + '\n'
1312
1313 c_file.writelines(lines)
1314
1315 c_file.write('};\n')
1316
1317 c_file.write('''
1318 int re_get_full_case_folding(RE_UINT32 codepoint, RE_UINT32* folded) {
1319 RE_UINT32 field_2;
1320 RE_UINT32 field_1;
1321 RE_UINT32 field_0;
1322 RE_UINT32 v;
1323 RE_UINT16* data;
1324
1325 field_2 = codepoint >> 10;
1326 field_1 = (codepoint >> 5) & 0x1F;
1327 field_0 = codepoint & 0x1F;
1328
1329 v = re_full_folding_table_1[field_2];
1330 v = re_full_folding_table_2[(v << 5) | field_1];
1331 v = re_full_folding_table_3[(v << 5) | field_0];
1332
1333 data = re_full_folding_table_4[v].data;
1334 folded[0] = codepoint ^ data[0];
1335
1336 if (data[1] == 0)
1337 return 1;
1338
1339 folded[1] = data[1];
1340
1341 if (data[2] == 0)
1342 return 2;
1343
1344 folded[2] = data[2];
1345
1346 return 3;
1347 }
1348 ''')
1349
1350 def generate_code(unicode_data, unicode_version, output_folder):
1351 print('Generating code')
1352
1353 # Codepoints that expand on full casefolding.
1354 expanded = []
1355
1356 for key, ranges in unicode_data['full_folding'].items():
1357 if len(key) > 1:
1358 for lower, upper in ranges:
1359 expanded.extend(range(lower, upper + 1))
1360
1361 expanded.sort()
1362
1363 # Assign the property and value IDs.
1364 properties = unicode_data['properties']
1365 prop_list = list(unique(properties.values(), key=id))
1366 prop_list.sort(key=preferred)
1367
1368 unicode_data['property_table_count'] = len(properties)
1369 unicode_data['property_count'] = len(prop_list)
1370
1371 no_yes_maybe = {
1372 'NO', 'N', 'FALSE', 'F',
1373 'YES', 'Y', 'TRUE', 'T',
1374 'MAYBE', 'M',
1375 }
1376
1377 yes_no_maybe_dict = {'No': 0, 'Yes': 1, 'Maybe': 2}
1378
1379 for prop_id, property in enumerate(prop_list):
1380 property['id'] = prop_id
1381
1382 if property['names'][0] == 'Script_Extensions':
1383 script_count = 1 + max(val['id'] for val in
1384 properties[munge('Script')]['values'].values())
1385
1386 def make_key(value):
1387 return value['codepoints'].lowest()
1388
1389 val_list = list(unique(property['values'].values(), key=id))
1390 val_list.sort(key=make_key)
1391
1392 for val_id, value in enumerate(val_list):
1393 value['id'] = script_count + val_id
1394 else:
1395 default = property['default']
1396
1397 if not (set(property['values']) - no_yes_maybe):
1398
1399 def make_key(value):
1400 return yes_no_maybe_dict[value['names'][0]]
1401
1402 else:
1403
1404 def make_key(value):
1405 if any(munge(name) == default for name in value['names']):
1406 return (0, )
1407
1408 if 'codepoints' not in value:
1409 return (2, )
1410
1411 return 1, value['codepoints'].lowest()
1412
1413 val_list = list(unique(property['values'].values(), key=id))
1414 val_list.sort(key=make_key)
1415
1416 def make_key(val):
1417 name_list = [name for name in val['names'] if '&' in name]
1418
1419 if name_list:
1420 return 1, name_list[0][0]
1421
1422 return 0
1423
1424 if property['names'][0] == 'General_Category':
1425
1426 def make_key(value):
1427 for name in value['names']:
1428 if '&' in name:
1429 return (1, name)
1430
1431 if value.get('codepoints'):
1432 return (0, )
1433
1434 return (2, munge(value['names'][0]))
1435
1436 for val_id, value in enumerate(sorted(val_list, key=make_key)):
1437 value['id'] = val_id
1438 else:
1439 for val_id, value in enumerate(val_list):
1440 value['id'] = val_id
1441
1442 # Collect the value sets.
1443 valueset_dict = {}
1444
1445 for property in sorted(prop_list, key=lambda prop: prop['id']):
1446 prop_name = property['names'][0]
1447
1448 if prop_name == 'Script_Extensions':
1449 property['valueset_id'] = properties[munge('Script')]['valueset_id']
1450 else:
1451 valueset = []
1452
1453 val_list = list(unique(property['values'].values(), key=id))
1454
1455 for value in sorted(val_list, key=lambda val: val['id']):
1456 valueset.append((value['id'], tuple(value['names'])))
1457
1458 valueset_id = valueset_dict.setdefault(tuple(valueset),
1459 len(valueset_dict))
1460 property['valueset_id'] = valueset_id
1461
1462 strings = collect_strings(properties)
1463
1464 c_path = join(output_folder, '_regex_unicode.c')
1465 h_path = join(output_folder, '_regex_unicode.h')
1466
1467 with open(c_path, 'w', newline='\n', encoding='ascii') as c_file:
1468 c_file.write('''\
1469 /* For Unicode version {} */
1470
1471 #include "_regex_unicode.h"
1472
1473 #define RE_BLANK_MASK ((1 << RE_PROP_ZL) | (1 << RE_PROP_ZP))
1474 #define RE_GRAPH_MASK ((1 << RE_PROP_CC) | (1 << RE_PROP_CS) | (1 << RE_PROP_CN))
1475 #define RE_WORD_MASK (RE_PROP_M_MASK | (1 << RE_PROP_ND) | (1 << RE_PROP_PC))
1476
1477 typedef struct {{
1478 RE_UINT8 scripts[RE_MAX_SCX];
1479 }} RE_ScriptExt;
1480
1481 typedef struct {{
1482 RE_UINT32 delta;
1483 RE_UINT16 others[RE_MAX_CASES - 1];
1484 }} RE_AllCases;
1485
1486 typedef struct {{
1487 RE_UINT16 data[RE_MAX_FOLDED];
1488 }} RE_FullCaseFolding;
1489
1490 /* Strings. */
1491 char* re_strings[] = {{
1492 '''.format(unicode_version))
1493
1494 lines = []
1495
1496 for string in strings:
1497 lines.append(' "{}",\n'.format(string))
1498
1499 strings_dict = {string: i for i, string in enumerate(strings)}
1500
1501 unicode_data['string_count'] = len(strings_dict)
1502
1503 c_file.writelines(lines)
1504 c_file.write('''\
1505 };
1506
1507 /* Properties. */
1508 RE_Property re_properties[] = {
1509 ''')
1510
1511 for prop_id, property in enumerate(sorted(prop_list, key=lambda prop:
1512 prop['id'])):
1513 for name in property['names']:
1514 c_file.write(' {{{:4}, {:2}, {:2}}}, /* {} */\n'.format(strings_dict[munge(name)],
1515 prop_id, property['valueset_id'], munge(name)))
1516
1517 c_file.write('''\
1518 };
1519
1520 /* Property values. */
1521 RE_PropertyValue re_property_values[] = {
1522 ''')
1523
1524 def make_key(names):
1525 if any(len(name) == 2 for name in names):
1526 return 0
1527
1528 return 1
1529
1530 gc_valset_id = properties[munge('General_Category')]['valueset_id']
1531 count = 0
1532
1533 for valset, valset_id in sorted(valueset_dict.items(), key=lambda pair:
1534 pair[1]):
1535 for val_id, names in valset:
1536 if valset_id == gc_valset_id:
1537 names = sorted(names, key=make_key)
1538
1539 for name in names:
1540 c_file.write(''' {{{:4}, {:2}, {:3}}}, /* {} */\n'''.format(strings_dict[munge(name)],
1541 valset_id, val_id, munge(name)))
1542
1543 count += len(names)
1544
1545 unicode_data['valueset_table_count'] = count
1546
1547 c_file.write('};\n')
1548
1549 c_file.write('''\n/* Codepoints which expand on full case-folding. */\n''')
1550
1551 unicode_data['expanded_count'] = len(expanded)
1552 generate_table('re_expand_on_folding', expanded, c_file, max_columns=8, public=True)
1553
1554 for property in prop_list:
1555 print(' {}'.format(property['names'][0]), flush=True)
1556
1557 if property['names'][0] == 'Script_Extensions':
1558 generate_script_extensions_lookup(properties, property, c_file)
1559 else:
1560 generate_lookup(property, c_file)
1561
1562 print(' All cases', flush=True)
1563 generate_all_cases(unicode_data, c_file)
1564
1565 print(' Simple case folding', flush=True)
1566 generate_simple_case_folding(unicode_data, c_file)
1567
1568 print(' Full case folding', flush=True)
1569 generate_full_case_folding(unicode_data, c_file)
1570
1571 c_file.write('''
1572 /* Property function table. */
1573 RE_GetPropertyFunc re_get_property[] = {
1574 ''')
1575
1576 lines = []
1577
1578 for property in prop_list:
1579 prop_name = property['names'][0].lower()
1580
1581 if prop_name == 'script_extensions':
1582 lines.append(' 0,\n')
1583 else:
1584 lines.append(' re_get_{},\n'.format(prop_name))
1585
1586 lines[-1] = lines[-1].rstrip(',\n') + '\n'
1587
1588 c_file.writelines(lines)
1589
1590 c_file.write('};\n')
1591
1592 with open(h_path, 'w', newline='\n', encoding='ascii') as h_file:
1593 property = unicode_data['properties'][munge('Script_Extensions')]
1594 max_scx = max(len(key) for key in property['values'])
1595
1596 h_file.write('''\
1597 typedef unsigned char RE_UINT8;
1598 typedef signed char RE_INT8;
1599 typedef unsigned short RE_UINT16;
1600 typedef signed short RE_INT16;
1601 typedef unsigned int RE_UINT32;
1602 typedef signed int RE_INT32;
1603
1604 typedef unsigned char BOOL;
1605 #if !defined(FALSE) || !defined(TRUE)
1606 #define FALSE 0
1607 #define TRUE 1
1608 #endif
1609
1610 #define RE_ASCII_MAX 0x7F
1611 #define RE_LOCALE_MAX 0xFF
1612
1613 #define RE_MAX_CASES 4
1614 #define RE_MAX_FOLDED 3
1615 #define RE_MAX_SCX {}
1616
1617 typedef struct RE_Property {{
1618 RE_UINT16 name;
1619 RE_UINT8 id;
1620 RE_UINT8 value_set;
1621 }} RE_Property;
1622
1623 typedef struct RE_PropertyValue {{
1624 RE_UINT16 name;
1625 RE_UINT8 value_set;
1626 RE_UINT16 id;
1627 }} RE_PropertyValue;
1628
1629 typedef RE_UINT32 (*RE_GetPropertyFunc)(RE_UINT32 codepoint);
1630 '''.format(max_scx))
1631
1632 gc_id = properties[munge('General_Category')]['id']
1633 cased_id = properties[munge('Cased')]['id']
1634 upper_id = properties[munge('Uppercase')]['id']
1635 lower_id = properties[munge('Lowercase')]['id']
1636 scx_id = properties[munge('Script_Extensions')]['id']
1637
1638 h_file.write('''
1639 #define RE_PROP_GC 0x{:X}
1640 #define RE_PROP_CASED 0x{:X}
1641 #define RE_PROP_UPPERCASE 0x{:X}
1642 #define RE_PROP_LOWERCASE 0x{:X}
1643 #define RE_PROP_SCX 0x{:X}
1644
1645 '''.format(gc_id, cased_id, upper_id, lower_id, scx_id))
1646
1647 gc_values = properties[munge('General_Category')]['values']
1648 group_names = set('C L M N P S Z Assigned Cased_Letter'.split())
1649
1650 names = set(gc_values) & set(munge(name) for name in group_names)
1651
1652 for name in sorted(names, key=lambda name: gc_values[name]['id']):
1653 h_file.write('#define RE_PROP_{} {}\n'.format(name,
1654 gc_values[name]['id']))
1655
1656 h_file.write('\n')
1657
1658 val_list = []
1659 masks = {}
1660
1661 for name in gc_values:
1662 if len(name) != 2 or not name.isalpha():
1663 continue
1664
1665 if not gc_values[name].get('codepoints'):
1666 continue
1667
1668 val_id = gc_values[name]['id']
1669 val_list.append((val_id, name))
1670 masks.setdefault(name[0], 0)
1671 masks[name[0]] |= 1 << val_id
1672
1673 for val_id, name in sorted(val_list):
1674 h_file.write('#define RE_PROP_{} {}\n'.format(name, val_id))
1675
1676 h_file.write('\n')
1677
1678 for name, mask in sorted(masks.items()):
1679 h_file.write('#define RE_PROP_{}_MASK 0x{:08X}\n'.format(name,
1680 mask))
1681
1682 h_file.write('\n')
1683
1684 common = '''
1685 Alnum Alpha Any Ascii Blank Cntrl Digit Graph Lower Print Space
1686 Upper Word Xdigit Posix_Alnum Posix_Digit Posix_Punct Posix_Xdigit
1687 '''
1688
1689 for name in common.split():
1690 property = properties.get(munge(name))
1691
1692 if property is not None:
1693 h_file.write('#define RE_PROP_{} 0x{:06X}\n'.format(name.upper(),
1694 (property['id'] << 16) | 1))
1695 else:
1696 for prop_name in ['GC', 'Script', 'Block']:
1697 property = properties[munge(prop_name)]
1698 value = property['values'].get(munge(name))
1699
1700 if value is not None:
1701 h_file.write('#define RE_PROP_{} 0x{:06X}\n'.format(name.upper(),
1702 (property['id'] << 16) | value['id']))
1703 break
1704
1705 h_file.write('\n')
1706
1707 val_list = unique(properties[munge('Word_Break')]['values'].values(),
1708 key=id)
1709 values = [(value['id'], value['names'][0]) for value in val_list]
1710
1711 for val_id, name in sorted(values):
1712 h_file.write('#define RE_WBREAK_{} {}\n'.format(munge(name),
1713 val_id))
1714
1715 h_file.write('\n')
1716
1717 val_list = unique(properties[munge('Grapheme_Cluster_Break')]['values'].values(),
1718 key=id)
1719 values = [(value['id'], value['names'][0]) for value in val_list]
1720
1721 for val_id, name in sorted(values):
1722 h_file.write('#define RE_GBREAK_{} {}\n'.format(munge(name),
1723 val_id))
1724
1725 h_file.write('\n')
1726
1727 val_list = unique(properties[munge('Line_Break')]['values'].values(),
1728 key=id)
1729 values = [(value['id'], value['names'][0]) for value in val_list]
1730
1731 for val_id, name in sorted(values):
1732 h_file.write('#define RE_LBREAK_{} {}\n'.format(munge(name),
1733 val_id))
1734
1735 h_file.write('\n')
1736
1737 val_list = unique(properties[munge('Indic_Conjunct_Break')]['values'].values(),
1738 key=id)
1739 values = [(value['id'], value['names'][0]) for value in val_list]
1740
1741 for val_id, name in sorted(values):
1742 h_file.write('#define RE_INCB_{} {}\n'.format(munge(name),
1743 val_id))
1744
1745 h_file.write('\n')
1746
1747 h_file.write('extern char* re_strings[{}];\n'.format(unicode_data['string_count']))
1748 h_file.write('extern RE_Property re_properties[{}];\n'.format(unicode_data['property_table_count']))
1749 h_file.write('extern RE_PropertyValue re_property_values[{}];\n'.format(unicode_data['valueset_table_count']))
1750 h_file.write('extern RE_UINT16 re_expand_on_folding[{}];\n'.format(unicode_data['expanded_count']))
1751 h_file.write('extern RE_GetPropertyFunc re_get_property[{}];\n'.format(unicode_data['property_count']))
1752
1753 h_file.write('\n')
1754
1755 for property in prop_list:
1756 prop_name = property['names'][0]
1757
1758 if prop_name == 'Script_Extensions':
1759 h_file.write('int re_get_{}(RE_UINT32 codepoint, RE_UINT8* scripts);\n'.format(prop_name.lower()))
1760 else:
1761 h_file.write('RE_UINT32 re_get_{}(RE_UINT32 codepoint);\n'.format(prop_name.lower()))
1762
1763 h_file.write('int re_get_all_cases(RE_UINT32 codepoint, RE_UINT32* cases);\n')
1764 h_file.write('RE_UINT32 re_get_simple_case_folding(RE_UINT32 codepoint);\n')
1765 h_file.write('int re_get_full_case_folding(RE_UINT32 codepoint, RE_UINT32* folded);\n')
1766
1767 # The Unicode version.
1768 UNICODE_VERSION = '16.0.0'
1769
1770 this_folder = dirname(__file__)
1771
1772 # The URL from which the Unicode data can be obtained.
1773 ucd_zip_url = 'https://www.unicode.org/Public/zipped/%s/UCD.zip' % UNICODE_VERSION
1774
1775 ucd_zip_path = join(this_folder, 'UCD.zip')
1776
1777 if not have_ucd_version(ucd_zip_path, UNICODE_VERSION):
1778 # Download the zipped Unicode data.
1779 print('Downloading UCD.zip for Unicode %s' % UNICODE_VERSION, flush=True)
1780 urlretrieve(ucd_zip_url, ucd_zip_path)
1781
1782 NUM_CODEPOINTS = 0x110000
1783
1784 # The generated C files will be written into this folder.
1785 tools_folder = dirname(__file__)
1786
1787 unicode_data = parse_unicode_data_files(ucd_zip_path)
1788 make_additional_properties(unicode_data)
1789 write_summary(unicode_data, UNICODE_VERSION, this_folder)
1790
1791 binary_dict = make_binary_dict()
1792
1793 generate_code(unicode_data, UNICODE_VERSION, this_folder)
1794
1795 print('\nSuccessfully generated _regex_unicode.h and _regex_unicode.c in %s' % tools_folder)