Fix lexer being extremely slow on large amounts of whitespace. Fixes #857
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Peter Dolak · committed by Kevin Brown · parent fd89fed · Browse files · 1 file·+30 added−43 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+30 added−43 removed
- other:+30 added−43 removed
Provenance
- Commit
7d00a40- Tree
b34f0ff- Author
Peter Dolak <peter.dolak@7segments.com>- Committer
Kevin Brown <kevin@kevin-brown.com>- Parent
fd89fed
1 file changed+30 added−43 removed
modified:jinja2/lexer.py+30 added-43 removed
407 unmodified lines408 _lexer_cache[key] = lexer409 return lexer410 411 412+class OptionalLStrip(tuple):413+ def __new__(cls, *members, **kwargs):414+ return super(OptionalLStrip, cls).__new__(cls, members)415+416+417 class Lexer(object):418 """Class that implements a lexer for a given environment. Automatically419 created by the environment class, usually you don't have to do that.420 26 unmodified lines447 448 # block suffix if trimming is enabled449 block_suffix_re = environment.trim_blocks and '\\n?' or ''450 446- # strip leading spaces if lstrip_blocks is enabled447- prefix_re = {}448- if environment.lstrip_blocks:449- # use '{%+' to manually disable lstrip_blocks behavior450- no_lstrip_re = e('+')451- # detect overlap between block and variable or comment strings452- block_diff = c(r'^%s(.*)' % e(environment.block_start_string))453- # make sure we don't mistake a block for a variable or a comment454- m = block_diff.match(environment.comment_start_string)455- no_lstrip_re += m and r'|%s' % e(m.group(1)) or ''456- m = block_diff.match(environment.variable_start_string)457- no_lstrip_re += m and r'|%s' % e(m.group(1)) or ''451+ # strip leading spaces in blocks/comments if lstrip_blocks is enabled452+ # use for example '{%+' to disable lstrip_blocks behavior453+ self.lstrip_blocks_unless_re = c(r'[^ \t]') if environment.lstrip_blocks else None454 459- # detect overlap between comment and variable strings460- comment_diff = c(r'^%s(.*)' % e(environment.comment_start_string))461- m = comment_diff.match(environment.variable_start_string)462- no_variable_re = m and r'(?!%s)' % e(m.group(1)) or ''463-464- lstrip_re = r'^[ \t]*'465- block_prefix_re = r'%s%s(?!%s)|%s\+?' % (466- lstrip_re,467- e(environment.block_start_string),468- no_lstrip_re,469- e(environment.block_start_string),470- )471- comment_prefix_re = r'%s%s%s|%s\+?' % (472- lstrip_re,473- e(environment.comment_start_string),474- no_variable_re,475- e(environment.comment_start_string),476- )477- prefix_re['block'] = block_prefix_re478- prefix_re['comment'] = comment_prefix_re479- else:480- block_prefix_re = '%s' % e(environment.block_start_string)481-455 self.newline_sequence = environment.newline_sequence456 self.keep_trailing_newline = environment.keep_trailing_newline457 458 # global lexing rules459 self.rules = {460 'root': [461 # directives462 (c('(.*?)(?:%s)' % '|'.join(490- [r'(?P<raw_begin>(?:\s*%s\-|%s)\s*raw\s*(?:\-%s\s*|%s))' % (463+ [r'(?P<raw_begin>%s(\-|\+|)\s*raw\s*(?:\-%s\s*|%s))' % (464 e(environment.block_start_string),492- block_prefix_re,465 e(environment.block_end_string),466 e(environment.block_end_string)467 )] + [496- r'(?P<%s_begin>\s*%s\-|%s)' % (n, r, prefix_re.get(n,r))468+ r'(?P<%s_begin>%s(\-|\+|))' % (n, r)469 for n, r in root_tag_rules498- ])), (TOKEN_DATA, '#bygroup'), '#bygroup'),470+ ])), OptionalLStrip(TOKEN_DATA, '#bygroup'), '#bygroup'),471 # data472 (c('.+'), TOKEN_DATA, None)473 ],474 # comments21 unmodified lines496 )), TOKEN_VARIABLE_END, '#pop')497 ] + tag_rules,498 # raw block499 TOKEN_RAW_BEGIN: [528- (c(r'(.*?)((?:\s*%s\-|%s)\s*endraw\s*(?:\-%s\s*|%s%s))' % (500+ (c(r'(.*?)((?:%s(\-|\+|))\s*endraw\s*(?:\-%s\s*|%s%s))' % (501 e(environment.block_start_string),530- block_prefix_re,502 e(environment.block_end_string),503 e(environment.block_end_string),504 block_suffix_re534- )), (TOKEN_DATA, TOKEN_RAW_END), '#pop'),505+ )), OptionalLStrip(TOKEN_DATA, TOKEN_RAW_END), '#pop'),506 (c('(.)'), (Failure('Missing end of raw directive'),), None)507 ],508 # line statements509 TOKEN_LINESTATEMENT_BEGIN: [60 unmodified lines570 def tokeniter(self, source, name, filename=None, state=None):571 """This method tokenizes the text and returns the tokens in a572 generator. Use this method if you just want to tokenize a template.573 """574+ neg_lstrip_re = self.lstrip_blocks_unless_re575 source = text_type(source)576 lines = source.splitlines()577 if self.keep_trailing_newline and source:578 for newline in ('\r\n', '\r', '\n'):32 unmodified lines611 continue612 613 # tuples support more options614 if isinstance(tokens, tuple):615+ groups = m.groups()616+617+ if isinstance(tokens, OptionalLStrip):618+ # state supports lstrip, determine override (-/+)619+ strip_sign = next(group for group in groups[2::2]620+ if group is not None)621+ if strip_sign == '-':622+ groups = (groups[0].rstrip(),) + groups[1:]623+ elif strip_sign != '+' and neg_lstrip_re is not None \624+ and not m.groupdict().get('variable_begin'):625+ # no override, but lstrip_blocks enabled626+ l_pos = groups[0].rfind('\n') + 1627+ if not neg_lstrip_re.search(groups[0], l_pos):628+ groups = (groups[0][:l_pos],) + groups[1:]629+630 for idx, token in enumerate(tokens):631 # failure group632 if token.__class__ is Failure:633 raise token(lineno, filename)12 unmodified lines646 ' but no group matched'647 % regex)648 # normal group649 else:663- data = m.group(idx + 1)650+ data = groups[idx]651 if data or token not in ignore_if_empty:652 yield lineno, token, data653 lineno += data.count('\n')654 72 unmodified lines