generate_identifier_pattern.py
This file
Path
scripts/generate_identifier_pattern.py
77 lines · 2.1 KiB · Python
Last changed by
Merge pull request #731 from pallets/feature/kill-stringdefsDavid Lordbefore adoption47ef6a3
History of this fileTake it
Merge pull request #731 from pallets/feature/kill-stringdefsDavid Lordbefore adoption47ef6a3
lines 1–77why, one step back1#!/usr/bin/env python32import itertools3import os4import re5import sys67if sys.version_info[0] < 3:8 raise RuntimeError('This needs to run on Python 3.')91011def get_characters():12 """Find every Unicode character that is valid in a Python `identifier`_ but13 is not matched by the regex ``\w`` group.1415 ``\w`` matches some characters that aren't valid in identifiers, but16 :meth:`str.isidentifier` will catch that later in lexing.1718 All start characters are valid continue characters, so we only test for19 continue characters.2021 _identifier: https://docs.python.org/3/reference/lexical_analysis.html#identifiers22 """23 for cp in range(sys.maxunicode + 1):24 s = chr(cp)2526 if ('a' + s).isidentifier() and not re.match(r'\w', s):27 yield s282930def collapse_ranges(data):31 """Given a sorted list of unique characters, generate ranges representing32 sequential code points.3334 Source: https://stackoverflow.com/a/4629241/40061735 """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]424344def build_pattern(ranges):45 """Output the regex pattern for ranges of characters.4647 One and two character ranges output the individual characters.48 """49 out = []5051 for a, b in ranges:52 if a == b: # single char53 out.append(a)54 elif ord(b) - ord(a) == 1: # two chars, range is redundant55 out.append(a)56 out.append(b)57 else:58 out.append(f'{a}-{b}')5960 return ''.join(out)616263def main():64 """Build the regex pattern and write it to the file65 :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 ))7071 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')747576if __name__ == '__main__':77 main()