Skip to content

Commit fb1e453

Browse files
committed
go back to generating regex, simplified
new version uses ~2KB vs 200KB memory, is ~100x faster to load move script to generate pattern to scripts directory add more tests
1 parent 1f1f031 commit fb1e453

4 files changed

Lines changed: 100 additions & 12 deletions

File tree

jinja2/_identifier.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# generated by scripts/generate_identifier_pattern.py
2+
pattern = '·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-ٰٟۖ-ۜ۟-۪ۤۧۨ-ܑۭܰ-݊ަ-ް߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣔ-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣঁ-ঃ়া-ৄেৈো-্ৗৢৣਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑੰੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣஂா-ூெ-ைொ-்ௗఀ-ఃా-ౄె-ైొ-్ౕౖౢౣಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣංඃ්ා-ුූෘ-ෟෲෳัิ-ฺ็-๎ັິ-ູົຼ່-ໍ༹༘༙༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏႚ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝᠋-᠍ᢅᢆᢩᤠ-ᤫᤰ-᤻ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼᪰-᪽ᬀ-ᬄ᬴-᭄᭫-᭳ᮀ-ᮂᮡ-ᮭ᯦-᯳ᰤ-᰷᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰℘℮⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣠-꣱ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀ꧥꨩ-ꨶꩃꩌꩍꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭ﬞ︀-️︠-︯︳︴﹍-﹏_𐇽𐋠𐍶-𐍺𐨁-𐨃𐨅𐨆𐨌-𐨏𐨸-𐨿𐨺𐫦𐫥𑀀-𑀂𑀸-𑁆𑁿-𑂂𑂰-𑂺𑄀-𑄂𑄧-𑅳𑄴𑆀-𑆂𑆳-𑇊𑇀-𑇌𑈬-𑈷𑈾𑋟-𑋪𑌀-𑌃𑌼𑌾-𑍄𑍇𑍈𑍋-𑍍𑍗𑍢𑍣𑍦-𑍬𑍰-𑍴𑐵-𑑆𑒰-𑓃𑖯-𑖵𑖸-𑗀𑗜𑗝𑘰-𑙀𑚫-𑚷𑜝-𑜫𑰯-𑰶𑰸-𑰿𑲒-𑲧𑲩-𑲶𖫰-𖫴𖬰-𖬶𖽑-𖽾𖾏-𖾒𛲝𛲞𝅥-𝅩𝅭-𝅲𝅻-𝆂𝆅-𝆋𝆪-𝆭𝉂-𝉄𝨀-𝨶𝨻-𝩬𝩵𝪄𝪛-𝪟𝪡-𝪯𞀀-𞀆𞀈-𞀘𞀛-𞀡𞀣𞀤𞀦-𞣐𞀪-𞣖𞥄-𞥊󠄀-󠇯'

jinja2/lexer.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -32,22 +32,25 @@
3232
r'|"([^"\\]*(?:\\.[^"\\]*)*)")', re.S)
3333
integer_re = re.compile(r'\d+')
3434

35-
# we use the unicode identifier rule if this python version is able
36-
# to handle unicode identifiers, otherwise the standard ASCII one.
3735
try:
36+
# check if this Python supports Unicode identifiers
3837
compile('föö', '<unknown>', 'eval')
3938
except SyntaxError:
39+
# no Unicode support, use ASCII identifiers
4040
name_re = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*')
4141
check_ident = False
4242
else:
43-
# for whatever reason these do not exist in 'some' verisons of
44-
# python 3 within \w so we just add them. These are
45-
# 0x1885 MONGOLIAN LETTER ALI GALI BALUDA
46-
# 0x1886 MONGOLIAN LETTER ALI GALI THREE BALUDA
47-
# 0x2118 SCRIPT CAPITAL P
48-
# 0x212e ESTIMATED SYMBOL
49-
name_re = re.compile(r'[\w\u1885\u1886\u2118\u212e]+')
43+
# Unicode support, build a pattern to match valid characters, and set flag
44+
# to use str.isidentifier to validate during lexing
45+
from jinja2 import _identifier
46+
name_re = re.compile(r'[\w{0}]+'.format(_identifier.pattern))
5047
check_ident = True
48+
# remove the pattern from memory after building the regex
49+
import sys
50+
del sys.modules['jinja2._identifier']
51+
import jinja2
52+
del jinja2._identifier
53+
del _identifier
5154

5255
float_re = re.compile(r'(?<!\.)\d+\.\d+')
5356
newline_re = re.compile(r'(\r\n|\r|\n)')
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
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()

tests/test_lexnparse.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -131,18 +131,24 @@ def test_trailing_newline(self, env):
131131
(u'föö', False, True),
132132
(u'き', False, True),
133133
(u'_', True, True),
134-
(u'1a', False, False),
135-
# special cases in addition to \w
134+
(u'1a', False, False), # invalid ascii start
135+
(u'a-', False, False), # invalid ascii continue
136+
(u'🐍', False, False), # invalid unicode start
137+
(u'a🐍', False, False), # invalid unicode continue
138+
# start characters not matched by \w
136139
(u'\u1885', False, True),
137140
(u'\u1886', False, True),
138141
(u'\u2118', False, True),
139142
(u'\u212e', False, True),
143+
# continue character not matched by \w
144+
(u'\xb7', False, False),
145+
(u'a\xb7', False, True),
140146
))
141147
def test_name(self, env, name, valid2, valid3):
142148
t = u'{{ ' + name + u' }}'
143149

144150
if (valid2 and PY2) or (valid3 and not PY2):
145-
# shouldn't raise
151+
# valid for version being tested, shouldn't raise
146152
env.from_string(t)
147153
else:
148154
pytest.raises(TemplateSyntaxError, env.from_string, t)

0 commit comments

Comments
 (0)