parser.py
This file
Path
src/jinja2/parser.py
1,032 lines · 38.7 KiB · Python
Last changed by
Merge branch '3.0.x'David Lordbefore adoption80e6c4b
History of this fileTake it
The walk stopped after 200 commits: lines older than d312609 point at it.
isolate bytecode cache testsDavid Lordbefore adoptiond312609
line 1why, one step back1"""Parse tokens from the lexer into nodes for the compiler."""Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 2–4why, one step back2import typing3import typing as t4isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 5–10why, one step back5from . import nodes6from .exceptions import TemplateAssertionError7from .exceptions import TemplateSyntaxError8from .lexer import describe_token9from .lexer import describe_token_expr10Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 11–17why, one step back11if t.TYPE_CHECKING:12 import typing_extensions as te13 from .environment import Environment1415_ImportInclude = t.TypeVar("_ImportInclude", nodes.Import, nodes.Include)16_MacroCall = t.TypeVar("_MacroCall", nodes.Macro, nodes.CallBlock)17isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 18–35why, one step back18_statement_keywords = frozenset(19 [20 "for",21 "if",22 "block",23 "extends",24 "print",25 "macro",26 "include",27 "from",28 "import",29 "set",30 "with",31 "autoescape",32 ]33)34_compare_operators = frozenset(["eq", "ne", "lt", "lteq", "gt", "gteq"])35Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 36why, one step back36_math_nodes: t.Dict[str, t.Type[nodes.Expr]] = {isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 37–45why, one step back37 "add": nodes.Add,38 "sub": nodes.Sub,39 "mul": nodes.Mul,40 "div": nodes.Div,41 "floordiv": nodes.FloorDiv,42 "mod": nodes.Mod,43}4445Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5
line 46why, one step back46class Parser:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 47–50why, one step back47 """This is the central parsing class Jinja uses. It's passed to48 extensions and can be used to parse expressions or statements.49 """50Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 51–58why, one step back51 def __init__(52 self,53 environment: "Environment",54 source: str,55 name: t.Optional[str] = None,56 filename: t.Optional[str] = None,57 state: t.Optional[str] = None,58 ) -> None:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 59–63why, one step back59 self.environment = environment60 self.stream = environment._tokenize(source, name, filename, state)61 self.name = name62 self.filename = filename63 self.closed = FalseMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 64–66why, one step back64 self.extensions: t.Dict[65 str, t.Callable[["Parser"], t.Union[nodes.Node, t.List[nodes.Node]]]66 ] = {}isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 67–70why, one step back67 for extension in environment.iter_extensions():68 for tag in extension.tags:69 self.extensions[tag] = extension.parse70 self._last_identifier = 0Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 71–72why, one step back71 self._tag_stack: t.List[str] = []72 self._end_token_stack: t.List[t.Tuple[str, ...]] = []isolate bytecode cache testsDavid Lordbefore adoptiond312609
line 73why, one step back73Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 74–78why, one step back74 def fail(75 self,76 msg: str,77 lineno: t.Optional[int] = None,78 exc: t.Type[TemplateSyntaxError] = TemplateSyntaxError,Merge pull request #1434 from pallets/update-typingDavid Lordbefore adoptiona2e83d0
line 79why, one step back79 ) -> "te.NoReturn":isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 80–87why, one step back80 """Convenience method that raises `exc` with the message, passed81 line number or last line number as well as the current name and82 filename.83 """84 if lineno is None:85 lineno = self.stream.current.lineno86 raise exc(msg, lineno, self.name, self.filename)87Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 88–92why, one step back88 def _fail_ut_eof(89 self,90 name: t.Optional[str],91 end_token_stack: t.List[t.Tuple[str, ...]],92 lineno: t.Optional[int],Merge pull request #1434 from pallets/update-typingDavid Lordbefore adoptiona2e83d0
line 93why, one step back93 ) -> "te.NoReturn":Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 94why, one step back94 expected: t.Set[str] = set()isolate bytecode cache testsDavid Lordbefore adoptiond312609
line 95why, one step back95 for exprs in end_token_stack:Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 96why, one step back96 expected.update(map(describe_token_expr, exprs))isolate bytecode cache testsDavid Lordbefore adoptiond312609
line 97why, one step back97 if end_token_stack:Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 98why, one step back98 currently_looking: t.Optional[str] = " or ".join(Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5
line 99why, one step back99 map(repr, map(describe_token_expr, end_token_stack[-1]))isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 100–106why, one step back100 )101 else:102 currently_looking = None103104 if name is None:105 message = ["Unexpected end of template."]106 else:Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5
line 107why, one step back107 message = [f"Encountered unknown tag {name!r}."]isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 108–111why, one step back108109 if currently_looking:110 if name is not None and name in expected:111 message.append(Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5
lines 112–113why, one step back112 "You probably made a nesting mistake. Jinja is expecting this tag,"113 f" but currently looking for {currently_looking}."isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 114–116why, one step back114 )115 else:116 message.append(Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5
line 117why, one step back117 f"Jinja was looking for the following tags: {currently_looking}."isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 118–121why, one step back118 )119120 if self._tag_stack:121 message.append(Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5
lines 122–123why, one step back122 "The innermost block that needs to be closed is"123 f" {self._tag_stack[-1]!r}."isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 124–127why, one step back124 )125126 self.fail(" ".join(message), lineno)127Merge pull request #1434 from pallets/update-typingDavid Lordbefore adoptiona2e83d0
lines 128–130why, one step back128 def fail_unknown_tag(129 self, name: str, lineno: t.Optional[int] = None130 ) -> "te.NoReturn":isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 131–134why, one step back131 """Called if the parser encounters an unknown tag. Tries to fail132 with a human readable error message that could help to identify133 the problem.134 """Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 135why, one step back135 self._fail_ut_eof(name, self._end_token_stack, lineno)isolate bytecode cache testsDavid Lordbefore adoptiond312609
line 136why, one step back136Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 137–140why, one step back137 def fail_eof(138 self,139 end_tokens: t.Optional[t.Tuple[str, ...]] = None,140 lineno: t.Optional[int] = None,Merge pull request #1434 from pallets/update-typingDavid Lordbefore adoptiona2e83d0
line 141why, one step back141 ) -> "te.NoReturn":isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 142–145why, one step back142 """Like fail_unknown_tag but for end of template situations."""143 stack = list(self._end_token_stack)144 if end_tokens is not None:145 stack.append(end_tokens)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 146why, one step back146 self._fail_ut_eof(None, stack, lineno)isolate bytecode cache testsDavid Lordbefore adoptiond312609
line 147why, one step back147Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 148–150why, one step back148 def is_tuple_end(149 self, extra_end_rules: t.Optional[t.Tuple[str, ...]] = None150 ) -> bool:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 151–154why, one step back151 """Are we at the end of a tuple?"""152 if self.stream.current.type in ("variable_end", "block_end", "rparen"):153 return True154 elif extra_end_rules is not None:Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 155why, one step back155 return self.stream.current.test_any(extra_end_rules) # type: ignoreisolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 156–157why, one step back156 return False157Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 158why, one step back158 def free_identifier(self, lineno: t.Optional[int] = None) -> nodes.InternalName:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 159–161why, one step back159 """Return a new free identifier as :class:`~jinja2.nodes.InternalName`."""160 self._last_identifier += 1161 rv = object.__new__(nodes.InternalName)Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5
line 162why, one step back162 nodes.Node.__init__(rv, f"fi{self._last_identifier}", lineno=lineno)Merge branch '3.0.x'David Lordbefore adoption896a621
line 163why, one step back163 return rvisolate bytecode cache testsDavid Lordbefore adoptiond312609
line 164why, one step back164Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 165why, one step back165 def parse_statement(self) -> t.Union[nodes.Node, t.List[nodes.Node]]:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 166–173why, one step back166 """Parse a single statement."""167 token = self.stream.current168 if token.type != "name":169 self.fail("tag name expected", token.lineno)170 self._tag_stack.append(token.value)171 pop_tag = True172 try:173 if token.value in _statement_keywords:Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 174–175why, one step back174 f = getattr(self, f"parse_{self.stream.current.value}")175 return f() # type: ignoreisolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 176–193why, one step back176 if token.value == "call":177 return self.parse_call_block()178 if token.value == "filter":179 return self.parse_filter_block()180 ext = self.extensions.get(token.value)181 if ext is not None:182 return ext(self)183184 # did not work out, remove the token we pushed by accident185 # from the stack so that the unknown tag fail function can186 # produce a proper error message.187 self._tag_stack.pop()188 pop_tag = False189 self.fail_unknown_tag(token.value, token.lineno)190 finally:191 if pop_tag:192 self._tag_stack.pop()193Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 194–196why, one step back194 def parse_statements(195 self, end_tokens: t.Tuple[str, ...], drop_needle: bool = False196 ) -> t.List[nodes.Node]:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 197–222why, one step back197 """Parse multiple statements into a list until one of the end tokens198 is reached. This is used to parse the body of statements as it also199 parses template data if appropriate. The parser checks first if the200 current token is a colon and skips it if there is one. Then it checks201 for the block end and parses until if one of the `end_tokens` is202 reached. Per default the active token in the stream at the end of203 the call is the matched end token. If this is not wanted `drop_needle`204 can be set to `True` and the end token is removed.205 """206 # the first token may be a colon for python compatibility207 self.stream.skip_if("colon")208209 # in the future it would be possible to add whole code sections210 # by adding some sort of end of statement token and parsing those here.211 self.stream.expect("block_end")212 result = self.subparse(end_tokens)213214 # we reached the end of the template too early, the subparser215 # does not check for this, so we do that now216 if self.stream.current.type == "eof":217 self.fail_eof(end_tokens)218219 if drop_needle:220 next(self.stream)221 return result222Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 223why, one step back223 def parse_set(self) -> t.Union[nodes.Assign, nodes.AssignBlock]:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 224–233why, one step back224 """Parse an assign statement."""225 lineno = next(self.stream).lineno226 target = self.parse_assign_target(with_namespace=True)227 if self.stream.skip_if("assign"):228 expr = self.parse_tuple()229 return nodes.Assign(target, expr, lineno=lineno)230 filter_node = self.parse_filter(None)231 body = self.parse_statements(("name:endset",), drop_needle=True)232 return nodes.AssignBlock(target, filter_node, body, lineno=lineno)233Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 234why, one step back234 def parse_for(self) -> nodes.For:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 235–252why, one step back235 """Parse a for loop."""236 lineno = self.stream.expect("name:for").lineno237 target = self.parse_assign_target(extra_end_rules=("name:in",))238 self.stream.expect("name:in")239 iter = self.parse_tuple(240 with_condexpr=False, extra_end_rules=("name:recursive",)241 )242 test = None243 if self.stream.skip_if("name:if"):244 test = self.parse_expression()245 recursive = self.stream.skip_if("name:recursive")246 body = self.parse_statements(("name:endfor", "name:else"))247 if next(self.stream).value == "endfor":248 else_ = []249 else:250 else_ = self.parse_statements(("name:endfor",), drop_needle=True)251 return nodes.For(target, iter, body, else_, test, recursive, lineno=lineno)252Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 253why, one step back253 def parse_if(self) -> nodes.If:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 254–255why, one step back254 """Parse an if construct."""255 node = result = nodes.If(lineno=self.stream.expect("name:if").lineno)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 256why, one step back256 while True:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 257–270why, one step back257 node.test = self.parse_tuple(with_condexpr=False)258 node.body = self.parse_statements(("name:elif", "name:else", "name:endif"))259 node.elif_ = []260 node.else_ = []261 token = next(self.stream)262 if token.test("name:elif"):263 node = nodes.If(lineno=self.stream.current.lineno)264 result.elif_.append(node)265 continue266 elif token.test("name:else"):267 result.else_ = self.parse_statements(("name:endif",), drop_needle=True)268 break269 return result270Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 271why, one step back271 def parse_with(self) -> nodes.With:isolate bytecode cache testsDavid Lordbefore adoptiond312609
line 272why, one step back272 node = nodes.With(lineno=next(self.stream).lineno)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 273–274why, one step back273 targets: t.List[nodes.Expr] = []274 values: t.List[nodes.Expr] = []isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 275–287why, one step back275 while self.stream.current.type != "block_end":276 if targets:277 self.stream.expect("comma")278 target = self.parse_assign_target()279 target.set_ctx("param")280 targets.append(target)281 self.stream.expect("assign")282 values.append(self.parse_expression())283 node.targets = targets284 node.values = values285 node.body = self.parse_statements(("name:endwith",), drop_needle=True)286 return node287Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 288why, one step back288 def parse_autoescape(self) -> nodes.Scope:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 289–293why, one step back289 node = nodes.ScopedEvalContextModifier(lineno=next(self.stream).lineno)290 node.options = [nodes.Keyword("autoescape", self.parse_expression())]291 node.body = self.parse_statements(("name:endautoescape",), drop_needle=True)292 return nodes.Scope([node])293Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 294why, one step back294 def parse_block(self) -> nodes.Block:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 295–297why, one step back295 node = nodes.Block(lineno=next(self.stream).lineno)296 node.name = self.stream.expect("name").value297 node.scoped = self.stream.skip_if("name:scoped")Merge pull request #1233 from MLH-Fellowship/required-blocksAmy Leibefore adoption35e8f0a
line 298why, one step back298 node.required = self.stream.skip_if("name:required")isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 299–304why, one step back299300 # common problem people encounter when switching from django301 # to jinja. we do not support hyphens in block names, so let's302 # raise a nicer error message in that case.303 if self.stream.current.type == "sub":304 self.fail(Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5
lines 305–306why, one step back305 "Block names in Jinja have to be valid Python identifiers and may not"306 " contain hyphens, use an underscore instead."isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 307–309why, one step back307 )308309 node.body = self.parse_statements(("name:endblock",), drop_needle=True)Merge pull request #1233 from MLH-Fellowship/required-blocksAmy Leibefore adoption35e8f0a
lines 310–316why, one step back310311 # enforce that required blocks only contain whitespace or comments312 # by asserting that the body, if not empty, is just TemplateData nodes313 # with whitespace data314 if node.required and not all(315 isinstance(child, nodes.TemplateData) and child.data.isspace()316 for body in node.bodyMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 317why, one step back317 for child in body.nodes # type: ignoreMerge pull request #1233 from MLH-Fellowship/required-blocksAmy Leibefore adoption35e8f0a
lines 318–320why, one step back318 ):319 self.fail("Required blocks can only contain comments or whitespace")320isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 321–323why, one step back321 self.stream.skip_if("name:" + node.name)322 return node323Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 324why, one step back324 def parse_extends(self) -> nodes.Extends:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 325–328why, one step back325 node = nodes.Extends(lineno=next(self.stream).lineno)326 node.template = self.parse_expression()327 return node328Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 329–331why, one step back329 def parse_import_context(330 self, node: _ImportInclude, default: bool331 ) -> _ImportInclude:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 332–340why, one step back332 if self.stream.current.test_any(333 "name:with", "name:without"334 ) and self.stream.look().test("name:context"):335 node.with_context = next(self.stream).value == "with"336 self.stream.skip()337 else:338 node.with_context = default339 return node340Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 341why, one step back341 def parse_include(self) -> nodes.Include:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 342–352why, one step back342 node = nodes.Include(lineno=next(self.stream).lineno)343 node.template = self.parse_expression()344 if self.stream.current.test("name:ignore") and self.stream.look().test(345 "name:missing"346 ):347 node.ignore_missing = True348 self.stream.skip(2)349 else:350 node.ignore_missing = False351 return self.parse_import_context(node, True)352Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 353why, one step back353 def parse_import(self) -> nodes.Import:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 354–359why, one step back354 node = nodes.Import(lineno=next(self.stream).lineno)355 node.template = self.parse_expression()356 self.stream.expect("name:as")357 node.target = self.parse_assign_target(name_only=True).name358 return self.parse_import_context(node, False)359Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 360why, one step back360 def parse_from(self) -> nodes.FromImport:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 361–365why, one step back361 node = nodes.FromImport(lineno=next(self.stream).lineno)362 node.template = self.parse_expression()363 self.stream.expect("name:import")364 node.names = []365Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 366why, one step back366 def parse_context() -> bool:Merge branch '3.0.x'David Lordbefore adoption80e6c4b
lines 367–370why, one step back367 if self.stream.current.value in {368 "with",369 "without",370 } and self.stream.look().test("name:context"):isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 371–375why, one step back371 node.with_context = next(self.stream).value == "with"372 self.stream.skip()373 return True374 return False375Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 376why, one step back376 while True:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 377–401why, one step back377 if node.names:378 self.stream.expect("comma")379 if self.stream.current.type == "name":380 if parse_context():381 break382 target = self.parse_assign_target(name_only=True)383 if target.name.startswith("_"):384 self.fail(385 "names starting with an underline can not be imported",386 target.lineno,387 exc=TemplateAssertionError,388 )389 if self.stream.skip_if("name:as"):390 alias = self.parse_assign_target(name_only=True)391 node.names.append((target.name, alias.name))392 else:393 node.names.append(target.name)394 if parse_context() or self.stream.current.type != "comma":395 break396 else:397 self.stream.expect("name")398 if not hasattr(node, "with_context"):399 node.with_context = False400 return node401Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 402–404why, one step back402 def parse_signature(self, node: _MacroCall) -> None:403 args = node.args = []404 defaults = node.defaults = []isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 405–417why, one step back405 self.stream.expect("lparen")406 while self.stream.current.type != "rparen":407 if args:408 self.stream.expect("comma")409 arg = self.parse_assign_target(name_only=True)410 arg.set_ctx("param")411 if self.stream.skip_if("assign"):412 defaults.append(self.parse_expression())413 elif defaults:414 self.fail("non-default argument follows default argument")415 args.append(arg)416 self.stream.expect("rparen")417Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 418why, one step back418 def parse_call_block(self) -> nodes.CallBlock:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 419–425why, one step back419 node = nodes.CallBlock(lineno=next(self.stream).lineno)420 if self.stream.current.type == "lparen":421 self.parse_signature(node)422 else:423 node.args = []424 node.defaults = []425Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 426–427why, one step back426 call_node = self.parse_expression()427 if not isinstance(call_node, nodes.Call):isolate bytecode cache testsDavid Lordbefore adoptiond312609
line 428why, one step back428 self.fail("expected call", node.lineno)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 429why, one step back429 node.call = call_nodeisolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 430–432why, one step back430 node.body = self.parse_statements(("name:endcall",), drop_needle=True)431 return node432Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 433why, one step back433 def parse_filter_block(self) -> nodes.FilterBlock:isolate bytecode cache testsDavid Lordbefore adoptiond312609
line 434why, one step back434 node = nodes.FilterBlock(lineno=next(self.stream).lineno)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 435why, one step back435 node.filter = self.parse_filter(None, start_inline=True) # type: ignoreisolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 436–438why, one step back436 node.body = self.parse_statements(("name:endfilter",), drop_needle=True)437 return node438Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 439why, one step back439 def parse_macro(self) -> nodes.Macro:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 440–445why, one step back440 node = nodes.Macro(lineno=next(self.stream).lineno)441 node.name = self.parse_assign_target(name_only=True).name442 self.parse_signature(node)443 node.body = self.parse_statements(("name:endmacro",), drop_needle=True)444 return node445Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 446why, one step back446 def parse_print(self) -> nodes.Output:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 447–454why, one step back447 node = nodes.Output(lineno=next(self.stream).lineno)448 node.nodes = []449 while self.stream.current.type != "block_end":450 if node.nodes:451 self.stream.expect("comma")452 node.nodes.append(self.parse_expression())453 return node454Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 455why, one step back455 @typing.overloadisolate bytecode cache testsDavid Lordbefore adoptiond312609
line 456why, one step back456 def parse_assign_target(Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 457–462why, one step back457 self, with_tuple: bool = ..., name_only: "te.Literal[True]" = ...458 ) -> nodes.Name:459 ...460461 @typing.overload462 def parse_assign_target(isolate bytecode cache testsDavid Lordbefore adoptiond312609
line 463why, one step back463 self,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 464–477why, one step back464 with_tuple: bool = True,465 name_only: bool = False,466 extra_end_rules: t.Optional[t.Tuple[str, ...]] = None,467 with_namespace: bool = False,468 ) -> t.Union[nodes.NSRef, nodes.Name, nodes.Tuple]:469 ...470471 def parse_assign_target(472 self,473 with_tuple: bool = True,474 name_only: bool = False,475 extra_end_rules: t.Optional[t.Tuple[str, ...]] = None,476 with_namespace: bool = False,477 ) -> t.Union[nodes.NSRef, nodes.Name, nodes.Tuple]:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 478–485why, one step back478 """Parse an assignment target. As Jinja allows assignments to479 tuples, this function can parse all allowed assignment targets. Per480 default assignments to tuples are parsed, that can be disable however481 by setting `with_tuple` to `False`. If only assignments to names are482 wanted `name_only` can be set to `True`. The `extra_end_rules`483 parameter is forwarded to the tuple parsing function. If484 `with_namespace` is enabled, a namespace assignment may be parsed.485 """Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 486–487why, one step back486 target: nodes.Expr487isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 488–502why, one step back488 if with_namespace and self.stream.look().type == "dot":489 token = self.stream.expect("name")490 next(self.stream) # dot491 attr = self.stream.expect("name")492 target = nodes.NSRef(token.value, attr.value, lineno=token.lineno)493 elif name_only:494 token = self.stream.expect("name")495 target = nodes.Name(token.value, "store", lineno=token.lineno)496 else:497 if with_tuple:498 target = self.parse_tuple(499 simplified=True, extra_end_rules=extra_end_rules500 )501 else:502 target = self.parse_primary()Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 503why, one step back503isolate bytecode cache testsDavid Lordbefore adoptiond312609
line 504why, one step back504 target.set_ctx("store")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 505why, one step back505isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 506–507why, one step back506 if not target.can_assign():507 self.fail(Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 508why, one step back508 f"can't assign to {type(target).__name__.lower()!r}", target.linenoisolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 509–510why, one step back509 )510Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 511–513why, one step back511 return target # type: ignore512513 def parse_expression(self, with_condexpr: bool = True) -> nodes.Expr:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 514–521why, one step back514 """Parse an expression. Per default all expressions are parsed, if515 the optional `with_condexpr` parameter is set to `False` conditional516 expressions are not parsed.517 """518 if with_condexpr:519 return self.parse_condexpr()520 return self.parse_or()521Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 522why, one step back522 def parse_condexpr(self) -> nodes.Expr:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 523–524why, one step back523 lineno = self.stream.current.lineno524 expr1 = self.parse_or()Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 525–526why, one step back525 expr3: t.Optional[nodes.Expr]526isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 527–536why, one step back527 while self.stream.skip_if("name:if"):528 expr2 = self.parse_or()529 if self.stream.skip_if("name:else"):530 expr3 = self.parse_condexpr()531 else:532 expr3 = None533 expr1 = nodes.CondExpr(expr2, expr1, expr3, lineno=lineno)534 lineno = self.stream.current.lineno535 return expr1536Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 537why, one step back537 def parse_or(self) -> nodes.Expr:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 538–545why, one step back538 lineno = self.stream.current.lineno539 left = self.parse_and()540 while self.stream.skip_if("name:or"):541 right = self.parse_and()542 left = nodes.Or(left, right, lineno=lineno)543 lineno = self.stream.current.lineno544 return left545Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 546why, one step back546 def parse_and(self) -> nodes.Expr:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 547–554why, one step back547 lineno = self.stream.current.lineno548 left = self.parse_not()549 while self.stream.skip_if("name:and"):550 right = self.parse_not()551 left = nodes.And(left, right, lineno=lineno)552 lineno = self.stream.current.lineno553 return left554Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 555why, one step back555 def parse_not(self) -> nodes.Expr:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 556–560why, one step back556 if self.stream.current.test("name:not"):557 lineno = next(self.stream).lineno558 return nodes.Not(self.parse_not(), lineno=lineno)559 return self.parse_compare()560Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 561why, one step back561 def parse_compare(self) -> nodes.Expr:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 562–564why, one step back562 lineno = self.stream.current.lineno563 expr = self.parse_math1()564 ops = []Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 565why, one step back565 while True:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 566–583why, one step back566 token_type = self.stream.current.type567 if token_type in _compare_operators:568 next(self.stream)569 ops.append(nodes.Operand(token_type, self.parse_math1()))570 elif self.stream.skip_if("name:in"):571 ops.append(nodes.Operand("in", self.parse_math1()))572 elif self.stream.current.test("name:not") and self.stream.look().test(573 "name:in"574 ):575 self.stream.skip(2)576 ops.append(nodes.Operand("notin", self.parse_math1()))577 else:578 break579 lineno = self.stream.current.lineno580 if not ops:581 return expr582 return nodes.Compare(expr, ops, lineno=lineno)583Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 584why, one step back584 def parse_math1(self) -> nodes.Expr:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 585–594why, one step back585 lineno = self.stream.current.lineno586 left = self.parse_concat()587 while self.stream.current.type in ("add", "sub"):588 cls = _math_nodes[self.stream.current.type]589 next(self.stream)590 right = self.parse_concat()591 left = cls(left, right, lineno=lineno)592 lineno = self.stream.current.lineno593 return left594Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 595why, one step back595 def parse_concat(self) -> nodes.Expr:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 596–604why, one step back596 lineno = self.stream.current.lineno597 args = [self.parse_math2()]598 while self.stream.current.type == "tilde":599 next(self.stream)600 args.append(self.parse_math2())601 if len(args) == 1:602 return args[0]603 return nodes.Concat(args, lineno=lineno)604Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 605why, one step back605 def parse_math2(self) -> nodes.Expr:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 606–615why, one step back606 lineno = self.stream.current.lineno607 left = self.parse_pow()608 while self.stream.current.type in ("mul", "div", "floordiv", "mod"):609 cls = _math_nodes[self.stream.current.type]610 next(self.stream)611 right = self.parse_pow()612 left = cls(left, right, lineno=lineno)613 lineno = self.stream.current.lineno614 return left615Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 616why, one step back616 def parse_pow(self) -> nodes.Expr:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 617–625why, one step back617 lineno = self.stream.current.lineno618 left = self.parse_unary()619 while self.stream.current.type == "pow":620 next(self.stream)621 right = self.parse_unary()622 left = nodes.Pow(left, right, lineno=lineno)623 lineno = self.stream.current.lineno624 return left625Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 626why, one step back626 def parse_unary(self, with_filter: bool = True) -> nodes.Expr:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 627–628why, one step back627 token_type = self.stream.current.type628 lineno = self.stream.current.linenoMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 629–630why, one step back629 node: nodes.Expr630isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 631–643why, one step back631 if token_type == "sub":632 next(self.stream)633 node = nodes.Neg(self.parse_unary(False), lineno=lineno)634 elif token_type == "add":635 next(self.stream)636 node = nodes.Pos(self.parse_unary(False), lineno=lineno)637 else:638 node = self.parse_primary()639 node = self.parse_postfix(node)640 if with_filter:641 node = self.parse_filter_expr(node)642 return node643Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 644why, one step back644 def parse_primary(self) -> nodes.Expr:isolate bytecode cache testsDavid Lordbefore adoptiond312609
line 645why, one step back645 token = self.stream.currentMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 646why, one step back646 node: nodes.Exprisolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 647–674why, one step back647 if token.type == "name":648 if token.value in ("true", "false", "True", "False"):649 node = nodes.Const(token.value in ("true", "True"), lineno=token.lineno)650 elif token.value in ("none", "None"):651 node = nodes.Const(None, lineno=token.lineno)652 else:653 node = nodes.Name(token.value, "load", lineno=token.lineno)654 next(self.stream)655 elif token.type == "string":656 next(self.stream)657 buf = [token.value]658 lineno = token.lineno659 while self.stream.current.type == "string":660 buf.append(self.stream.current.value)661 next(self.stream)662 node = nodes.Const("".join(buf), lineno=lineno)663 elif token.type in ("integer", "float"):664 next(self.stream)665 node = nodes.Const(token.value, lineno=token.lineno)666 elif token.type == "lparen":667 next(self.stream)668 node = self.parse_tuple(explicit_parentheses=True)669 self.stream.expect("rparen")670 elif token.type == "lbracket":671 node = self.parse_list()672 elif token.type == "lbrace":673 node = self.parse_dict()674 else:Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5
line 675why, one step back675 self.fail(f"unexpected {describe_token(token)!r}", token.lineno)isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 676–679why, one step back676 return node677678 def parse_tuple(679 self,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 680–684why, one step back680 simplified: bool = False,681 with_condexpr: bool = True,682 extra_end_rules: t.Optional[t.Tuple[str, ...]] = None,683 explicit_parentheses: bool = False,684 ) -> t.Union[nodes.Tuple, nodes.Expr]:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 685–709why, one step back685 """Works like `parse_expression` but if multiple expressions are686 delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.687 This method could also return a regular expression instead of a tuple688 if no commas where found.689690 The default parsing mode is a full tuple. If `simplified` is `True`691 only names and literals are parsed. The `no_condexpr` parameter is692 forwarded to :meth:`parse_expression`.693694 Because tuples do not require delimiters and may end in a bogus comma695 an extra hint is needed that marks the end of a tuple. For example696 for loops support tuples between `for` and `in`. In that case the697 `extra_end_rules` is set to ``['name:in']``.698699 `explicit_parentheses` is true if the parsing was triggered by an700 expression in parentheses. This is used to figure out if an empty701 tuple is a valid expression or not.702 """703 lineno = self.stream.current.lineno704 if simplified:705 parse = self.parse_primary706 elif with_condexpr:707 parse = self.parse_expression708 else:709Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 710why, one step back710 def parse() -> nodes.Expr:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 711–712why, one step back711 return self.parse_expression(with_condexpr=False)712Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 713why, one step back713 args: t.List[nodes.Expr] = []isolate bytecode cache testsDavid Lordbefore adoptiond312609
line 714why, one step back714 is_tuple = FalseMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 715–716why, one step back715716 while True:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 717–737why, one step back717 if args:718 self.stream.expect("comma")719 if self.is_tuple_end(extra_end_rules):720 break721 args.append(parse())722 if self.stream.current.type == "comma":723 is_tuple = True724 else:725 break726 lineno = self.stream.current.lineno727728 if not is_tuple:729 if args:730 return args[0]731732 # if we don't have explicit parentheses, an empty tuple is733 # not a valid expression. This would mean nothing (literally734 # nothing) in the spot of an expression would be an empty735 # tuple.736 if not explicit_parentheses:737 self.fail(Merge pull request #1136 from pallets/drop-python2David Lordbefore adoption3915eb5
lines 738–739why, one step back738 "Expected an expression,"739 f" got {describe_token(self.stream.current)!r}"isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 740–743why, one step back740 )741742 return nodes.Tuple(args, "load", lineno=lineno)743Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 744why, one step back744 def parse_list(self) -> nodes.List:isolate bytecode cache testsDavid Lordbefore adoptiond312609
line 745why, one step back745 token = self.stream.expect("lbracket")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 746why, one step back746 items: t.List[nodes.Expr] = []isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 747–755why, one step back747 while self.stream.current.type != "rbracket":748 if items:749 self.stream.expect("comma")750 if self.stream.current.type == "rbracket":751 break752 items.append(self.parse_expression())753 self.stream.expect("rbracket")754 return nodes.List(items, lineno=token.lineno)755Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 756why, one step back756 def parse_dict(self) -> nodes.Dict:isolate bytecode cache testsDavid Lordbefore adoptiond312609
line 757why, one step back757 token = self.stream.expect("lbrace")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 758why, one step back758 items: t.List[nodes.Pair] = []isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 759–770why, one step back759 while self.stream.current.type != "rbrace":760 if items:761 self.stream.expect("comma")762 if self.stream.current.type == "rbrace":763 break764 key = self.parse_expression()765 self.stream.expect("colon")766 value = self.parse_expression()767 items.append(nodes.Pair(key, value, lineno=key.lineno))768 self.stream.expect("rbrace")769 return nodes.Dict(items, lineno=token.lineno)770Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 771–772why, one step back771 def parse_postfix(self, node: nodes.Expr) -> nodes.Expr:772 while True:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 773–783why, one step back773 token_type = self.stream.current.type774 if token_type == "dot" or token_type == "lbracket":775 node = self.parse_subscript(node)776 # calls are valid both after postfix expressions (getattr777 # and getitem) as well as filters and tests778 elif token_type == "lparen":779 node = self.parse_call(node)780 else:781 break782 return node783Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 784–785why, one step back784 def parse_filter_expr(self, node: nodes.Expr) -> nodes.Expr:785 while True:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 786–787why, one step back786 token_type = self.stream.current.type787 if token_type == "pipe":Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 788why, one step back788 node = self.parse_filter(node) # type: ignoreisolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 789–798why, one step back789 elif token_type == "name" and self.stream.current.value == "is":790 node = self.parse_test(node)791 # calls are valid both after postfix expressions (getattr792 # and getitem) as well as filters and tests793 elif token_type == "lparen":794 node = self.parse_call(node)795 else:796 break797 return node798Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 799–801why, one step back799 def parse_subscript(800 self, node: nodes.Expr801 ) -> t.Union[nodes.Getattr, nodes.Getitem]:isolate bytecode cache testsDavid Lordbefore adoptiond312609
line 802why, one step back802 token = next(self.stream)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 803–804why, one step back803 arg: nodes.Expr804isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 805–816why, one step back805 if token.type == "dot":806 attr_token = self.stream.current807 next(self.stream)808 if attr_token.type == "name":809 return nodes.Getattr(810 node, attr_token.value, "load", lineno=token.lineno811 )812 elif attr_token.type != "integer":813 self.fail("expected name or number", attr_token.lineno)814 arg = nodes.Const(attr_token.value, lineno=attr_token.lineno)815 return nodes.Getitem(node, arg, "load", lineno=token.lineno)816 if token.type == "lbracket":Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 817why, one step back817 args: t.List[nodes.Expr] = []isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 818–829why, one step back818 while self.stream.current.type != "rbracket":819 if args:820 self.stream.expect("comma")821 args.append(self.parse_subscribed())822 self.stream.expect("rbracket")823 if len(args) == 1:824 arg = args[0]825 else:826 arg = nodes.Tuple(args, "load", lineno=token.lineno)827 return nodes.Getitem(node, arg, "load", lineno=token.lineno)828 self.fail("expected subscript expression", token.lineno)829Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 830why, one step back830 def parse_subscribed(self) -> nodes.Expr:isolate bytecode cache testsDavid Lordbefore adoptiond312609
line 831why, one step back831 lineno = self.stream.current.linenoMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 832why, one step back832 args: t.List[t.Optional[nodes.Expr]]isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 833–861why, one step back833834 if self.stream.current.type == "colon":835 next(self.stream)836 args = [None]837 else:838 node = self.parse_expression()839 if self.stream.current.type != "colon":840 return node841 next(self.stream)842 args = [node]843844 if self.stream.current.type == "colon":845 args.append(None)846 elif self.stream.current.type not in ("rbracket", "comma"):847 args.append(self.parse_expression())848 else:849 args.append(None)850851 if self.stream.current.type == "colon":852 next(self.stream)853 if self.stream.current.type not in ("rbracket", "comma"):854 args.append(self.parse_expression())855 else:856 args.append(None)857 else:858 args.append(None)859860 return nodes.Slice(lineno=lineno, *args)861Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 862why, one step back862 def parse_call_args(self) -> t.Tuple:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 863–865why, one step back863 token = self.stream.expect("lparen")864 args = []865 kwargs = []Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 866–867why, one step back866 dyn_args = None867 dyn_kwargs = Noneisolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 868–869why, one step back868 require_comma = False869Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 870why, one step back870 def ensure(expr: bool) -> None:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 871–876why, one step back871 if not expr:872 self.fail("invalid syntax for function call expression", token.lineno)873874 while self.stream.current.type != "rparen":875 if require_comma:876 self.stream.expect("comma")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 877why, one step back877isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 878–880why, one step back878 # support for trailing comma879 if self.stream.current.type == "rparen":880 breakMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 881why, one step back881isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 882–906why, one step back882 if self.stream.current.type == "mul":883 ensure(dyn_args is None and dyn_kwargs is None)884 next(self.stream)885 dyn_args = self.parse_expression()886 elif self.stream.current.type == "pow":887 ensure(dyn_kwargs is None)888 next(self.stream)889 dyn_kwargs = self.parse_expression()890 else:891 if (892 self.stream.current.type == "name"893 and self.stream.look().type == "assign"894 ):895 # Parsing a kwarg896 ensure(dyn_kwargs is None)897 key = self.stream.current.value898 self.stream.skip(2)899 value = self.parse_expression()900 kwargs.append(nodes.Keyword(key, value, lineno=value.lineno))901 else:902 # Parsing an arg903 ensure(dyn_args is None and dyn_kwargs is None and not kwargs)904 args.append(self.parse_expression())905906 require_comma = TrueMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 907why, one step back907isolate bytecode cache testsDavid Lordbefore adoptiond312609
line 908why, one step back908 self.stream.expect("rparen")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 909why, one step back909 return args, kwargs, dyn_args, dyn_kwargsisolate bytecode cache testsDavid Lordbefore adoptiond312609
line 910why, one step back910Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 911–915why, one step back911 def parse_call(self, node: nodes.Expr) -> nodes.Call:912 # The lparen will be expected in parse_call_args, but the lineno913 # needs to be recorded before the stream is advanced.914 token = self.stream.current915 args, kwargs, dyn_args, dyn_kwargs = self.parse_call_args()isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 916–917why, one step back916 return nodes.Call(node, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno)917Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 918–920why, one step back918 def parse_filter(919 self, node: t.Optional[nodes.Expr], start_inline: bool = False920 ) -> t.Optional[nodes.Expr]:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 921–929why, one step back921 while self.stream.current.type == "pipe" or start_inline:922 if not start_inline:923 next(self.stream)924 token = self.stream.expect("name")925 name = token.value926 while self.stream.current.type == "dot":927 next(self.stream)928 name += "." + self.stream.expect("name").value929 if self.stream.current.type == "lparen":Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 930why, one step back930 args, kwargs, dyn_args, dyn_kwargs = self.parse_call_args()isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 931–940why, one step back931 else:932 args = []933 kwargs = []934 dyn_args = dyn_kwargs = None935 node = nodes.Filter(936 node, name, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno937 )938 start_inline = False939 return node940Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 941why, one step back941 def parse_test(self, node: nodes.Expr) -> nodes.Expr:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 942–954why, one step back942 token = next(self.stream)943 if self.stream.current.test("name:not"):944 next(self.stream)945 negated = True946 else:947 negated = False948 name = self.stream.expect("name").value949 while self.stream.current.type == "dot":950 next(self.stream)951 name += "." + self.stream.expect("name").value952 dyn_args = dyn_kwargs = None953 kwargs = []954 if self.stream.current.type == "lparen":Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 955why, one step back955 args, kwargs, dyn_args, dyn_kwargs = self.parse_call_args()Merge branch '3.0.x'David Lordbefore adoption80e6c4b
lines 956–964why, one step back956 elif self.stream.current.type in {957 "name",958 "string",959 "integer",960 "float",961 "lparen",962 "lbracket",963 "lbrace",964 } and not self.stream.current.test_any("name:else", "name:or", "name:and"):isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 965–978why, one step back965 if self.stream.current.test("name:is"):966 self.fail("You cannot chain multiple tests with is")967 arg_node = self.parse_primary()968 arg_node = self.parse_postfix(arg_node)969 args = [arg_node]970 else:971 args = []972 node = nodes.Test(973 node, name, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno974 )975 if negated:976 node = nodes.Not(node, lineno=token.lineno)977 return node978Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 979–983why, one step back979 def subparse(980 self, end_tokens: t.Optional[t.Tuple[str, ...]] = None981 ) -> t.List[nodes.Node]:982 body: t.List[nodes.Node] = []983 data_buffer: t.List[nodes.Node] = []isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 984–988why, one step back984 add_data = data_buffer.append985986 if end_tokens is not None:987 self._end_token_stack.append(end_tokens)988Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 989why, one step back989 def flush_data() -> None:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 990–1027why, one step back990 if data_buffer:991 lineno = data_buffer[0].lineno992 body.append(nodes.Output(data_buffer[:], lineno=lineno))993 del data_buffer[:]994995 try:996 while self.stream:997 token = self.stream.current998 if token.type == "data":999 if token.value:1000 add_data(nodes.TemplateData(token.value, lineno=token.lineno))1001 next(self.stream)1002 elif token.type == "variable_begin":1003 next(self.stream)1004 add_data(self.parse_tuple(with_condexpr=True))1005 self.stream.expect("variable_end")1006 elif token.type == "block_begin":1007 flush_data()1008 next(self.stream)1009 if end_tokens is not None and self.stream.current.test_any(1010 *end_tokens1011 ):1012 return body1013 rv = self.parse_statement()1014 if isinstance(rv, list):1015 body.extend(rv)1016 else:1017 body.append(rv)1018 self.stream.expect("block_end")1019 else:1020 raise AssertionError("internal parsing error")10211022 flush_data()1023 finally:1024 if end_tokens is not None:1025 self._end_token_stack.pop()1026 return body1027Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1028why, one step back1028 def parse(self) -> nodes.Template:isolate bytecode cache testsDavid Lordbefore adoptiond312609
lines 1029–1032why, one step back1029 """Parse the whole template into a `Template` node."""1030 result = nodes.Template(self.subparse(), lineno=1)1031 result.set_environment(self.environment)1032 return result