compiler.py
This file
Path
src/jinja2/compiler.py
1,992 lines · 72.2 KiB · Python
Last changed by
drop end of life python versions (#2096)David Lordbefore adoption49c48a0
History of this fileTake it
The walk stopped after 200 commits: lines older than c580dd0 point at it.
update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1why, one step back1"""Compiles nodes from the parser into Python code."""Merge branch '3.1.x'David Lordbefore adoptionde61312
line 2why, one step back2Merge pull request #1361 from pallets/consistencyDavid Lordbefore adoptionab9cd8c
line 3why, one step back3import typing as tMerge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 4why, one step back4from contextlib import contextmanagerupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 5–21why, one step back5from functools import update_wrapper6from io import StringIO7from itertools import chain8from keyword import iskeyword as is_python_keyword910from markupsafe import escape11from markupsafe import Markup1213from . import nodes14from .exceptions import TemplateAssertionError15from .idtracking import Symbols16from .idtracking import VAR_LOAD_ALIAS17from .idtracking import VAR_LOAD_PARAMETER18from .idtracking import VAR_LOAD_RESOLVE19from .idtracking import VAR_LOAD_UNDEFINED20from .nodes import EvalContext21from .optimizer import OptimizerMerge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 22why, one step back22from .utils import _PassArgupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 23–25why, one step back23from .utils import concat24from .visitor import NodeVisitor25Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 26why, one step back26if t.TYPE_CHECKING:Merge pull request #1434 from pallets/update-typingDavid Lordbefore adoptiona2e83d0
line 27why, one step back27 import typing_extensions as teMerge branch '3.1.x'David Lordbefore adoptionde61312
line 28why, one step back28Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 29–32why, one step back29 from .environment import Environment3031F = t.TypeVar("F", bound=t.Callable[..., t.Any])32update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 33–44why, one step back33operators = {34 "eq": "==",35 "ne": "!=",36 "gt": ">",37 "gteq": ">=",38 "lt": "<",39 "lteq": "<=",40 "in": "in",41 "notin": "not in",42}4344Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 45–48why, one step back45def optimizeconst(f: F) -> F:46 def new_func(47 self: "CodeGenerator", node: nodes.Expr, frame: "Frame", **kwargs: t.Any48 ) -> t.Any:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 49why, one step back49 # Only optimize if the frame is not volatileMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 50why, one step back50 if self.optimizer is not None and not frame.eval_ctx.volatile:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 51why, one step back51 new_node = self.optimizer.visit(node, frame.eval_ctx)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 52why, one step back52update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 53–54why, one step back53 if new_node != node:54 return self.visit(new_node, frame)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 55why, one step back55update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 56–57why, one step back56 return f(self, node, frame, **kwargs)57Bump the python-requirements group in /requirements with 5 updates (#1973)David Lordbefore adoptionc6dd4ba
line 58why, one step back58 return update_wrapper(new_func, f) # type: ignore[return-value]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 59–60why, one step back5960Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 61–64why, one step back61def _make_binop(op: str) -> t.Callable[["CodeGenerator", nodes.BinExpr, "Frame"], None]:62 @optimizeconst63 def visitor(self: "CodeGenerator", node: nodes.BinExpr, frame: Frame) -> None:64 if (Merge branch '3.1.x'David Lordbefore adoptionde61312
line 65why, one step back65 self.environment.sandboxed and op in self.environment.intercepted_binops # type: ignoreMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 66–87why, one step back66 ):67 self.write(f"environment.call_binop(context, {op!r}, ")68 self.visit(node.left, frame)69 self.write(", ")70 self.visit(node.right, frame)71 else:72 self.write("(")73 self.visit(node.left, frame)74 self.write(f" {op} ")75 self.visit(node.right, frame)7677 self.write(")")7879 return visitor808182def _make_unop(83 op: str,84) -> t.Callable[["CodeGenerator", nodes.UnaryExpr, "Frame"], None]:85 @optimizeconst86 def visitor(self: "CodeGenerator", node: nodes.UnaryExpr, frame: Frame) -> None:87 if (Merge branch '3.1.x'David Lordbefore adoptionde61312
line 88why, one step back88 self.environment.sandboxed and op in self.environment.intercepted_unops # type: ignoreMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 89–100why, one step back89 ):90 self.write(f"environment.call_unop(context, {op!r}, ")91 self.visit(node.node, frame)92 else:93 self.write("(" + op)94 self.visit(node.node, frame)9596 self.write(")")9798 return visitor99100update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 101why, one step back101def generate(Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 102–103why, one step back102 node: nodes.Template,103 environment: "Environment",drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 104–106why, one step back104 name: str | None,105 filename: str | None,106 stream: t.TextIO | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 107–108why, one step back107 defer_init: bool = False,108 optimized: bool = True,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 109why, one step back109) -> str | None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 110–112why, one step back110 """Generate the python source for a node tree."""111 if not isinstance(node, nodes.Template):112 raise TypeError("Can't compile non template nodes")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 113why, one step back113update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 114–117why, one step back114 generator = environment.code_generator_class(115 environment, name, filename, stream, defer_init, optimized116 )117 generator.visit(node)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 118why, one step back118update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 119why, one step back119 if stream is None:Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 120why, one step back120 return generator.stream.getvalue() # type: ignoreupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 121why, one step back121Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 122why, one step back122 return Noneupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 123why, one step back123Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 124–125why, one step back124125def has_safe_repr(value: t.Any) -> bool:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 126–135why, one step back126 """Does the node have a safe representation?"""127 if value is None or value is NotImplemented or value is Ellipsis:128 return True129130 if type(value) in {bool, int, float, complex, range, str, Markup}:131 return True132133 if type(value) in {tuple, list, set, frozenset}:134 return all(has_safe_repr(v) for v in value)135Merge branch '3.1.x'David Lordbefore adoptionde61312
line 136why, one step back136 if type(value) is dict: # noqa E721update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 137–141why, one step back137 return all(has_safe_repr(k) and has_safe_repr(v) for k, v in value.items())138139 return False140141Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 142why, one step back142def find_undeclared(nodes: t.Iterable[nodes.Node], names: t.Iterable[str]) -> set[str]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 143–155why, one step back143 """Check if the names passed are accessed undeclared. The return value144 is a set of all the undeclared names from the sequence of names found.145 """146 visitor = UndeclaredNameVisitor(names)147 try:148 for node in nodes:149 visitor.visit(node)150 except VisitorExit:151 pass152 return visitor.undeclared153154155class MacroRef:drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 156why, one step back156 def __init__(self, node: nodes.Macro | nodes.CallBlock) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 157–165why, one step back157 self.node = node158 self.accesses_caller = False159 self.accesses_kwargs = False160 self.accesses_varargs = False161162163class Frame:164 """Holds compile time information for us."""165Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 166–169why, one step back166 def __init__(167 self,168 eval_ctx: EvalContext,169 parent: t.Optional["Frame"] = None,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 170why, one step back170 level: int | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 171why, one step back171 ) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 172–173why, one step back172 self.eval_ctx = eval_ctx173Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 174–187why, one step back174 # the parent of this frame175 self.parent = parent176177 if parent is None:178 self.symbols = Symbols(level=level)179180 # in some dynamic inheritance situations the compiler needs to add181 # write tests around output statements.182 self.require_output_check = False183184 # inside some tags we are using a buffer rather than yield statements.185 # this for example affects {% filter %} or {% macro %}. If a frame186 # is buffered this variable points to the name of the list used as187 # buffer.drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 188why, one step back188 self.buffer: str | None = NoneMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 189–190why, one step back189190 # the name of the block we're in, otherwise None.drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 191why, one step back191 self.block: str | None = NoneMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 192–198why, one step back192193 else:194 self.symbols = Symbols(parent.symbols, level=level)195 self.require_output_check = parent.require_output_check196 self.buffer = parent.buffer197 self.block = parent.block198update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 199–206why, one step back199 # a toplevel frame is the root + soft frames such as if conditions.200 self.toplevel = False201202 # the root frame is basically just the outermost frame, so no if203 # conditions. This information is used to optimize inheritance204 # situations.205 self.rootlevel = False206Merge pull request #1242 from MLH-Fellowship/context-bugAmy Leibefore adoptionf71f5eb
lines 207–211why, one step back207 # variables set inside of loops and blocks should not affect outer frames,208 # but they still needs to be kept track of as part of the active context.209 self.loop_frame = False210 self.block_frame = False211Merge pull request #1248 from MLH-Fellowship/test-for-filterDavid Lordbefore adoptionaf5d80e
lines 212–216why, one step back212 # track whether the frame is being used in an if-statement or conditional213 # expression as it determines which errors should be raised during runtime214 # or compile time.215 self.soft_frame = False216Merge branch 'stable'David Lordbefore adoption6aeab5d
line 217why, one step back217 def copy(self) -> "te.Self":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 218why, one step back218 """Create a copy of the current one."""Merge branch '3.0.x'David Lordbefore adoption896a621
line 219why, one step back219 rv = object.__new__(self.__class__)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 220–223why, one step back220 rv.__dict__.update(self.__dict__)221 rv.symbols = self.symbols.copy()222 return rv223Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 224why, one step back224 def inner(self, isolated: bool = False) -> "Frame":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 225–229why, one step back225 """Return an inner frame."""226 if isolated:227 return Frame(self.eval_ctx, level=self.symbols.level + 1)228 return Frame(self.eval_ctx, self)229Merge branch 'stable'David Lordbefore adoption6aeab5d
line 230why, one step back230 def soft(self) -> "te.Self":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 231–234why, one step back231 """Return a soft frame. A soft frame may not be modified as232 standalone thing as it shares the resources with the frame it233 was created of, but it's not a rootlevel frame any longer.234Merge pull request #1248 from MLH-Fellowship/test-for-filterDavid Lordbefore adoptionaf5d80e
lines 235–236why, one step back235 This is only used to implement if-statements and conditional236 expressions.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 237–239why, one step back237 """238 rv = self.copy()239 rv.rootlevel = FalseMerge pull request #1248 from MLH-Fellowship/test-for-filterDavid Lordbefore adoptionaf5d80e
line 240why, one step back240 rv.soft_frame = Trueupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 241–252why, one step back241 return rv242243 __copy__ = copy244245246class VisitorExit(RuntimeError):247 """Exception used by the `UndeclaredNameVisitor` to signal a stop."""248249250class DependencyFinderVisitor(NodeVisitor):251 """A visitor that collects filter and test calls."""252Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 253why, one step back253 def __init__(self) -> None:Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
lines 254–255why, one step back254 self.filters: set[str] = set()255 self.tests: set[str] = set()update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 256why, one step back256Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 257why, one step back257 def visit_Filter(self, node: nodes.Filter) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 258–260why, one step back258 self.generic_visit(node)259 self.filters.add(node.name)260Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 261why, one step back261 def visit_Test(self, node: nodes.Test) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 262–264why, one step back262 self.generic_visit(node)263 self.tests.add(node.name)264Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 265why, one step back265 def visit_Block(self, node: nodes.Block) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 266–274why, one step back266 """Stop visiting at blocks."""267268269class UndeclaredNameVisitor(NodeVisitor):270 """A visitor that checks if a name is accessed without being271 declared. This is different from the frame visitor as it will272 not stop at closure frames.273 """274Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 275why, one step back275 def __init__(self, names: t.Iterable[str]) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 276why, one step back276 self.names = set(names)Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 277why, one step back277 self.undeclared: set[str] = set()update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 278why, one step back278Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 279why, one step back279 def visit_Name(self, node: nodes.Name) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 280–286why, one step back280 if node.ctx == "load" and node.name in self.names:281 self.undeclared.add(node.name)282 if self.undeclared == self.names:283 raise VisitorExit()284 else:285 self.names.discard(node.name)286Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 287why, one step back287 def visit_Block(self, node: nodes.Block) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 288–299why, one step back288 """Stop visiting a blocks."""289290291class CompilerExit(Exception):292 """Raised if the compiler encountered a situation where it just293 doesn't make sense to further process the code. Any block that294 raises such an exception is not further processed.295 """296297298class CodeGenerator(NodeVisitor):299 def __init__(Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 300–301why, one step back300 self,301 environment: "Environment",drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 302–304why, one step back302 name: str | None,303 filename: str | None,304 stream: t.TextIO | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 305–307why, one step back305 defer_init: bool = False,306 optimized: bool = True,307 ) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 308–315why, one step back308 if stream is None:309 stream = StringIO()310 self.environment = environment311 self.name = name312 self.filename = filename313 self.stream = stream314 self.created_block_context = False315 self.defer_init = defer_initdrop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 316why, one step back316 self.optimizer: Optimizer | None = NoneMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 317why, one step back317update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 318–321why, one step back318 if optimized:319 self.optimizer = Optimizer(environment)320321 # aliases for importsUpdated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 322why, one step back322 self.import_aliases: dict[str, str] = {}update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 323–325why, one step back323324 # a registry for all blocks. Because blocks are moved out325 # into the global python scope they are registered hereUpdated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 326why, one step back326 self.blocks: dict[str, nodes.Block] = {}update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 327–339why, one step back327328 # the number of extends statements so far329 self.extends_so_far = 0330331 # some templates have a rootlevel extends. In this case we332 # can safely assume that we're a child template and do some333 # more optimizations.334 self.has_known_extends = False335336 # the current line number337 self.code_lineno = 1338339 # registry of all filters and tests (global, not block local)Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
lines 340–341why, one step back340 self.tests: dict[str, str] = {}341 self.filters: dict[str, str] = {}update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 342–343why, one step back342343 # the debug informationUpdated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 344why, one step back344 self.debug_info: list[tuple[int, int]] = []drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 345why, one step back345 self._write_debug_info: int | None = Noneupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 346–363why, one step back346347 # the number of new lines before the next write()348 self._new_lines = 0349350 # the line number of the last written statement351 self._last_line = 0352353 # true if nothing was written so far.354 self._first_write = True355356 # used by the `temporary_identifier` method to get new357 # unique, temporary identifier358 self._last_identifier = 0359360 # the current indentation361 self._indentation = 0362363 # Tracks toplevel assignmentsUpdated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 364why, one step back364 self._assign_stack: list[set[str]] = []update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 365–366why, one step back365366 # Tracks parameter definition blocksUpdated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 367why, one step back367 self._param_def_block: list[set[str]] = []update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 368–371why, one step back368369 # Tracks the current context.370 self._context_reference_stack = ["context"]371Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 372–375why, one step back372 @property373 def optimized(self) -> bool:374 return self.optimizer is not None375update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 376–377why, one step back376 # -- Various compilation helpers377Merge pull request #1434 from pallets/update-typingDavid Lordbefore adoptiona2e83d0
line 378why, one step back378 def fail(self, msg: str, lineno: int) -> "te.NoReturn":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 379–381why, one step back379 """Fail with a :exc:`TemplateAssertionError`."""380 raise TemplateAssertionError(msg, lineno, self.name, self.filename)381Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 382why, one step back382 def temporary_identifier(self) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 383–386why, one step back383 """Get a new unique identifier."""384 self._last_identifier += 1385 return f"t_{self._last_identifier}"386Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 387why, one step back387 def buffer(self, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 388–391why, one step back388 """Enable buffering for the frame from that point onwards."""389 frame.buffer = self.temporary_identifier()390 self.writeline(f"{frame.buffer} = []")391Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 392–394why, one step back392 def return_buffer_contents(393 self, frame: Frame, force_unescaped: bool = False394 ) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 395–411why, one step back395 """Return the buffer contents of the frame."""396 if not force_unescaped:397 if frame.eval_ctx.volatile:398 self.writeline("if context.eval_ctx.autoescape:")399 self.indent()400 self.writeline(f"return Markup(concat({frame.buffer}))")401 self.outdent()402 self.writeline("else:")403 self.indent()404 self.writeline(f"return concat({frame.buffer})")405 self.outdent()406 return407 elif frame.eval_ctx.autoescape:408 self.writeline(f"return Markup(concat({frame.buffer}))")409 return410 self.writeline(f"return concat({frame.buffer})")411Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 412why, one step back412 def indent(self) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 413–415why, one step back413 """Indent by one."""414 self._indentation += 1415Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 416why, one step back416 def outdent(self, step: int = 1) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 417–419why, one step back417 """Outdent by step."""418 self._indentation -= step419drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 420why, one step back420 def start_write(self, frame: Frame, node: nodes.Node | None = None) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 421–426why, one step back421 """Yield or write into the frame buffer."""422 if frame.buffer is None:423 self.writeline("yield ", node)424 else:425 self.writeline(f"{frame.buffer}.append(", node)426Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 427why, one step back427 def end_write(self, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 428–431why, one step back428 """End the writing process started by `start_write`."""429 if frame.buffer is not None:430 self.write(")")431Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 432why, one step back432 def simple_write(drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 433why, one step back433 self, s: str, frame: Frame, node: nodes.Node | None = NoneMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 434why, one step back434 ) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 435–439why, one step back435 """Simple shortcut for start_write + write + end_write."""436 self.start_write(frame, node)437 self.write(s)438 self.end_write(frame)439Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 440why, one step back440 def blockvisit(self, nodes: t.Iterable[nodes.Node], frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 441–450why, one step back441 """Visit a list of nodes as block in a frame. If the current frame442 is no buffer a dummy ``if 0: yield None`` is written automatically.443 """444 try:445 self.writeline("pass")446 for node in nodes:447 self.visit(node, frame)448 except CompilerExit:449 pass450Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 451why, one step back451 def write(self, x: str) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 452–464why, one step back452 """Write a string into the output stream."""453 if self._new_lines:454 if not self._first_write:455 self.stream.write("\n" * self._new_lines)456 self.code_lineno += self._new_lines457 if self._write_debug_info is not None:458 self.debug_info.append((self._write_debug_info, self.code_lineno))459 self._write_debug_info = None460 self._first_write = False461 self.stream.write(" " * self._indentation)462 self._new_lines = 0463 self.stream.write(x)464drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 465why, one step back465 def writeline(self, x: str, node: nodes.Node | None = None, extra: int = 0) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 466–469why, one step back466 """Combination of newline and write."""467 self.newline(node, extra)468 self.write(x)469drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 470why, one step back470 def newline(self, node: nodes.Node | None = None, extra: int = 0) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 471–476why, one step back471 """Add one or more newlines before the next write."""472 self._new_lines = max(self._new_lines, 1 + extra)473 if node is not None and node.lineno != self._last_line:474 self._write_debug_info = node.lineno475 self._last_line = node.lineno476Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 477–478why, one step back477 def signature(478 self,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 479why, one step back479 node: nodes.Call | nodes.Filter | nodes.Test,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 480why, one step back480 frame: Frame,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 481why, one step back481 extra_kwargs: t.Mapping[str, t.Any] | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 482why, one step back482 ) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 483–490why, one step back483 """Writes a function call to the stream for the current node.484 A leading comma is added automatically. The extra keyword485 arguments may not include python keywords otherwise a syntax486 error could occur. The extra keyword arguments should be given487 as python dict.488 """489 # if any of the given keyword arguments is a python keyword490 # we have to make sure that no invalid call is created.Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 491–494why, one step back491 kwarg_workaround = any(492 is_python_keyword(t.cast(str, k))493 for k in chain((x.key for x in node.kwargs), extra_kwargs or ())494 )update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 495–533why, one step back495496 for arg in node.args:497 self.write(", ")498 self.visit(arg, frame)499500 if not kwarg_workaround:501 for kwarg in node.kwargs:502 self.write(", ")503 self.visit(kwarg, frame)504 if extra_kwargs is not None:505 for key, value in extra_kwargs.items():506 self.write(f", {key}={value}")507 if node.dyn_args:508 self.write(", *")509 self.visit(node.dyn_args, frame)510511 if kwarg_workaround:512 if node.dyn_kwargs is not None:513 self.write(", **dict({")514 else:515 self.write(", **{")516 for kwarg in node.kwargs:517 self.write(f"{kwarg.key!r}: ")518 self.visit(kwarg.value, frame)519 self.write(", ")520 if extra_kwargs is not None:521 for key, value in extra_kwargs.items():522 self.write(f"{key!r}: {value}, ")523 if node.dyn_kwargs is not None:524 self.write("}, **")525 self.visit(node.dyn_kwargs, frame)526 self.write(")")527 else:528 self.write("}")529530 elif node.dyn_kwargs is not None:531 self.write(", **")532 self.visit(node.dyn_kwargs, frame)533Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 534why, one step back534 def pull_dependencies(self, nodes: t.Iterable[nodes.Node]) -> None:Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 535–544why, one step back535 """Find all filter and test names used in the template and536 assign them to variables in the compiled namespace. Checking537 that the names are registered with the environment is done when538 compiling the Filter and Test nodes. If the node is in an If or539 CondExpr node, the check is done at runtime instead.540541 .. versionchanged:: 3.0542 Filters and tests in If and CondExpr nodes are checked at543 runtime instead of compile time.544 """update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 545why, one step back545 visitor = DependencyFinderVisitor()Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 546why, one step back546update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 547–548why, one step back547 for node in nodes:548 visitor.visit(node)Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 549why, one step back549Merge branch '3.1.x'David Lordbefore adoptionde61312
lines 550–556why, one step back550 for id_map, names, dependency in (551 (self.filters, visitor.filters, "filters"),552 (553 self.tests,554 visitor.tests,555 "tests",556 ),Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 557why, one step back557 ):Merge remote-tracking branch 'origin/3.0.x'David Lordbefore adoption35c69e9
line 558why, one step back558 for name in sorted(names):Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 559–560why, one step back559 if name not in id_map:560 id_map[name] = self.temporary_identifier()Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 561why, one step back561Merge pull request #1248 from MLH-Fellowship/test-for-filterDavid Lordbefore adoptionaf5d80e
lines 562–565why, one step back562 # add check during runtime that dependencies used inside of executed563 # blocks are defined, as this step may be skipped during compile time564 self.writeline("try:")565 self.indent()Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 566why, one step back566 self.writeline(f"{id_map[name]} = environment.{dependency}[{name!r}]")Merge pull request #1248 from MLH-Fellowship/test-for-filterDavid Lordbefore adoptionaf5d80e
lines 567–570why, one step back567 self.outdent()568 self.writeline("except KeyError:")569 self.indent()570 self.writeline("@internalcode")Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 571why, one step back571 self.writeline(f"def {id_map[name]}(*unused):")Merge pull request #1248 from MLH-Fellowship/test-for-filterDavid Lordbefore adoptionaf5d80e
lines 572–573why, one step back572 self.indent()573 self.writeline(Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 574–575why, one step back574 f'raise TemplateRuntimeError("No {dependency[:-1]}'575 f' named {name!r} found.")'Merge pull request #1248 from MLH-Fellowship/test-for-filterDavid Lordbefore adoptionaf5d80e
lines 576–578why, one step back576 )577 self.outdent()578 self.outdent()update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 579why, one step back579Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 580why, one step back580 def enter_frame(self, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 581–595why, one step back581 undefs = []582 for target, (action, param) in frame.symbols.loads.items():583 if action == VAR_LOAD_PARAMETER:584 pass585 elif action == VAR_LOAD_RESOLVE:586 self.writeline(f"{target} = {self.get_resolve_func()}({param!r})")587 elif action == VAR_LOAD_ALIAS:588 self.writeline(f"{target} = {param}")589 elif action == VAR_LOAD_UNDEFINED:590 undefs.append(target)591 else:592 raise NotImplementedError("unknown load instruction")593 if undefs:594 self.writeline(f"{' = '.join(undefs)} = missing")595Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 596why, one step back596 def leave_frame(self, frame: Frame, with_python_scope: bool = False) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 597–603why, one step back597 if not with_python_scope:598 undefs = []599 for target in frame.symbols.loads:600 undefs.append(target)601 if undefs:602 self.writeline(f"{' = '.join(undefs)} = missing")603Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 604why, one step back604 def choose_async(self, async_value: str = "async ", sync_value: str = "") -> str:Merge pull request #1152 from angelafrentz/refactor_ternary_statement_compilerDavid Lordbefore adoption94b381d
lines 605–606why, one step back605 return async_value if self.environment.is_async else sync_value606Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 607why, one step back607 def func(self, name: str) -> str:Merge pull request #1152 from angelafrentz/refactor_ternary_statement_compilerDavid Lordbefore adoption94b381d
line 608why, one step back608 return f"{self.choose_async()}def {name}"update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 609why, one step back609Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 610why, one step back610 def macro_body(drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 611why, one step back611 self, node: nodes.Macro | nodes.CallBlock, frame: FrameUpdated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 612why, one step back612 ) -> tuple[Frame, MacroRef]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 613–620why, one step back613 """Dump the function def of a macro or call block."""614 frame = frame.inner()615 frame.symbols.analyze_node(node)616 macro_ref = MacroRef(node)617618 explicit_caller = None619 skip_special_params = set()620 args = []Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 621why, one step back621update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 622–692why, one step back622 for idx, arg in enumerate(node.args):623 if arg.name == "caller":624 explicit_caller = idx625 if arg.name in ("kwargs", "varargs"):626 skip_special_params.add(arg.name)627 args.append(frame.symbols.ref(arg.name))628629 undeclared = find_undeclared(node.body, ("caller", "kwargs", "varargs"))630631 if "caller" in undeclared:632 # In older Jinja versions there was a bug that allowed caller633 # to retain the special behavior even if it was mentioned in634 # the argument list. However thankfully this was only really635 # working if it was the last argument. So we are explicitly636 # checking this now and error out if it is anywhere else in637 # the argument list.638 if explicit_caller is not None:639 try:640 node.defaults[explicit_caller - len(node.args)]641 except IndexError:642 self.fail(643 "When defining macros or call blocks the "644 'special "caller" argument must be omitted '645 "or be given a default.",646 node.lineno,647 )648 else:649 args.append(frame.symbols.declare_parameter("caller"))650 macro_ref.accesses_caller = True651 if "kwargs" in undeclared and "kwargs" not in skip_special_params:652 args.append(frame.symbols.declare_parameter("kwargs"))653 macro_ref.accesses_kwargs = True654 if "varargs" in undeclared and "varargs" not in skip_special_params:655 args.append(frame.symbols.declare_parameter("varargs"))656 macro_ref.accesses_varargs = True657658 # macros are delayed, they never require output checks659 frame.require_output_check = False660 frame.symbols.analyze_node(node)661 self.writeline(f"{self.func('macro')}({', '.join(args)}):", node)662 self.indent()663664 self.buffer(frame)665 self.enter_frame(frame)666667 self.push_parameter_definitions(frame)668 for idx, arg in enumerate(node.args):669 ref = frame.symbols.ref(arg.name)670 self.writeline(f"if {ref} is missing:")671 self.indent()672 try:673 default = node.defaults[idx - len(node.args)]674 except IndexError:675 self.writeline(676 f'{ref} = undefined("parameter {arg.name!r} was not provided",'677 f" name={arg.name!r})"678 )679 else:680 self.writeline(f"{ref} = ")681 self.visit(default, frame)682 self.mark_parameter_stored(ref)683 self.outdent()684 self.pop_parameter_definitions()685686 self.blockvisit(node.body, frame)687 self.return_buffer_contents(frame, force_unescaped=True)688 self.leave_frame(frame, with_python_scope=True)689 self.outdent()690691 return frame, macro_ref692Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 693why, one step back693 def macro_def(self, macro_ref: MacroRef, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 694–704why, one step back694 """Dump the macro definition for the def created by macro_body."""695 arg_tuple = ", ".join(repr(x.name) for x in macro_ref.node.args)696 name = getattr(macro_ref.node, "name", None)697 if len(macro_ref.node.args) == 1:698 arg_tuple += ","699 self.write(700 f"Macro(environment, macro, {name!r}, ({arg_tuple}),"701 f" {macro_ref.accesses_kwargs!r}, {macro_ref.accesses_varargs!r},"702 f" {macro_ref.accesses_caller!r}, context.eval_ctx.autoescape)"703 )704Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 705why, one step back705 def position(self, node: nodes.Node) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 706–711why, one step back706 """Return a human readable position for the node."""707 rv = f"line {node.lineno}"708 if self.name is not None:709 rv = f"{rv} in {self.name!r}"710 return rv711Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 712why, one step back712 def dump_local_context(self, frame: Frame) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 713–718why, one step back713 items_kv = ", ".join(714 f"{name!r}: {target}"715 for name, target in frame.symbols.dump_stores().items()716 )717 return f"{{{items_kv}}}"718Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 719why, one step back719 def write_commons(self) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 720–725why, one step back720 """Writes a common preamble that is used by root and block functions.721 Primarily this sets up common local helpers and enforces a generator722 through a dead branch.723 """724 self.writeline("resolve = context.resolve_or_missing")725 self.writeline("undefined = environment.undefined")Merge pull request #1511 from mkrizek/issue-1510David Lordbefore adoption7d72eb7
line 726why, one step back726 self.writeline("concat = environment.concat")update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 727–731why, one step back727 # always use the standard Undefined class for the implicit else of728 # conditional expressions729 self.writeline("cond_expr_undefined = Undefined")730 self.writeline("if 0: yield None")731Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 732why, one step back732 def push_parameter_definitions(self, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 733–740why, one step back733 """Pushes all parameter targets from the given frame into a local734 stack that permits tracking of yet to be assigned parameters. In735 particular this enables the optimization from `visit_Name` to skip736 undefined expressions for parameters in macros as macros can reference737 otherwise unbound parameters.738 """739 self._param_def_block.append(frame.symbols.dump_param_targets())740Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 741why, one step back741 def pop_parameter_definitions(self) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 742–744why, one step back742 """Pops the current parameter definitions set."""743 self._param_def_block.pop()744Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 745why, one step back745 def mark_parameter_stored(self, target: str) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 746–751why, one step back746 """Marks a parameter in the current parameter definitions as stored.747 This will skip the enforced undefined checks.748 """749 if self._param_def_block:750 self._param_def_block[-1].discard(target)751Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 752why, one step back752 def push_context_reference(self, target: str) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 753–754why, one step back753 self._context_reference_stack.append(target)754Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 755why, one step back755 def pop_context_reference(self) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 756–757why, one step back756 self._context_reference_stack.pop()757Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 758why, one step back758 def get_context_ref(self) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 759–760why, one step back759 return self._context_reference_stack[-1]760Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 761why, one step back761 def get_resolve_func(self) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 762–766why, one step back762 target = self._context_reference_stack[-1]763 if target == "context":764 return "resolve"765 return f"{target}.resolve"766Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 767why, one step back767 def derive_context(self, frame: Frame) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 768–769why, one step back768 return f"{self.get_context_ref()}.derived({self.dump_local_context(frame)})"769Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 770why, one step back770 def parameter_is_undeclared(self, target: str) -> bool:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 771–775why, one step back771 """Checks if a given target is an undeclared parameter."""772 if not self._param_def_block:773 return False774 return target in self._param_def_block[-1]775Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 776why, one step back776 def push_assign_tracking(self) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 777–779why, one step back777 """Pushes a new layer for assignment tracking."""778 self._assign_stack.append(set())779Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 780why, one step back780 def pop_assign_tracking(self, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 781–784why, one step back781 """Pops the topmost level for assignment tracking and updates the782 context variables if necessary.783 """784 vars = self._assign_stack.pop()Merge pull request #1242 from MLH-Fellowship/context-bugAmy Leibefore adoptionf71f5eb
lines 785–790why, one step back785 if (786 not frame.block_frame787 and not frame.loop_frame788 and not frame.toplevel789 or not vars790 ):update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 791–795why, one step back791 return792 public_names = [x for x in vars if x[:1] != "_"]793 if len(vars) == 1:794 name = next(iter(vars))795 ref = frame.symbols.ref(name)Merge pull request #1242 from MLH-Fellowship/context-bugAmy Leibefore adoptionf71f5eb
lines 796–801why, one step back796 if frame.loop_frame:797 self.writeline(f"_loop_vars[{name!r}] = {ref}")798 return799 if frame.block_frame:800 self.writeline(f"_block_vars[{name!r}] = {ref}")801 returnupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 802–803why, one step back802 self.writeline(f"context.vars[{name!r}] = {ref}")803 else:Merge pull request #1242 from MLH-Fellowship/context-bugAmy Leibefore adoptionf71f5eb
lines 804–809why, one step back804 if frame.loop_frame:805 self.writeline("_loop_vars.update({")806 elif frame.block_frame:807 self.writeline("_block_vars.update({")808 else:809 self.writeline("context.vars.update({")Merge branch 'stable'David Lordbefore adoption6aeab5d
line 810why, one step back810 for idx, name in enumerate(sorted(vars)):update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 811–815why, one step back811 if idx:812 self.write(", ")813 ref = frame.symbols.ref(name)814 self.write(f"{name!r}: {ref}")815 self.write("})")Merge pull request #1242 from MLH-Fellowship/context-bugAmy Leibefore adoptionf71f5eb
line 816why, one step back816 if not frame.block_frame and not frame.loop_frame and public_names:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 817–819why, one step back817 if len(public_names) == 1:818 self.writeline(f"context.exported_vars.add({public_names[0]!r})")819 else:Merge branch 'stable'David Lordbefore adoption6aeab5d
line 820why, one step back820 names_str = ", ".join(map(repr, sorted(public_names)))update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 821–824why, one step back821 self.writeline(f"context.exported_vars.update(({names_str}))")822823 # -- Statement Visitors824drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 825why, one step back825 def visit_Template(self, node: nodes.Template, frame: Frame | None = None) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 826–828why, one step back826 assert frame is None, "no root frame allowed"827 eval_ctx = EvalContext(self.environment, self.name)828Merge branch '3.1.x'David Lordbefore adoptionde61312
lines 829–830why, one step back829 from .runtime import async_exported830 from .runtime import exportedupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 831–832why, one step back831832 if self.environment.is_async:Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 833–837why, one step back833 exported_names = sorted(exported + async_exported)834 else:835 exported_names = sorted(exported)836837 self.writeline("from jinja2.runtime import " + ", ".join(exported_names))update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 838–898why, one step back838839 # if we want a deferred initialization we cannot move the840 # environment into a local name841 envenv = "" if self.defer_init else ", environment=environment"842843 # do we have an extends tag at all? If not, we can save some844 # overhead by just not processing any inheritance code.845 have_extends = node.find(nodes.Extends) is not None846847 # find all blocks848 for block in node.find_all(nodes.Block):849 if block.name in self.blocks:850 self.fail(f"block {block.name!r} defined twice", block.lineno)851 self.blocks[block.name] = block852853 # find all imports and import them854 for import_ in node.find_all(nodes.ImportedName):855 if import_.importname not in self.import_aliases:856 imp = import_.importname857 self.import_aliases[imp] = alias = self.temporary_identifier()858 if "." in imp:859 module, obj = imp.rsplit(".", 1)860 self.writeline(f"from {module} import {obj} as {alias}")861 else:862 self.writeline(f"import {imp} as {alias}")863864 # add the load name865 self.writeline(f"name = {self.name!r}")866867 # generate the root render function.868 self.writeline(869 f"{self.func('root')}(context, missing=missing{envenv}):", extra=1870 )871 self.indent()872 self.write_commons()873874 # process the root875 frame = Frame(eval_ctx)876 if "self" in find_undeclared(node.body, ("self",)):877 ref = frame.symbols.declare_parameter("self")878 self.writeline(f"{ref} = TemplateReference(context)")879 frame.symbols.analyze_node(node)880 frame.toplevel = frame.rootlevel = True881 frame.require_output_check = have_extends and not self.has_known_extends882 if have_extends:883 self.writeline("parent_template = None")884 self.enter_frame(frame)885 self.pull_dependencies(node.body)886 self.blockvisit(node.body, frame)887 self.leave_frame(frame, with_python_scope=True)888 self.outdent()889890 # make sure that the parent root is called.891 if have_extends:892 if not self.has_known_extends:893 self.indent()894 self.writeline("if parent_template is not None:")895 self.indent()896 if not self.environment.is_async:897 self.writeline("yield from parent_template.root_render_func(context)")898 else:Merge branch '3.1.x'David Lordbefore adoptionb002d9c
lines 899–900why, one step back899 self.writeline("agen = parent_template.root_render_func(context)")900 self.writeline("try:")update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 901why, one step back901 self.indent()Merge branch '3.1.x'David Lordbefore adoptionb002d9c
lines 902–903why, one step back902 self.writeline("async for event in agen:")903 self.indent()update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 904–905why, one step back904 self.writeline("yield event")905 self.outdent()Merge branch '3.1.x'David Lordbefore adoptionb002d9c
lines 906–907why, one step back906 self.outdent()907 self.writeline("finally: await agen.aclose()")update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 908–922why, one step back908 self.outdent(1 + (not self.has_known_extends))909910 # at this point we now have the blocks collected and can visit them too.911 for name, block in self.blocks.items():912 self.writeline(913 f"{self.func('block_' + name)}(context, missing=missing{envenv}):",914 block,915 1,916 )917 self.indent()918 self.write_commons()919 # It's important that we do not make this frame a child of the920 # toplevel template. This would cause a variety of921 # interesting issues with identifier tracking.922 block_frame = Frame(eval_ctx)Merge pull request #1242 from MLH-Fellowship/context-bugAmy Leibefore adoptionf71f5eb
line 923why, one step back923 block_frame.block_frame = Trueupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 924–932why, one step back924 undeclared = find_undeclared(block.body, ("self", "super"))925 if "self" in undeclared:926 ref = block_frame.symbols.declare_parameter("self")927 self.writeline(f"{ref} = TemplateReference(context)")928 if "super" in undeclared:929 ref = block_frame.symbols.declare_parameter("super")930 self.writeline(f"{ref} = context.super({name!r}, block_{name})")931 block_frame.symbols.analyze_node(block)932 block_frame.block = nameMerge pull request #1242 from MLH-Fellowship/context-bugAmy Leibefore adoptionf71f5eb
line 933why, one step back933 self.writeline("_block_vars = {}")update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 934–944why, one step back934 self.enter_frame(block_frame)935 self.pull_dependencies(block.body)936 self.blockvisit(block.body, block_frame)937 self.leave_frame(block_frame, with_python_scope=True)938 self.outdent()939940 blocks_kv_str = ", ".join(f"{x!r}: block_{x}" for x in self.blocks)941 self.writeline(f"blocks = {{{blocks_kv_str}}}", extra=1)942 debug_kv_str = "&".join(f"{k}={v}" for k, v in self.debug_info)943 self.writeline(f"debug_info = {debug_kv_str!r}")944Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 945why, one step back945 def visit_Block(self, node: nodes.Block, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 946–976why, one step back946 """Call a block and register it for the template."""947 level = 0948 if frame.toplevel:949 # if we know that we are a child template, there is no need to950 # check if we are one951 if self.has_known_extends:952 return953 if self.extends_so_far > 0:954 self.writeline("if parent_template is None:")955 self.indent()956 level += 1957958 if node.scoped:959 context = self.derive_context(frame)960 else:961 context = self.get_context_ref()962963 if node.required:964 self.writeline(f"if len(context.blocks[{node.name!r}]) <= 1:", node)965 self.indent()966 self.writeline(967 f'raise TemplateRuntimeError("Required block {node.name!r} not found")',968 node,969 )970 self.outdent()971972 if not self.environment.is_async and frame.buffer is None:973 self.writeline(974 f"yield from context.blocks[{node.name!r}][0]({context})", node975 )976 else:Merge branch '3.1.x'David Lordbefore adoptionb002d9c
lines 977–979why, one step back977 self.writeline(f"gen = context.blocks[{node.name!r}][0]({context})")978 self.writeline("try:")979 self.indent()update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 980why, one step back980 self.writeline(Merge branch '3.1.x'David Lordbefore adoptionb002d9c
line 981why, one step back981 f"{self.choose_async()}for event in gen:",Merge pull request #1152 from angelafrentz/refactor_ternary_statement_compilerDavid Lordbefore adoption94b381d
line 982why, one step back982 node,update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 983–986why, one step back983 )984 self.indent()985 self.simple_write("event", frame)986 self.outdent()Merge branch '3.1.x'David Lordbefore adoptionb002d9c
lines 987–990why, one step back987 self.outdent()988 self.writeline(989 f"finally: {self.choose_async('await gen.aclose()', 'gen.close()')}"990 )update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 991–993why, one step back991992 self.outdent(level)993Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 994why, one step back994 def visit_Extends(self, node: nodes.Extends, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 995–1035why, one step back995 """Calls the extender."""996 if not frame.toplevel:997 self.fail("cannot use extend from a non top-level scope", node.lineno)998999 # if the number of extends statements in general is zero so1000 # far, we don't have to add a check if something extended1001 # the template before this one.1002 if self.extends_so_far > 0:1003 # if we have a known extends we just add a template runtime1004 # error into the generated code. We could catch that at compile1005 # time too, but i welcome it not to confuse users by throwing the1006 # same error at different times just "because we can".1007 if not self.has_known_extends:1008 self.writeline("if parent_template is not None:")1009 self.indent()1010 self.writeline('raise TemplateRuntimeError("extended multiple times")')10111012 # if we have a known extends already we don't need that code here1013 # as we know that the template execution will end here.1014 if self.has_known_extends:1015 raise CompilerExit()1016 else:1017 self.outdent()10181019 self.writeline("parent_template = environment.get_template(", node)1020 self.visit(node.template, frame)1021 self.write(f", {self.name!r})")1022 self.writeline("for name, parent_block in parent_template.blocks.items():")1023 self.indent()1024 self.writeline("context.blocks.setdefault(name, []).append(parent_block)")1025 self.outdent()10261027 # if this extends statement was in the root level we can take1028 # advantage of that information and simplify the generated code1029 # in the top level from this point onwards1030 if frame.rootlevel:1031 self.has_known_extends = True10321033 # and now we have one more1034 self.extends_so_far += 11035Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1036why, one step back1036 def visit_Include(self, node: nodes.Include, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1037–1062why, one step back1037 """Handles includes."""1038 if node.ignore_missing:1039 self.writeline("try:")1040 self.indent()10411042 func_name = "get_or_select_template"1043 if isinstance(node.template, nodes.Const):1044 if isinstance(node.template.value, str):1045 func_name = "get_template"1046 elif isinstance(node.template.value, (tuple, list)):1047 func_name = "select_template"1048 elif isinstance(node.template, (nodes.Tuple, nodes.List)):1049 func_name = "select_template"10501051 self.writeline(f"template = environment.{func_name}(", node)1052 self.visit(node.template, frame)1053 self.write(f", {self.name!r})")1054 if node.ignore_missing:1055 self.outdent()1056 self.writeline("except TemplateNotFound:")1057 self.indent()1058 self.writeline("pass")1059 self.outdent()1060 self.writeline("else:")1061 self.indent()1062Merge branch '3.1.x'David Lordbefore adoptionb002d9c
lines 1063–1067why, one step back1063 def loop_body() -> None:1064 self.indent()1065 self.simple_write("event", frame)1066 self.outdent()1067update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1068–1069why, one step back1068 if node.with_context:1069 self.writeline(Merge branch '3.1.x'David Lordbefore adoptionb002d9c
line 1070why, one step back1070 f"gen = template.root_render_func("update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1071why, one step back1071 "template.new_context(context.get_all(), True,"Merge branch '3.1.x'David Lordbefore adoptionb002d9c
line 1072why, one step back1072 f" {self.dump_local_context(frame)}))"update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1073why, one step back1073 )Merge branch '3.1.x'David Lordbefore adoptionb002d9c
lines 1074–1081why, one step back1074 self.writeline("try:")1075 self.indent()1076 self.writeline(f"{self.choose_async()}for event in gen:")1077 loop_body()1078 self.outdent()1079 self.writeline(1080 f"finally: {self.choose_async('await gen.aclose()', 'gen.close()')}"1081 )update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1082–1086why, one step back1082 elif self.environment.is_async:1083 self.writeline(1084 "for event in (await template._get_default_module_async())"1085 "._body_stream:"1086 )Merge branch '3.1.x'David Lordbefore adoptionb002d9c
line 1087why, one step back1087 loop_body()update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1088–1093why, one step back1088 else:1089 self.writeline("yield from template._get_default_module()._body_stream")10901091 if node.ignore_missing:1092 self.outdent()1093Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1094why, one step back1094 def _import_common(drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1095why, one step back1095 self, node: nodes.Import | nodes.FromImport, frame: FrameMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1096why, one step back1096 ) -> None:Merge pull request #1152 from angelafrentz/refactor_ternary_statement_compilerDavid Lordbefore adoption94b381d
line 1097why, one step back1097 self.write(f"{self.choose_async('await ')}environment.get_template(")update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1098–1099why, one step back1098 self.visit(node.template, frame)1099 self.write(f", {self.name!r}).")Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 1100why, one step back1100update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1101why, one step back1101 if node.with_context:Merge pull request #1152 from angelafrentz/refactor_ternary_statement_compilerDavid Lordbefore adoption94b381d
line 1102why, one step back1102 f_name = f"make_module{self.choose_async('_async')}"update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1103why, one step back1103 self.write(Merge pull request #1152 from angelafrentz/refactor_ternary_statement_compilerDavid Lordbefore adoption94b381d
line 1104why, one step back1104 f"{f_name}(context.get_all(), True, {self.dump_local_context(frame)})"update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1105–1106why, one step back1105 )1106 else:Merge branch '3.0.x'David Lordbefore adoptionf20a9c9
line 1107why, one step back1107 self.write(f"_get_default_module{self.choose_async('_async')}(context)")Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 1108why, one step back1108Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1109why, one step back1109 def visit_Import(self, node: nodes.Import, frame: Frame) -> None:Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
lines 1110–1116why, one step back1110 """Visit regular imports."""1111 self.writeline(f"{frame.symbols.ref(node.target)} = ", node)1112 if frame.toplevel:1113 self.write(f"context.vars[{node.target!r}] = ")11141115 self._import_common(node, frame)1116update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1117–1119why, one step back1117 if frame.toplevel and not node.target.startswith("_"):1118 self.writeline(f"context.exported_vars.discard({node.target!r})")1119Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1120why, one step back1120 def visit_FromImport(self, node: nodes.FromImport, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1121–1122why, one step back1121 """Visit named imports."""1122 self.newline(node)Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
lines 1123–1124why, one step back1123 self.write("included_template = ")1124 self._import_common(node, frame)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1125–1137why, one step back1125 var_names = []1126 discarded_names = []1127 for name in node.names:1128 if isinstance(name, tuple):1129 name, alias = name1130 else:1131 alias = name1132 self.writeline(1133 f"{frame.symbols.ref(alias)} ="1134 f" getattr(included_template, {name!r}, missing)"1135 )1136 self.writeline(f"if {frame.symbols.ref(alias)} is missing:")1137 self.indent()Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 1138–1142why, one step back1138 # The position will contain the template name, and will be formatted1139 # into a string that will be compiled into an f-string. Curly braces1140 # in the name must be replaced with escapes so that they will not be1141 # executed as part of the f-string.1142 position = self.position(node).replace("{", "{{").replace("}", "}}")update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1143–1144why, one step back1143 message = (1144 "the template {included_template.__name__!r}"Merge branch 'stable'David Lordbefore adoption6aeab5d
line 1145why, one step back1145 f" (imported on {position})"update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1146–1174why, one step back1146 f" does not export the requested name {name!r}"1147 )1148 self.writeline(1149 f"{frame.symbols.ref(alias)} = undefined(f{message!r}, name={name!r})"1150 )1151 self.outdent()1152 if frame.toplevel:1153 var_names.append(alias)1154 if not alias.startswith("_"):1155 discarded_names.append(alias)11561157 if var_names:1158 if len(var_names) == 1:1159 name = var_names[0]1160 self.writeline(f"context.vars[{name!r}] = {frame.symbols.ref(name)}")1161 else:1162 names_kv = ", ".join(1163 f"{name!r}: {frame.symbols.ref(name)}" for name in var_names1164 )1165 self.writeline(f"context.vars.update({{{names_kv}}})")1166 if discarded_names:1167 if len(discarded_names) == 1:1168 self.writeline(f"context.exported_vars.discard({discarded_names[0]!r})")1169 else:1170 names_str = ", ".join(map(repr, discarded_names))1171 self.writeline(1172 f"context.exported_vars.difference_update(({names_str}))"1173 )1174Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1175why, one step back1175 def visit_For(self, node: nodes.For, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1176why, one step back1176 loop_frame = frame.inner()Merge pull request #1242 from MLH-Fellowship/context-bugAmy Leibefore adoptionf71f5eb
line 1177why, one step back1177 loop_frame.loop_frame = Trueupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1178–1182why, one step back1178 test_frame = frame.inner()1179 else_frame = frame.inner()11801181 # try to figure out if we have an extended loop. An extended loop1182 # is necessary if the loop is in recursive mode if the special loopMerge pull request #1242 from MLH-Fellowship/context-bugAmy Leibefore adoptionf71f5eb
lines 1183–1188why, one step back1183 # variable is accessed in the body if the body is a scoped block.1184 extended_loop = (1185 node.recursive1186 or "loop"1187 in find_undeclared(node.iter_child_nodes(only=("body",)), ("loop",))1188 or any(block.scoped for block in node.find_all(nodes.Block))update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1189–1204why, one step back1189 )11901191 loop_ref = None1192 if extended_loop:1193 loop_ref = loop_frame.symbols.declare_parameter("loop")11941195 loop_frame.symbols.analyze_node(node, for_branch="body")1196 if node.else_:1197 else_frame.symbols.analyze_node(node, for_branch="else")11981199 if node.test:1200 loop_filter_func = self.temporary_identifier()1201 test_frame.symbols.analyze_node(node, for_branch="test")1202 self.writeline(f"{self.func(loop_filter_func)}(fiter):", node.test)1203 self.indent()1204 self.enter_frame(test_frame)Merge pull request #1152 from angelafrentz/refactor_ternary_statement_compilerDavid Lordbefore adoption94b381d
line 1205why, one step back1205 self.writeline(self.choose_async("async for ", "for "))update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1206–1207why, one step back1206 self.visit(node.target, loop_frame)1207 self.write(" in ")Merge pull request #1152 from angelafrentz/refactor_ternary_statement_compilerDavid Lordbefore adoption94b381d
line 1208why, one step back1208 self.write(self.choose_async("auto_aiter(fiter)", "fiter"))update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1209–1248why, one step back1209 self.write(":")1210 self.indent()1211 self.writeline("if ", node.test)1212 self.visit(node.test, test_frame)1213 self.write(":")1214 self.indent()1215 self.writeline("yield ")1216 self.visit(node.target, loop_frame)1217 self.outdent(3)1218 self.leave_frame(test_frame, with_python_scope=True)12191220 # if we don't have an recursive loop we have to find the shadowed1221 # variables at that point. Because loops can be nested but the loop1222 # variable is a special one we have to enforce aliasing for it.1223 if node.recursive:1224 self.writeline(1225 f"{self.func('loop')}(reciter, loop_render_func, depth=0):", node1226 )1227 self.indent()1228 self.buffer(loop_frame)12291230 # Use the same buffer for the else frame1231 else_frame.buffer = loop_frame.buffer12321233 # make sure the loop variable is a special one and raise a template1234 # assertion error if a loop tries to write to loop1235 if extended_loop:1236 self.writeline(f"{loop_ref} = missing")12371238 for name in node.find_all(nodes.Name):1239 if name.ctx == "store" and name.name == "loop":1240 self.fail(1241 "Can't assign to special loop variable in for-loop target",1242 name.lineno,1243 )12441245 if node.else_:1246 iteration_indicator = self.temporary_identifier()1247 self.writeline(f"{iteration_indicator} = 1")1248Merge pull request #1152 from angelafrentz/refactor_ternary_statement_compilerDavid Lordbefore adoption94b381d
line 1249why, one step back1249 self.writeline(self.choose_async("async for ", "for "), node)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1250–1251why, one step back1250 self.visit(node.target, loop_frame)1251 if extended_loop:Merge pull request #1152 from angelafrentz/refactor_ternary_statement_compilerDavid Lordbefore adoption94b381d
line 1252why, one step back1252 self.write(f", {loop_ref} in {self.choose_async('Async')}LoopContext(")update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1253–1276why, one step back1253 else:1254 self.write(" in ")12551256 if node.test:1257 self.write(f"{loop_filter_func}(")1258 if node.recursive:1259 self.write("reciter")1260 else:1261 if self.environment.is_async and not extended_loop:1262 self.write("auto_aiter(")1263 self.visit(node.iter, frame)1264 if self.environment.is_async and not extended_loop:1265 self.write(")")1266 if node.test:1267 self.write(")")12681269 if node.recursive:1270 self.write(", undefined, loop_render_func, depth):")1271 else:1272 self.write(", undefined):" if extended_loop else ":")12731274 self.indent()1275 self.enter_frame(loop_frame)1276Merge pull request #1242 from MLH-Fellowship/context-bugAmy Leibefore adoptionf71f5eb
line 1277why, one step back1277 self.writeline("_loop_vars = {}")update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1278–1299why, one step back1278 self.blockvisit(node.body, loop_frame)1279 if node.else_:1280 self.writeline(f"{iteration_indicator} = 0")1281 self.outdent()1282 self.leave_frame(1283 loop_frame, with_python_scope=node.recursive and not node.else_1284 )12851286 if node.else_:1287 self.writeline(f"if {iteration_indicator}:")1288 self.indent()1289 self.enter_frame(else_frame)1290 self.blockvisit(node.else_, else_frame)1291 self.leave_frame(else_frame)1292 self.outdent()12931294 # if the node was recursive we have to return the buffer contents1295 # and start the iteration code1296 if node.recursive:1297 self.return_buffer_contents(loop_frame)1298 self.outdent()1299 self.start_write(frame, node)Merge pull request #1152 from angelafrentz/refactor_ternary_statement_compilerDavid Lordbefore adoption94b381d
line 1300why, one step back1300 self.write(f"{self.choose_async('await ')}loop(")update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1301–1307why, one step back1301 if self.environment.is_async:1302 self.write("auto_aiter(")1303 self.visit(node.iter, frame)1304 if self.environment.is_async:1305 self.write(")")1306 self.write(", loop)")1307 self.end_write(frame)Merge remote-tracking branch 'origin/3.0.x'David Lordbefore adoption35c69e9
lines 1308–1312why, one step back13081309 # at the end of the iteration, clear any assignments made in the1310 # loop from the top level1311 if self._assign_stack:1312 self._assign_stack[-1].difference_update(loop_frame.symbols.stores)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1313why, one step back1313Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1314why, one step back1314 def visit_If(self, node: nodes.If, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1315–1334why, one step back1315 if_frame = frame.soft()1316 self.writeline("if ", node)1317 self.visit(node.test, if_frame)1318 self.write(":")1319 self.indent()1320 self.blockvisit(node.body, if_frame)1321 self.outdent()1322 for elif_ in node.elif_:1323 self.writeline("elif ", elif_)1324 self.visit(elif_.test, if_frame)1325 self.write(":")1326 self.indent()1327 self.blockvisit(elif_.body, if_frame)1328 self.outdent()1329 if node.else_:1330 self.writeline("else:")1331 self.indent()1332 self.blockvisit(node.else_, if_frame)1333 self.outdent()1334Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1335why, one step back1335 def visit_Macro(self, node: nodes.Macro, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1336–1344why, one step back1336 macro_frame, macro_ref = self.macro_body(node, frame)1337 self.newline()1338 if frame.toplevel:1339 if not node.name.startswith("_"):1340 self.write(f"context.exported_vars.add({node.name!r})")1341 self.writeline(f"context.vars[{node.name!r}] = ")1342 self.write(f"{frame.symbols.ref(node.name)} = ")1343 self.macro_def(macro_ref, macro_frame)1344Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1345why, one step back1345 def visit_CallBlock(self, node: nodes.CallBlock, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1346–1352why, one step back1346 call_frame, macro_ref = self.macro_body(node, frame)1347 self.writeline("caller = ")1348 self.macro_def(macro_ref, call_frame)1349 self.start_write(frame, node)1350 self.visit_Call(node.call, frame, forward_caller=True)1351 self.end_write(frame)1352Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1353why, one step back1353 def visit_FilterBlock(self, node: nodes.FilterBlock, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1354–1363why, one step back1354 filter_frame = frame.inner()1355 filter_frame.symbols.analyze_node(node)1356 self.enter_frame(filter_frame)1357 self.buffer(filter_frame)1358 self.blockvisit(node.body, filter_frame)1359 self.start_write(frame, node)1360 self.visit_Filter(node.filter, filter_frame)1361 self.end_write(frame)1362 self.leave_frame(filter_frame)1363Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1364why, one step back1364 def visit_With(self, node: nodes.With, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1365–1367why, one step back1365 with_frame = frame.inner()1366 with_frame.symbols.analyze_node(node)1367 self.enter_frame(with_frame)drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1368why, one step back1368 for target, expr in zip(node.targets, node.values, strict=False):update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1369–1375why, one step back1369 self.newline()1370 self.visit(target, with_frame)1371 self.write(" = ")1372 self.visit(expr, frame)1373 self.blockvisit(node.body, with_frame)1374 self.leave_frame(with_frame)1375Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1376why, one step back1376 def visit_ExprStmt(self, node: nodes.ExprStmt, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1377–1379why, one step back1377 self.newline(node)1378 self.visit(node.node, frame)1379Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1380why, one step back1380 class _FinalizeInfo(t.NamedTuple):drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 1381–1382why, one step back1381 const: t.Callable[..., str] | None1382 src: str | NoneMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1383–1391why, one step back13831384 @staticmethod1385 def _default_finalize(value: t.Any) -> t.Any:1386 """The default finalize function if the environment isn't1387 configured with one. Or, if the environment has one, this is1388 called on that function's output for constants.1389 """1390 return str(value)1391drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1392why, one step back1392 _finalize: _FinalizeInfo | None = Noneupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1393why, one step back1393Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1394why, one step back1394 def _make_finalize(self) -> _FinalizeInfo:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1395–1409why, one step back1395 """Build the finalize function to be used on constants and at1396 runtime. Cached so it's only created once for all output nodes.13971398 Returns a ``namedtuple`` with the following attributes:13991400 ``const``1401 A function to finalize constant data at compile time.14021403 ``src``1404 Source code to output around nodes to be evaluated at1405 runtime.1406 """1407 if self._finalize is not None:1408 return self._finalize1409drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1410why, one step back1410 finalize: t.Callable[..., t.Any] | Noneupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1411–1416why, one step back1411 finalize = default = self._default_finalize1412 src = None14131414 if self.environment.finalize:1415 src = "environment.finalize("1416 env_finalize = self.environment.finalizeMerge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
lines 1417–1420why, one step back1417 pass_arg = {1418 _PassArg.context: "context",1419 _PassArg.eval_context: "context.eval_ctx",1420 _PassArg.environment: "environment",Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1421–1423why, one step back1421 }.get(1422 _PassArg.from_obj(env_finalize) # type: ignore1423 )Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 1424why, one step back1424 finalize = Noneupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1425why, one step back1425Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 1426why, one step back1426 if pass_arg is None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1427why, one step back1427Merge branch '3.1.x'David Lordbefore adoption3fd91e4
line 1428why, one step back1428 def finalize(value: t.Any) -> t.Any: # noqa: F811Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 1429why, one step back1429 return default(env_finalize(value))update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1430why, one step back1430Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
lines 1431–1435why, one step back1431 else:1432 src = f"{src}{pass_arg}, "14331434 if pass_arg == "environment":1435Merge branch '3.1.x'David Lordbefore adoption3fd91e4
line 1436why, one step back1436 def finalize(value: t.Any) -> t.Any: # noqa: F811Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
lines 1437–1438why, one step back1437 return default(env_finalize(self.environment, value))1438update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1439–1441why, one step back1439 self._finalize = self._FinalizeInfo(finalize, src)1440 return self._finalize1441Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1442why, one step back1442 def _output_const_repr(self, group: t.Iterable[t.Any]) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1443–1448why, one step back1443 """Given a group of constant values converted from ``Output``1444 child nodes, produce a string to write to the template module1445 source.1446 """1447 return repr(concat(group))1448Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1449–1451why, one step back1449 def _output_child_to_const(1450 self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo1451 ) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1452–1467why, one step back1452 """Try to optimize a child of an ``Output`` node by trying to1453 convert it to constant, finalized data at compile time.14541455 If :exc:`Impossible` is raised, the node is not constant and1456 will be evaluated at runtime. Any other exception will also be1457 evaluated at runtime for easier debugging.1458 """1459 const = node.as_const(frame.eval_ctx)14601461 if frame.eval_ctx.autoescape:1462 const = escape(const)14631464 # Template data doesn't go through finalize.1465 if isinstance(node, nodes.TemplateData):1466 return str(const)1467Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1468why, one step back1468 return finalize.const(const) # type: ignoreupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1469why, one step back1469Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1470–1472why, one step back1470 def _output_child_pre(1471 self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo1472 ) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1473–1485why, one step back1473 """Output extra source code before visiting a child of an1474 ``Output`` node.1475 """1476 if frame.eval_ctx.volatile:1477 self.write("(escape if context.eval_ctx.autoescape else str)(")1478 elif frame.eval_ctx.autoescape:1479 self.write("escape(")1480 else:1481 self.write("str(")14821483 if finalize.src is not None:1484 self.write(finalize.src)1485Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1486–1488why, one step back1486 def _output_child_post(1487 self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo1488 ) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1489–1496why, one step back1489 """Output extra source code after visiting a child of an1490 ``Output`` node.1491 """1492 self.write(")")14931494 if finalize.src is not None:1495 self.write(")")1496Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1497why, one step back1497 def visit_Output(self, node: nodes.Output, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1498–1507why, one step back1498 # If an extends is active, don't render outside a block.1499 if frame.require_output_check:1500 # A top-level extends is known to exist at compile time.1501 if self.has_known_extends:1502 return15031504 self.writeline("if parent_template is None:")1505 self.indent()15061507 finalize = self._make_finalize()drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1508why, one step back1508 body: list[list[t.Any] | nodes.Expr] = []update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1509–1575why, one step back15091510 # Evaluate constants at compile time if possible. Each item in1511 # body will be either a list of static data or a node to be1512 # evaluated at runtime.1513 for child in node.nodes:1514 try:1515 if not (1516 # If the finalize function requires runtime context,1517 # constants can't be evaluated at compile time.1518 finalize.const1519 # Unless it's basic template data that won't be1520 # finalized anyway.1521 or isinstance(child, nodes.TemplateData)1522 ):1523 raise nodes.Impossible()15241525 const = self._output_child_to_const(child, frame, finalize)1526 except (nodes.Impossible, Exception):1527 # The node was not constant and needs to be evaluated at1528 # runtime. Or another error was raised, which is easier1529 # to debug at runtime.1530 body.append(child)1531 continue15321533 if body and isinstance(body[-1], list):1534 body[-1].append(const)1535 else:1536 body.append([const])15371538 if frame.buffer is not None:1539 if len(body) == 1:1540 self.writeline(f"{frame.buffer}.append(")1541 else:1542 self.writeline(f"{frame.buffer}.extend((")15431544 self.indent()15451546 for item in body:1547 if isinstance(item, list):1548 # A group of constant data to join and output.1549 val = self._output_const_repr(item)15501551 if frame.buffer is None:1552 self.writeline("yield " + val)1553 else:1554 self.writeline(val + ",")1555 else:1556 if frame.buffer is None:1557 self.writeline("yield ", item)1558 else:1559 self.newline(item)15601561 # A node to be evaluated at runtime.1562 self._output_child_pre(item, frame, finalize)1563 self.visit(item, frame)1564 self._output_child_post(item, frame, finalize)15651566 if frame.buffer is not None:1567 self.write(",")15681569 if frame.buffer is not None:1570 self.outdent()1571 self.writeline(")" if len(body) == 1 else "))")15721573 if frame.require_output_check:1574 self.outdent()1575Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1576why, one step back1576 def visit_Assign(self, node: nodes.Assign, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1577why, one step back1577 self.push_assign_tracking()Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 1578–1582why, one step back15781579 # ``a.b`` is allowed for assignment, and is parsed as an NSRef. However,1580 # it is only valid if it references a Namespace object. Emit a check for1581 # that for each ref here, before assignment code is emitted. This can't1582 # be done in visit_NSRef as the ref could be in the middle of a tuple.Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 1583why, one step back1583 seen_refs: set[str] = set()Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 1584–1600why, one step back15841585 for nsref in node.find_all(nodes.NSRef):1586 if nsref.name in seen_refs:1587 # Only emit the check for each reference once, in case the same1588 # ref is used multiple times in a tuple, `ns.a, ns.b = c, d`.1589 continue15901591 seen_refs.add(nsref.name)1592 ref = frame.symbols.ref(nsref.name)1593 self.writeline(f"if not isinstance({ref}, Namespace):")1594 self.indent()1595 self.writeline(1596 "raise TemplateRuntimeError"1597 '("cannot assign attribute on non-namespace object")'1598 )1599 self.outdent()1600update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1601–1606why, one step back1601 self.newline(node)1602 self.visit(node.target, frame)1603 self.write(" = ")1604 self.visit(node.node, frame)1605 self.pop_assign_tracking(frame)1606Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1607why, one step back1607 def visit_AssignBlock(self, node: nodes.AssignBlock, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1608–1630why, one step back1608 self.push_assign_tracking()1609 block_frame = frame.inner()1610 # This is a special case. Since a set block always captures we1611 # will disable output checks. This way one can use set blocks1612 # toplevel even in extended templates.1613 block_frame.require_output_check = False1614 block_frame.symbols.analyze_node(node)1615 self.enter_frame(block_frame)1616 self.buffer(block_frame)1617 self.blockvisit(node.body, block_frame)1618 self.newline(node)1619 self.visit(node.target, frame)1620 self.write(" = (Markup if context.eval_ctx.autoescape else identity)(")1621 if node.filter is not None:1622 self.visit_Filter(node.filter, block_frame)1623 else:1624 self.write(f"concat({block_frame.buffer})")1625 self.write(")")1626 self.pop_assign_tracking(frame)1627 self.leave_frame(block_frame)16281629 # -- Expression Visitors1630Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1631why, one step back1631 def visit_Name(self, node: nodes.Name, frame: Frame) -> None:Merge pull request #1242 from MLH-Fellowship/context-bugAmy Leibefore adoptionf71f5eb
lines 1632–1634why, one step back1632 if node.ctx == "store" and (1633 frame.toplevel or frame.loop_frame or frame.block_frame1634 ):update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1635–1655why, one step back1635 if self._assign_stack:1636 self._assign_stack[-1].add(node.name)1637 ref = frame.symbols.ref(node.name)16381639 # If we are looking up a variable we might have to deal with the1640 # case where it's undefined. We can skip that case if the load1641 # instruction indicates a parameter which are always defined.1642 if node.ctx == "load":1643 load = frame.symbols.find_load(ref)1644 if not (1645 load is not None1646 and load[0] == VAR_LOAD_PARAMETER1647 and not self.parameter_is_undeclared(ref)1648 ):1649 self.write(1650 f"(undefined(name={node.name!r}) if {ref} is missing else {ref})"1651 )1652 return16531654 self.write(ref)1655Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1656why, one step back1656 def visit_NSRef(self, node: nodes.NSRef, frame: Frame) -> None:Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 1657–1660why, one step back1657 # NSRef is a dotted assignment target a.b=c, but uses a[b]=c internally.1658 # visit_Assign emits code to validate that each ref is to a Namespace1659 # object only. That can't be emitted here as the ref could be in the1660 # middle of a tuple assignment.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1661–1663why, one step back1661 ref = frame.symbols.ref(node.name)1662 self.writeline(f"{ref}[{node.attr!r}]")1663Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1664why, one step back1664 def visit_Const(self, node: nodes.Const, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1665–1670why, one step back1665 val = node.as_const(frame.eval_ctx)1666 if isinstance(val, float):1667 self.write(str(val))1668 else:1669 self.write(repr(val))1670Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1671why, one step back1671 def visit_TemplateData(self, node: nodes.TemplateData, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1672–1678why, one step back1672 try:1673 self.write(repr(node.as_const(frame.eval_ctx)))1674 except nodes.Impossible:1675 self.write(1676 f"(Markup if context.eval_ctx.autoescape else identity)({node.data!r})"1677 )1678Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1679why, one step back1679 def visit_Tuple(self, node: nodes.Tuple, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1680–1687why, one step back1680 self.write("(")1681 idx = -11682 for idx, item in enumerate(node.items):1683 if idx:1684 self.write(", ")1685 self.visit(item, frame)1686 self.write(",)" if idx == 0 else ")")1687Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1688why, one step back1688 def visit_List(self, node: nodes.List, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1689–1695why, one step back1689 self.write("[")1690 for idx, item in enumerate(node.items):1691 if idx:1692 self.write(", ")1693 self.visit(item, frame)1694 self.write("]")1695Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1696why, one step back1696 def visit_Dict(self, node: nodes.Dict, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1697–1705why, one step back1697 self.write("{")1698 for idx, item in enumerate(node.items):1699 if idx:1700 self.write(", ")1701 self.visit(item.key, frame)1702 self.write(": ")1703 self.visit(item.value, frame)1704 self.write("}")1705Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1706–1717why, one step back1706 visit_Add = _make_binop("+")1707 visit_Sub = _make_binop("-")1708 visit_Mul = _make_binop("*")1709 visit_Div = _make_binop("/")1710 visit_FloorDiv = _make_binop("//")1711 visit_Pow = _make_binop("**")1712 visit_Mod = _make_binop("%")1713 visit_And = _make_binop("and")1714 visit_Or = _make_binop("or")1715 visit_Pos = _make_unop("+")1716 visit_Neg = _make_unop("-")1717 visit_Not = _make_unop("not ")update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1718–1719why, one step back17181719 @optimizeconstMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1720why, one step back1720 def visit_Concat(self, node: nodes.Concat, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1721–1733why, one step back1721 if frame.eval_ctx.volatile:1722 func_name = "(markup_join if context.eval_ctx.volatile else str_join)"1723 elif frame.eval_ctx.autoescape:1724 func_name = "markup_join"1725 else:1726 func_name = "str_join"1727 self.write(f"{func_name}((")1728 for arg in node.nodes:1729 self.visit(arg, frame)1730 self.write(", ")1731 self.write("))")17321733 @optimizeconstMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1734why, one step back1734 def visit_Compare(self, node: nodes.Compare, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1735–1740why, one step back1735 self.write("(")1736 self.visit(node.expr, frame)1737 for op in node.ops:1738 self.visit(op, frame)1739 self.write(")")1740Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1741why, one step back1741 def visit_Operand(self, node: nodes.Operand, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1742–1745why, one step back1742 self.write(f" {operators[node.op]} ")1743 self.visit(node.expr, frame)17441745 @optimizeconstMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1746why, one step back1746 def visit_Getattr(self, node: nodes.Getattr, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1747–1757why, one step back1747 if self.environment.is_async:1748 self.write("(await auto_await(")17491750 self.write("environment.getattr(")1751 self.visit(node.node, frame)1752 self.write(f", {node.attr!r})")17531754 if self.environment.is_async:1755 self.write("))")17561757 @optimizeconstMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1758why, one step back1758 def visit_Getitem(self, node: nodes.Getitem, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1759–1777why, one step back1759 # slices bypass the environment getitem method.1760 if isinstance(node.arg, nodes.Slice):1761 self.visit(node.node, frame)1762 self.write("[")1763 self.visit(node.arg, frame)1764 self.write("]")1765 else:1766 if self.environment.is_async:1767 self.write("(await auto_await(")17681769 self.write("environment.getitem(")1770 self.visit(node.node, frame)1771 self.write(", ")1772 self.visit(node.arg, frame)1773 self.write(")")17741775 if self.environment.is_async:1776 self.write("))")1777Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1778why, one step back1778 def visit_Slice(self, node: nodes.Slice, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1779–1787why, one step back1779 if node.start is not None:1780 self.visit(node.start, frame)1781 self.write(":")1782 if node.stop is not None:1783 self.visit(node.stop, frame)1784 if node.step is not None:1785 self.write(":")1786 self.visit(node.step, frame)1787Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 1788why, one step back1788 @contextmanagerMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1789why, one step back1789 def _filter_test_common(drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1790why, one step back1790 self, node: nodes.Filter | nodes.Test, frame: Frame, is_filter: boolMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1791why, one step back1791 ) -> t.Iterator[None]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1792why, one step back1792 if self.environment.is_async:Merge pull request #1614 from pallets/async-env-filterDavid Lordbefore adoption20eb7f5
line 1793why, one step back1793 self.write("(await auto_await(")Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 1794why, one step back1794Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1795–1800why, one step back1795 if is_filter:1796 self.write(f"{self.filters[node.name]}(")1797 func = self.environment.filters.get(node.name)1798 else:1799 self.write(f"{self.tests[node.name]}(")1800 func = self.environment.tests.get(node.name)Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 1801–1804why, one step back18011802 # When inside an If or CondExpr frame, allow the filter to be1803 # undefined at compile time and only raise an error if it's1804 # actually called at runtime. See pull_dependencies.Merge pull request #1248 from MLH-Fellowship/test-for-filterDavid Lordbefore adoptionaf5d80e
line 1805why, one step back1805 if func is None and not frame.soft_frame:Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1806why, one step back1806 type_name = "filter" if is_filter else "test"Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 1807–1808why, one step back1807 self.fail(f"No {type_name} named {node.name!r}.", node.lineno)1808Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
lines 1809–1812why, one step back1809 pass_arg = {1810 _PassArg.context: "context",1811 _PassArg.eval_context: "context.eval_ctx",1812 _PassArg.environment: "environment",Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1813–1815why, one step back1813 }.get(1814 _PassArg.from_obj(func) # type: ignore1815 )Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
lines 1816–1818why, one step back18161817 if pass_arg is not None:1818 self.write(f"{pass_arg}, ")update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1819why, one step back1819Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 1820–1823why, one step back1820 # Back to the visitor function to handle visiting the target of1821 # the filter or test.1822 yield1823update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1824–1825why, one step back1824 self.signature(node, frame)1825 self.write(")")Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 1826why, one step back1826update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1827why, one step back1827 if self.environment.is_async:Merge pull request #1614 from pallets/async-env-filterDavid Lordbefore adoption20eb7f5
line 1828why, one step back1828 self.write("))")update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1829–1830why, one step back18291830 @optimizeconstMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1831why, one step back1831 def visit_Filter(self, node: nodes.Filter, frame: Frame) -> None:Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 1832–1847why, one step back1832 with self._filter_test_common(node, frame, True):1833 # if the filter node is None we are inside a filter block1834 # and want to write to the current buffer1835 if node.node is not None:1836 self.visit(node.node, frame)1837 elif frame.eval_ctx.volatile:1838 self.write(1839 f"(Markup(concat({frame.buffer}))"1840 f" if context.eval_ctx.autoescape else concat({frame.buffer}))"1841 )1842 elif frame.eval_ctx.autoescape:1843 self.write(f"Markup(concat({frame.buffer}))")1844 else:1845 self.write(f"concat({frame.buffer})")18461847 @optimizeconstMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1848why, one step back1848 def visit_Test(self, node: nodes.Test, frame: Frame) -> None:Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 1849–1850why, one step back1849 with self._filter_test_common(node, frame, False):1850 self.visit(node.node, frame)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1851–1852why, one step back18511852 @optimizeconstMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1853why, one step back1853 def visit_CondExpr(self, node: nodes.CondExpr, frame: Frame) -> None:Merge pull request #1248 from MLH-Fellowship/test-for-filterDavid Lordbefore adoptionaf5d80e
lines 1854–1855why, one step back1854 frame = frame.soft()1855Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1856why, one step back1856 def write_expr2() -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1857why, one step back1857 if node.expr2 is not None:Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1858–1860why, one step back1858 self.visit(node.expr2, frame)1859 return1860update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1861–1875why, one step back1861 self.write(1862 f'cond_expr_undefined("the inline if-expression on'1863 f" {self.position(node)} evaluated to false and no else"1864 f' section was defined.")'1865 )18661867 self.write("(")1868 self.visit(node.expr1, frame)1869 self.write(" if ")1870 self.visit(node.test, frame)1871 self.write(" else ")1872 write_expr2()1873 self.write(")")18741875 @optimizeconstMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1876–1878why, one step back1876 def visit_Call(1877 self, node: nodes.Call, frame: Frame, forward_caller: bool = False1878 ) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1879why, one step back1879 if self.environment.is_async:Merge pull request #1614 from pallets/async-env-filterDavid Lordbefore adoption20eb7f5
line 1880why, one step back1880 self.write("(await auto_await(")update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1881–1886why, one step back1881 if self.environment.sandboxed:1882 self.write("environment.call(context, ")1883 else:1884 self.write("context.call(")1885 self.visit(node.node, frame)1886 extra_kwargs = {"caller": "caller"} if forward_caller else NoneMerge pull request #1242 from MLH-Fellowship/context-bugAmy Leibefore adoptionf71f5eb
lines 1887–1892why, one step back1887 loop_kwargs = {"_loop_vars": "_loop_vars"} if frame.loop_frame else {}1888 block_kwargs = {"_block_vars": "_block_vars"} if frame.block_frame else {}1889 if extra_kwargs:1890 extra_kwargs.update(loop_kwargs, **block_kwargs)1891 elif loop_kwargs or block_kwargs:1892 extra_kwargs = dict(loop_kwargs, **block_kwargs)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1893–1895why, one step back1893 self.signature(node, frame, extra_kwargs)1894 self.write(")")1895 if self.environment.is_async:Merge pull request #1614 from pallets/async-env-filterDavid Lordbefore adoption20eb7f5
line 1896why, one step back1896 self.write("))")update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1897why, one step back1897Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1898why, one step back1898 def visit_Keyword(self, node: nodes.Keyword, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1899–1903why, one step back1899 self.write(node.key + "=")1900 self.visit(node.value, frame)19011902 # -- Unused nodes for extensions1903Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1904why, one step back1904 def visit_MarkSafe(self, node: nodes.MarkSafe, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1905–1908why, one step back1905 self.write("Markup(")1906 self.visit(node.expr, frame)1907 self.write(")")1908Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1909–1911why, one step back1909 def visit_MarkSafeIfAutoescape(1910 self, node: nodes.MarkSafeIfAutoescape, frame: Frame1911 ) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1912–1915why, one step back1912 self.write("(Markup if context.eval_ctx.autoescape else identity)(")1913 self.visit(node.expr, frame)1914 self.write(")")1915Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1916–1918why, one step back1916 def visit_EnvironmentAttribute(1917 self, node: nodes.EnvironmentAttribute, frame: Frame1918 ) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1919–1920why, one step back1919 self.write("environment." + node.name)1920Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1921–1923why, one step back1921 def visit_ExtensionAttribute(1922 self, node: nodes.ExtensionAttribute, frame: Frame1923 ) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1924–1925why, one step back1924 self.write(f"environment.extensions[{node.identifier!r}].{node.name}")1925Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1926why, one step back1926 def visit_ImportedName(self, node: nodes.ImportedName, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1927–1928why, one step back1927 self.write(self.import_aliases[node.importname])1928Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1929why, one step back1929 def visit_InternalName(self, node: nodes.InternalName, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1930–1931why, one step back1930 self.write(node.name)1931Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1932–1934why, one step back1932 def visit_ContextReference(1933 self, node: nodes.ContextReference, frame: Frame1934 ) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1935–1936why, one step back1935 self.write("context")1936Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1937–1939why, one step back1937 def visit_DerivedContextReference(1938 self, node: nodes.DerivedContextReference, frame: Frame1939 ) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1940–1941why, one step back1940 self.write(self.derive_context(frame))1941Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1942why, one step back1942 def visit_Continue(self, node: nodes.Continue, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1943–1944why, one step back1943 self.writeline("continue", node)1944Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1945why, one step back1945 def visit_Break(self, node: nodes.Break, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1946–1947why, one step back1946 self.writeline("break", node)1947Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1948why, one step back1948 def visit_Scope(self, node: nodes.Scope, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1949–1954why, one step back1949 scope_frame = frame.inner()1950 scope_frame.symbols.analyze_node(node)1951 self.enter_frame(scope_frame)1952 self.blockvisit(node.body, scope_frame)1953 self.leave_frame(scope_frame)1954Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1955why, one step back1955 def visit_OverlayScope(self, node: nodes.OverlayScope, frame: Frame) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1956–1968why, one step back1956 ctx = self.temporary_identifier()1957 self.writeline(f"{ctx} = {self.derive_context(frame)}")1958 self.writeline(f"{ctx}.vars = ")1959 self.visit(node.context, frame)1960 self.push_context_reference(ctx)19611962 scope_frame = frame.inner(isolated=True)1963 scope_frame.symbols.analyze_node(node)1964 self.enter_frame(scope_frame)1965 self.blockvisit(node.body, scope_frame)1966 self.leave_frame(scope_frame)1967 self.pop_context_reference()1968Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1969–1971why, one step back1969 def visit_EvalContextModifier(1970 self, node: nodes.EvalContextModifier, frame: Frame1971 ) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1972–1981why, one step back1972 for keyword in node.options:1973 self.writeline(f"context.eval_ctx.{keyword.key} = ")1974 self.visit(keyword.value, frame)1975 try:1976 val = keyword.value.as_const(frame.eval_ctx)1977 except nodes.Impossible:1978 frame.eval_ctx.volatile = True1979 else:1980 setattr(frame.eval_ctx, keyword.key, val)1981Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1982–1984why, one step back1982 def visit_ScopedEvalContextModifier(1983 self, node: nodes.ScopedEvalContextModifier, frame: Frame1984 ) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1985–1992why, one step back1985 old_ctx_name = self.temporary_identifier()1986 saved_ctx = frame.eval_ctx.save()1987 self.writeline(f"{old_ctx_name} = context.eval_ctx.save()")1988 self.visit_EvalContextModifier(node, frame)1989 for child in node.body:1990 self.visit(child, frame)1991 frame.eval_ctx.revert(saved_ctx)1992 self.writeline(f"context.eval_ctx.revert({old_ctx_name})")