Skip to content
Myr

generate_identifier_pattern.py

This file

Path

scripts/generate_identifier_pattern.py

74 lines · 2.0 KiB · Python

Last changed by

Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5

History of this file

Take it

1import itertools2import os3import re4import sys567def get_characters():8    """Find every Unicode character that is valid in a Python `identifier`_ but9    is not matched by the regex ``\\w`` group.1011    ``\\w`` matches some characters that aren't valid in identifiers, but12    :meth:`str.isidentifier` will catch that later in lexing.1314    All start characters are valid continue characters, so we only test for15    continue characters.1617    _identifier: https://docs.python.org/3/reference/lexical_analysis.html#identifiers18    """19    for cp in range(sys.maxunicode + 1):20        s = chr(cp)2122        if ("a" + s).isidentifier() and not re.match(r"\w", s):23            yield s242526def collapse_ranges(data):27    """Given a sorted list of unique characters, generate ranges representing28    sequential code points.2930    Source: https://stackoverflow.com/a/4629241/40061731    """32    for _, b in itertools.groupby(enumerate(data), lambda x: ord(x[1]) - x[0]):33        b = list(b)34        yield b[0][1], b[-1][1]353637def build_pattern(ranges):38    """Output the regex pattern for ranges of characters.3940    One and two character ranges output the individual characters.41    """42    out = []4344    for a, b in ranges:45        if a == b:  # single char46            out.append(a)47        elif ord(b) - ord(a) == 1:  # two chars, range is redundant48            out.append(a)49            out.append(b)50        else:51            out.append(f"{a}-{b}")5253    return "".join(out)545556def main():57    """Build the regex pattern and write it to58    ``jinja2/_identifier.py``.59    """60    pattern = build_pattern(collapse_ranges(get_characters()))61    filename = os.path.abspath(62        os.path.join(os.path.dirname(__file__), "..", "src", "jinja2", "_identifier.py")63    )6465    with open(filename, "w", encoding="utf8") as f:66        f.write("import re\n\n")67        f.write("# generated by scripts/generate_identifier_pattern.py\n")68        f.write("pattern = re.compile(\n")69        f.write(f'    r"[\\w{pattern}]+"  # noqa: B950\n')70        f.write(")\n")717273if __name__ == "__main__":74    main()