Skip to content
Myr

Merge pull request #858 from exponea/857-lexer-whitespace-performance

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

Fix lexer being extremely slow on large amounts of whitespace. Fixes #857

authored by David Lord · committed by GitHub · parents 381d72a, 37249c0 · Browse files · 1 file+52 added−58 removed
This commit

State

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

Diff stats

1 file+52 added−58 removed

  • other:+52 added−58 removed

1 file+52 added−58 removed

modified:jinja2/lexer.py+52 added-58 removed
21 unmodified lines
22from jinja2._compat import implements_iterator, intern, iteritems, text_type23from jinja2.exceptions import TemplateSyntaxError24from jinja2.utils import LRUCache2526from ast import literal_eval # to support scientific notation2726# cache for the lexers. Exists in order to be able to have multiple27# environments with the same lexer28_lexer_cache = LRUCache(50)29
390 unmodified lines
420 _lexer_cache[key] = lexer421 return lexer422423424class OptionalLStrip(tuple):425 """A special tuple for marking a point in the state that can have426 lstrip applied.427 """428429 # Even though it looks like a no-op, creating instances fails430 # without this.431 def __new__(cls, *members, **kwargs):432 return super(OptionalLStrip, cls).__new__(cls, members)433434435class Lexer(object):436 """Class that implements a lexer for a given environment. Automatically437 created by the environment class, usually you don't have to do that.438
26 unmodified lines
465466 # block suffix if trimming is enabled467 block_suffix_re = environment.trim_blocks and '\\n?' or ''468460 # strip leading spaces if lstrip_blocks is enabled461 prefix_re = {}462 no_lstrip_re = e('+')463 # detect overlap between block and variable or comment strings464 block_diff = c(r'^%s(.*)' % e(environment.block_start_string))465 # make sure we don't mistake a block for a variable or a comment466 m = block_diff.match(environment.comment_start_string)467 no_lstrip_re += m and r'|%s' % e(m.group(1)) or ''468 m = block_diff.match(environment.variable_start_string)469 no_lstrip_re += m and r'|%s' % e(m.group(1)) or ''470 # detect overlap between comment and variable strings471 comment_diff = c(r'^%s(.*)' % e(environment.comment_start_string))472 m = comment_diff.match(environment.variable_start_string)473 no_variable_re = m and r'(?!%s)' % e(m.group(1)) or ''469 # If lstrip is enabled, it should not be applied if there is any470 # non-whitespace between the newline and block.471 self.lstrip_unless_re = c(r"[^ \t]") if environment.lstrip_blocks else None472475 if environment.lstrip_blocks:476 # use '{%+' to manually disable lstrip_blocks behavior477 lstrip_re = r'^[ \t]*'478 block_prefix_re = r'%s%s(?!%s)|%s\+?' % (479 lstrip_re,480 e(environment.block_start_string),481 no_lstrip_re,482 e(environment.block_start_string),483 )484 comment_prefix_re = r'%s%s%s|%s\+?' % (485 lstrip_re,486 e(environment.comment_start_string),487 no_variable_re,488 e(environment.comment_start_string),489 )490 else:491 # If lstrip_blocks is False, then '{%+' is allowed but a NOP492 block_prefix_re = r'%s(?!%s)|%s\+?' % (493 e(environment.block_start_string),494 no_lstrip_re,495 e(environment.block_start_string),496 )497 comment_prefix_re = r'%s%s|%s\+?' % (498 e(environment.comment_start_string),499 no_variable_re,500 e(environment.comment_start_string),501 )502503 prefix_re['block'] = block_prefix_re504 prefix_re['comment'] = comment_prefix_re505473 self.newline_sequence = environment.newline_sequence474 self.keep_trailing_newline = environment.keep_trailing_newline475476 # global lexing rules477 self.rules = {478 'root': [479 # directives480 (c('(.*?)(?:%s)' % '|'.join(514 [r'(?P<raw_begin>(?:\s*%s\-|%s)\s*raw\s*(?:\-%s\s*|%s))' % (481 [r'(?P<raw_begin>%s(\-|\+|)\s*raw\s*(?:\-%s\s*|%s))' % (482 e(environment.block_start_string),516 block_prefix_re,483 e(environment.block_end_string),484 e(environment.block_end_string)485 )] + [520 r'(?P<%s_begin>\s*%s\-|%s)' % (n, r, prefix_re.get(n,r))486 r'(?P<%s_begin>%s(\-|\+|))' % (n, r)487 for n, r in root_tag_rules522 ])), (TOKEN_DATA, '#bygroup'), '#bygroup'),488 ])), OptionalLStrip(TOKEN_DATA, '#bygroup'), '#bygroup'),489 # data490 (c('.+'), TOKEN_DATA, None)491 ],492 # comments
21 unmodified lines
514 )), TOKEN_VARIABLE_END, '#pop')515 ] + tag_rules,516 # raw block517 TOKEN_RAW_BEGIN: [552 (c(r'(.*?)((?:\s*%s\-|%s)\s*endraw\s*(?:\-%s\s*|%s%s))' % (518 (c(r'(.*?)((?:%s(\-|\+|))\s*endraw\s*(?:\-%s\s*|%s%s))' % (519 e(environment.block_start_string),554 block_prefix_re,520 e(environment.block_end_string),521 e(environment.block_end_string),522 block_suffix_re558 )), (TOKEN_DATA, TOKEN_RAW_END), '#pop'),523 )), OptionalLStrip(TOKEN_DATA, TOKEN_RAW_END), '#pop'),524 (c('(.)'), (Failure('Missing end of raw directive'),), None)525 ],526 # line statements527 TOKEN_LINESTATEMENT_BEGIN: [
75 unmodified lines
603 stack = ['root']604 if state is not None and state != 'root':605 assert state in ('variable', 'block'), 'invalid state'606 stack.append(state + '_begin')642 else:643 state = 'root'607 statetokens = self.rules[stack[-1]]608 source_length = len(source)646609 balancing_stack = []610 lstrip_unless_re = self.lstrip_unless_re611612 while 1:613 # tokenizer loop614 for regex, tokens, new_state in statetokens:
12 unmodified lines
627 continue628629 # tuples support more options630 if isinstance(tokens, tuple):631 groups = m.groups()632633 if isinstance(tokens, OptionalLStrip):634 # Rule supports lstrip. Match will look like635 # text, block type, whitespace control, type, control, ...636 text = groups[0]637638 # Skipping the text and first type, every other group is the639 # whitespace control for each type. One of the groups will be640 # -, +, or empty string instead of None.641 strip_sign = next(g for g in groups[2::2] if g is not None)642643 if strip_sign == "-":644 # Strip all whitespace between the text and the tag.645 groups = (text.rstrip(),) + groups[1:]646 elif (647 # Not marked for preserving whitespace.648 strip_sign != "+"649 # lstrip is enabled.650 and lstrip_unless_re is not None651 # Not a variable expression.652 and not m.groupdict().get("variable_begin")653 ):654 # The start of text between the last newline and the tag.655 l_pos = text.rfind('\n') + 1656657 # If there's only whitespace between the newline and the658 # tag, strip it.659 if not lstrip_unless_re.search(text, l_pos):660 groups = (text[:l_pos],) + groups[1:]661662 for idx, token in enumerate(tokens):663 # failure group664 if token.__class__ is Failure:665 raise token(lineno, filename)
12 unmodified lines
678 ' but no group matched'679 % regex)680 # normal group681 else:688 data = m.group(idx + 1)682 data = groups[idx]683 if data or token not in ignore_if_empty:684 yield lineno, token, data685 lineno += data.count('\n')686
72 unmodified lines