|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import itertools |
| 3 | +import os |
| 4 | +import re |
| 5 | +import sys |
| 6 | + |
| 7 | +if sys.version_info[0] < 3: |
| 8 | + raise RuntimeError('This needs to run on Python 3.') |
| 9 | + |
| 10 | + |
| 11 | +def get_characters(): |
| 12 | + """Find every Unicode character that is valid in a Python `identifier`_ but |
| 13 | + is not matched by the regex ``\w`` group. |
| 14 | +
|
| 15 | + ``\w`` matches some characters that aren't valid in identifiers, but |
| 16 | + :meth:`str.isidentifier` will catch that later in lexing. |
| 17 | +
|
| 18 | + All start characters are valid continue characters, so we only test for |
| 19 | + continue characters. |
| 20 | +
|
| 21 | + _identifier: https://docs.python.org/3/reference/lexical_analysis.html#identifiers |
| 22 | + """ |
| 23 | + for cp in range(sys.maxunicode + 1): |
| 24 | + s = chr(cp) |
| 25 | + |
| 26 | + if ('a' + s).isidentifier() and not re.match(r'\w', s): |
| 27 | + yield s |
| 28 | + |
| 29 | + |
| 30 | +def collapse_ranges(data): |
| 31 | + """Given a sorted list of unique characters, generate ranges representing |
| 32 | + sequential code points. |
| 33 | +
|
| 34 | + Source: https://stackoverflow.com/a/4629241/400617 |
| 35 | + """ |
| 36 | + for a, b in itertools.groupby( |
| 37 | + enumerate(data), |
| 38 | + lambda x: ord(x[1]) - x[0] |
| 39 | + ): |
| 40 | + b = list(b) |
| 41 | + yield b[0][1], b[-1][1] |
| 42 | + |
| 43 | + |
| 44 | +def build_pattern(ranges): |
| 45 | + """Output the regex pattern for ranges of characters. |
| 46 | +
|
| 47 | + One and two character ranges output the individual characters. |
| 48 | + """ |
| 49 | + out = [] |
| 50 | + |
| 51 | + for a, b in ranges: |
| 52 | + if a == b: # single char |
| 53 | + out.append(a) |
| 54 | + elif ord(b) - ord(a) == 1: # two chars, range is redundant |
| 55 | + out.append(a) |
| 56 | + out.append(b) |
| 57 | + else: |
| 58 | + out.append(f'{a}-{b}') |
| 59 | + |
| 60 | + return ''.join(out) |
| 61 | + |
| 62 | + |
| 63 | +def main(): |
| 64 | + """Build the regex pattern and write it to the file |
| 65 | + :file:`jinja2/_identifier.py`.""" |
| 66 | + pattern = build_pattern(collapse_ranges(get_characters())) |
| 67 | + filename = os.path.abspath(os.path.join( |
| 68 | + os.path.dirname(__file__), '..', 'jinja2', '_identifier.py' |
| 69 | + )) |
| 70 | + |
| 71 | + with open(filename, 'w', encoding='utf8') as f: |
| 72 | + f.write('# generated by scripts/generate_identifier_pattern.py\n') |
| 73 | + f.write(f'pattern = \'{pattern}\'\n') |
| 74 | + |
| 75 | + |
| 76 | +if __name__ == '__main__': |
| 77 | + main() |
0 commit comments