parser.py
This file
Path
jinja2/parser.py
870 lines · 33.6 KiB · Python
Last changed by
Fixed long standing wrong operator precedenceArmin Ronacherbefore adoption4fa3712
History of this fileTake it
1# -*- coding: utf-8 -*-2"""3 jinja2.parser4 ~~~~~~~~~~~~~56 Implements the template parser.78 :copyright: (c) 2010 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10"""11from jinja2 import nodes12from jinja2.exceptions import TemplateSyntaxError, TemplateAssertionError13from jinja2.lexer import describe_token, describe_token_expr14from jinja2._compat import imap151617_statement_keywords = frozenset(['for', 'if', 'block', 'extends', 'print',18 'macro', 'include', 'from', 'import',19 'set'])20_compare_operators = frozenset(['eq', 'ne', 'lt', 'lteq', 'gt', 'gteq'])2122_math_nodes = {23 'add': nodes.Add,24 'sub': nodes.Sub,25 'mul': nodes.Mul,26 'div': nodes.Div,27 'floordiv': nodes.FloorDiv,28 'mod': nodes.Mod,29}303132class Parser(object):33 """This is the central parsing class Jinja2 uses. It's passed to34 extensions and can be used to parse expressions or statements.35 """3637 def __init__(self, environment, source, name=None, filename=None,38 state=None):39 self.environment = environment40 self.stream = environment._tokenize(source, name, filename, state)41 self.name = name42 self.filename = filename43 self.closed = False44 self.extensions = {}45 for extension in environment.iter_extensions():46 for tag in extension.tags:47 self.extensions[tag] = extension.parse48 self._last_identifier = 049 self._tag_stack = []50 self._end_token_stack = []5152 def fail(self, msg, lineno=None, exc=TemplateSyntaxError):53 """Convenience method that raises `exc` with the message, passed54 line number or last line number as well as the current name and55 filename.56 """57 if lineno is None:58 lineno = self.stream.current.lineno59 raise exc(msg, lineno, self.name, self.filename)6061 def _fail_ut_eof(self, name, end_token_stack, lineno):62 expected = []63 for exprs in end_token_stack:64 expected.extend(imap(describe_token_expr, exprs))65 if end_token_stack:66 currently_looking = ' or '.join(67 "'%s'" % describe_token_expr(expr)68 for expr in end_token_stack[-1])69 else:70 currently_looking = None7172 if name is None:73 message = ['Unexpected end of template.']74 else:75 message = ['Encountered unknown tag \'%s\'.' % name]7677 if currently_looking:78 if name is not None and name in expected:79 message.append('You probably made a nesting mistake. Jinja '80 'is expecting this tag, but currently looking '81 'for %s.' % currently_looking)82 else:83 message.append('Jinja was looking for the following tags: '84 '%s.' % currently_looking)8586 if self._tag_stack:87 message.append('The innermost block that needs to be '88 'closed is \'%s\'.' % self._tag_stack[-1])8990 self.fail(' '.join(message), lineno)9192 def fail_unknown_tag(self, name, lineno=None):93 """Called if the parser encounters an unknown tag. Tries to fail94 with a human readable error message that could help to identify95 the problem.96 """97 return self._fail_ut_eof(name, self._end_token_stack, lineno)9899 def fail_eof(self, end_tokens=None, lineno=None):100 """Like fail_unknown_tag but for end of template situations."""101 stack = list(self._end_token_stack)102 if end_tokens is not None:103 stack.append(end_tokens)104 return self._fail_ut_eof(None, stack, lineno)105106 def is_tuple_end(self, extra_end_rules=None):107 """Are we at the end of a tuple?"""108 if self.stream.current.type in ('variable_end', 'block_end', 'rparen'):109 return True110 elif extra_end_rules is not None:111 return self.stream.current.test_any(extra_end_rules)112 return False113114 def free_identifier(self, lineno=None):115 """Return a new free identifier as :class:`~jinja2.nodes.InternalName`."""116 self._last_identifier += 1117 rv = object.__new__(nodes.InternalName)118 nodes.Node.__init__(rv, 'fi%d' % self._last_identifier, lineno=lineno)119 return rv120121 def parse_statement(self):122 """Parse a single statement."""123 token = self.stream.current124 if token.type != 'name':125 self.fail('tag name expected', token.lineno)126 self._tag_stack.append(token.value)127 pop_tag = True128 try:129 if token.value in _statement_keywords:130 return getattr(self, 'parse_' + self.stream.current.value)()131 if token.value == 'call':132 return self.parse_call_block()133 if token.value == 'filter':134 return self.parse_filter_block()135 ext = self.extensions.get(token.value)136 if ext is not None:137 return ext(self)138139 # did not work out, remove the token we pushed by accident140 # from the stack so that the unknown tag fail function can141 # produce a proper error message.142 self._tag_stack.pop()143 pop_tag = False144 self.fail_unknown_tag(token.value, token.lineno)145 finally:146 if pop_tag:147 self._tag_stack.pop()148149 def parse_statements(self, end_tokens, drop_needle=False):150 """Parse multiple statements into a list until one of the end tokens151 is reached. This is used to parse the body of statements as it also152 parses template data if appropriate. The parser checks first if the153 current token is a colon and skips it if there is one. Then it checks154 for the block end and parses until if one of the `end_tokens` is155 reached. Per default the active token in the stream at the end of156 the call is the matched end token. If this is not wanted `drop_needle`157 can be set to `True` and the end token is removed.158 """159 # the first token may be a colon for python compatibility160 self.stream.skip_if('colon')161162 # in the future it would be possible to add whole code sections163 # by adding some sort of end of statement token and parsing those here.164 self.stream.expect('block_end')165 result = self.subparse(end_tokens)166167 # we reached the end of the template too early, the subparser168 # does not check for this, so we do that now169 if self.stream.current.type == 'eof':170 self.fail_eof(end_tokens)171172 if drop_needle:173 next(self.stream)174 return result175176 def parse_set(self):177 """Parse an assign statement."""178 lineno = next(self.stream).lineno179 target = self.parse_assign_target()180 if self.stream.skip_if('assign'):181 expr = self.parse_tuple()182 return nodes.Assign(target, expr, lineno=lineno)183 body = self.parse_statements(('name:endset',),184 drop_needle=True)185 return nodes.AssignBlock(target, body, lineno=lineno)186187 def parse_for(self):188 """Parse a for loop."""189 lineno = self.stream.expect('name:for').lineno190 target = self.parse_assign_target(extra_end_rules=('name:in',))191 self.stream.expect('name:in')192 iter = self.parse_tuple(with_condexpr=False,193 extra_end_rules=('name:recursive',))194 test = None195 if self.stream.skip_if('name:if'):196 test = self.parse_expression()197 recursive = self.stream.skip_if('name:recursive')198 body = self.parse_statements(('name:endfor', 'name:else'))199 if next(self.stream).value == 'endfor':200 else_ = []201 else:202 else_ = self.parse_statements(('name:endfor',), drop_needle=True)203 return nodes.For(target, iter, body, else_, test,204 recursive, lineno=lineno)205206 def parse_if(self):207 """Parse an if construct."""208 node = result = nodes.If(lineno=self.stream.expect('name:if').lineno)209 while 1:210 node.test = self.parse_tuple(with_condexpr=False)211 node.body = self.parse_statements(('name:elif', 'name:else',212 'name:endif'))213 token = next(self.stream)214 if token.test('name:elif'):215 new_node = nodes.If(lineno=self.stream.current.lineno)216 node.else_ = [new_node]217 node = new_node218 continue219 elif token.test('name:else'):220 node.else_ = self.parse_statements(('name:endif',),221 drop_needle=True)222 else:223 node.else_ = []224 break225 return result226227 def parse_block(self):228 node = nodes.Block(lineno=next(self.stream).lineno)229 node.name = self.stream.expect('name').value230 node.scoped = self.stream.skip_if('name:scoped')231232 # common problem people encounter when switching from django233 # to jinja. we do not support hyphens in block names, so let's234 # raise a nicer error message in that case.235 if self.stream.current.type == 'sub':236 self.fail('Block names in Jinja have to be valid Python '237 'identifiers and may not contain hyphens, use an '238 'underscore instead.')239240 node.body = self.parse_statements(('name:endblock',), drop_needle=True)241 self.stream.skip_if('name:' + node.name)242 return node243244 def parse_extends(self):245 node = nodes.Extends(lineno=next(self.stream).lineno)246 node.template = self.parse_expression()247 return node248249 def parse_import_context(self, node, default):250 if self.stream.current.test_any('name:with', 'name:without') and \251 self.stream.look().test('name:context'):252 node.with_context = next(self.stream).value == 'with'253 self.stream.skip()254 else:255 node.with_context = default256 return node257258 def parse_include(self):259 node = nodes.Include(lineno=next(self.stream).lineno)260 node.template = self.parse_expression()261 if self.stream.current.test('name:ignore') and \262 self.stream.look().test('name:missing'):263 node.ignore_missing = True264 self.stream.skip(2)265 else:266 node.ignore_missing = False267 return self.parse_import_context(node, True)268269 def parse_import(self):270 node = nodes.Import(lineno=next(self.stream).lineno)271 node.template = self.parse_expression()272 self.stream.expect('name:as')273 node.target = self.parse_assign_target(name_only=True).name274 return self.parse_import_context(node, False)275276 def parse_from(self):277 node = nodes.FromImport(lineno=next(self.stream).lineno)278 node.template = self.parse_expression()279 self.stream.expect('name:import')280 node.names = []281282 def parse_context():283 if self.stream.current.value in ('with', 'without') and \284 self.stream.look().test('name:context'):285 node.with_context = next(self.stream).value == 'with'286 self.stream.skip()287 return True288 return False289290 while 1:291 if node.names:292 self.stream.expect('comma')293 if self.stream.current.type == 'name':294 if parse_context():295 break296 target = self.parse_assign_target(name_only=True)297 if target.name.startswith('_'):298 self.fail('names starting with an underline can not '299 'be imported', target.lineno,300 exc=TemplateAssertionError)301 if self.stream.skip_if('name:as'):302 alias = self.parse_assign_target(name_only=True)303 node.names.append((target.name, alias.name))304 else:305 node.names.append(target.name)306 if parse_context() or self.stream.current.type != 'comma':307 break308 else:309 break310 if not hasattr(node, 'with_context'):311 node.with_context = False312 self.stream.skip_if('comma')313 return node314315 def parse_signature(self, node):316 node.args = args = []317 node.defaults = defaults = []318 self.stream.expect('lparen')319 while self.stream.current.type != 'rparen':320 if args:321 self.stream.expect('comma')322 arg = self.parse_assign_target(name_only=True)323 arg.set_ctx('param')324 if self.stream.skip_if('assign'):325 defaults.append(self.parse_expression())326 elif defaults:327 self.fail('non-default argument follows default argument')328 args.append(arg)329 self.stream.expect('rparen')330331 def parse_call_block(self):332 node = nodes.CallBlock(lineno=next(self.stream).lineno)333 if self.stream.current.type == 'lparen':334 self.parse_signature(node)335 else:336 node.args = []337 node.defaults = []338339 node.call = self.parse_expression()340 if not isinstance(node.call, nodes.Call):341 self.fail('expected call', node.lineno)342 node.body = self.parse_statements(('name:endcall',), drop_needle=True)343 return node344345 def parse_filter_block(self):346 node = nodes.FilterBlock(lineno=next(self.stream).lineno)347 node.filter = self.parse_filter(None, start_inline=True)348 node.body = self.parse_statements(('name:endfilter',),349 drop_needle=True)350 return node351352 def parse_macro(self):353 node = nodes.Macro(lineno=next(self.stream).lineno)354 node.name = self.parse_assign_target(name_only=True).name355 self.parse_signature(node)356 node.body = self.parse_statements(('name:endmacro',),357 drop_needle=True)358 return node359360 def parse_print(self):361 node = nodes.Output(lineno=next(self.stream).lineno)362 node.nodes = []363 while self.stream.current.type != 'block_end':364 if node.nodes:365 self.stream.expect('comma')366 node.nodes.append(self.parse_expression())367 return node368369 def parse_assign_target(self, with_tuple=True, name_only=False,370 extra_end_rules=None):371 """Parse an assignment target. As Jinja2 allows assignments to372 tuples, this function can parse all allowed assignment targets. Per373 default assignments to tuples are parsed, that can be disable however374 by setting `with_tuple` to `False`. If only assignments to names are375 wanted `name_only` can be set to `True`. The `extra_end_rules`376 parameter is forwarded to the tuple parsing function.377 """378 if name_only:379 token = self.stream.expect('name')380 target = nodes.Name(token.value, 'store', lineno=token.lineno)381 else:382 if with_tuple:383 target = self.parse_tuple(simplified=True,384 extra_end_rules=extra_end_rules)385 else:386 target = self.parse_primary()387 target.set_ctx('store')388 if not target.can_assign():389 self.fail('can\'t assign to %r' % target.__class__.390 __name__.lower(), target.lineno)391 return target392393 def parse_expression(self, with_condexpr=True):394 """Parse an expression. Per default all expressions are parsed, if395 the optional `with_condexpr` parameter is set to `False` conditional396 expressions are not parsed.397 """398 if with_condexpr:399 return self.parse_condexpr()400 return self.parse_or()401402 def parse_condexpr(self):403 lineno = self.stream.current.lineno404 expr1 = self.parse_or()405 while self.stream.skip_if('name:if'):406 expr2 = self.parse_or()407 if self.stream.skip_if('name:else'):408 expr3 = self.parse_condexpr()409 else:410 expr3 = None411 expr1 = nodes.CondExpr(expr2, expr1, expr3, lineno=lineno)412 lineno = self.stream.current.lineno413 return expr1414415 def parse_or(self):416 lineno = self.stream.current.lineno417 left = self.parse_and()418 while self.stream.skip_if('name:or'):419 right = self.parse_and()420 left = nodes.Or(left, right, lineno=lineno)421 lineno = self.stream.current.lineno422 return left423424 def parse_and(self):425 lineno = self.stream.current.lineno426 left = self.parse_not()427 while self.stream.skip_if('name:and'):428 right = self.parse_not()429 left = nodes.And(left, right, lineno=lineno)430 lineno = self.stream.current.lineno431 return left432433 def parse_not(self):434 if self.stream.current.test('name:not'):435 lineno = next(self.stream).lineno436 return nodes.Not(self.parse_not(), lineno=lineno)437 return self.parse_compare()438439 def parse_compare(self):440 lineno = self.stream.current.lineno441 expr = self.parse_math1()442 ops = []443 while 1:444 token_type = self.stream.current.type445 if token_type in _compare_operators:446 next(self.stream)447 ops.append(nodes.Operand(token_type, self.parse_math1()))448 elif self.stream.skip_if('name:in'):449 ops.append(nodes.Operand('in', self.parse_math1()))450 elif (self.stream.current.test('name:not') and451 self.stream.look().test('name:in')):452 self.stream.skip(2)453 ops.append(nodes.Operand('notin', self.parse_math1()))454 else:455 break456 lineno = self.stream.current.lineno457 if not ops:458 return expr459 return nodes.Compare(expr, ops, lineno=lineno)460461 def parse_math1(self):462 lineno = self.stream.current.lineno463 left = self.parse_concat()464 while self.stream.current.type in ('add', 'sub'):465 cls = _math_nodes[self.stream.current.type]466 next(self.stream)467 right = self.parse_concat()468 left = cls(left, right, lineno=lineno)469 lineno = self.stream.current.lineno470 return left471472 def parse_concat(self):473 lineno = self.stream.current.lineno474 args = [self.parse_math2()]475 while self.stream.current.type == 'tilde':476 next(self.stream)477 args.append(self.parse_math2())478 if len(args) == 1:479 return args[0]480 return nodes.Concat(args, lineno=lineno)481482 def parse_math2(self):483 lineno = self.stream.current.lineno484 left = self.parse_pow()485 while self.stream.current.type in ('mul', 'div', 'floordiv', 'mod'):486 cls = _math_nodes[self.stream.current.type]487 next(self.stream)488 right = self.parse_pow()489 left = cls(left, right, lineno=lineno)490 lineno = self.stream.current.lineno491 return left492493 def parse_pow(self):494 lineno = self.stream.current.lineno495 left = self.parse_unary()496 while self.stream.current.type == 'pow':497 next(self.stream)498 right = self.parse_unary()499 left = nodes.Pow(left, right, lineno=lineno)500 lineno = self.stream.current.lineno501 return left502503 def parse_unary(self, with_filter=True):504 token_type = self.stream.current.type505 lineno = self.stream.current.lineno506 if token_type == 'sub':507 next(self.stream)508 node = nodes.Neg(self.parse_unary(False), lineno=lineno)509 elif token_type == 'add':510 next(self.stream)511 node = nodes.Pos(self.parse_unary(False), lineno=lineno)512 else:513 node = self.parse_primary()514 node = self.parse_postfix(node)515 if with_filter:516 node = self.parse_filter_expr(node)517 return node518519 def parse_primary(self):520 token = self.stream.current521 if token.type == 'name':522 if token.value in ('true', 'false', 'True', 'False'):523 node = nodes.Const(token.value in ('true', 'True'),524 lineno=token.lineno)525 elif token.value in ('none', 'None'):526 node = nodes.Const(None, lineno=token.lineno)527 else:528 node = nodes.Name(token.value, 'load', lineno=token.lineno)529 next(self.stream)530 elif token.type == 'string':531 next(self.stream)532 buf = [token.value]533 lineno = token.lineno534 while self.stream.current.type == 'string':535 buf.append(self.stream.current.value)536 next(self.stream)537 node = nodes.Const(''.join(buf), lineno=lineno)538 elif token.type in ('integer', 'float'):539 next(self.stream)540 node = nodes.Const(token.value, lineno=token.lineno)541 elif token.type == 'lparen':542 next(self.stream)543 node = self.parse_tuple(explicit_parentheses=True)544 self.stream.expect('rparen')545 elif token.type == 'lbracket':546 node = self.parse_list()547 elif token.type == 'lbrace':548 node = self.parse_dict()549 else:550 self.fail("unexpected '%s'" % describe_token(token), token.lineno)551 return node552553 def parse_tuple(self, simplified=False, with_condexpr=True,554 extra_end_rules=None, explicit_parentheses=False):555 """Works like `parse_expression` but if multiple expressions are556 delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.557 This method could also return a regular expression instead of a tuple558 if no commas where found.559560 The default parsing mode is a full tuple. If `simplified` is `True`561 only names and literals are parsed. The `no_condexpr` parameter is562 forwarded to :meth:`parse_expression`.563564 Because tuples do not require delimiters and may end in a bogus comma565 an extra hint is needed that marks the end of a tuple. For example566 for loops support tuples between `for` and `in`. In that case the567 `extra_end_rules` is set to ``['name:in']``.568569 `explicit_parentheses` is true if the parsing was triggered by an570 expression in parentheses. This is used to figure out if an empty571 tuple is a valid expression or not.572 """573 lineno = self.stream.current.lineno574 if simplified:575 parse = self.parse_primary576 elif with_condexpr:577 parse = self.parse_expression578 else:579 parse = lambda: self.parse_expression(with_condexpr=False)580 args = []581 is_tuple = False582 while 1:583 if args:584 self.stream.expect('comma')585 if self.is_tuple_end(extra_end_rules):586 break587 args.append(parse())588 if self.stream.current.type == 'comma':589 is_tuple = True590 else:591 break592 lineno = self.stream.current.lineno593594 if not is_tuple:595 if args:596 return args[0]597598 # if we don't have explicit parentheses, an empty tuple is599 # not a valid expression. This would mean nothing (literally600 # nothing) in the spot of an expression would be an empty601 # tuple.602 if not explicit_parentheses:603 self.fail('Expected an expression, got \'%s\'' %604 describe_token(self.stream.current))605606 return nodes.Tuple(args, 'load', lineno=lineno)607608 def parse_list(self):609 token = self.stream.expect('lbracket')610 items = []611 while self.stream.current.type != 'rbracket':612 if items:613 self.stream.expect('comma')614 if self.stream.current.type == 'rbracket':615 break616 items.append(self.parse_expression())617 self.stream.expect('rbracket')618 return nodes.List(items, lineno=token.lineno)619620 def parse_dict(self):621 token = self.stream.expect('lbrace')622 items = []623 while self.stream.current.type != 'rbrace':624 if items:625 self.stream.expect('comma')626 if self.stream.current.type == 'rbrace':627 break628 key = self.parse_expression()629 self.stream.expect('colon')630 value = self.parse_expression()631 items.append(nodes.Pair(key, value, lineno=key.lineno))632 self.stream.expect('rbrace')633 return nodes.Dict(items, lineno=token.lineno)634635 def parse_postfix(self, node):636 while 1:637 token_type = self.stream.current.type638 if token_type == 'dot' or token_type == 'lbracket':639 node = self.parse_subscript(node)640 # calls are valid both after postfix expressions (getattr641 # and getitem) as well as filters and tests642 elif token_type == 'lparen':643 node = self.parse_call(node)644 else:645 break646 return node647648 def parse_filter_expr(self, node):649 while 1:650 token_type = self.stream.current.type651 if token_type == 'pipe':652 node = self.parse_filter(node)653 elif token_type == 'name' and self.stream.current.value == 'is':654 node = self.parse_test(node)655 # calls are valid both after postfix expressions (getattr656 # and getitem) as well as filters and tests657 elif token_type == 'lparen':658 node = self.parse_call(node)659 else:660 break661 return node662663 def parse_subscript(self, node):664 token = next(self.stream)665 if token.type == 'dot':666 attr_token = self.stream.current667 next(self.stream)668 if attr_token.type == 'name':669 return nodes.Getattr(node, attr_token.value, 'load',670 lineno=token.lineno)671 elif attr_token.type != 'integer':672 self.fail('expected name or number', attr_token.lineno)673 arg = nodes.Const(attr_token.value, lineno=attr_token.lineno)674 return nodes.Getitem(node, arg, 'load', lineno=token.lineno)675 if token.type == 'lbracket':676 args = []677 while self.stream.current.type != 'rbracket':678 if args:679 self.stream.expect('comma')680 args.append(self.parse_subscribed())681 self.stream.expect('rbracket')682 if len(args) == 1:683 arg = args[0]684 else:685 arg = nodes.Tuple(args, 'load', lineno=token.lineno)686 return nodes.Getitem(node, arg, 'load', lineno=token.lineno)687 self.fail('expected subscript expression', self.lineno)688689 def parse_subscribed(self):690 lineno = self.stream.current.lineno691692 if self.stream.current.type == 'colon':693 next(self.stream)694 args = [None]695 else:696 node = self.parse_expression()697 if self.stream.current.type != 'colon':698 return node699 next(self.stream)700 args = [node]701702 if self.stream.current.type == 'colon':703 args.append(None)704 elif self.stream.current.type not in ('rbracket', 'comma'):705 args.append(self.parse_expression())706 else:707 args.append(None)708709 if self.stream.current.type == 'colon':710 next(self.stream)711 if self.stream.current.type not in ('rbracket', 'comma'):712 args.append(self.parse_expression())713 else:714 args.append(None)715 else:716 args.append(None)717718 return nodes.Slice(lineno=lineno, *args)719720 def parse_call(self, node):721 token = self.stream.expect('lparen')722 args = []723 kwargs = []724 dyn_args = dyn_kwargs = None725 require_comma = False726727 def ensure(expr):728 if not expr:729 self.fail('invalid syntax for function call expression',730 token.lineno)731732 while self.stream.current.type != 'rparen':733 if require_comma:734 self.stream.expect('comma')735 # support for trailing comma736 if self.stream.current.type == 'rparen':737 break738 if self.stream.current.type == 'mul':739 ensure(dyn_args is None and dyn_kwargs is None)740 next(self.stream)741 dyn_args = self.parse_expression()742 elif self.stream.current.type == 'pow':743 ensure(dyn_kwargs is None)744 next(self.stream)745 dyn_kwargs = self.parse_expression()746 else:747 ensure(dyn_args is None and dyn_kwargs is None)748 if self.stream.current.type == 'name' and \749 self.stream.look().type == 'assign':750 key = self.stream.current.value751 self.stream.skip(2)752 value = self.parse_expression()753 kwargs.append(nodes.Keyword(key, value,754 lineno=value.lineno))755 else:756 ensure(not kwargs)757 args.append(self.parse_expression())758759 require_comma = True760 self.stream.expect('rparen')761762 if node is None:763 return args, kwargs, dyn_args, dyn_kwargs764 return nodes.Call(node, args, kwargs, dyn_args, dyn_kwargs,765 lineno=token.lineno)766767 def parse_filter(self, node, start_inline=False):768 while self.stream.current.type == 'pipe' or start_inline:769 if not start_inline:770 next(self.stream)771 token = self.stream.expect('name')772 name = token.value773 while self.stream.current.type == 'dot':774 next(self.stream)775 name += '.' + self.stream.expect('name').value776 if self.stream.current.type == 'lparen':777 args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)778 else:779 args = []780 kwargs = []781 dyn_args = dyn_kwargs = None782 node = nodes.Filter(node, name, args, kwargs, dyn_args,783 dyn_kwargs, lineno=token.lineno)784 start_inline = False785 return node786787 def parse_test(self, node):788 token = next(self.stream)789 if self.stream.current.test('name:not'):790 next(self.stream)791 negated = True792 else:793 negated = False794 name = self.stream.expect('name').value795 while self.stream.current.type == 'dot':796 next(self.stream)797 name += '.' + self.stream.expect('name').value798 dyn_args = dyn_kwargs = None799 kwargs = []800 if self.stream.current.type == 'lparen':801 args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)802 elif (self.stream.current.type in ('name', 'string', 'integer',803 'float', 'lparen', 'lbracket',804 'lbrace') and not805 self.stream.current.test_any('name:else', 'name:or',806 'name:and')):807 if self.stream.current.test('name:is'):808 self.fail('You cannot chain multiple tests with is')809 args = [self.parse_expression()]810 else:811 args = []812 node = nodes.Test(node, name, args, kwargs, dyn_args,813 dyn_kwargs, lineno=token.lineno)814 if negated:815 node = nodes.Not(node, lineno=token.lineno)816 return node817818 def subparse(self, end_tokens=None):819 body = []820 data_buffer = []821 add_data = data_buffer.append822823 if end_tokens is not None:824 self._end_token_stack.append(end_tokens)825826 def flush_data():827 if data_buffer:828 lineno = data_buffer[0].lineno829 body.append(nodes.Output(data_buffer[:], lineno=lineno))830 del data_buffer[:]831832 try:833 while self.stream:834 token = self.stream.current835 if token.type == 'data':836 if token.value:837 add_data(nodes.TemplateData(token.value,838 lineno=token.lineno))839 next(self.stream)840 elif token.type == 'variable_begin':841 next(self.stream)842 add_data(self.parse_tuple(with_condexpr=True))843 self.stream.expect('variable_end')844 elif token.type == 'block_begin':845 flush_data()846 next(self.stream)847 if end_tokens is not None and \848 self.stream.current.test_any(*end_tokens):849 return body850 rv = self.parse_statement()851 if isinstance(rv, list):852 body.extend(rv)853 else:854 body.append(rv)855 self.stream.expect('block_end')856 else:857 raise AssertionError('internal parsing error')858859 flush_data()860 finally:861 if end_tokens is not None:862 self._end_token_stack.pop()863864 return body865866 def parse(self):867 """Parse the whole template into a `Template` node."""868 result = nodes.Template(self.subparse(), lineno=1)869 result.set_environment(self.environment)870 return result