compiler.py 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960
  1. """Compiles nodes from the parser into Python code."""
  2. import typing as t
  3. from contextlib import contextmanager
  4. from functools import update_wrapper
  5. from io import StringIO
  6. from itertools import chain
  7. from keyword import iskeyword as is_python_keyword
  8. from markupsafe import escape
  9. from markupsafe import Markup
  10. from . import nodes
  11. from .exceptions import TemplateAssertionError
  12. from .idtracking import Symbols
  13. from .idtracking import VAR_LOAD_ALIAS
  14. from .idtracking import VAR_LOAD_PARAMETER
  15. from .idtracking import VAR_LOAD_RESOLVE
  16. from .idtracking import VAR_LOAD_UNDEFINED
  17. from .nodes import EvalContext
  18. from .optimizer import Optimizer
  19. from .utils import _PassArg
  20. from .utils import concat
  21. from .visitor import NodeVisitor
  22. if t.TYPE_CHECKING:
  23. import typing_extensions as te
  24. from .environment import Environment
  25. F = t.TypeVar("F", bound=t.Callable[..., t.Any])
  26. operators = {
  27. "eq": "==",
  28. "ne": "!=",
  29. "gt": ">",
  30. "gteq": ">=",
  31. "lt": "<",
  32. "lteq": "<=",
  33. "in": "in",
  34. "notin": "not in",
  35. }
  36. def optimizeconst(f: F) -> F:
  37. def new_func(
  38. self: "CodeGenerator", node: nodes.Expr, frame: "Frame", **kwargs: t.Any
  39. ) -> t.Any:
  40. # Only optimize if the frame is not volatile
  41. if self.optimizer is not None and not frame.eval_ctx.volatile:
  42. new_node = self.optimizer.visit(node, frame.eval_ctx)
  43. if new_node != node:
  44. return self.visit(new_node, frame)
  45. return f(self, node, frame, **kwargs)
  46. return update_wrapper(t.cast(F, new_func), f)
  47. def _make_binop(op: str) -> t.Callable[["CodeGenerator", nodes.BinExpr, "Frame"], None]:
  48. @optimizeconst
  49. def visitor(self: "CodeGenerator", node: nodes.BinExpr, frame: Frame) -> None:
  50. if (
  51. self.environment.sandboxed and op in self.environment.intercepted_binops # type: ignore
  52. ):
  53. self.write(f"environment.call_binop(context, {op!r}, ")
  54. self.visit(node.left, frame)
  55. self.write(", ")
  56. self.visit(node.right, frame)
  57. else:
  58. self.write("(")
  59. self.visit(node.left, frame)
  60. self.write(f" {op} ")
  61. self.visit(node.right, frame)
  62. self.write(")")
  63. return visitor
  64. def _make_unop(
  65. op: str,
  66. ) -> t.Callable[["CodeGenerator", nodes.UnaryExpr, "Frame"], None]:
  67. @optimizeconst
  68. def visitor(self: "CodeGenerator", node: nodes.UnaryExpr, frame: Frame) -> None:
  69. if (
  70. self.environment.sandboxed and op in self.environment.intercepted_unops # type: ignore
  71. ):
  72. self.write(f"environment.call_unop(context, {op!r}, ")
  73. self.visit(node.node, frame)
  74. else:
  75. self.write("(" + op)
  76. self.visit(node.node, frame)
  77. self.write(")")
  78. return visitor
  79. def generate(
  80. node: nodes.Template,
  81. environment: "Environment",
  82. name: t.Optional[str],
  83. filename: t.Optional[str],
  84. stream: t.Optional[t.TextIO] = None,
  85. defer_init: bool = False,
  86. optimized: bool = True,
  87. ) -> t.Optional[str]:
  88. """Generate the python source for a node tree."""
  89. if not isinstance(node, nodes.Template):
  90. raise TypeError("Can't compile non template nodes")
  91. generator = environment.code_generator_class(
  92. environment, name, filename, stream, defer_init, optimized
  93. )
  94. generator.visit(node)
  95. if stream is None:
  96. return generator.stream.getvalue() # type: ignore
  97. return None
  98. def has_safe_repr(value: t.Any) -> bool:
  99. """Does the node have a safe representation?"""
  100. if value is None or value is NotImplemented or value is Ellipsis:
  101. return True
  102. if type(value) in {bool, int, float, complex, range, str, Markup}:
  103. return True
  104. if type(value) in {tuple, list, set, frozenset}:
  105. return all(has_safe_repr(v) for v in value)
  106. if type(value) is dict: # noqa E721
  107. return all(has_safe_repr(k) and has_safe_repr(v) for k, v in value.items())
  108. return False
  109. def find_undeclared(
  110. nodes: t.Iterable[nodes.Node], names: t.Iterable[str]
  111. ) -> t.Set[str]:
  112. """Check if the names passed are accessed undeclared. The return value
  113. is a set of all the undeclared names from the sequence of names found.
  114. """
  115. visitor = UndeclaredNameVisitor(names)
  116. try:
  117. for node in nodes:
  118. visitor.visit(node)
  119. except VisitorExit:
  120. pass
  121. return visitor.undeclared
  122. class MacroRef:
  123. def __init__(self, node: t.Union[nodes.Macro, nodes.CallBlock]) -> None:
  124. self.node = node
  125. self.accesses_caller = False
  126. self.accesses_kwargs = False
  127. self.accesses_varargs = False
  128. class Frame:
  129. """Holds compile time information for us."""
  130. def __init__(
  131. self,
  132. eval_ctx: EvalContext,
  133. parent: t.Optional["Frame"] = None,
  134. level: t.Optional[int] = None,
  135. ) -> None:
  136. self.eval_ctx = eval_ctx
  137. # the parent of this frame
  138. self.parent = parent
  139. if parent is None:
  140. self.symbols = Symbols(level=level)
  141. # in some dynamic inheritance situations the compiler needs to add
  142. # write tests around output statements.
  143. self.require_output_check = False
  144. # inside some tags we are using a buffer rather than yield statements.
  145. # this for example affects {% filter %} or {% macro %}. If a frame
  146. # is buffered this variable points to the name of the list used as
  147. # buffer.
  148. self.buffer: t.Optional[str] = None
  149. # the name of the block we're in, otherwise None.
  150. self.block: t.Optional[str] = None
  151. else:
  152. self.symbols = Symbols(parent.symbols, level=level)
  153. self.require_output_check = parent.require_output_check
  154. self.buffer = parent.buffer
  155. self.block = parent.block
  156. # a toplevel frame is the root + soft frames such as if conditions.
  157. self.toplevel = False
  158. # the root frame is basically just the outermost frame, so no if
  159. # conditions. This information is used to optimize inheritance
  160. # situations.
  161. self.rootlevel = False
  162. # variables set inside of loops and blocks should not affect outer frames,
  163. # but they still needs to be kept track of as part of the active context.
  164. self.loop_frame = False
  165. self.block_frame = False
  166. # track whether the frame is being used in an if-statement or conditional
  167. # expression as it determines which errors should be raised during runtime
  168. # or compile time.
  169. self.soft_frame = False
  170. def copy(self) -> "Frame":
  171. """Create a copy of the current one."""
  172. rv = object.__new__(self.__class__)
  173. rv.__dict__.update(self.__dict__)
  174. rv.symbols = self.symbols.copy()
  175. return rv
  176. def inner(self, isolated: bool = False) -> "Frame":
  177. """Return an inner frame."""
  178. if isolated:
  179. return Frame(self.eval_ctx, level=self.symbols.level + 1)
  180. return Frame(self.eval_ctx, self)
  181. def soft(self) -> "Frame":
  182. """Return a soft frame. A soft frame may not be modified as
  183. standalone thing as it shares the resources with the frame it
  184. was created of, but it's not a rootlevel frame any longer.
  185. This is only used to implement if-statements and conditional
  186. expressions.
  187. """
  188. rv = self.copy()
  189. rv.rootlevel = False
  190. rv.soft_frame = True
  191. return rv
  192. __copy__ = copy
  193. class VisitorExit(RuntimeError):
  194. """Exception used by the `UndeclaredNameVisitor` to signal a stop."""
  195. class DependencyFinderVisitor(NodeVisitor):
  196. """A visitor that collects filter and test calls."""
  197. def __init__(self) -> None:
  198. self.filters: t.Set[str] = set()
  199. self.tests: t.Set[str] = set()
  200. def visit_Filter(self, node: nodes.Filter) -> None:
  201. self.generic_visit(node)
  202. self.filters.add(node.name)
  203. def visit_Test(self, node: nodes.Test) -> None:
  204. self.generic_visit(node)
  205. self.tests.add(node.name)
  206. def visit_Block(self, node: nodes.Block) -> None:
  207. """Stop visiting at blocks."""
  208. class UndeclaredNameVisitor(NodeVisitor):
  209. """A visitor that checks if a name is accessed without being
  210. declared. This is different from the frame visitor as it will
  211. not stop at closure frames.
  212. """
  213. def __init__(self, names: t.Iterable[str]) -> None:
  214. self.names = set(names)
  215. self.undeclared: t.Set[str] = set()
  216. def visit_Name(self, node: nodes.Name) -> None:
  217. if node.ctx == "load" and node.name in self.names:
  218. self.undeclared.add(node.name)
  219. if self.undeclared == self.names:
  220. raise VisitorExit()
  221. else:
  222. self.names.discard(node.name)
  223. def visit_Block(self, node: nodes.Block) -> None:
  224. """Stop visiting a blocks."""
  225. class CompilerExit(Exception):
  226. """Raised if the compiler encountered a situation where it just
  227. doesn't make sense to further process the code. Any block that
  228. raises such an exception is not further processed.
  229. """
  230. class CodeGenerator(NodeVisitor):
  231. def __init__(
  232. self,
  233. environment: "Environment",
  234. name: t.Optional[str],
  235. filename: t.Optional[str],
  236. stream: t.Optional[t.TextIO] = None,
  237. defer_init: bool = False,
  238. optimized: bool = True,
  239. ) -> None:
  240. if stream is None:
  241. stream = StringIO()
  242. self.environment = environment
  243. self.name = name
  244. self.filename = filename
  245. self.stream = stream
  246. self.created_block_context = False
  247. self.defer_init = defer_init
  248. self.optimizer: t.Optional[Optimizer] = None
  249. if optimized:
  250. self.optimizer = Optimizer(environment)
  251. # aliases for imports
  252. self.import_aliases: t.Dict[str, str] = {}
  253. # a registry for all blocks. Because blocks are moved out
  254. # into the global python scope they are registered here
  255. self.blocks: t.Dict[str, nodes.Block] = {}
  256. # the number of extends statements so far
  257. self.extends_so_far = 0
  258. # some templates have a rootlevel extends. In this case we
  259. # can safely assume that we're a child template and do some
  260. # more optimizations.
  261. self.has_known_extends = False
  262. # the current line number
  263. self.code_lineno = 1
  264. # registry of all filters and tests (global, not block local)
  265. self.tests: t.Dict[str, str] = {}
  266. self.filters: t.Dict[str, str] = {}
  267. # the debug information
  268. self.debug_info: t.List[t.Tuple[int, int]] = []
  269. self._write_debug_info: t.Optional[int] = None
  270. # the number of new lines before the next write()
  271. self._new_lines = 0
  272. # the line number of the last written statement
  273. self._last_line = 0
  274. # true if nothing was written so far.
  275. self._first_write = True
  276. # used by the `temporary_identifier` method to get new
  277. # unique, temporary identifier
  278. self._last_identifier = 0
  279. # the current indentation
  280. self._indentation = 0
  281. # Tracks toplevel assignments
  282. self._assign_stack: t.List[t.Set[str]] = []
  283. # Tracks parameter definition blocks
  284. self._param_def_block: t.List[t.Set[str]] = []
  285. # Tracks the current context.
  286. self._context_reference_stack = ["context"]
  287. @property
  288. def optimized(self) -> bool:
  289. return self.optimizer is not None
  290. # -- Various compilation helpers
  291. def fail(self, msg: str, lineno: int) -> "te.NoReturn":
  292. """Fail with a :exc:`TemplateAssertionError`."""
  293. raise TemplateAssertionError(msg, lineno, self.name, self.filename)
  294. def temporary_identifier(self) -> str:
  295. """Get a new unique identifier."""
  296. self._last_identifier += 1
  297. return f"t_{self._last_identifier}"
  298. def buffer(self, frame: Frame) -> None:
  299. """Enable buffering for the frame from that point onwards."""
  300. frame.buffer = self.temporary_identifier()
  301. self.writeline(f"{frame.buffer} = []")
  302. def return_buffer_contents(
  303. self, frame: Frame, force_unescaped: bool = False
  304. ) -> None:
  305. """Return the buffer contents of the frame."""
  306. if not force_unescaped:
  307. if frame.eval_ctx.volatile:
  308. self.writeline("if context.eval_ctx.autoescape:")
  309. self.indent()
  310. self.writeline(f"return Markup(concat({frame.buffer}))")
  311. self.outdent()
  312. self.writeline("else:")
  313. self.indent()
  314. self.writeline(f"return concat({frame.buffer})")
  315. self.outdent()
  316. return
  317. elif frame.eval_ctx.autoescape:
  318. self.writeline(f"return Markup(concat({frame.buffer}))")
  319. return
  320. self.writeline(f"return concat({frame.buffer})")
  321. def indent(self) -> None:
  322. """Indent by one."""
  323. self._indentation += 1
  324. def outdent(self, step: int = 1) -> None:
  325. """Outdent by step."""
  326. self._indentation -= step
  327. def start_write(self, frame: Frame, node: t.Optional[nodes.Node] = None) -> None:
  328. """Yield or write into the frame buffer."""
  329. if frame.buffer is None:
  330. self.writeline("yield ", node)
  331. else:
  332. self.writeline(f"{frame.buffer}.append(", node)
  333. def end_write(self, frame: Frame) -> None:
  334. """End the writing process started by `start_write`."""
  335. if frame.buffer is not None:
  336. self.write(")")
  337. def simple_write(
  338. self, s: str, frame: Frame, node: t.Optional[nodes.Node] = None
  339. ) -> None:
  340. """Simple shortcut for start_write + write + end_write."""
  341. self.start_write(frame, node)
  342. self.write(s)
  343. self.end_write(frame)
  344. def blockvisit(self, nodes: t.Iterable[nodes.Node], frame: Frame) -> None:
  345. """Visit a list of nodes as block in a frame. If the current frame
  346. is no buffer a dummy ``if 0: yield None`` is written automatically.
  347. """
  348. try:
  349. self.writeline("pass")
  350. for node in nodes:
  351. self.visit(node, frame)
  352. except CompilerExit:
  353. pass
  354. def write(self, x: str) -> None:
  355. """Write a string into the output stream."""
  356. if self._new_lines:
  357. if not self._first_write:
  358. self.stream.write("\n" * self._new_lines)
  359. self.code_lineno += self._new_lines
  360. if self._write_debug_info is not None:
  361. self.debug_info.append((self._write_debug_info, self.code_lineno))
  362. self._write_debug_info = None
  363. self._first_write = False
  364. self.stream.write(" " * self._indentation)
  365. self._new_lines = 0
  366. self.stream.write(x)
  367. def writeline(
  368. self, x: str, node: t.Optional[nodes.Node] = None, extra: int = 0
  369. ) -> None:
  370. """Combination of newline and write."""
  371. self.newline(node, extra)
  372. self.write(x)
  373. def newline(self, node: t.Optional[nodes.Node] = None, extra: int = 0) -> None:
  374. """Add one or more newlines before the next write."""
  375. self._new_lines = max(self._new_lines, 1 + extra)
  376. if node is not None and node.lineno != self._last_line:
  377. self._write_debug_info = node.lineno
  378. self._last_line = node.lineno
  379. def signature(
  380. self,
  381. node: t.Union[nodes.Call, nodes.Filter, nodes.Test],
  382. frame: Frame,
  383. extra_kwargs: t.Optional[t.Mapping[str, t.Any]] = None,
  384. ) -> None:
  385. """Writes a function call to the stream for the current node.
  386. A leading comma is added automatically. The extra keyword
  387. arguments may not include python keywords otherwise a syntax
  388. error could occur. The extra keyword arguments should be given
  389. as python dict.
  390. """
  391. # if any of the given keyword arguments is a python keyword
  392. # we have to make sure that no invalid call is created.
  393. kwarg_workaround = any(
  394. is_python_keyword(t.cast(str, k))
  395. for k in chain((x.key for x in node.kwargs), extra_kwargs or ())
  396. )
  397. for arg in node.args:
  398. self.write(", ")
  399. self.visit(arg, frame)
  400. if not kwarg_workaround:
  401. for kwarg in node.kwargs:
  402. self.write(", ")
  403. self.visit(kwarg, frame)
  404. if extra_kwargs is not None:
  405. for key, value in extra_kwargs.items():
  406. self.write(f", {key}={value}")
  407. if node.dyn_args:
  408. self.write(", *")
  409. self.visit(node.dyn_args, frame)
  410. if kwarg_workaround:
  411. if node.dyn_kwargs is not None:
  412. self.write(", **dict({")
  413. else:
  414. self.write(", **{")
  415. for kwarg in node.kwargs:
  416. self.write(f"{kwarg.key!r}: ")
  417. self.visit(kwarg.value, frame)
  418. self.write(", ")
  419. if extra_kwargs is not None:
  420. for key, value in extra_kwargs.items():
  421. self.write(f"{key!r}: {value}, ")
  422. if node.dyn_kwargs is not None:
  423. self.write("}, **")
  424. self.visit(node.dyn_kwargs, frame)
  425. self.write(")")
  426. else:
  427. self.write("}")
  428. elif node.dyn_kwargs is not None:
  429. self.write(", **")
  430. self.visit(node.dyn_kwargs, frame)
  431. def pull_dependencies(self, nodes: t.Iterable[nodes.Node]) -> None:
  432. """Find all filter and test names used in the template and
  433. assign them to variables in the compiled namespace. Checking
  434. that the names are registered with the environment is done when
  435. compiling the Filter and Test nodes. If the node is in an If or
  436. CondExpr node, the check is done at runtime instead.
  437. .. versionchanged:: 3.0
  438. Filters and tests in If and CondExpr nodes are checked at
  439. runtime instead of compile time.
  440. """
  441. visitor = DependencyFinderVisitor()
  442. for node in nodes:
  443. visitor.visit(node)
  444. for id_map, names, dependency in (
  445. (self.filters, visitor.filters, "filters"),
  446. (
  447. self.tests,
  448. visitor.tests,
  449. "tests",
  450. ),
  451. ):
  452. for name in sorted(names):
  453. if name not in id_map:
  454. id_map[name] = self.temporary_identifier()
  455. # add check during runtime that dependencies used inside of executed
  456. # blocks are defined, as this step may be skipped during compile time
  457. self.writeline("try:")
  458. self.indent()
  459. self.writeline(f"{id_map[name]} = environment.{dependency}[{name!r}]")
  460. self.outdent()
  461. self.writeline("except KeyError:")
  462. self.indent()
  463. self.writeline("@internalcode")
  464. self.writeline(f"def {id_map[name]}(*unused):")
  465. self.indent()
  466. self.writeline(
  467. f'raise TemplateRuntimeError("No {dependency[:-1]}'
  468. f' named {name!r} found.")'
  469. )
  470. self.outdent()
  471. self.outdent()
  472. def enter_frame(self, frame: Frame) -> None:
  473. undefs = []
  474. for target, (action, param) in frame.symbols.loads.items():
  475. if action == VAR_LOAD_PARAMETER:
  476. pass
  477. elif action == VAR_LOAD_RESOLVE:
  478. self.writeline(f"{target} = {self.get_resolve_func()}({param!r})")
  479. elif action == VAR_LOAD_ALIAS:
  480. self.writeline(f"{target} = {param}")
  481. elif action == VAR_LOAD_UNDEFINED:
  482. undefs.append(target)
  483. else:
  484. raise NotImplementedError("unknown load instruction")
  485. if undefs:
  486. self.writeline(f"{' = '.join(undefs)} = missing")
  487. def leave_frame(self, frame: Frame, with_python_scope: bool = False) -> None:
  488. if not with_python_scope:
  489. undefs = []
  490. for target in frame.symbols.loads:
  491. undefs.append(target)
  492. if undefs:
  493. self.writeline(f"{' = '.join(undefs)} = missing")
  494. def choose_async(self, async_value: str = "async ", sync_value: str = "") -> str:
  495. return async_value if self.environment.is_async else sync_value
  496. def func(self, name: str) -> str:
  497. return f"{self.choose_async()}def {name}"
  498. def macro_body(
  499. self, node: t.Union[nodes.Macro, nodes.CallBlock], frame: Frame
  500. ) -> t.Tuple[Frame, MacroRef]:
  501. """Dump the function def of a macro or call block."""
  502. frame = frame.inner()
  503. frame.symbols.analyze_node(node)
  504. macro_ref = MacroRef(node)
  505. explicit_caller = None
  506. skip_special_params = set()
  507. args = []
  508. for idx, arg in enumerate(node.args):
  509. if arg.name == "caller":
  510. explicit_caller = idx
  511. if arg.name in ("kwargs", "varargs"):
  512. skip_special_params.add(arg.name)
  513. args.append(frame.symbols.ref(arg.name))
  514. undeclared = find_undeclared(node.body, ("caller", "kwargs", "varargs"))
  515. if "caller" in undeclared:
  516. # In older Jinja versions there was a bug that allowed caller
  517. # to retain the special behavior even if it was mentioned in
  518. # the argument list. However thankfully this was only really
  519. # working if it was the last argument. So we are explicitly
  520. # checking this now and error out if it is anywhere else in
  521. # the argument list.
  522. if explicit_caller is not None:
  523. try:
  524. node.defaults[explicit_caller - len(node.args)]
  525. except IndexError:
  526. self.fail(
  527. "When defining macros or call blocks the "
  528. 'special "caller" argument must be omitted '
  529. "or be given a default.",
  530. node.lineno,
  531. )
  532. else:
  533. args.append(frame.symbols.declare_parameter("caller"))
  534. macro_ref.accesses_caller = True
  535. if "kwargs" in undeclared and "kwargs" not in skip_special_params:
  536. args.append(frame.symbols.declare_parameter("kwargs"))
  537. macro_ref.accesses_kwargs = True
  538. if "varargs" in undeclared and "varargs" not in skip_special_params:
  539. args.append(frame.symbols.declare_parameter("varargs"))
  540. macro_ref.accesses_varargs = True
  541. # macros are delayed, they never require output checks
  542. frame.require_output_check = False
  543. frame.symbols.analyze_node(node)
  544. self.writeline(f"{self.func('macro')}({', '.join(args)}):", node)
  545. self.indent()
  546. self.buffer(frame)
  547. self.enter_frame(frame)
  548. self.push_parameter_definitions(frame)
  549. for idx, arg in enumerate(node.args):
  550. ref = frame.symbols.ref(arg.name)
  551. self.writeline(f"if {ref} is missing:")
  552. self.indent()
  553. try:
  554. default = node.defaults[idx - len(node.args)]
  555. except IndexError:
  556. self.writeline(
  557. f'{ref} = undefined("parameter {arg.name!r} was not provided",'
  558. f" name={arg.name!r})"
  559. )
  560. else:
  561. self.writeline(f"{ref} = ")
  562. self.visit(default, frame)
  563. self.mark_parameter_stored(ref)
  564. self.outdent()
  565. self.pop_parameter_definitions()
  566. self.blockvisit(node.body, frame)
  567. self.return_buffer_contents(frame, force_unescaped=True)
  568. self.leave_frame(frame, with_python_scope=True)
  569. self.outdent()
  570. return frame, macro_ref
  571. def macro_def(self, macro_ref: MacroRef, frame: Frame) -> None:
  572. """Dump the macro definition for the def created by macro_body."""
  573. arg_tuple = ", ".join(repr(x.name) for x in macro_ref.node.args)
  574. name = getattr(macro_ref.node, "name", None)
  575. if len(macro_ref.node.args) == 1:
  576. arg_tuple += ","
  577. self.write(
  578. f"Macro(environment, macro, {name!r}, ({arg_tuple}),"
  579. f" {macro_ref.accesses_kwargs!r}, {macro_ref.accesses_varargs!r},"
  580. f" {macro_ref.accesses_caller!r}, context.eval_ctx.autoescape)"
  581. )
  582. def position(self, node: nodes.Node) -> str:
  583. """Return a human readable position for the node."""
  584. rv = f"line {node.lineno}"
  585. if self.name is not None:
  586. rv = f"{rv} in {self.name!r}"
  587. return rv
  588. def dump_local_context(self, frame: Frame) -> str:
  589. items_kv = ", ".join(
  590. f"{name!r}: {target}"
  591. for name, target in frame.symbols.dump_stores().items()
  592. )
  593. return f"{{{items_kv}}}"
  594. def write_commons(self) -> None:
  595. """Writes a common preamble that is used by root and block functions.
  596. Primarily this sets up common local helpers and enforces a generator
  597. through a dead branch.
  598. """
  599. self.writeline("resolve = context.resolve_or_missing")
  600. self.writeline("undefined = environment.undefined")
  601. self.writeline("concat = environment.concat")
  602. # always use the standard Undefined class for the implicit else of
  603. # conditional expressions
  604. self.writeline("cond_expr_undefined = Undefined")
  605. self.writeline("if 0: yield None")
  606. def push_parameter_definitions(self, frame: Frame) -> None:
  607. """Pushes all parameter targets from the given frame into a local
  608. stack that permits tracking of yet to be assigned parameters. In
  609. particular this enables the optimization from `visit_Name` to skip
  610. undefined expressions for parameters in macros as macros can reference
  611. otherwise unbound parameters.
  612. """
  613. self._param_def_block.append(frame.symbols.dump_param_targets())
  614. def pop_parameter_definitions(self) -> None:
  615. """Pops the current parameter definitions set."""
  616. self._param_def_block.pop()
  617. def mark_parameter_stored(self, target: str) -> None:
  618. """Marks a parameter in the current parameter definitions as stored.
  619. This will skip the enforced undefined checks.
  620. """
  621. if self._param_def_block:
  622. self._param_def_block[-1].discard(target)
  623. def push_context_reference(self, target: str) -> None:
  624. self._context_reference_stack.append(target)
  625. def pop_context_reference(self) -> None:
  626. self._context_reference_stack.pop()
  627. def get_context_ref(self) -> str:
  628. return self._context_reference_stack[-1]
  629. def get_resolve_func(self) -> str:
  630. target = self._context_reference_stack[-1]
  631. if target == "context":
  632. return "resolve"
  633. return f"{target}.resolve"
  634. def derive_context(self, frame: Frame) -> str:
  635. return f"{self.get_context_ref()}.derived({self.dump_local_context(frame)})"
  636. def parameter_is_undeclared(self, target: str) -> bool:
  637. """Checks if a given target is an undeclared parameter."""
  638. if not self._param_def_block:
  639. return False
  640. return target in self._param_def_block[-1]
  641. def push_assign_tracking(self) -> None:
  642. """Pushes a new layer for assignment tracking."""
  643. self._assign_stack.append(set())
  644. def pop_assign_tracking(self, frame: Frame) -> None:
  645. """Pops the topmost level for assignment tracking and updates the
  646. context variables if necessary.
  647. """
  648. vars = self._assign_stack.pop()
  649. if (
  650. not frame.block_frame
  651. and not frame.loop_frame
  652. and not frame.toplevel
  653. or not vars
  654. ):
  655. return
  656. public_names = [x for x in vars if x[:1] != "_"]
  657. if len(vars) == 1:
  658. name = next(iter(vars))
  659. ref = frame.symbols.ref(name)
  660. if frame.loop_frame:
  661. self.writeline(f"_loop_vars[{name!r}] = {ref}")
  662. return
  663. if frame.block_frame:
  664. self.writeline(f"_block_vars[{name!r}] = {ref}")
  665. return
  666. self.writeline(f"context.vars[{name!r}] = {ref}")
  667. else:
  668. if frame.loop_frame:
  669. self.writeline("_loop_vars.update({")
  670. elif frame.block_frame:
  671. self.writeline("_block_vars.update({")
  672. else:
  673. self.writeline("context.vars.update({")
  674. for idx, name in enumerate(vars):
  675. if idx:
  676. self.write(", ")
  677. ref = frame.symbols.ref(name)
  678. self.write(f"{name!r}: {ref}")
  679. self.write("})")
  680. if not frame.block_frame and not frame.loop_frame and public_names:
  681. if len(public_names) == 1:
  682. self.writeline(f"context.exported_vars.add({public_names[0]!r})")
  683. else:
  684. names_str = ", ".join(map(repr, public_names))
  685. self.writeline(f"context.exported_vars.update(({names_str}))")
  686. # -- Statement Visitors
  687. def visit_Template(
  688. self, node: nodes.Template, frame: t.Optional[Frame] = None
  689. ) -> None:
  690. assert frame is None, "no root frame allowed"
  691. eval_ctx = EvalContext(self.environment, self.name)
  692. from .runtime import async_exported
  693. from .runtime import exported
  694. if self.environment.is_async:
  695. exported_names = sorted(exported + async_exported)
  696. else:
  697. exported_names = sorted(exported)
  698. self.writeline("from jinja2.runtime import " + ", ".join(exported_names))
  699. # if we want a deferred initialization we cannot move the
  700. # environment into a local name
  701. envenv = "" if self.defer_init else ", environment=environment"
  702. # do we have an extends tag at all? If not, we can save some
  703. # overhead by just not processing any inheritance code.
  704. have_extends = node.find(nodes.Extends) is not None
  705. # find all blocks
  706. for block in node.find_all(nodes.Block):
  707. if block.name in self.blocks:
  708. self.fail(f"block {block.name!r} defined twice", block.lineno)
  709. self.blocks[block.name] = block
  710. # find all imports and import them
  711. for import_ in node.find_all(nodes.ImportedName):
  712. if import_.importname not in self.import_aliases:
  713. imp = import_.importname
  714. self.import_aliases[imp] = alias = self.temporary_identifier()
  715. if "." in imp:
  716. module, obj = imp.rsplit(".", 1)
  717. self.writeline(f"from {module} import {obj} as {alias}")
  718. else:
  719. self.writeline(f"import {imp} as {alias}")
  720. # add the load name
  721. self.writeline(f"name = {self.name!r}")
  722. # generate the root render function.
  723. self.writeline(
  724. f"{self.func('root')}(context, missing=missing{envenv}):", extra=1
  725. )
  726. self.indent()
  727. self.write_commons()
  728. # process the root
  729. frame = Frame(eval_ctx)
  730. if "self" in find_undeclared(node.body, ("self",)):
  731. ref = frame.symbols.declare_parameter("self")
  732. self.writeline(f"{ref} = TemplateReference(context)")
  733. frame.symbols.analyze_node(node)
  734. frame.toplevel = frame.rootlevel = True
  735. frame.require_output_check = have_extends and not self.has_known_extends
  736. if have_extends:
  737. self.writeline("parent_template = None")
  738. self.enter_frame(frame)
  739. self.pull_dependencies(node.body)
  740. self.blockvisit(node.body, frame)
  741. self.leave_frame(frame, with_python_scope=True)
  742. self.outdent()
  743. # make sure that the parent root is called.
  744. if have_extends:
  745. if not self.has_known_extends:
  746. self.indent()
  747. self.writeline("if parent_template is not None:")
  748. self.indent()
  749. if not self.environment.is_async:
  750. self.writeline("yield from parent_template.root_render_func(context)")
  751. else:
  752. self.writeline(
  753. "async for event in parent_template.root_render_func(context):"
  754. )
  755. self.indent()
  756. self.writeline("yield event")
  757. self.outdent()
  758. self.outdent(1 + (not self.has_known_extends))
  759. # at this point we now have the blocks collected and can visit them too.
  760. for name, block in self.blocks.items():
  761. self.writeline(
  762. f"{self.func('block_' + name)}(context, missing=missing{envenv}):",
  763. block,
  764. 1,
  765. )
  766. self.indent()
  767. self.write_commons()
  768. # It's important that we do not make this frame a child of the
  769. # toplevel template. This would cause a variety of
  770. # interesting issues with identifier tracking.
  771. block_frame = Frame(eval_ctx)
  772. block_frame.block_frame = True
  773. undeclared = find_undeclared(block.body, ("self", "super"))
  774. if "self" in undeclared:
  775. ref = block_frame.symbols.declare_parameter("self")
  776. self.writeline(f"{ref} = TemplateReference(context)")
  777. if "super" in undeclared:
  778. ref = block_frame.symbols.declare_parameter("super")
  779. self.writeline(f"{ref} = context.super({name!r}, block_{name})")
  780. block_frame.symbols.analyze_node(block)
  781. block_frame.block = name
  782. self.writeline("_block_vars = {}")
  783. self.enter_frame(block_frame)
  784. self.pull_dependencies(block.body)
  785. self.blockvisit(block.body, block_frame)
  786. self.leave_frame(block_frame, with_python_scope=True)
  787. self.outdent()
  788. blocks_kv_str = ", ".join(f"{x!r}: block_{x}" for x in self.blocks)
  789. self.writeline(f"blocks = {{{blocks_kv_str}}}", extra=1)
  790. debug_kv_str = "&".join(f"{k}={v}" for k, v in self.debug_info)
  791. self.writeline(f"debug_info = {debug_kv_str!r}")
  792. def visit_Block(self, node: nodes.Block, frame: Frame) -> None:
  793. """Call a block and register it for the template."""
  794. level = 0
  795. if frame.toplevel:
  796. # if we know that we are a child template, there is no need to
  797. # check if we are one
  798. if self.has_known_extends:
  799. return
  800. if self.extends_so_far > 0:
  801. self.writeline("if parent_template is None:")
  802. self.indent()
  803. level += 1
  804. if node.scoped:
  805. context = self.derive_context(frame)
  806. else:
  807. context = self.get_context_ref()
  808. if node.required:
  809. self.writeline(f"if len(context.blocks[{node.name!r}]) <= 1:", node)
  810. self.indent()
  811. self.writeline(
  812. f'raise TemplateRuntimeError("Required block {node.name!r} not found")',
  813. node,
  814. )
  815. self.outdent()
  816. if not self.environment.is_async and frame.buffer is None:
  817. self.writeline(
  818. f"yield from context.blocks[{node.name!r}][0]({context})", node
  819. )
  820. else:
  821. self.writeline(
  822. f"{self.choose_async()}for event in"
  823. f" context.blocks[{node.name!r}][0]({context}):",
  824. node,
  825. )
  826. self.indent()
  827. self.simple_write("event", frame)
  828. self.outdent()
  829. self.outdent(level)
  830. def visit_Extends(self, node: nodes.Extends, frame: Frame) -> None:
  831. """Calls the extender."""
  832. if not frame.toplevel:
  833. self.fail("cannot use extend from a non top-level scope", node.lineno)
  834. # if the number of extends statements in general is zero so
  835. # far, we don't have to add a check if something extended
  836. # the template before this one.
  837. if self.extends_so_far > 0:
  838. # if we have a known extends we just add a template runtime
  839. # error into the generated code. We could catch that at compile
  840. # time too, but i welcome it not to confuse users by throwing the
  841. # same error at different times just "because we can".
  842. if not self.has_known_extends:
  843. self.writeline("if parent_template is not None:")
  844. self.indent()
  845. self.writeline('raise TemplateRuntimeError("extended multiple times")')
  846. # if we have a known extends already we don't need that code here
  847. # as we know that the template execution will end here.
  848. if self.has_known_extends:
  849. raise CompilerExit()
  850. else:
  851. self.outdent()
  852. self.writeline("parent_template = environment.get_template(", node)
  853. self.visit(node.template, frame)
  854. self.write(f", {self.name!r})")
  855. self.writeline("for name, parent_block in parent_template.blocks.items():")
  856. self.indent()
  857. self.writeline("context.blocks.setdefault(name, []).append(parent_block)")
  858. self.outdent()
  859. # if this extends statement was in the root level we can take
  860. # advantage of that information and simplify the generated code
  861. # in the top level from this point onwards
  862. if frame.rootlevel:
  863. self.has_known_extends = True
  864. # and now we have one more
  865. self.extends_so_far += 1
  866. def visit_Include(self, node: nodes.Include, frame: Frame) -> None:
  867. """Handles includes."""
  868. if node.ignore_missing:
  869. self.writeline("try:")
  870. self.indent()
  871. func_name = "get_or_select_template"
  872. if isinstance(node.template, nodes.Const):
  873. if isinstance(node.template.value, str):
  874. func_name = "get_template"
  875. elif isinstance(node.template.value, (tuple, list)):
  876. func_name = "select_template"
  877. elif isinstance(node.template, (nodes.Tuple, nodes.List)):
  878. func_name = "select_template"
  879. self.writeline(f"template = environment.{func_name}(", node)
  880. self.visit(node.template, frame)
  881. self.write(f", {self.name!r})")
  882. if node.ignore_missing:
  883. self.outdent()
  884. self.writeline("except TemplateNotFound:")
  885. self.indent()
  886. self.writeline("pass")
  887. self.outdent()
  888. self.writeline("else:")
  889. self.indent()
  890. skip_event_yield = False
  891. if node.with_context:
  892. self.writeline(
  893. f"{self.choose_async()}for event in template.root_render_func("
  894. "template.new_context(context.get_all(), True,"
  895. f" {self.dump_local_context(frame)})):"
  896. )
  897. elif self.environment.is_async:
  898. self.writeline(
  899. "for event in (await template._get_default_module_async())"
  900. "._body_stream:"
  901. )
  902. else:
  903. self.writeline("yield from template._get_default_module()._body_stream")
  904. skip_event_yield = True
  905. if not skip_event_yield:
  906. self.indent()
  907. self.simple_write("event", frame)
  908. self.outdent()
  909. if node.ignore_missing:
  910. self.outdent()
  911. def _import_common(
  912. self, node: t.Union[nodes.Import, nodes.FromImport], frame: Frame
  913. ) -> None:
  914. self.write(f"{self.choose_async('await ')}environment.get_template(")
  915. self.visit(node.template, frame)
  916. self.write(f", {self.name!r}).")
  917. if node.with_context:
  918. f_name = f"make_module{self.choose_async('_async')}"
  919. self.write(
  920. f"{f_name}(context.get_all(), True, {self.dump_local_context(frame)})"
  921. )
  922. else:
  923. self.write(f"_get_default_module{self.choose_async('_async')}(context)")
  924. def visit_Import(self, node: nodes.Import, frame: Frame) -> None:
  925. """Visit regular imports."""
  926. self.writeline(f"{frame.symbols.ref(node.target)} = ", node)
  927. if frame.toplevel:
  928. self.write(f"context.vars[{node.target!r}] = ")
  929. self._import_common(node, frame)
  930. if frame.toplevel and not node.target.startswith("_"):
  931. self.writeline(f"context.exported_vars.discard({node.target!r})")
  932. def visit_FromImport(self, node: nodes.FromImport, frame: Frame) -> None:
  933. """Visit named imports."""
  934. self.newline(node)
  935. self.write("included_template = ")
  936. self._import_common(node, frame)
  937. var_names = []
  938. discarded_names = []
  939. for name in node.names:
  940. if isinstance(name, tuple):
  941. name, alias = name
  942. else:
  943. alias = name
  944. self.writeline(
  945. f"{frame.symbols.ref(alias)} ="
  946. f" getattr(included_template, {name!r}, missing)"
  947. )
  948. self.writeline(f"if {frame.symbols.ref(alias)} is missing:")
  949. self.indent()
  950. message = (
  951. "the template {included_template.__name__!r}"
  952. f" (imported on {self.position(node)})"
  953. f" does not export the requested name {name!r}"
  954. )
  955. self.writeline(
  956. f"{frame.symbols.ref(alias)} = undefined(f{message!r}, name={name!r})"
  957. )
  958. self.outdent()
  959. if frame.toplevel:
  960. var_names.append(alias)
  961. if not alias.startswith("_"):
  962. discarded_names.append(alias)
  963. if var_names:
  964. if len(var_names) == 1:
  965. name = var_names[0]
  966. self.writeline(f"context.vars[{name!r}] = {frame.symbols.ref(name)}")
  967. else:
  968. names_kv = ", ".join(
  969. f"{name!r}: {frame.symbols.ref(name)}" for name in var_names
  970. )
  971. self.writeline(f"context.vars.update({{{names_kv}}})")
  972. if discarded_names:
  973. if len(discarded_names) == 1:
  974. self.writeline(f"context.exported_vars.discard({discarded_names[0]!r})")
  975. else:
  976. names_str = ", ".join(map(repr, discarded_names))
  977. self.writeline(
  978. f"context.exported_vars.difference_update(({names_str}))"
  979. )
  980. def visit_For(self, node: nodes.For, frame: Frame) -> None:
  981. loop_frame = frame.inner()
  982. loop_frame.loop_frame = True
  983. test_frame = frame.inner()
  984. else_frame = frame.inner()
  985. # try to figure out if we have an extended loop. An extended loop
  986. # is necessary if the loop is in recursive mode if the special loop
  987. # variable is accessed in the body if the body is a scoped block.
  988. extended_loop = (
  989. node.recursive
  990. or "loop"
  991. in find_undeclared(node.iter_child_nodes(only=("body",)), ("loop",))
  992. or any(block.scoped for block in node.find_all(nodes.Block))
  993. )
  994. loop_ref = None
  995. if extended_loop:
  996. loop_ref = loop_frame.symbols.declare_parameter("loop")
  997. loop_frame.symbols.analyze_node(node, for_branch="body")
  998. if node.else_:
  999. else_frame.symbols.analyze_node(node, for_branch="else")
  1000. if node.test:
  1001. loop_filter_func = self.temporary_identifier()
  1002. test_frame.symbols.analyze_node(node, for_branch="test")
  1003. self.writeline(f"{self.func(loop_filter_func)}(fiter):", node.test)
  1004. self.indent()
  1005. self.enter_frame(test_frame)
  1006. self.writeline(self.choose_async("async for ", "for "))
  1007. self.visit(node.target, loop_frame)
  1008. self.write(" in ")
  1009. self.write(self.choose_async("auto_aiter(fiter)", "fiter"))
  1010. self.write(":")
  1011. self.indent()
  1012. self.writeline("if ", node.test)
  1013. self.visit(node.test, test_frame)
  1014. self.write(":")
  1015. self.indent()
  1016. self.writeline("yield ")
  1017. self.visit(node.target, loop_frame)
  1018. self.outdent(3)
  1019. self.leave_frame(test_frame, with_python_scope=True)
  1020. # if we don't have an recursive loop we have to find the shadowed
  1021. # variables at that point. Because loops can be nested but the loop
  1022. # variable is a special one we have to enforce aliasing for it.
  1023. if node.recursive:
  1024. self.writeline(
  1025. f"{self.func('loop')}(reciter, loop_render_func, depth=0):", node
  1026. )
  1027. self.indent()
  1028. self.buffer(loop_frame)
  1029. # Use the same buffer for the else frame
  1030. else_frame.buffer = loop_frame.buffer
  1031. # make sure the loop variable is a special one and raise a template
  1032. # assertion error if a loop tries to write to loop
  1033. if extended_loop:
  1034. self.writeline(f"{loop_ref} = missing")
  1035. for name in node.find_all(nodes.Name):
  1036. if name.ctx == "store" and name.name == "loop":
  1037. self.fail(
  1038. "Can't assign to special loop variable in for-loop target",
  1039. name.lineno,
  1040. )
  1041. if node.else_:
  1042. iteration_indicator = self.temporary_identifier()
  1043. self.writeline(f"{iteration_indicator} = 1")
  1044. self.writeline(self.choose_async("async for ", "for "), node)
  1045. self.visit(node.target, loop_frame)
  1046. if extended_loop:
  1047. self.write(f", {loop_ref} in {self.choose_async('Async')}LoopContext(")
  1048. else:
  1049. self.write(" in ")
  1050. if node.test:
  1051. self.write(f"{loop_filter_func}(")
  1052. if node.recursive:
  1053. self.write("reciter")
  1054. else:
  1055. if self.environment.is_async and not extended_loop:
  1056. self.write("auto_aiter(")
  1057. self.visit(node.iter, frame)
  1058. if self.environment.is_async and not extended_loop:
  1059. self.write(")")
  1060. if node.test:
  1061. self.write(")")
  1062. if node.recursive:
  1063. self.write(", undefined, loop_render_func, depth):")
  1064. else:
  1065. self.write(", undefined):" if extended_loop else ":")
  1066. self.indent()
  1067. self.enter_frame(loop_frame)
  1068. self.writeline("_loop_vars = {}")
  1069. self.blockvisit(node.body, loop_frame)
  1070. if node.else_:
  1071. self.writeline(f"{iteration_indicator} = 0")
  1072. self.outdent()
  1073. self.leave_frame(
  1074. loop_frame, with_python_scope=node.recursive and not node.else_
  1075. )
  1076. if node.else_:
  1077. self.writeline(f"if {iteration_indicator}:")
  1078. self.indent()
  1079. self.enter_frame(else_frame)
  1080. self.blockvisit(node.else_, else_frame)
  1081. self.leave_frame(else_frame)
  1082. self.outdent()
  1083. # if the node was recursive we have to return the buffer contents
  1084. # and start the iteration code
  1085. if node.recursive:
  1086. self.return_buffer_contents(loop_frame)
  1087. self.outdent()
  1088. self.start_write(frame, node)
  1089. self.write(f"{self.choose_async('await ')}loop(")
  1090. if self.environment.is_async:
  1091. self.write("auto_aiter(")
  1092. self.visit(node.iter, frame)
  1093. if self.environment.is_async:
  1094. self.write(")")
  1095. self.write(", loop)")
  1096. self.end_write(frame)
  1097. # at the end of the iteration, clear any assignments made in the
  1098. # loop from the top level
  1099. if self._assign_stack:
  1100. self._assign_stack[-1].difference_update(loop_frame.symbols.stores)
  1101. def visit_If(self, node: nodes.If, frame: Frame) -> None:
  1102. if_frame = frame.soft()
  1103. self.writeline("if ", node)
  1104. self.visit(node.test, if_frame)
  1105. self.write(":")
  1106. self.indent()
  1107. self.blockvisit(node.body, if_frame)
  1108. self.outdent()
  1109. for elif_ in node.elif_:
  1110. self.writeline("elif ", elif_)
  1111. self.visit(elif_.test, if_frame)
  1112. self.write(":")
  1113. self.indent()
  1114. self.blockvisit(elif_.body, if_frame)
  1115. self.outdent()
  1116. if node.else_:
  1117. self.writeline("else:")
  1118. self.indent()
  1119. self.blockvisit(node.else_, if_frame)
  1120. self.outdent()
  1121. def visit_Macro(self, node: nodes.Macro, frame: Frame) -> None:
  1122. macro_frame, macro_ref = self.macro_body(node, frame)
  1123. self.newline()
  1124. if frame.toplevel:
  1125. if not node.name.startswith("_"):
  1126. self.write(f"context.exported_vars.add({node.name!r})")
  1127. self.writeline(f"context.vars[{node.name!r}] = ")
  1128. self.write(f"{frame.symbols.ref(node.name)} = ")
  1129. self.macro_def(macro_ref, macro_frame)
  1130. def visit_CallBlock(self, node: nodes.CallBlock, frame: Frame) -> None:
  1131. call_frame, macro_ref = self.macro_body(node, frame)
  1132. self.writeline("caller = ")
  1133. self.macro_def(macro_ref, call_frame)
  1134. self.start_write(frame, node)
  1135. self.visit_Call(node.call, frame, forward_caller=True)
  1136. self.end_write(frame)
  1137. def visit_FilterBlock(self, node: nodes.FilterBlock, frame: Frame) -> None:
  1138. filter_frame = frame.inner()
  1139. filter_frame.symbols.analyze_node(node)
  1140. self.enter_frame(filter_frame)
  1141. self.buffer(filter_frame)
  1142. self.blockvisit(node.body, filter_frame)
  1143. self.start_write(frame, node)
  1144. self.visit_Filter(node.filter, filter_frame)
  1145. self.end_write(frame)
  1146. self.leave_frame(filter_frame)
  1147. def visit_With(self, node: nodes.With, frame: Frame) -> None:
  1148. with_frame = frame.inner()
  1149. with_frame.symbols.analyze_node(node)
  1150. self.enter_frame(with_frame)
  1151. for target, expr in zip(node.targets, node.values):
  1152. self.newline()
  1153. self.visit(target, with_frame)
  1154. self.write(" = ")
  1155. self.visit(expr, frame)
  1156. self.blockvisit(node.body, with_frame)
  1157. self.leave_frame(with_frame)
  1158. def visit_ExprStmt(self, node: nodes.ExprStmt, frame: Frame) -> None:
  1159. self.newline(node)
  1160. self.visit(node.node, frame)
  1161. class _FinalizeInfo(t.NamedTuple):
  1162. const: t.Optional[t.Callable[..., str]]
  1163. src: t.Optional[str]
  1164. @staticmethod
  1165. def _default_finalize(value: t.Any) -> t.Any:
  1166. """The default finalize function if the environment isn't
  1167. configured with one. Or, if the environment has one, this is
  1168. called on that function's output for constants.
  1169. """
  1170. return str(value)
  1171. _finalize: t.Optional[_FinalizeInfo] = None
  1172. def _make_finalize(self) -> _FinalizeInfo:
  1173. """Build the finalize function to be used on constants and at
  1174. runtime. Cached so it's only created once for all output nodes.
  1175. Returns a ``namedtuple`` with the following attributes:
  1176. ``const``
  1177. A function to finalize constant data at compile time.
  1178. ``src``
  1179. Source code to output around nodes to be evaluated at
  1180. runtime.
  1181. """
  1182. if self._finalize is not None:
  1183. return self._finalize
  1184. finalize: t.Optional[t.Callable[..., t.Any]]
  1185. finalize = default = self._default_finalize
  1186. src = None
  1187. if self.environment.finalize:
  1188. src = "environment.finalize("
  1189. env_finalize = self.environment.finalize
  1190. pass_arg = {
  1191. _PassArg.context: "context",
  1192. _PassArg.eval_context: "context.eval_ctx",
  1193. _PassArg.environment: "environment",
  1194. }.get(
  1195. _PassArg.from_obj(env_finalize) # type: ignore
  1196. )
  1197. finalize = None
  1198. if pass_arg is None:
  1199. def finalize(value: t.Any) -> t.Any: # noqa: F811
  1200. return default(env_finalize(value))
  1201. else:
  1202. src = f"{src}{pass_arg}, "
  1203. if pass_arg == "environment":
  1204. def finalize(value: t.Any) -> t.Any: # noqa: F811
  1205. return default(env_finalize(self.environment, value))
  1206. self._finalize = self._FinalizeInfo(finalize, src)
  1207. return self._finalize
  1208. def _output_const_repr(self, group: t.Iterable[t.Any]) -> str:
  1209. """Given a group of constant values converted from ``Output``
  1210. child nodes, produce a string to write to the template module
  1211. source.
  1212. """
  1213. return repr(concat(group))
  1214. def _output_child_to_const(
  1215. self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo
  1216. ) -> str:
  1217. """Try to optimize a child of an ``Output`` node by trying to
  1218. convert it to constant, finalized data at compile time.
  1219. If :exc:`Impossible` is raised, the node is not constant and
  1220. will be evaluated at runtime. Any other exception will also be
  1221. evaluated at runtime for easier debugging.
  1222. """
  1223. const = node.as_const(frame.eval_ctx)
  1224. if frame.eval_ctx.autoescape:
  1225. const = escape(const)
  1226. # Template data doesn't go through finalize.
  1227. if isinstance(node, nodes.TemplateData):
  1228. return str(const)
  1229. return finalize.const(const) # type: ignore
  1230. def _output_child_pre(
  1231. self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo
  1232. ) -> None:
  1233. """Output extra source code before visiting a child of an
  1234. ``Output`` node.
  1235. """
  1236. if frame.eval_ctx.volatile:
  1237. self.write("(escape if context.eval_ctx.autoescape else str)(")
  1238. elif frame.eval_ctx.autoescape:
  1239. self.write("escape(")
  1240. else:
  1241. self.write("str(")
  1242. if finalize.src is not None:
  1243. self.write(finalize.src)
  1244. def _output_child_post(
  1245. self, node: nodes.Expr, frame: Frame, finalize: _FinalizeInfo
  1246. ) -> None:
  1247. """Output extra source code after visiting a child of an
  1248. ``Output`` node.
  1249. """
  1250. self.write(")")
  1251. if finalize.src is not None:
  1252. self.write(")")
  1253. def visit_Output(self, node: nodes.Output, frame: Frame) -> None:
  1254. # If an extends is active, don't render outside a block.
  1255. if frame.require_output_check:
  1256. # A top-level extends is known to exist at compile time.
  1257. if self.has_known_extends:
  1258. return
  1259. self.writeline("if parent_template is None:")
  1260. self.indent()
  1261. finalize = self._make_finalize()
  1262. body: t.List[t.Union[t.List[t.Any], nodes.Expr]] = []
  1263. # Evaluate constants at compile time if possible. Each item in
  1264. # body will be either a list of static data or a node to be
  1265. # evaluated at runtime.
  1266. for child in node.nodes:
  1267. try:
  1268. if not (
  1269. # If the finalize function requires runtime context,
  1270. # constants can't be evaluated at compile time.
  1271. finalize.const
  1272. # Unless it's basic template data that won't be
  1273. # finalized anyway.
  1274. or isinstance(child, nodes.TemplateData)
  1275. ):
  1276. raise nodes.Impossible()
  1277. const = self._output_child_to_const(child, frame, finalize)
  1278. except (nodes.Impossible, Exception):
  1279. # The node was not constant and needs to be evaluated at
  1280. # runtime. Or another error was raised, which is easier
  1281. # to debug at runtime.
  1282. body.append(child)
  1283. continue
  1284. if body and isinstance(body[-1], list):
  1285. body[-1].append(const)
  1286. else:
  1287. body.append([const])
  1288. if frame.buffer is not None:
  1289. if len(body) == 1:
  1290. self.writeline(f"{frame.buffer}.append(")
  1291. else:
  1292. self.writeline(f"{frame.buffer}.extend((")
  1293. self.indent()
  1294. for item in body:
  1295. if isinstance(item, list):
  1296. # A group of constant data to join and output.
  1297. val = self._output_const_repr(item)
  1298. if frame.buffer is None:
  1299. self.writeline("yield " + val)
  1300. else:
  1301. self.writeline(val + ",")
  1302. else:
  1303. if frame.buffer is None:
  1304. self.writeline("yield ", item)
  1305. else:
  1306. self.newline(item)
  1307. # A node to be evaluated at runtime.
  1308. self._output_child_pre(item, frame, finalize)
  1309. self.visit(item, frame)
  1310. self._output_child_post(item, frame, finalize)
  1311. if frame.buffer is not None:
  1312. self.write(",")
  1313. if frame.buffer is not None:
  1314. self.outdent()
  1315. self.writeline(")" if len(body) == 1 else "))")
  1316. if frame.require_output_check:
  1317. self.outdent()
  1318. def visit_Assign(self, node: nodes.Assign, frame: Frame) -> None:
  1319. self.push_assign_tracking()
  1320. self.newline(node)
  1321. self.visit(node.target, frame)
  1322. self.write(" = ")
  1323. self.visit(node.node, frame)
  1324. self.pop_assign_tracking(frame)
  1325. def visit_AssignBlock(self, node: nodes.AssignBlock, frame: Frame) -> None:
  1326. self.push_assign_tracking()
  1327. block_frame = frame.inner()
  1328. # This is a special case. Since a set block always captures we
  1329. # will disable output checks. This way one can use set blocks
  1330. # toplevel even in extended templates.
  1331. block_frame.require_output_check = False
  1332. block_frame.symbols.analyze_node(node)
  1333. self.enter_frame(block_frame)
  1334. self.buffer(block_frame)
  1335. self.blockvisit(node.body, block_frame)
  1336. self.newline(node)
  1337. self.visit(node.target, frame)
  1338. self.write(" = (Markup if context.eval_ctx.autoescape else identity)(")
  1339. if node.filter is not None:
  1340. self.visit_Filter(node.filter, block_frame)
  1341. else:
  1342. self.write(f"concat({block_frame.buffer})")
  1343. self.write(")")
  1344. self.pop_assign_tracking(frame)
  1345. self.leave_frame(block_frame)
  1346. # -- Expression Visitors
  1347. def visit_Name(self, node: nodes.Name, frame: Frame) -> None:
  1348. if node.ctx == "store" and (
  1349. frame.toplevel or frame.loop_frame or frame.block_frame
  1350. ):
  1351. if self._assign_stack:
  1352. self._assign_stack[-1].add(node.name)
  1353. ref = frame.symbols.ref(node.name)
  1354. # If we are looking up a variable we might have to deal with the
  1355. # case where it's undefined. We can skip that case if the load
  1356. # instruction indicates a parameter which are always defined.
  1357. if node.ctx == "load":
  1358. load = frame.symbols.find_load(ref)
  1359. if not (
  1360. load is not None
  1361. and load[0] == VAR_LOAD_PARAMETER
  1362. and not self.parameter_is_undeclared(ref)
  1363. ):
  1364. self.write(
  1365. f"(undefined(name={node.name!r}) if {ref} is missing else {ref})"
  1366. )
  1367. return
  1368. self.write(ref)
  1369. def visit_NSRef(self, node: nodes.NSRef, frame: Frame) -> None:
  1370. # NSRefs can only be used to store values; since they use the normal
  1371. # `foo.bar` notation they will be parsed as a normal attribute access
  1372. # when used anywhere but in a `set` context
  1373. ref = frame.symbols.ref(node.name)
  1374. self.writeline(f"if not isinstance({ref}, Namespace):")
  1375. self.indent()
  1376. self.writeline(
  1377. "raise TemplateRuntimeError"
  1378. '("cannot assign attribute on non-namespace object")'
  1379. )
  1380. self.outdent()
  1381. self.writeline(f"{ref}[{node.attr!r}]")
  1382. def visit_Const(self, node: nodes.Const, frame: Frame) -> None:
  1383. val = node.as_const(frame.eval_ctx)
  1384. if isinstance(val, float):
  1385. self.write(str(val))
  1386. else:
  1387. self.write(repr(val))
  1388. def visit_TemplateData(self, node: nodes.TemplateData, frame: Frame) -> None:
  1389. try:
  1390. self.write(repr(node.as_const(frame.eval_ctx)))
  1391. except nodes.Impossible:
  1392. self.write(
  1393. f"(Markup if context.eval_ctx.autoescape else identity)({node.data!r})"
  1394. )
  1395. def visit_Tuple(self, node: nodes.Tuple, frame: Frame) -> None:
  1396. self.write("(")
  1397. idx = -1
  1398. for idx, item in enumerate(node.items):
  1399. if idx:
  1400. self.write(", ")
  1401. self.visit(item, frame)
  1402. self.write(",)" if idx == 0 else ")")
  1403. def visit_List(self, node: nodes.List, frame: Frame) -> None:
  1404. self.write("[")
  1405. for idx, item in enumerate(node.items):
  1406. if idx:
  1407. self.write(", ")
  1408. self.visit(item, frame)
  1409. self.write("]")
  1410. def visit_Dict(self, node: nodes.Dict, frame: Frame) -> None:
  1411. self.write("{")
  1412. for idx, item in enumerate(node.items):
  1413. if idx:
  1414. self.write(", ")
  1415. self.visit(item.key, frame)
  1416. self.write(": ")
  1417. self.visit(item.value, frame)
  1418. self.write("}")
  1419. visit_Add = _make_binop("+")
  1420. visit_Sub = _make_binop("-")
  1421. visit_Mul = _make_binop("*")
  1422. visit_Div = _make_binop("/")
  1423. visit_FloorDiv = _make_binop("//")
  1424. visit_Pow = _make_binop("**")
  1425. visit_Mod = _make_binop("%")
  1426. visit_And = _make_binop("and")
  1427. visit_Or = _make_binop("or")
  1428. visit_Pos = _make_unop("+")
  1429. visit_Neg = _make_unop("-")
  1430. visit_Not = _make_unop("not ")
  1431. @optimizeconst
  1432. def visit_Concat(self, node: nodes.Concat, frame: Frame) -> None:
  1433. if frame.eval_ctx.volatile:
  1434. func_name = "(markup_join if context.eval_ctx.volatile else str_join)"
  1435. elif frame.eval_ctx.autoescape:
  1436. func_name = "markup_join"
  1437. else:
  1438. func_name = "str_join"
  1439. self.write(f"{func_name}((")
  1440. for arg in node.nodes:
  1441. self.visit(arg, frame)
  1442. self.write(", ")
  1443. self.write("))")
  1444. @optimizeconst
  1445. def visit_Compare(self, node: nodes.Compare, frame: Frame) -> None:
  1446. self.write("(")
  1447. self.visit(node.expr, frame)
  1448. for op in node.ops:
  1449. self.visit(op, frame)
  1450. self.write(")")
  1451. def visit_Operand(self, node: nodes.Operand, frame: Frame) -> None:
  1452. self.write(f" {operators[node.op]} ")
  1453. self.visit(node.expr, frame)
  1454. @optimizeconst
  1455. def visit_Getattr(self, node: nodes.Getattr, frame: Frame) -> None:
  1456. if self.environment.is_async:
  1457. self.write("(await auto_await(")
  1458. self.write("environment.getattr(")
  1459. self.visit(node.node, frame)
  1460. self.write(f", {node.attr!r})")
  1461. if self.environment.is_async:
  1462. self.write("))")
  1463. @optimizeconst
  1464. def visit_Getitem(self, node: nodes.Getitem, frame: Frame) -> None:
  1465. # slices bypass the environment getitem method.
  1466. if isinstance(node.arg, nodes.Slice):
  1467. self.visit(node.node, frame)
  1468. self.write("[")
  1469. self.visit(node.arg, frame)
  1470. self.write("]")
  1471. else:
  1472. if self.environment.is_async:
  1473. self.write("(await auto_await(")
  1474. self.write("environment.getitem(")
  1475. self.visit(node.node, frame)
  1476. self.write(", ")
  1477. self.visit(node.arg, frame)
  1478. self.write(")")
  1479. if self.environment.is_async:
  1480. self.write("))")
  1481. def visit_Slice(self, node: nodes.Slice, frame: Frame) -> None:
  1482. if node.start is not None:
  1483. self.visit(node.start, frame)
  1484. self.write(":")
  1485. if node.stop is not None:
  1486. self.visit(node.stop, frame)
  1487. if node.step is not None:
  1488. self.write(":")
  1489. self.visit(node.step, frame)
  1490. @contextmanager
  1491. def _filter_test_common(
  1492. self, node: t.Union[nodes.Filter, nodes.Test], frame: Frame, is_filter: bool
  1493. ) -> t.Iterator[None]:
  1494. if self.environment.is_async:
  1495. self.write("(await auto_await(")
  1496. if is_filter:
  1497. self.write(f"{self.filters[node.name]}(")
  1498. func = self.environment.filters.get(node.name)
  1499. else:
  1500. self.write(f"{self.tests[node.name]}(")
  1501. func = self.environment.tests.get(node.name)
  1502. # When inside an If or CondExpr frame, allow the filter to be
  1503. # undefined at compile time and only raise an error if it's
  1504. # actually called at runtime. See pull_dependencies.
  1505. if func is None and not frame.soft_frame:
  1506. type_name = "filter" if is_filter else "test"
  1507. self.fail(f"No {type_name} named {node.name!r}.", node.lineno)
  1508. pass_arg = {
  1509. _PassArg.context: "context",
  1510. _PassArg.eval_context: "context.eval_ctx",
  1511. _PassArg.environment: "environment",
  1512. }.get(
  1513. _PassArg.from_obj(func) # type: ignore
  1514. )
  1515. if pass_arg is not None:
  1516. self.write(f"{pass_arg}, ")
  1517. # Back to the visitor function to handle visiting the target of
  1518. # the filter or test.
  1519. yield
  1520. self.signature(node, frame)
  1521. self.write(")")
  1522. if self.environment.is_async:
  1523. self.write("))")
  1524. @optimizeconst
  1525. def visit_Filter(self, node: nodes.Filter, frame: Frame) -> None:
  1526. with self._filter_test_common(node, frame, True):
  1527. # if the filter node is None we are inside a filter block
  1528. # and want to write to the current buffer
  1529. if node.node is not None:
  1530. self.visit(node.node, frame)
  1531. elif frame.eval_ctx.volatile:
  1532. self.write(
  1533. f"(Markup(concat({frame.buffer}))"
  1534. f" if context.eval_ctx.autoescape else concat({frame.buffer}))"
  1535. )
  1536. elif frame.eval_ctx.autoescape:
  1537. self.write(f"Markup(concat({frame.buffer}))")
  1538. else:
  1539. self.write(f"concat({frame.buffer})")
  1540. @optimizeconst
  1541. def visit_Test(self, node: nodes.Test, frame: Frame) -> None:
  1542. with self._filter_test_common(node, frame, False):
  1543. self.visit(node.node, frame)
  1544. @optimizeconst
  1545. def visit_CondExpr(self, node: nodes.CondExpr, frame: Frame) -> None:
  1546. frame = frame.soft()
  1547. def write_expr2() -> None:
  1548. if node.expr2 is not None:
  1549. self.visit(node.expr2, frame)
  1550. return
  1551. self.write(
  1552. f'cond_expr_undefined("the inline if-expression on'
  1553. f" {self.position(node)} evaluated to false and no else"
  1554. f' section was defined.")'
  1555. )
  1556. self.write("(")
  1557. self.visit(node.expr1, frame)
  1558. self.write(" if ")
  1559. self.visit(node.test, frame)
  1560. self.write(" else ")
  1561. write_expr2()
  1562. self.write(")")
  1563. @optimizeconst
  1564. def visit_Call(
  1565. self, node: nodes.Call, frame: Frame, forward_caller: bool = False
  1566. ) -> None:
  1567. if self.environment.is_async:
  1568. self.write("(await auto_await(")
  1569. if self.environment.sandboxed:
  1570. self.write("environment.call(context, ")
  1571. else:
  1572. self.write("context.call(")
  1573. self.visit(node.node, frame)
  1574. extra_kwargs = {"caller": "caller"} if forward_caller else None
  1575. loop_kwargs = {"_loop_vars": "_loop_vars"} if frame.loop_frame else {}
  1576. block_kwargs = {"_block_vars": "_block_vars"} if frame.block_frame else {}
  1577. if extra_kwargs:
  1578. extra_kwargs.update(loop_kwargs, **block_kwargs)
  1579. elif loop_kwargs or block_kwargs:
  1580. extra_kwargs = dict(loop_kwargs, **block_kwargs)
  1581. self.signature(node, frame, extra_kwargs)
  1582. self.write(")")
  1583. if self.environment.is_async:
  1584. self.write("))")
  1585. def visit_Keyword(self, node: nodes.Keyword, frame: Frame) -> None:
  1586. self.write(node.key + "=")
  1587. self.visit(node.value, frame)
  1588. # -- Unused nodes for extensions
  1589. def visit_MarkSafe(self, node: nodes.MarkSafe, frame: Frame) -> None:
  1590. self.write("Markup(")
  1591. self.visit(node.expr, frame)
  1592. self.write(")")
  1593. def visit_MarkSafeIfAutoescape(
  1594. self, node: nodes.MarkSafeIfAutoescape, frame: Frame
  1595. ) -> None:
  1596. self.write("(Markup if context.eval_ctx.autoescape else identity)(")
  1597. self.visit(node.expr, frame)
  1598. self.write(")")
  1599. def visit_EnvironmentAttribute(
  1600. self, node: nodes.EnvironmentAttribute, frame: Frame
  1601. ) -> None:
  1602. self.write("environment." + node.name)
  1603. def visit_ExtensionAttribute(
  1604. self, node: nodes.ExtensionAttribute, frame: Frame
  1605. ) -> None:
  1606. self.write(f"environment.extensions[{node.identifier!r}].{node.name}")
  1607. def visit_ImportedName(self, node: nodes.ImportedName, frame: Frame) -> None:
  1608. self.write(self.import_aliases[node.importname])
  1609. def visit_InternalName(self, node: nodes.InternalName, frame: Frame) -> None:
  1610. self.write(node.name)
  1611. def visit_ContextReference(
  1612. self, node: nodes.ContextReference, frame: Frame
  1613. ) -> None:
  1614. self.write("context")
  1615. def visit_DerivedContextReference(
  1616. self, node: nodes.DerivedContextReference, frame: Frame
  1617. ) -> None:
  1618. self.write(self.derive_context(frame))
  1619. def visit_Continue(self, node: nodes.Continue, frame: Frame) -> None:
  1620. self.writeline("continue", node)
  1621. def visit_Break(self, node: nodes.Break, frame: Frame) -> None:
  1622. self.writeline("break", node)
  1623. def visit_Scope(self, node: nodes.Scope, frame: Frame) -> None:
  1624. scope_frame = frame.inner()
  1625. scope_frame.symbols.analyze_node(node)
  1626. self.enter_frame(scope_frame)
  1627. self.blockvisit(node.body, scope_frame)
  1628. self.leave_frame(scope_frame)
  1629. def visit_OverlayScope(self, node: nodes.OverlayScope, frame: Frame) -> None:
  1630. ctx = self.temporary_identifier()
  1631. self.writeline(f"{ctx} = {self.derive_context(frame)}")
  1632. self.writeline(f"{ctx}.vars = ")
  1633. self.visit(node.context, frame)
  1634. self.push_context_reference(ctx)
  1635. scope_frame = frame.inner(isolated=True)
  1636. scope_frame.symbols.analyze_node(node)
  1637. self.enter_frame(scope_frame)
  1638. self.blockvisit(node.body, scope_frame)
  1639. self.leave_frame(scope_frame)
  1640. self.pop_context_reference()
  1641. def visit_EvalContextModifier(
  1642. self, node: nodes.EvalContextModifier, frame: Frame
  1643. ) -> None:
  1644. for keyword in node.options:
  1645. self.writeline(f"context.eval_ctx.{keyword.key} = ")
  1646. self.visit(keyword.value, frame)
  1647. try:
  1648. val = keyword.value.as_const(frame.eval_ctx)
  1649. except nodes.Impossible:
  1650. frame.eval_ctx.volatile = True
  1651. else:
  1652. setattr(frame.eval_ctx, keyword.key, val)
  1653. def visit_ScopedEvalContextModifier(
  1654. self, node: nodes.ScopedEvalContextModifier, frame: Frame
  1655. ) -> None:
  1656. old_ctx_name = self.temporary_identifier()
  1657. saved_ctx = frame.eval_ctx.save()
  1658. self.writeline(f"{old_ctx_name} = context.eval_ctx.save()")
  1659. self.visit_EvalContextModifier(node, frame)
  1660. for child in node.body:
  1661. self.visit(child, frame)
  1662. frame.eval_ctx.revert(saved_ctx)
  1663. self.writeline(f"context.eval_ctx.revert({old_ctx_name})")