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
Provenance
- Commit
fb1e453- Tree
4ca9c2a- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
1f1f031
4 files changed+100 added−12 removed
added:jinja2/_identifier.py+2 added
1+# generated by scripts/generate_identifier_pattern.py2+pattern = '·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-ٰٟۖ-ۜ۟-۪ۤۧۨ-ܑۭܰ-݊ަ-ް߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣔ-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣঁ-ঃ়া-ৄেৈো-্ৗৢৣਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑੰੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣஂா-ூெ-ைொ-்ௗఀ-ఃా-ౄె-ైొ-్ౕౖౢౣಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣංඃ්ා-ුූෘ-ෟෲෳัิ-ฺ็-๎ັິ-ູົຼ່-ໍ༹༘༙༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏႚ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝᠋-᠍ᢅᢆᢩᤠ-ᤫᤰ-᤻ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼᪰-᪽ᬀ-ᬄ᬴-᭄᭫-᭳ᮀ-ᮂᮡ-ᮭ᯦-᯳ᰤ-᰷᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰℘℮⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣠-꣱ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀ꧥꨩ-ꨶꩃꩌꩍꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭ﬞ︀-️︠-︯︳︴﹍-﹏_𐇽𐋠𐍶-𐍺𐨁-𐨃𐨅𐨆𐨌-𐨏𐨸-𐨿𐨺𐫦𐫥𑀀-𑀂𑀸-𑁆𑁿-𑂂𑂰-𑂺𑄀-𑄂𑄧-𑅳𑄴𑆀-𑆂𑆳-𑇊𑇀-𑇌𑈬-𑈷𑈾𑋟-𑋪𑌀-𑌃𑌼𑌾-𑍄𑍇𑍈𑍋-𑍍𑍗𑍢𑍣𑍦-𑍬𑍰-𑍴𑐵-𑑆𑒰-𑓃𑖯-𑖵𑖸-𑗀𑗜𑗝𑘰-𑙀𑚫-𑚷𑜝-𑜫𑰯-𑰶𑰸-𑰿𑲒-𑲧𑲩-𑲶𖫰-𖫴𖬰-𖬶𖽑-𖽾𖾏-𖾒𛲝𛲞𝅥-𝅩𝅭-𝅲𝅻-𝆂𝆅-𝆋𝆪-𝆭𝉂-𝉄𝨀-𝨶𝨻-𝩬𝩵𝪄𝪛-𝪟𝪡-𝪯𞀀-𞀆𞀈-𞀘𞀛-𞀡𞀣𞀤𞀦-𞣐𞀪-𞣖𞥄-𞥊󠄀-󠇯'modified:jinja2/lexer.py+12 added-9 removed
30 unmodified lines31 string_re = re.compile(r"('([^'\\]*(?:\\.[^'\\]*)*)'"32 r'|"([^"\\]*(?:\\.[^"\\]*)*)")', re.S)33 integer_re = re.compile(r'\d+')34 35-# we use the unicode identifier rule if this python version is able36-# to handle unicode identifiers, otherwise the standard ASCII one.35 try:36+ # check if this Python supports Unicode identifiers37 compile('föö', '<unknown>', 'eval')38 except SyntaxError:39+ # no Unicode support, use ASCII identifiers40 name_re = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*')41 check_ident = False42 else: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 _identifier54 55 float_re = re.compile(r'(?<!\.)\d+\.\d+')56 newline_re = re.compile(r'(\r\n|\r|\n)')57 679 unmodified linesadded:scripts/generate_identifier_pattern.py+77 added
1+#!/usr/bin/env python32+import itertools3+import os4+import re5+import sys6+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`_ but13+ is not matched by the regex ``\w`` group.14+15+ ``\w`` matches some characters that aren't valid in identifiers, but16+ :meth:`str.isidentifier` will catch that later in lexing.17+18+ All start characters are valid continue characters, so we only test for19+ continue characters.20+21+ _identifier: https://docs.python.org/3/reference/lexical_analysis.html#identifiers22+ """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 s28+29+30+def collapse_ranges(data):31+ """Given a sorted list of unique characters, generate ranges representing32+ sequential code points.33+34+ 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]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 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}')59+60+ return ''.join(out)61+62+63+def 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+ ))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()modified:tests/test_lexnparse.py+9 added-3 removed
129 unmodified lines130 (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' }}'149 150 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