Skip to content
Myr

go back to generating regex, simplified

Before adoption: this commit came in with the history the project adopted, so no landing records it.

new version uses ~2KB vs 200KB memory, is ~100x faster to load move script to generate pattern to scripts directory add more tests

authored by David Lord · committed by David Lord · parent 1f1f031 · Browse files · 4 files+100 added−12 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+100 added−12 removed

  • tests:+9 added−3 removed
  • other:+91 added−9 removed

4 files+100 added−12 removed

added:jinja2/_identifier.py+2 added
1# generated by scripts/generate_identifier_pattern.py2pattern = '·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-ٰٟۖ-ۜ۟-۪ۤۧۨ-ܑۭܰ-݊ަ-ް߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣔ-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣঁ-ঃ়া-ৄেৈো-্ৗৢৣਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑੰੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣஂா-ூெ-ைொ-்ௗఀ-ఃా-ౄె-ైొ-్ౕౖౢౣಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣංඃ්ා-ුූෘ-ෟෲෳัิ-ฺ็-๎ັິ-ູົຼ່-ໍ༹༘༙༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏႚ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝᠋-᠍ᢅᢆᢩᤠ-ᤫᤰ-᤻ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼᪰-᪽ᬀ-ᬄ᬴-᭄᭫-᭳ᮀ-ᮂᮡ-ᮭ᯦-᯳ᰤ-᰷᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰℘℮⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣠-꣱ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀ꧥꨩ-ꨶꩃꩌꩍꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭ﬞ︀-️︠-︯︳︴﹍-﹏_𐇽𐋠𐍶-𐍺𐨁-𐨃𐨅𐨆𐨌-𐨏𐨸-𐨿𐨺𐫦𐫥𑀀-𑀂𑀸-𑁆𑁿-𑂂𑂰-𑂺𑄀-𑄂𑄧-𑅳𑄴𑆀-𑆂𑆳-𑇊𑇀-𑇌𑈬-𑈷𑈾𑋟-𑋪𑌀-𑌃𑌼𑌾-𑍄𑍇𑍈𑍋-𑍍𑍗𑍢𑍣𑍦-𑍬𑍰-𑍴𑐵-𑑆𑒰-𑓃𑖯-𑖵𑖸-𑗀𑗜𑗝𑘰-𑙀𑚫-𑚷𑜝-𑜫𑰯-𑰶𑰸-𑰿𑲒-𑲧𑲩-𑲶𖫰-𖫴𖬰-𖬶𖽑-𖽾𖾏-𖾒𛲝𛲞𝅥-𝅩𝅭-𝅲𝅻-𝆂𝆅-𝆋𝆪-𝆭𝉂-𝉄𝨀-𝨶𝨻-𝩬𝩵𝪄𝪛-𝪟𝪡-𝪯𞀀-𞀆𞀈-𞀘𞀛-𞀡𞀣𞀤𞀦-𞣐𞀪-𞣖𞥄-𞥊󠄀-󠇯'
modified:jinja2/lexer.py+12 added-9 removed
30 unmodified lines
31string_re = re.compile(r"('([^'\\]*(?:\\.[^'\\]*)*)'"32 r'|"([^"\\]*(?:\\.[^"\\]*)*)")', re.S)33integer_re = re.compile(r'\d+')3435# we use the unicode identifier rule if this python version is able36# to handle unicode identifiers, otherwise the standard ASCII one.35try:36 # check if this Python supports Unicode identifiers37 compile('föö', '<unknown>', 'eval')38except SyntaxError:39 # no Unicode support, use ASCII identifiers40 name_re = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*')41 check_ident = False42else:43 # for whatever reason these do not exist in 'some' verisons of44 # python 3 within \w so we just add them. These are45 # 0x1885 MONGOLIAN LETTER ALI GALI BALUDA46 # 0x1886 MONGOLIAN LETTER ALI GALI THREE BALUDA47 # 0x2118 SCRIPT CAPITAL P48 # 0x212e ESTIMATED SYMBOL49 name_re = re.compile(r'[\w\u1885\u1886\u2118\u212e]+')43 # Unicode support, build a pattern to match valid characters, and set flag44 # to use str.isidentifier to validate during lexing45 from jinja2 import _identifier46 name_re = re.compile(r'[\w{0}]+'.format(_identifier.pattern))47 check_ident = True48 # remove the pattern from memory after building the regex49 import sys50 del sys.modules['jinja2._identifier']51 import jinja252 del jinja2._identifier53 del _identifier5455float_re = re.compile(r'(?<!\.)\d+\.\d+')56newline_re = re.compile(r'(\r\n|\r|\n)')57
679 unmodified lines
added:scripts/generate_identifier_pattern.py+77 added
1#!/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()
modified:tests/test_lexnparse.py+9 added-3 removed
129 unmodified lines
130 (u'foo', True, True),131 (u'föö', False, True),132 (u'き', False, True),133 (u'_', True, True),134 (u'1a', False, False),135 # special cases in addition to \w134 (u'1a', False, False), # invalid ascii start135 (u'a-', False, False), # invalid ascii continue136 (u'🐍', False, False), # invalid unicode start137 (u'a🐍', False, False), # invalid unicode continue138 # start characters not matched by \w139 (u'\u1885', False, True),140 (u'\u1886', False, True),141 (u'\u2118', False, True),142 (u'\u212e', False, True),143 # continue character not matched by \w144 (u'\xb7', False, False),145 (u'a\xb7', False, True),146 ))147 def test_name(self, env, name, valid2, valid3):148 t = u'{{ ' + name + u' }}'149150 if (valid2 and PY2) or (valid3 and not PY2):145 # shouldn't raise151 # valid for version being tested, shouldn't raise152 env.from_string(t)153 else:154 pytest.raises(TemplateSyntaxError, env.from_string, t)155
485 unmodified lines