blob: 36f55a907957cbe65408b60133ba93645bd34da1 [file] [log] [blame]
Armin Ronachere791c2a2008-04-07 18:39:54 +02001# -*- coding: utf-8 -*-
2"""
3 jinja2.compiler
4 ~~~~~~~~~~~~~~~
5
6 Compiles nodes into python code.
7
Armin Ronacher62ccd1b2009-01-04 14:26:19 +01008 :copyright: (c) 2009 by the Jinja Team.
Armin Ronacherd7764372008-07-15 00:11:14 +02009 :license: BSD.
Armin Ronachere791c2a2008-04-07 18:39:54 +020010"""
Armin Ronachere791c2a2008-04-07 18:39:54 +020011from cStringIO import StringIO
Armin Ronacherd1ff8582008-05-11 00:30:43 +020012from itertools import chain
Armin Ronachere791c2a2008-04-07 18:39:54 +020013from jinja2 import nodes
14from jinja2.visitor import NodeVisitor, NodeTransformer
15from jinja2.exceptions import TemplateAssertionError
Armin Ronacher9a0078d2008-08-13 18:24:17 +020016from jinja2.utils import Markup, concat, escape, is_python_keyword
Armin Ronachere791c2a2008-04-07 18:39:54 +020017
18
19operators = {
20 'eq': '==',
21 'ne': '!=',
22 'gt': '>',
23 'gteq': '>=',
24 'lt': '<',
25 'lteq': '<=',
26 'in': 'in',
27 'notin': 'not in'
28}
29
Armin Ronacher3d8b7842008-04-13 13:16:50 +020030try:
31 exec '(0 if 0 else 0)'
32except SyntaxError:
33 have_condexpr = False
34else:
35 have_condexpr = True
36
37
Armin Ronacher8e8d0712008-04-16 23:10:49 +020038def generate(node, environment, name, filename, stream=None):
Armin Ronacherbcb7c532008-04-11 16:30:34 +020039 """Generate the python source for a node tree."""
Armin Ronacher023b5e92008-05-08 11:03:10 +020040 if not isinstance(node, nodes.Template):
41 raise TypeError('Can\'t compile non template nodes')
Armin Ronacher8e8d0712008-04-16 23:10:49 +020042 generator = CodeGenerator(environment, name, filename, stream)
Armin Ronachere791c2a2008-04-07 18:39:54 +020043 generator.visit(node)
44 if stream is None:
45 return generator.stream.getvalue()
46
47
Armin Ronacher4dfc9752008-04-09 15:03:29 +020048def has_safe_repr(value):
49 """Does the node have a safe representation?"""
Armin Ronacherd55ab532008-04-09 16:13:39 +020050 if value is None or value is NotImplemented or value is Ellipsis:
Armin Ronacher4dfc9752008-04-09 15:03:29 +020051 return True
Armin Ronacherd55ab532008-04-09 16:13:39 +020052 if isinstance(value, (bool, int, long, float, complex, basestring,
Armin Ronacher32a910f2008-04-26 23:21:03 +020053 xrange, Markup)):
Armin Ronacher4dfc9752008-04-09 15:03:29 +020054 return True
Armin Ronacherd55ab532008-04-09 16:13:39 +020055 if isinstance(value, (tuple, list, set, frozenset)):
Armin Ronacher4dfc9752008-04-09 15:03:29 +020056 for item in value:
57 if not has_safe_repr(item):
58 return False
59 return True
60 elif isinstance(value, dict):
61 for key, value in value.iteritems():
62 if not has_safe_repr(key):
63 return False
64 if not has_safe_repr(value):
65 return False
66 return True
67 return False
68
69
Armin Ronacherc9705c22008-04-27 21:28:03 +020070def find_undeclared(nodes, names):
71 """Check if the names passed are accessed undeclared. The return value
72 is a set of all the undeclared names from the sequence of names found.
73 """
74 visitor = UndeclaredNameVisitor(names)
75 try:
76 for node in nodes:
77 visitor.visit(node)
78 except VisitorExit:
79 pass
80 return visitor.undeclared
81
82
Armin Ronachere791c2a2008-04-07 18:39:54 +020083class Identifiers(object):
84 """Tracks the status of identifiers in frames."""
85
86 def __init__(self):
87 # variables that are known to be declared (probably from outer
88 # frames or because they are special for the frame)
89 self.declared = set()
90
Armin Ronacher10f3ba22008-04-18 11:30:37 +020091 # undeclared variables from outer scopes
92 self.outer_undeclared = set()
93
Armin Ronachere791c2a2008-04-07 18:39:54 +020094 # names that are accessed without being explicitly declared by
95 # this one or any of the outer scopes. Names can appear both in
96 # declared and undeclared.
97 self.undeclared = set()
98
99 # names that are declared locally
100 self.declared_locally = set()
101
102 # names that are declared by parameters
103 self.declared_parameter = set()
104
105 def add_special(self, name):
106 """Register a special name like `loop`."""
107 self.undeclared.discard(name)
108 self.declared.add(name)
109
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200110 def is_declared(self, name, local_only=False):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200111 """Check if a name is declared in this or an outer scope."""
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200112 if name in self.declared_locally or name in self.declared_parameter:
113 return True
114 if local_only:
115 return False
116 return name in self.declared
Armin Ronachere791c2a2008-04-07 18:39:54 +0200117
Armin Ronachere791c2a2008-04-07 18:39:54 +0200118
119class Frame(object):
Armin Ronacher75cfb862008-04-11 13:47:22 +0200120 """Holds compile time information for us."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200121
122 def __init__(self, parent=None):
123 self.identifiers = Identifiers()
Armin Ronacherfed44b52008-04-13 19:42:53 +0200124
Armin Ronacher75cfb862008-04-11 13:47:22 +0200125 # a toplevel frame is the root + soft frames such as if conditions.
Armin Ronacher8efc5222008-04-08 14:47:40 +0200126 self.toplevel = False
Armin Ronacherfed44b52008-04-13 19:42:53 +0200127
Armin Ronacher75cfb862008-04-11 13:47:22 +0200128 # the root frame is basically just the outermost frame, so no if
129 # conditions. This information is used to optimize inheritance
130 # situations.
131 self.rootlevel = False
Armin Ronacherfed44b52008-04-13 19:42:53 +0200132
Armin Ronacher79668952008-09-23 22:52:46 +0200133 # in some dynamic inheritance situations the compiler needs to add
134 # write tests around output statements.
135 self.require_output_check = parent and parent.require_output_check
Armin Ronacherf40c8842008-09-17 18:51:26 +0200136
Armin Ronacherfed44b52008-04-13 19:42:53 +0200137 # inside some tags we are using a buffer rather than yield statements.
138 # this for example affects {% filter %} or {% macro %}. If a frame
139 # is buffered this variable points to the name of the list used as
140 # buffer.
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200141 self.buffer = None
Armin Ronacherfed44b52008-04-13 19:42:53 +0200142
Armin Ronacherfed44b52008-04-13 19:42:53 +0200143 # the name of the block we're in, otherwise None.
Armin Ronacher8efc5222008-04-08 14:47:40 +0200144 self.block = parent and parent.block or None
Armin Ronacherfed44b52008-04-13 19:42:53 +0200145
Armin Ronacher271a0eb2009-02-11 22:49:08 +0100146 # a set of actually assigned names
147 self.assigned_names = set()
148
Armin Ronacherfed44b52008-04-13 19:42:53 +0200149 # the parent of this frame
150 self.parent = parent
151
Armin Ronachere791c2a2008-04-07 18:39:54 +0200152 if parent is not None:
153 self.identifiers.declared.update(
154 parent.identifiers.declared |
Armin Ronacherb3a1fcf2008-05-15 11:04:14 +0200155 parent.identifiers.declared_parameter |
Armin Ronacher271a0eb2009-02-11 22:49:08 +0100156 parent.assigned_names
Armin Ronachere791c2a2008-04-07 18:39:54 +0200157 )
Armin Ronacher10f3ba22008-04-18 11:30:37 +0200158 self.identifiers.outer_undeclared.update(
159 parent.identifiers.undeclared -
160 self.identifiers.declared
161 )
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200162 self.buffer = parent.buffer
Armin Ronachere791c2a2008-04-07 18:39:54 +0200163
Armin Ronacher8efc5222008-04-08 14:47:40 +0200164 def copy(self):
165 """Create a copy of the current one."""
Armin Ronacher9a0078d2008-08-13 18:24:17 +0200166 rv = object.__new__(self.__class__)
167 rv.__dict__.update(self.__dict__)
168 rv.identifiers = object.__new__(self.identifiers.__class__)
169 rv.identifiers.__dict__.update(self.identifiers.__dict__)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200170 return rv
171
Armin Ronacherc9705c22008-04-27 21:28:03 +0200172 def inspect(self, nodes, hard_scope=False):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200173 """Walk the node and check for identifiers. If the scope is hard (eg:
174 enforce on a python level) overrides from outer scopes are tracked
175 differently.
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200176 """
177 visitor = FrameIdentifierVisitor(self.identifiers, hard_scope)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200178 for node in nodes:
Armin Ronacherc9705c22008-04-27 21:28:03 +0200179 visitor.visit(node)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200180
Armin Ronacher271a0eb2009-02-11 22:49:08 +0100181 def find_shadowed(self, extra=()):
182 """Find all the shadowed names. extra is an iterable of variables
183 that may be defined with `add_special` which may occour scoped.
184 """
185 i = self.identifiers
186 return (i.declared | i.outer_undeclared) & \
187 (i.declared_locally | i.declared_parameter) | \
188 set(x for x in extra if i.is_declared(x))
189
Armin Ronachere791c2a2008-04-07 18:39:54 +0200190 def inner(self):
191 """Return an inner frame."""
192 return Frame(self)
193
Armin Ronacher75cfb862008-04-11 13:47:22 +0200194 def soft(self):
195 """Return a soft frame. A soft frame may not be modified as
196 standalone thing as it shares the resources with the frame it
197 was created of, but it's not a rootlevel frame any longer.
198 """
Armin Ronacher9a0078d2008-08-13 18:24:17 +0200199 rv = self.copy()
Armin Ronacher75cfb862008-04-11 13:47:22 +0200200 rv.rootlevel = False
201 return rv
202
Armin Ronacher9a0078d2008-08-13 18:24:17 +0200203 __copy__ = copy
204
Armin Ronachere791c2a2008-04-07 18:39:54 +0200205
Armin Ronacherc9705c22008-04-27 21:28:03 +0200206class VisitorExit(RuntimeError):
207 """Exception used by the `UndeclaredNameVisitor` to signal a stop."""
208
209
210class DependencyFinderVisitor(NodeVisitor):
211 """A visitor that collects filter and test calls."""
212
213 def __init__(self):
214 self.filters = set()
215 self.tests = set()
216
217 def visit_Filter(self, node):
218 self.generic_visit(node)
219 self.filters.add(node.name)
220
221 def visit_Test(self, node):
222 self.generic_visit(node)
223 self.tests.add(node.name)
224
225 def visit_Block(self, node):
226 """Stop visiting at blocks."""
227
228
229class UndeclaredNameVisitor(NodeVisitor):
230 """A visitor that checks if a name is accessed without being
231 declared. This is different from the frame visitor as it will
232 not stop at closure frames.
233 """
234
235 def __init__(self, names):
236 self.names = set(names)
237 self.undeclared = set()
238
239 def visit_Name(self, node):
240 if node.ctx == 'load' and node.name in self.names:
241 self.undeclared.add(node.name)
242 if self.undeclared == self.names:
243 raise VisitorExit()
244 else:
245 self.names.discard(node.name)
246
247 def visit_Block(self, node):
248 """Stop visiting a blocks."""
249
250
Armin Ronachere791c2a2008-04-07 18:39:54 +0200251class FrameIdentifierVisitor(NodeVisitor):
252 """A visitor for `Frame.inspect`."""
253
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200254 def __init__(self, identifiers, hard_scope):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200255 self.identifiers = identifiers
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200256 self.hard_scope = hard_scope
Armin Ronachere791c2a2008-04-07 18:39:54 +0200257
Armin Ronacherc9705c22008-04-27 21:28:03 +0200258 def visit_Name(self, node):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200259 """All assignments to names go through this function."""
Armin Ronachere9411b42008-05-15 16:22:07 +0200260 if node.ctx == 'store':
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200261 self.identifiers.declared_locally.add(node.name)
Armin Ronachere9411b42008-05-15 16:22:07 +0200262 elif node.ctx == 'param':
263 self.identifiers.declared_parameter.add(node.name)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200264 elif node.ctx == 'load' and not \
265 self.identifiers.is_declared(node.name, self.hard_scope):
266 self.identifiers.undeclared.add(node.name)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200267
Armin Ronacherc9705c22008-04-27 21:28:03 +0200268 def visit_Macro(self, node):
Armin Ronacherc9705c22008-04-27 21:28:03 +0200269 self.identifiers.declared_locally.add(node.name)
Armin Ronacher0611e492008-04-25 23:44:14 +0200270
Armin Ronacherc9705c22008-04-27 21:28:03 +0200271 def visit_Import(self, node):
272 self.generic_visit(node)
273 self.identifiers.declared_locally.add(node.target)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200274
Armin Ronacherc9705c22008-04-27 21:28:03 +0200275 def visit_FromImport(self, node):
276 self.generic_visit(node)
277 for name in node.names:
278 if isinstance(name, tuple):
279 self.identifiers.declared_locally.add(name[1])
280 else:
281 self.identifiers.declared_locally.add(name)
282
283 def visit_Assign(self, node):
Armin Ronacherebe55aa2008-04-10 20:51:23 +0200284 """Visit assignments in the correct order."""
Armin Ronacherc9705c22008-04-27 21:28:03 +0200285 self.visit(node.node)
286 self.visit(node.target)
Armin Ronacherebe55aa2008-04-10 20:51:23 +0200287
Armin Ronacherc9705c22008-04-27 21:28:03 +0200288 def visit_For(self, node):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200289 """Visiting stops at for blocks. However the block sequence
290 is visited as part of the outer scope.
291 """
Armin Ronacherc9705c22008-04-27 21:28:03 +0200292 self.visit(node.iter)
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200293
Armin Ronacherc9705c22008-04-27 21:28:03 +0200294 def visit_CallBlock(self, node):
295 for child in node.iter_child_nodes(exclude=('body',)):
296 self.visit(child)
297
298 def visit_FilterBlock(self, node):
299 self.visit(node.filter)
300
Armin Ronacher271a0eb2009-02-11 22:49:08 +0100301 def visit_Scope(self, node):
302 """Stop visiting at scopes."""
303
Armin Ronacherc9705c22008-04-27 21:28:03 +0200304 def visit_Block(self, node):
305 """Stop visiting at blocks."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200306
307
Armin Ronacher75cfb862008-04-11 13:47:22 +0200308class CompilerExit(Exception):
309 """Raised if the compiler encountered a situation where it just
310 doesn't make sense to further process the code. Any block that
Armin Ronacher0611e492008-04-25 23:44:14 +0200311 raises such an exception is not further processed.
312 """
Armin Ronacher75cfb862008-04-11 13:47:22 +0200313
314
Armin Ronachere791c2a2008-04-07 18:39:54 +0200315class CodeGenerator(NodeVisitor):
316
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200317 def __init__(self, environment, name, filename, stream=None):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200318 if stream is None:
319 stream = StringIO()
Christoph Hack65642a52008-04-08 14:46:56 +0200320 self.environment = environment
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200321 self.name = name
Armin Ronachere791c2a2008-04-07 18:39:54 +0200322 self.filename = filename
323 self.stream = stream
Armin Ronacherfed44b52008-04-13 19:42:53 +0200324
Armin Ronacher023b5e92008-05-08 11:03:10 +0200325 # aliases for imports
326 self.import_aliases = {}
327
Armin Ronacherfed44b52008-04-13 19:42:53 +0200328 # a registry for all blocks. Because blocks are moved out
329 # into the global python scope they are registered here
Armin Ronachere791c2a2008-04-07 18:39:54 +0200330 self.blocks = {}
Armin Ronacherfed44b52008-04-13 19:42:53 +0200331
332 # the number of extends statements so far
Armin Ronacher7fb38972008-04-11 13:54:28 +0200333 self.extends_so_far = 0
Armin Ronacherfed44b52008-04-13 19:42:53 +0200334
335 # some templates have a rootlevel extends. In this case we
336 # can safely assume that we're a child template and do some
337 # more optimizations.
Armin Ronacher75cfb862008-04-11 13:47:22 +0200338 self.has_known_extends = False
Armin Ronacherfed44b52008-04-13 19:42:53 +0200339
Armin Ronacherba3757b2008-04-16 19:43:16 +0200340 # the current line number
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200341 self.code_lineno = 1
Armin Ronacherba3757b2008-04-16 19:43:16 +0200342
Armin Ronacherb9e78752008-05-10 23:36:28 +0200343 # registry of all filters and tests (global, not block local)
344 self.tests = {}
345 self.filters = {}
346
Armin Ronacherba3757b2008-04-16 19:43:16 +0200347 # the debug information
348 self.debug_info = []
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200349 self._write_debug_info = None
Armin Ronacherba3757b2008-04-16 19:43:16 +0200350
Armin Ronacherfed44b52008-04-13 19:42:53 +0200351 # the number of new lines before the next write()
352 self._new_lines = 0
353
354 # the line number of the last written statement
Armin Ronachere791c2a2008-04-07 18:39:54 +0200355 self._last_line = 0
Armin Ronacherfed44b52008-04-13 19:42:53 +0200356
357 # true if nothing was written so far.
Armin Ronachere791c2a2008-04-07 18:39:54 +0200358 self._first_write = True
359
Armin Ronacherfed44b52008-04-13 19:42:53 +0200360 # used by the `temporary_identifier` method to get new
361 # unique, temporary identifier
362 self._last_identifier = 0
363
364 # the current indentation
365 self._indentation = 0
366
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200367 # -- Various compilation helpers
368
Armin Ronachere2244882008-05-19 09:25:57 +0200369 def fail(self, msg, lineno):
370 """Fail with a `TemplateAssertionError`."""
371 raise TemplateAssertionError(msg, lineno, self.name, self.filename)
372
Armin Ronachere791c2a2008-04-07 18:39:54 +0200373 def temporary_identifier(self):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200374 """Get a new unique identifier."""
375 self._last_identifier += 1
Armin Ronacher8a1d27f2008-05-19 08:37:19 +0200376 return 't_%d' % self._last_identifier
Armin Ronachere791c2a2008-04-07 18:39:54 +0200377
Armin Ronachered1e0d42008-05-18 20:25:28 +0200378 def buffer(self, frame):
379 """Enable buffering for the frame from that point onwards."""
Armin Ronachere2244882008-05-19 09:25:57 +0200380 frame.buffer = self.temporary_identifier()
381 self.writeline('%s = []' % frame.buffer)
Armin Ronachered1e0d42008-05-18 20:25:28 +0200382
383 def return_buffer_contents(self, frame):
384 """Return the buffer contents of the frame."""
385 if self.environment.autoescape:
386 self.writeline('return Markup(concat(%s))' % frame.buffer)
387 else:
388 self.writeline('return concat(%s)' % frame.buffer)
389
Armin Ronachere791c2a2008-04-07 18:39:54 +0200390 def indent(self):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200391 """Indent by one."""
392 self._indentation += 1
Armin Ronachere791c2a2008-04-07 18:39:54 +0200393
Armin Ronacher8efc5222008-04-08 14:47:40 +0200394 def outdent(self, step=1):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200395 """Outdent by step."""
396 self._indentation -= step
Armin Ronachere791c2a2008-04-07 18:39:54 +0200397
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200398 def start_write(self, frame, node=None):
399 """Yield or write into the frame buffer."""
400 if frame.buffer is None:
401 self.writeline('yield ', node)
402 else:
403 self.writeline('%s.append(' % frame.buffer, node)
404
405 def end_write(self, frame):
406 """End the writing process started by `start_write`."""
407 if frame.buffer is not None:
408 self.write(')')
409
410 def simple_write(self, s, frame, node=None):
411 """Simple shortcut for start_write + write + end_write."""
412 self.start_write(frame, node)
413 self.write(s)
414 self.end_write(frame)
415
Armin Ronacherf40c8842008-09-17 18:51:26 +0200416 def blockvisit(self, nodes, frame):
Armin Ronacherc9705c22008-04-27 21:28:03 +0200417 """Visit a list of nodes as block in a frame. If the current frame
418 is no buffer a dummy ``if 0: yield None`` is written automatically
419 unless the force_generator parameter is set to False.
Armin Ronacherfed44b52008-04-13 19:42:53 +0200420 """
Armin Ronacherf40c8842008-09-17 18:51:26 +0200421 if frame.buffer is None:
Armin Ronachere791c2a2008-04-07 18:39:54 +0200422 self.writeline('if 0: yield None')
Armin Ronacherf40c8842008-09-17 18:51:26 +0200423 else:
424 self.writeline('pass')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200425 try:
426 for node in nodes:
427 self.visit(node, frame)
428 except CompilerExit:
429 pass
Armin Ronachere791c2a2008-04-07 18:39:54 +0200430
431 def write(self, x):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200432 """Write a string into the output stream."""
433 if self._new_lines:
Armin Ronachere791c2a2008-04-07 18:39:54 +0200434 if not self._first_write:
Armin Ronacherfed44b52008-04-13 19:42:53 +0200435 self.stream.write('\n' * self._new_lines)
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200436 self.code_lineno += self._new_lines
437 if self._write_debug_info is not None:
438 self.debug_info.append((self._write_debug_info,
439 self.code_lineno))
440 self._write_debug_info = None
Armin Ronachere791c2a2008-04-07 18:39:54 +0200441 self._first_write = False
Armin Ronacherfed44b52008-04-13 19:42:53 +0200442 self.stream.write(' ' * self._indentation)
443 self._new_lines = 0
Armin Ronachere791c2a2008-04-07 18:39:54 +0200444 self.stream.write(x)
445
446 def writeline(self, x, node=None, extra=0):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200447 """Combination of newline and write."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200448 self.newline(node, extra)
449 self.write(x)
450
451 def newline(self, node=None, extra=0):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200452 """Add one or more newlines before the next write."""
453 self._new_lines = max(self._new_lines, 1 + extra)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200454 if node is not None and node.lineno != self._last_line:
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200455 self._write_debug_info = node.lineno
456 self._last_line = node.lineno
Armin Ronachere791c2a2008-04-07 18:39:54 +0200457
Armin Ronacherfd310492008-05-25 00:16:51 +0200458 def signature(self, node, frame, extra_kwargs=None):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200459 """Writes a function call to the stream for the current node.
Armin Ronacherfd310492008-05-25 00:16:51 +0200460 A leading comma is added automatically. The extra keyword
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200461 arguments may not include python keywords otherwise a syntax
462 error could occour. The extra keyword arguments should be given
463 as python dict.
Armin Ronacherfed44b52008-04-13 19:42:53 +0200464 """
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200465 # if any of the given keyword arguments is a python keyword
466 # we have to make sure that no invalid call is created.
467 kwarg_workaround = False
468 for kwarg in chain((x.key for x in node.kwargs), extra_kwargs or ()):
Armin Ronacher9a0078d2008-08-13 18:24:17 +0200469 if is_python_keyword(kwarg):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200470 kwarg_workaround = True
471 break
472
Armin Ronacher8efc5222008-04-08 14:47:40 +0200473 for arg in node.args:
Armin Ronacherfd310492008-05-25 00:16:51 +0200474 self.write(', ')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200475 self.visit(arg, frame)
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200476
477 if not kwarg_workaround:
478 for kwarg in node.kwargs:
Armin Ronacherfd310492008-05-25 00:16:51 +0200479 self.write(', ')
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200480 self.visit(kwarg, frame)
481 if extra_kwargs is not None:
482 for key, value in extra_kwargs.iteritems():
Armin Ronacherfd310492008-05-25 00:16:51 +0200483 self.write(', %s=%s' % (key, value))
Armin Ronacher8efc5222008-04-08 14:47:40 +0200484 if node.dyn_args:
Armin Ronacherfd310492008-05-25 00:16:51 +0200485 self.write(', *')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200486 self.visit(node.dyn_args, frame)
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200487
488 if kwarg_workaround:
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200489 if node.dyn_kwargs is not None:
Armin Ronacherfd310492008-05-25 00:16:51 +0200490 self.write(', **dict({')
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200491 else:
Armin Ronacherfd310492008-05-25 00:16:51 +0200492 self.write(', **{')
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200493 for kwarg in node.kwargs:
494 self.write('%r: ' % kwarg.key)
495 self.visit(kwarg.value, frame)
496 self.write(', ')
497 if extra_kwargs is not None:
498 for key, value in extra_kwargs.iteritems():
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200499 self.write('%r: %s, ' % (key, value))
500 if node.dyn_kwargs is not None:
501 self.write('}, **')
502 self.visit(node.dyn_kwargs, frame)
503 self.write(')')
504 else:
505 self.write('}')
506
507 elif node.dyn_kwargs is not None:
Armin Ronacherfd310492008-05-25 00:16:51 +0200508 self.write(', **')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200509 self.visit(node.dyn_kwargs, frame)
510
Armin Ronacherc9705c22008-04-27 21:28:03 +0200511 def pull_locals(self, frame):
512 """Pull all the references identifiers into the local scope."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200513 for name in frame.identifiers.undeclared:
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200514 self.writeline('l_%s = context.resolve(%r)' % (name, name))
Armin Ronacherc9705c22008-04-27 21:28:03 +0200515
516 def pull_dependencies(self, nodes):
517 """Pull all the dependencies."""
518 visitor = DependencyFinderVisitor()
519 for node in nodes:
520 visitor.visit(node)
Armin Ronacherb9e78752008-05-10 23:36:28 +0200521 for dependency in 'filters', 'tests':
522 mapping = getattr(self, dependency)
523 for name in getattr(visitor, dependency):
524 if name not in mapping:
525 mapping[name] = self.temporary_identifier()
526 self.writeline('%s = environment.%s[%r]' %
527 (mapping[name], dependency, name))
Armin Ronachere791c2a2008-04-07 18:39:54 +0200528
Armin Ronacher7887a8c2009-02-08 19:11:44 +0100529 def unoptimize_scope(self, frame):
530 """Disable Python optimizations for the frame."""
531 # XXX: this is not that nice but it has no real overhead. It
532 # mainly works because python finds the locals before dead code
533 # is removed. If that breaks we have to add a dummy function
534 # that just accepts the arguments and does nothing.
535 if frame.identifiers.declared:
536 self.writeline('if 0: dummy(%s)' % ', '.join(
537 'l_' + name for name in frame.identifiers.declared))
538
Armin Ronacher673aa882008-10-04 18:06:57 +0200539 def push_scope(self, frame, extra_vars=()):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200540 """This function returns all the shadowed variables in a dict
541 in the form name: alias and will write the required assignments
542 into the current scope. No indentation takes place.
Armin Ronacherff53c782008-08-13 18:55:50 +0200543
Armin Ronacher673aa882008-10-04 18:06:57 +0200544 This also predefines locally declared variables from the loop
545 body because under some circumstances it may be the case that
546
Armin Ronacher271a0eb2009-02-11 22:49:08 +0100547 `extra_vars` is passed to `Frame.find_shadowed`.
Armin Ronacherfed44b52008-04-13 19:42:53 +0200548 """
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200549 aliases = {}
Armin Ronacher271a0eb2009-02-11 22:49:08 +0100550 for name in frame.find_shadowed(extra_vars):
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200551 aliases[name] = ident = self.temporary_identifier()
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200552 self.writeline('%s = l_%s' % (ident, name))
Armin Ronacher673aa882008-10-04 18:06:57 +0200553 to_declare = set()
554 for name in frame.identifiers.declared_locally:
555 if name not in aliases:
556 to_declare.add('l_' + name)
557 if to_declare:
558 self.writeline(' = '.join(to_declare) + ' = missing')
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200559 return aliases
560
Armin Ronacher673aa882008-10-04 18:06:57 +0200561 def pop_scope(self, aliases, frame):
562 """Restore all aliases and delete unused variables."""
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200563 for name, alias in aliases.iteritems():
564 self.writeline('l_%s = %s' % (name, alias))
Armin Ronacher673aa882008-10-04 18:06:57 +0200565 to_delete = set()
566 for name in frame.identifiers.declared_locally:
567 if name not in aliases:
568 to_delete.add('l_' + name)
569 if to_delete:
Armin Ronacher330fbc02009-02-04 19:13:58 +0100570 # we cannot use the del statement here because enclosed
571 # scopes can trigger a SyntaxError:
572 # a = 42; b = lambda: a; del a
573 self.writeline(' = '.join(to_delete) + ' = missing')
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200574
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200575 def function_scoping(self, node, frame, children=None,
576 find_special=True):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200577 """In Jinja a few statements require the help of anonymous
578 functions. Those are currently macros and call blocks and in
579 the future also recursive loops. As there is currently
580 technical limitation that doesn't allow reading and writing a
581 variable in a scope where the initial value is coming from an
582 outer scope, this function tries to fall back with a common
583 error message. Additionally the frame passed is modified so
584 that the argumetns are collected and callers are looked up.
585
586 This will return the modified frame.
587 """
Armin Ronacherc9705c22008-04-27 21:28:03 +0200588 # we have to iterate twice over it, make sure that works
589 if children is None:
590 children = node.iter_child_nodes()
591 children = list(children)
Armin Ronacher71082072008-04-12 14:19:36 +0200592 func_frame = frame.inner()
Armin Ronacherc9705c22008-04-27 21:28:03 +0200593 func_frame.inspect(children, hard_scope=True)
Armin Ronacher71082072008-04-12 14:19:36 +0200594
595 # variables that are undeclared (accessed before declaration) and
596 # declared locally *and* part of an outside scope raise a template
597 # assertion error. Reason: we can't generate reasonable code from
Armin Ronacher02b42a82009-03-18 00:59:32 +0100598 # it without aliasing all the variables.
599 # this could be fixed in Python 3 where we have the nonlocal
600 # keyword or if we switch to bytecode generation
Armin Ronacher71082072008-04-12 14:19:36 +0200601 overriden_closure_vars = (
602 func_frame.identifiers.undeclared &
603 func_frame.identifiers.declared &
604 (func_frame.identifiers.declared_locally |
605 func_frame.identifiers.declared_parameter)
606 )
607 if overriden_closure_vars:
Armin Ronachere2244882008-05-19 09:25:57 +0200608 self.fail('It\'s not possible to set and access variables '
609 'derived from an outer scope! (affects: %s' %
610 ', '.join(sorted(overriden_closure_vars)), node.lineno)
Armin Ronacher71082072008-04-12 14:19:36 +0200611
612 # remove variables from a closure from the frame's undeclared
613 # identifiers.
614 func_frame.identifiers.undeclared -= (
615 func_frame.identifiers.undeclared &
616 func_frame.identifiers.declared
617 )
618
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200619 # no special variables for this scope, abort early
620 if not find_special:
621 return func_frame
622
Armin Ronacher963f97d2008-04-25 11:44:59 +0200623 func_frame.accesses_kwargs = False
624 func_frame.accesses_varargs = False
Armin Ronacher71082072008-04-12 14:19:36 +0200625 func_frame.accesses_caller = False
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200626 func_frame.arguments = args = ['l_' + x.name for x in node.args]
Armin Ronacher71082072008-04-12 14:19:36 +0200627
Armin Ronacherc9705c22008-04-27 21:28:03 +0200628 undeclared = find_undeclared(children, ('caller', 'kwargs', 'varargs'))
629
630 if 'caller' in undeclared:
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200631 func_frame.accesses_caller = True
632 func_frame.identifiers.add_special('caller')
633 args.append('l_caller')
Armin Ronacherc9705c22008-04-27 21:28:03 +0200634 if 'kwargs' in undeclared:
Armin Ronacher963f97d2008-04-25 11:44:59 +0200635 func_frame.accesses_kwargs = True
636 func_frame.identifiers.add_special('kwargs')
637 args.append('l_kwargs')
Armin Ronacherc9705c22008-04-27 21:28:03 +0200638 if 'varargs' in undeclared:
Armin Ronacher963f97d2008-04-25 11:44:59 +0200639 func_frame.accesses_varargs = True
640 func_frame.identifiers.add_special('varargs')
641 args.append('l_varargs')
Armin Ronacher71082072008-04-12 14:19:36 +0200642 return func_frame
643
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200644 def macro_body(self, node, frame, children=None):
645 """Dump the function def of a macro or call block."""
646 frame = self.function_scoping(node, frame, children)
Armin Ronachere308bf22008-10-30 19:18:45 +0100647 # macros are delayed, they never require output checks
648 frame.require_output_check = False
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200649 args = frame.arguments
650 self.writeline('def macro(%s):' % ', '.join(args), node)
651 self.indent()
652 self.buffer(frame)
653 self.pull_locals(frame)
654 self.blockvisit(node.body, frame)
655 self.return_buffer_contents(frame)
656 self.outdent()
657 return frame
658
659 def macro_def(self, node, frame):
660 """Dump the macro definition for the def created by macro_body."""
661 arg_tuple = ', '.join(repr(x.name) for x in node.args)
662 name = getattr(node, 'name', None)
663 if len(node.args) == 1:
664 arg_tuple += ','
665 self.write('Macro(environment, macro, %r, (%s), (' %
666 (name, arg_tuple))
667 for arg in node.defaults:
668 self.visit(arg, frame)
669 self.write(', ')
Armin Ronacher903d1682008-05-23 00:51:58 +0200670 self.write('), %r, %r, %r)' % (
671 bool(frame.accesses_kwargs),
672 bool(frame.accesses_varargs),
673 bool(frame.accesses_caller)
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200674 ))
675
Armin Ronacher547d0b62008-07-04 16:35:10 +0200676 def position(self, node):
677 """Return a human readable position for the node."""
678 rv = 'line %d' % node.lineno
679 if self.name is not None:
Armin Ronachercebd8382008-12-25 18:33:46 +0100680 rv += ' in ' + repr(self.name)
Armin Ronacher547d0b62008-07-04 16:35:10 +0200681 return rv
682
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200683 # -- Statement Visitors
Armin Ronachere791c2a2008-04-07 18:39:54 +0200684
685 def visit_Template(self, node, frame=None):
686 assert frame is None, 'no root frame allowed'
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200687 from jinja2.runtime import __all__ as exported
Armin Ronacher709f6e52008-04-28 18:18:16 +0200688 self.writeline('from __future__ import division')
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200689 self.writeline('from jinja2.runtime import ' + ', '.join(exported))
Armin Ronacher8edbe492008-04-10 20:43:43 +0200690
Armin Ronacher75cfb862008-04-11 13:47:22 +0200691 # do we have an extends tag at all? If not, we can save some
692 # overhead by just not processing any inheritance code.
693 have_extends = node.find(nodes.Extends) is not None
694
Armin Ronacher8edbe492008-04-10 20:43:43 +0200695 # find all blocks
696 for block in node.find_all(nodes.Block):
697 if block.name in self.blocks:
Armin Ronachere2244882008-05-19 09:25:57 +0200698 self.fail('block %r defined twice' % block.name, block.lineno)
Armin Ronacher8edbe492008-04-10 20:43:43 +0200699 self.blocks[block.name] = block
Armin Ronachere791c2a2008-04-07 18:39:54 +0200700
Armin Ronacher023b5e92008-05-08 11:03:10 +0200701 # find all imports and import them
702 for import_ in node.find_all(nodes.ImportedName):
703 if import_.importname not in self.import_aliases:
704 imp = import_.importname
705 self.import_aliases[imp] = alias = self.temporary_identifier()
706 if '.' in imp:
707 module, obj = imp.rsplit('.', 1)
708 self.writeline('from %s import %s as %s' %
709 (module, obj, alias))
710 else:
711 self.writeline('import %s as %s' % (imp, alias))
712
713 # add the load name
Armin Ronacherdc02b642008-05-15 22:47:27 +0200714 self.writeline('name = %r' % self.name)
Armin Ronacher023b5e92008-05-08 11:03:10 +0200715
Armin Ronacher8efc5222008-04-08 14:47:40 +0200716 # generate the root render function.
Armin Ronacher32a910f2008-04-26 23:21:03 +0200717 self.writeline('def root(context, environment=environment):', extra=1)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200718
719 # process the root
Armin Ronachere791c2a2008-04-07 18:39:54 +0200720 frame = Frame()
Armin Ronacherc9705c22008-04-27 21:28:03 +0200721 frame.inspect(node.body)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200722 frame.toplevel = frame.rootlevel = True
Armin Ronacher79668952008-09-23 22:52:46 +0200723 frame.require_output_check = have_extends and not self.has_known_extends
Armin Ronacherf059ec12008-04-11 22:21:00 +0200724 self.indent()
Armin Ronacherc9705c22008-04-27 21:28:03 +0200725 if have_extends:
726 self.writeline('parent_template = None')
Armin Ronacherc9705c22008-04-27 21:28:03 +0200727 if 'self' in find_undeclared(node.body, ('self',)):
728 frame.identifiers.add_special('self')
729 self.writeline('l_self = TemplateReference(context)')
Armin Ronacher6df604e2008-05-23 22:18:38 +0200730 self.pull_locals(frame)
731 self.pull_dependencies(node.body)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200732 self.blockvisit(node.body, frame)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200733 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200734
Armin Ronacher8efc5222008-04-08 14:47:40 +0200735 # make sure that the parent root is called.
Armin Ronacher75cfb862008-04-11 13:47:22 +0200736 if have_extends:
737 if not self.has_known_extends:
738 self.indent()
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200739 self.writeline('if parent_template is not None:')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200740 self.indent()
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200741 self.writeline('for event in parent_template.'
Armin Ronacher5411ce72008-05-25 11:36:22 +0200742 'root_render_func(context):')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200743 self.indent()
744 self.writeline('yield event')
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200745 self.outdent(2 + (not self.has_known_extends))
Armin Ronachere791c2a2008-04-07 18:39:54 +0200746
747 # at this point we now have the blocks collected and can visit them too.
748 for name, block in self.blocks.iteritems():
749 block_frame = Frame()
Armin Ronacherc9705c22008-04-27 21:28:03 +0200750 block_frame.inspect(block.body)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200751 block_frame.block = name
Armin Ronacherd4c64f72008-04-11 17:15:29 +0200752 self.writeline('def block_%s(context, environment=environment):'
753 % name, block, 1)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200754 self.indent()
755 undeclared = find_undeclared(block.body, ('self', 'super'))
756 if 'self' in undeclared:
757 block_frame.identifiers.add_special('self')
758 self.writeline('l_self = TemplateReference(context)')
759 if 'super' in undeclared:
760 block_frame.identifiers.add_special('super')
761 self.writeline('l_super = context.super(%r, '
762 'block_%s)' % (name, name))
Armin Ronachere791c2a2008-04-07 18:39:54 +0200763 self.pull_locals(block_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200764 self.pull_dependencies(block.body)
Armin Ronacher625215e2008-04-13 16:31:08 +0200765 self.blockvisit(block.body, block_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200766 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200767
Armin Ronacher75cfb862008-04-11 13:47:22 +0200768 self.writeline('blocks = {%s}' % ', '.join('%r: block_%s' % (x, x)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200769 for x in self.blocks),
770 extra=1)
771
772 # add a function that returns the debug info
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200773 self.writeline('debug_info = %r' % '&'.join('%s=%s' % x for x
774 in self.debug_info))
Armin Ronacher75cfb862008-04-11 13:47:22 +0200775
Armin Ronachere791c2a2008-04-07 18:39:54 +0200776 def visit_Block(self, node, frame):
777 """Call a block and register it for the template."""
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200778 level = 1
Armin Ronacher75cfb862008-04-11 13:47:22 +0200779 if frame.toplevel:
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200780 # if we know that we are a child template, there is no need to
781 # check if we are one
782 if self.has_known_extends:
783 return
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200784 if self.extends_so_far > 0:
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200785 self.writeline('if parent_template is None:')
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200786 self.indent()
787 level += 1
Armin Ronacher74a0cd92009-02-19 15:56:53 +0100788 if node.scoped:
789 context = 'context.derived(locals())'
790 else:
791 context = 'context'
792 self.writeline('for event in context.blocks[%r][0](%s):' % (
793 node.name, context), node)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200794 self.indent()
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200795 self.simple_write('event', frame)
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200796 self.outdent(level)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200797
798 def visit_Extends(self, node, frame):
799 """Calls the extender."""
Armin Ronacher8efc5222008-04-08 14:47:40 +0200800 if not frame.toplevel:
Armin Ronachere2244882008-05-19 09:25:57 +0200801 self.fail('cannot use extend from a non top-level scope',
802 node.lineno)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200803
Armin Ronacher7fb38972008-04-11 13:54:28 +0200804 # if the number of extends statements in general is zero so
805 # far, we don't have to add a check if something extended
806 # the template before this one.
807 if self.extends_so_far > 0:
Armin Ronacher75cfb862008-04-11 13:47:22 +0200808
Armin Ronacher7fb38972008-04-11 13:54:28 +0200809 # if we have a known extends we just add a template runtime
810 # error into the generated code. We could catch that at compile
811 # time too, but i welcome it not to confuse users by throwing the
812 # same error at different times just "because we can".
813 if not self.has_known_extends:
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200814 self.writeline('if parent_template is not None:')
Armin Ronacher7fb38972008-04-11 13:54:28 +0200815 self.indent()
816 self.writeline('raise TemplateRuntimeError(%r)' %
817 'extended multiple times')
Armin Ronacher79668952008-09-23 22:52:46 +0200818 self.outdent()
Armin Ronacher75cfb862008-04-11 13:47:22 +0200819
Armin Ronacher7fb38972008-04-11 13:54:28 +0200820 # if we have a known extends already we don't need that code here
821 # as we know that the template execution will end here.
822 if self.has_known_extends:
823 raise CompilerExit()
Armin Ronacher7fb38972008-04-11 13:54:28 +0200824
Armin Ronacher9d42abf2008-05-14 18:10:41 +0200825 self.writeline('parent_template = environment.get_template(', node)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200826 self.visit(node.template, frame)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200827 self.write(', %r)' % self.name)
828 self.writeline('for name, parent_block in parent_template.'
829 'blocks.iteritems():')
830 self.indent()
831 self.writeline('context.blocks.setdefault(name, []).'
Armin Ronacher83fbc0f2008-05-15 12:22:28 +0200832 'append(parent_block)')
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200833 self.outdent()
Armin Ronacher75cfb862008-04-11 13:47:22 +0200834
835 # if this extends statement was in the root level we can take
836 # advantage of that information and simplify the generated code
837 # in the top level from this point onwards
Armin Ronacher27069d72008-05-11 19:48:12 +0200838 if frame.rootlevel:
839 self.has_known_extends = True
Armin Ronachere791c2a2008-04-07 18:39:54 +0200840
Armin Ronacher7fb38972008-04-11 13:54:28 +0200841 # and now we have one more
842 self.extends_so_far += 1
843
Armin Ronacherf059ec12008-04-11 22:21:00 +0200844 def visit_Include(self, node, frame):
845 """Handles includes."""
Armin Ronacher7887a8c2009-02-08 19:11:44 +0100846 if node.with_context:
847 self.unoptimize_scope(frame)
Armin Ronacher37f58ce2008-12-27 13:10:38 +0100848 if node.ignore_missing:
849 self.writeline('try:')
850 self.indent()
851 self.writeline('template = environment.get_template(', node)
852 self.visit(node.template, frame)
853 self.write(', %r)' % self.name)
854 if node.ignore_missing:
855 self.outdent()
856 self.writeline('except TemplateNotFound:')
857 self.indent()
858 self.writeline('pass')
859 self.outdent()
860 self.writeline('else:')
861 self.indent()
862
Armin Ronacherea847c52008-05-02 20:04:32 +0200863 if node.with_context:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200864 self.writeline('for event in template.root_render_func('
Armin Ronacher673aa882008-10-04 18:06:57 +0200865 'template.new_context(context.parent, True, '
866 'locals())):')
Armin Ronacherea847c52008-05-02 20:04:32 +0200867 else:
Armin Ronacher37f58ce2008-12-27 13:10:38 +0100868 self.writeline('for event in template.module._body_stream:')
869
Armin Ronacherf059ec12008-04-11 22:21:00 +0200870 self.indent()
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200871 self.simple_write('event', frame)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200872 self.outdent()
873
Armin Ronacher37f58ce2008-12-27 13:10:38 +0100874 if node.ignore_missing:
875 self.outdent()
876
Armin Ronacher0611e492008-04-25 23:44:14 +0200877 def visit_Import(self, node, frame):
878 """Visit regular imports."""
Armin Ronacher7887a8c2009-02-08 19:11:44 +0100879 if node.with_context:
880 self.unoptimize_scope(frame)
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200881 self.writeline('l_%s = ' % node.target, node)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200882 if frame.toplevel:
Armin Ronacher53042292008-04-26 18:30:19 +0200883 self.write('context.vars[%r] = ' % node.target)
Armin Ronacher0611e492008-04-25 23:44:14 +0200884 self.write('environment.get_template(')
885 self.visit(node.template, frame)
Armin Ronacherea847c52008-05-02 20:04:32 +0200886 self.write(', %r).' % self.name)
887 if node.with_context:
Armin Ronacher673aa882008-10-04 18:06:57 +0200888 self.write('make_module(context.parent, True, locals())')
Armin Ronacherea847c52008-05-02 20:04:32 +0200889 else:
890 self.write('module')
Armin Ronacher903d1682008-05-23 00:51:58 +0200891 if frame.toplevel and not node.target.startswith('_'):
Armin Ronacher53042292008-04-26 18:30:19 +0200892 self.writeline('context.exported_vars.discard(%r)' % node.target)
Armin Ronacher271a0eb2009-02-11 22:49:08 +0100893 frame.assigned_names.add(node.target)
Armin Ronacher0611e492008-04-25 23:44:14 +0200894
895 def visit_FromImport(self, node, frame):
896 """Visit named imports."""
897 self.newline(node)
898 self.write('included_template = environment.get_template(')
899 self.visit(node.template, frame)
Armin Ronacherea847c52008-05-02 20:04:32 +0200900 self.write(', %r).' % self.name)
901 if node.with_context:
902 self.write('make_module(context.parent, True)')
903 else:
904 self.write('module')
Armin Ronachera78d2762008-05-15 23:18:07 +0200905
906 var_names = []
907 discarded_names = []
Armin Ronacher0611e492008-04-25 23:44:14 +0200908 for name in node.names:
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200909 if isinstance(name, tuple):
910 name, alias = name
911 else:
912 alias = name
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200913 self.writeline('l_%s = getattr(included_template, '
914 '%r, missing)' % (alias, name))
915 self.writeline('if l_%s is missing:' % alias)
Armin Ronacher0611e492008-04-25 23:44:14 +0200916 self.indent()
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200917 self.writeline('l_%s = environment.undefined(%r %% '
Armin Ronacherdc02b642008-05-15 22:47:27 +0200918 'included_template.__name__, '
Armin Ronacher0a2ac692008-05-13 01:03:08 +0200919 'name=%r)' %
Armin Ronacher547d0b62008-07-04 16:35:10 +0200920 (alias, 'the template %%r (imported on %s) does '
921 'not export the requested name %s' % (
922 self.position(node),
923 repr(name)
924 ), name))
Armin Ronacher0611e492008-04-25 23:44:14 +0200925 self.outdent()
926 if frame.toplevel:
Armin Ronachera78d2762008-05-15 23:18:07 +0200927 var_names.append(alias)
Armin Ronacher903d1682008-05-23 00:51:58 +0200928 if not alias.startswith('_'):
Armin Ronachera78d2762008-05-15 23:18:07 +0200929 discarded_names.append(alias)
Armin Ronacher271a0eb2009-02-11 22:49:08 +0100930 frame.assigned_names.add(alias)
Armin Ronachera78d2762008-05-15 23:18:07 +0200931
932 if var_names:
933 if len(var_names) == 1:
934 name = var_names[0]
935 self.writeline('context.vars[%r] = l_%s' % (name, name))
936 else:
937 self.writeline('context.vars.update({%s})' % ', '.join(
938 '%r: l_%s' % (name, name) for name in var_names
939 ))
940 if discarded_names:
941 if len(discarded_names) == 1:
942 self.writeline('context.exported_vars.discard(%r)' %
943 discarded_names[0])
944 else:
945 self.writeline('context.exported_vars.difference_'
946 'update((%s))' % ', '.join(map(repr, discarded_names)))
Armin Ronacherf059ec12008-04-11 22:21:00 +0200947
Armin Ronachere791c2a2008-04-07 18:39:54 +0200948 def visit_For(self, node, frame):
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200949 # when calculating the nodes for the inner frame we have to exclude
950 # the iterator contents from it
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200951 children = node.iter_child_nodes(exclude=('iter',))
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200952 if node.recursive:
953 loop_frame = self.function_scoping(node, frame, children,
954 find_special=False)
955 else:
956 loop_frame = frame.inner()
957 loop_frame.inspect(children)
958
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200959 # try to figure out if we have an extended loop. An extended loop
960 # is necessary if the loop is in recursive mode if the special loop
961 # variable is accessed in the body.
962 extended_loop = node.recursive or 'loop' in \
963 find_undeclared(node.iter_child_nodes(
964 only=('body',)), ('loop',))
965
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200966 # if we don't have an recursive loop we have to find the shadowed
Armin Ronacherff53c782008-08-13 18:55:50 +0200967 # variables at that point. Because loops can be nested but the loop
968 # variable is a special one we have to enforce aliasing for it.
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200969 if not node.recursive:
Armin Ronacher673aa882008-10-04 18:06:57 +0200970 aliases = self.push_scope(loop_frame, ('loop',))
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200971
972 # otherwise we set up a buffer and add a function def
973 else:
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200974 self.writeline('def loop(reciter, loop_render_func):', node)
975 self.indent()
Armin Ronachered1e0d42008-05-18 20:25:28 +0200976 self.buffer(loop_frame)
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200977 aliases = {}
978
Armin Ronacherff53c782008-08-13 18:55:50 +0200979 # make sure the loop variable is a special one and raise a template
980 # assertion error if a loop tries to write to loop
Armin Ronacher833a3b52008-08-14 12:31:12 +0200981 if extended_loop:
982 loop_frame.identifiers.add_special('loop')
Armin Ronacherff53c782008-08-13 18:55:50 +0200983 for name in node.find_all(nodes.Name):
984 if name.ctx == 'store' and name.name == 'loop':
985 self.fail('Can\'t assign to special loop variable '
986 'in for-loop target', name.lineno)
987
Armin Ronacherc9705c22008-04-27 21:28:03 +0200988 self.pull_locals(loop_frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200989 if node.else_:
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200990 iteration_indicator = self.temporary_identifier()
991 self.writeline('%s = 1' % iteration_indicator)
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200992
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200993 # Create a fake parent loop if the else or test section of a
994 # loop is accessing the special loop variable and no parent loop
995 # exists.
996 if 'loop' not in aliases and 'loop' in find_undeclared(
997 node.iter_child_nodes(only=('else_', 'test')), ('loop',)):
998 self.writeline("l_loop = environment.undefined(%r, name='loop')" %
Armin Ronacher547d0b62008-07-04 16:35:10 +0200999 ("'loop' is undefined. the filter section of a loop as well "
1000 "as the else block doesn't have access to the special 'loop'"
1001 " variable of the current loop. Because there is no parent "
1002 "loop it's undefined. Happened in loop on %s" %
1003 self.position(node)))
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001004
1005 self.writeline('for ', node)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001006 self.visit(node.target, loop_frame)
Armin Ronacher180a1bd2008-04-09 12:14:24 +02001007 self.write(extended_loop and ', l_loop in LoopContext(' or ' in ')
Armin Ronacher3d8b7842008-04-13 13:16:50 +02001008
Armin Ronacher3d8b7842008-04-13 13:16:50 +02001009 # if we have an extened loop and a node test, we filter in the
1010 # "outer frame".
1011 if extended_loop and node.test is not None:
1012 self.write('(')
1013 self.visit(node.target, loop_frame)
1014 self.write(' for ')
1015 self.visit(node.target, loop_frame)
1016 self.write(' in ')
Armin Ronacher1e1e8902008-05-11 23:21:16 +02001017 if node.recursive:
1018 self.write('reciter')
1019 else:
1020 self.visit(node.iter, loop_frame)
Armin Ronacher3d8b7842008-04-13 13:16:50 +02001021 self.write(' if (')
1022 test_frame = loop_frame.copy()
Armin Ronacher3d8b7842008-04-13 13:16:50 +02001023 self.visit(node.test, test_frame)
1024 self.write('))')
1025
Armin Ronacher1e1e8902008-05-11 23:21:16 +02001026 elif node.recursive:
1027 self.write('reciter')
Armin Ronacher3d8b7842008-04-13 13:16:50 +02001028 else:
1029 self.visit(node.iter, loop_frame)
1030
Armin Ronacher1e1e8902008-05-11 23:21:16 +02001031 if node.recursive:
1032 self.write(', recurse=loop_render_func):')
1033 else:
1034 self.write(extended_loop and '):' or ':')
Armin Ronacher3d8b7842008-04-13 13:16:50 +02001035
1036 # tests in not extended loops become a continue
1037 if not extended_loop and node.test is not None:
1038 self.indent()
Armin Ronacher47a506f2008-05-06 12:17:23 +02001039 self.writeline('if not ')
Armin Ronacher32a910f2008-04-26 23:21:03 +02001040 self.visit(node.test, loop_frame)
Armin Ronacher3d8b7842008-04-13 13:16:50 +02001041 self.write(':')
1042 self.indent()
1043 self.writeline('continue')
1044 self.outdent(2)
1045
Armin Ronacherc9705c22008-04-27 21:28:03 +02001046 self.indent()
Armin Ronacherf40c8842008-09-17 18:51:26 +02001047 self.blockvisit(node.body, loop_frame)
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001048 if node.else_:
1049 self.writeline('%s = 0' % iteration_indicator)
Armin Ronacherc9705c22008-04-27 21:28:03 +02001050 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +02001051
1052 if node.else_:
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001053 self.writeline('if %s:' % iteration_indicator)
Armin Ronacher3d8b7842008-04-13 13:16:50 +02001054 self.indent()
Armin Ronacherf40c8842008-09-17 18:51:26 +02001055 self.blockvisit(node.else_, loop_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +02001056 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +02001057
Armin Ronacherd4c64f72008-04-11 17:15:29 +02001058 # reset the aliases if there are any.
Armin Ronachercebd8382008-12-25 18:33:46 +01001059 if not node.recursive:
1060 self.pop_scope(aliases, loop_frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001061
Armin Ronacher1e1e8902008-05-11 23:21:16 +02001062 # if the node was recursive we have to return the buffer contents
1063 # and start the iteration code
1064 if node.recursive:
Armin Ronachered1e0d42008-05-18 20:25:28 +02001065 self.return_buffer_contents(loop_frame)
Armin Ronacher1e1e8902008-05-11 23:21:16 +02001066 self.outdent()
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001067 self.start_write(frame, node)
1068 self.write('loop(')
Armin Ronacher1e1e8902008-05-11 23:21:16 +02001069 self.visit(node.iter, frame)
1070 self.write(', loop)')
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001071 self.end_write(frame)
Armin Ronacher1e1e8902008-05-11 23:21:16 +02001072
Armin Ronachere791c2a2008-04-07 18:39:54 +02001073 def visit_If(self, node, frame):
Armin Ronacher75cfb862008-04-11 13:47:22 +02001074 if_frame = frame.soft()
Armin Ronachere791c2a2008-04-07 18:39:54 +02001075 self.writeline('if ', node)
Armin Ronacher75cfb862008-04-11 13:47:22 +02001076 self.visit(node.test, if_frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001077 self.write(':')
Armin Ronacherc9705c22008-04-27 21:28:03 +02001078 self.indent()
Armin Ronacher75cfb862008-04-11 13:47:22 +02001079 self.blockvisit(node.body, if_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +02001080 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +02001081 if node.else_:
1082 self.writeline('else:')
Armin Ronacherc9705c22008-04-27 21:28:03 +02001083 self.indent()
Armin Ronacher75cfb862008-04-11 13:47:22 +02001084 self.blockvisit(node.else_, if_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +02001085 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +02001086
Armin Ronacher8efc5222008-04-08 14:47:40 +02001087 def visit_Macro(self, node, frame):
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001088 macro_frame = self.macro_body(node, frame)
Armin Ronacher8efc5222008-04-08 14:47:40 +02001089 self.newline()
1090 if frame.toplevel:
Armin Ronacher903d1682008-05-23 00:51:58 +02001091 if not node.name.startswith('_'):
Armin Ronacherc9705c22008-04-27 21:28:03 +02001092 self.write('context.exported_vars.add(%r)' % node.name)
Armin Ronacher32a910f2008-04-26 23:21:03 +02001093 self.writeline('context.vars[%r] = ' % node.name)
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001094 self.write('l_%s = ' % node.name)
1095 self.macro_def(node, macro_frame)
Armin Ronacher271a0eb2009-02-11 22:49:08 +01001096 frame.assigned_names.add(node.name)
Armin Ronacher71082072008-04-12 14:19:36 +02001097
1098 def visit_CallBlock(self, node, frame):
Armin Ronacher3da90312008-05-23 16:37:28 +02001099 children = node.iter_child_nodes(exclude=('call',))
1100 call_frame = self.macro_body(node, frame, children)
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001101 self.writeline('caller = ')
1102 self.macro_def(node, call_frame)
1103 self.start_write(frame, node)
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001104 self.visit_Call(node.call, call_frame, forward_caller=True)
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001105 self.end_write(frame)
Armin Ronacherfa865fb2008-04-12 22:11:53 +02001106
1107 def visit_FilterBlock(self, node, frame):
1108 filter_frame = frame.inner()
1109 filter_frame.inspect(node.iter_child_nodes())
Armin Ronacher673aa882008-10-04 18:06:57 +02001110 aliases = self.push_scope(filter_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +02001111 self.pull_locals(filter_frame)
Armin Ronachered1e0d42008-05-18 20:25:28 +02001112 self.buffer(filter_frame)
Armin Ronacherf40c8842008-09-17 18:51:26 +02001113 self.blockvisit(node.body, filter_frame)
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001114 self.start_write(frame, node)
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001115 self.visit_Filter(node.filter, filter_frame)
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001116 self.end_write(frame)
Armin Ronacher673aa882008-10-04 18:06:57 +02001117 self.pop_scope(aliases, filter_frame)
Armin Ronacher8efc5222008-04-08 14:47:40 +02001118
Armin Ronachere791c2a2008-04-07 18:39:54 +02001119 def visit_ExprStmt(self, node, frame):
1120 self.newline(node)
Armin Ronacher6ce170c2008-04-25 12:32:36 +02001121 self.visit(node.node, frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001122
1123 def visit_Output(self, node, frame):
Armin Ronacher75cfb862008-04-11 13:47:22 +02001124 # if we have a known extends statement, we don't output anything
Armin Ronacher79668952008-09-23 22:52:46 +02001125 # if we are in a require_output_check section
1126 if self.has_known_extends and frame.require_output_check:
Armin Ronacher75cfb862008-04-11 13:47:22 +02001127 return
Armin Ronachere791c2a2008-04-07 18:39:54 +02001128
Armin Ronacher665bfb82008-07-14 13:41:46 +02001129 if self.environment.finalize:
1130 finalize = lambda x: unicode(self.environment.finalize(x))
1131 else:
1132 finalize = unicode
1133
Armin Ronacher75cfb862008-04-11 13:47:22 +02001134 self.newline(node)
Armin Ronacher8edbe492008-04-10 20:43:43 +02001135
Armin Ronacher79668952008-09-23 22:52:46 +02001136 # if we are inside a frame that requires output checking, we do so
Armin Ronacher7fb38972008-04-11 13:54:28 +02001137 outdent_later = False
Armin Ronacher79668952008-09-23 22:52:46 +02001138 if frame.require_output_check:
Armin Ronacher203bfcb2008-04-24 21:54:44 +02001139 self.writeline('if parent_template is None:')
Armin Ronacher75cfb862008-04-11 13:47:22 +02001140 self.indent()
Armin Ronacher7fb38972008-04-11 13:54:28 +02001141 outdent_later = True
Armin Ronacher75cfb862008-04-11 13:47:22 +02001142
Armin Ronachere791c2a2008-04-07 18:39:54 +02001143 # try to evaluate as many chunks as possible into a static
1144 # string at compile time.
1145 body = []
1146 for child in node.nodes:
1147 try:
Armin Ronacher9cf95912008-05-24 19:54:43 +02001148 const = child.as_const()
1149 except nodes.Impossible:
1150 body.append(child)
1151 continue
1152 try:
1153 if self.environment.autoescape:
1154 if hasattr(const, '__html__'):
1155 const = const.__html__()
1156 else:
1157 const = escape(const)
Armin Ronacher665bfb82008-07-14 13:41:46 +02001158 const = finalize(const)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001159 except:
Armin Ronacher9cf95912008-05-24 19:54:43 +02001160 # if something goes wrong here we evaluate the node
1161 # at runtime for easier debugging
Armin Ronachere791c2a2008-04-07 18:39:54 +02001162 body.append(child)
1163 continue
1164 if body and isinstance(body[-1], list):
1165 body[-1].append(const)
1166 else:
1167 body.append([const])
1168
Armin Ronachered1e0d42008-05-18 20:25:28 +02001169 # if we have less than 3 nodes or a buffer we yield or extend/append
1170 if len(body) < 3 or frame.buffer is not None:
Armin Ronacher32a910f2008-04-26 23:21:03 +02001171 if frame.buffer is not None:
Armin Ronacher1e1e8902008-05-11 23:21:16 +02001172 # for one item we append, for more we extend
1173 if len(body) == 1:
1174 self.writeline('%s.append(' % frame.buffer)
1175 else:
1176 self.writeline('%s.extend((' % frame.buffer)
Armin Ronacher1f627ff2008-05-15 13:23:26 +02001177 self.indent()
Armin Ronachere791c2a2008-04-07 18:39:54 +02001178 for item in body:
1179 if isinstance(item, list):
Armin Ronacherde6bf712008-04-26 01:44:14 +02001180 val = repr(concat(item))
Armin Ronacherfa865fb2008-04-12 22:11:53 +02001181 if frame.buffer is None:
1182 self.writeline('yield ' + val)
1183 else:
Armin Ronacher1f627ff2008-05-15 13:23:26 +02001184 self.writeline(val + ', ')
Armin Ronachere791c2a2008-04-07 18:39:54 +02001185 else:
Armin Ronacherfa865fb2008-04-12 22:11:53 +02001186 if frame.buffer is None:
Armin Ronachered1e0d42008-05-18 20:25:28 +02001187 self.writeline('yield ', item)
Armin Ronacher1f627ff2008-05-15 13:23:26 +02001188 else:
1189 self.newline(item)
Armin Ronacherd1342312008-04-28 12:20:12 +02001190 close = 1
1191 if self.environment.autoescape:
1192 self.write('escape(')
1193 else:
1194 self.write('unicode(')
1195 if self.environment.finalize is not None:
1196 self.write('environment.finalize(')
1197 close += 1
Armin Ronachere791c2a2008-04-07 18:39:54 +02001198 self.visit(item, frame)
Armin Ronacherd1342312008-04-28 12:20:12 +02001199 self.write(')' * close)
Armin Ronacher32a910f2008-04-26 23:21:03 +02001200 if frame.buffer is not None:
1201 self.write(', ')
1202 if frame.buffer is not None:
Armin Ronacher1e1e8902008-05-11 23:21:16 +02001203 # close the open parentheses
Armin Ronacher1f627ff2008-05-15 13:23:26 +02001204 self.outdent()
1205 self.writeline(len(body) == 1 and ')' or '))')
Armin Ronachere791c2a2008-04-07 18:39:54 +02001206
1207 # otherwise we create a format string as this is faster in that case
1208 else:
1209 format = []
1210 arguments = []
1211 for item in body:
1212 if isinstance(item, list):
Armin Ronacherde6bf712008-04-26 01:44:14 +02001213 format.append(concat(item).replace('%', '%%'))
Armin Ronachere791c2a2008-04-07 18:39:54 +02001214 else:
1215 format.append('%s')
1216 arguments.append(item)
Armin Ronachered1e0d42008-05-18 20:25:28 +02001217 self.writeline('yield ')
Armin Ronacherde6bf712008-04-26 01:44:14 +02001218 self.write(repr(concat(format)) + ' % (')
Armin Ronachere791c2a2008-04-07 18:39:54 +02001219 idx = -1
Armin Ronachera7f016d2008-05-16 00:22:40 +02001220 self.indent()
Armin Ronacher8e8d0712008-04-16 23:10:49 +02001221 for argument in arguments:
Armin Ronachered1e0d42008-05-18 20:25:28 +02001222 self.newline(argument)
Armin Ronacherd1342312008-04-28 12:20:12 +02001223 close = 0
1224 if self.environment.autoescape:
1225 self.write('escape(')
1226 close += 1
1227 if self.environment.finalize is not None:
1228 self.write('environment.finalize(')
1229 close += 1
Armin Ronachere791c2a2008-04-07 18:39:54 +02001230 self.visit(argument, frame)
Armin Ronacher1f627ff2008-05-15 13:23:26 +02001231 self.write(')' * close + ', ')
Armin Ronachera7f016d2008-05-16 00:22:40 +02001232 self.outdent()
1233 self.writeline(')')
Armin Ronachere791c2a2008-04-07 18:39:54 +02001234
Armin Ronacher7fb38972008-04-11 13:54:28 +02001235 if outdent_later:
Armin Ronacher75cfb862008-04-11 13:47:22 +02001236 self.outdent()
1237
Armin Ronacher8efc5222008-04-08 14:47:40 +02001238 def visit_Assign(self, node, frame):
1239 self.newline(node)
1240 # toplevel assignments however go into the local namespace and
1241 # the current template's context. We create a copy of the frame
1242 # here and add a set so that the Name visitor can add the assigned
1243 # names here.
1244 if frame.toplevel:
1245 assignment_frame = frame.copy()
Armin Ronacher271a0eb2009-02-11 22:49:08 +01001246 assignment_frame.toplevel_assignments = set()
Armin Ronacher8efc5222008-04-08 14:47:40 +02001247 else:
1248 assignment_frame = frame
1249 self.visit(node.target, assignment_frame)
1250 self.write(' = ')
1251 self.visit(node.node, frame)
Armin Ronacher9706fab2008-04-08 18:49:56 +02001252
1253 # make sure toplevel assignments are added to the context.
Armin Ronacher8efc5222008-04-08 14:47:40 +02001254 if frame.toplevel:
Armin Ronacher271a0eb2009-02-11 22:49:08 +01001255 public_names = [x for x in assignment_frame.toplevel_assignments
Armin Ronacher903d1682008-05-23 00:51:58 +02001256 if not x.startswith('_')]
Armin Ronacher271a0eb2009-02-11 22:49:08 +01001257 if len(assignment_frame.toplevel_assignments) == 1:
1258 name = iter(assignment_frame.toplevel_assignments).next()
Armin Ronacherd1ff8582008-05-11 00:30:43 +02001259 self.writeline('context.vars[%r] = l_%s' % (name, name))
Armin Ronacher69e12db2008-05-12 09:00:03 +02001260 else:
1261 self.writeline('context.vars.update({')
Armin Ronacher271a0eb2009-02-11 22:49:08 +01001262 for idx, name in enumerate(assignment_frame.toplevel_assignments):
Armin Ronacher69e12db2008-05-12 09:00:03 +02001263 if idx:
1264 self.write(', ')
1265 self.write('%r: l_%s' % (name, name))
1266 self.write('})')
1267 if public_names:
1268 if len(public_names) == 1:
1269 self.writeline('context.exported_vars.add(%r)' %
1270 public_names[0])
1271 else:
1272 self.writeline('context.exported_vars.update((%s))' %
1273 ', '.join(map(repr, public_names)))
Armin Ronacher8efc5222008-04-08 14:47:40 +02001274
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001275 # -- Expression Visitors
1276
Armin Ronachere791c2a2008-04-07 18:39:54 +02001277 def visit_Name(self, node, frame):
Armin Ronacherc9705c22008-04-27 21:28:03 +02001278 if node.ctx == 'store' and frame.toplevel:
Armin Ronacher271a0eb2009-02-11 22:49:08 +01001279 frame.toplevel_assignments.add(node.name)
Armin Ronacherd1ff8582008-05-11 00:30:43 +02001280 self.write('l_' + node.name)
Armin Ronacher271a0eb2009-02-11 22:49:08 +01001281 frame.assigned_names.add(node.name)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001282
1283 def visit_Const(self, node, frame):
1284 val = node.value
1285 if isinstance(val, float):
Armin Ronachere791c2a2008-04-07 18:39:54 +02001286 self.write(str(val))
1287 else:
1288 self.write(repr(val))
1289
Armin Ronacher5411ce72008-05-25 11:36:22 +02001290 def visit_TemplateData(self, node, frame):
1291 self.write(repr(node.as_const()))
1292
Armin Ronacher8efc5222008-04-08 14:47:40 +02001293 def visit_Tuple(self, node, frame):
1294 self.write('(')
1295 idx = -1
1296 for idx, item in enumerate(node.items):
1297 if idx:
1298 self.write(', ')
1299 self.visit(item, frame)
1300 self.write(idx == 0 and ',)' or ')')
1301
Armin Ronacher8edbe492008-04-10 20:43:43 +02001302 def visit_List(self, node, frame):
1303 self.write('[')
1304 for idx, item in enumerate(node.items):
1305 if idx:
1306 self.write(', ')
1307 self.visit(item, frame)
1308 self.write(']')
1309
1310 def visit_Dict(self, node, frame):
1311 self.write('{')
1312 for idx, item in enumerate(node.items):
1313 if idx:
1314 self.write(', ')
1315 self.visit(item.key, frame)
1316 self.write(': ')
1317 self.visit(item.value, frame)
1318 self.write('}')
1319
Armin Ronachere791c2a2008-04-07 18:39:54 +02001320 def binop(operator):
1321 def visitor(self, node, frame):
1322 self.write('(')
1323 self.visit(node.left, frame)
1324 self.write(' %s ' % operator)
1325 self.visit(node.right, frame)
1326 self.write(')')
1327 return visitor
1328
1329 def uaop(operator):
1330 def visitor(self, node, frame):
1331 self.write('(' + operator)
Armin Ronacher9a822052008-04-17 18:44:07 +02001332 self.visit(node.node, frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001333 self.write(')')
1334 return visitor
1335
1336 visit_Add = binop('+')
1337 visit_Sub = binop('-')
1338 visit_Mul = binop('*')
1339 visit_Div = binop('/')
1340 visit_FloorDiv = binop('//')
1341 visit_Pow = binop('**')
1342 visit_Mod = binop('%')
1343 visit_And = binop('and')
1344 visit_Or = binop('or')
1345 visit_Pos = uaop('+')
1346 visit_Neg = uaop('-')
1347 visit_Not = uaop('not ')
1348 del binop, uaop
1349
Armin Ronacherd1342312008-04-28 12:20:12 +02001350 def visit_Concat(self, node, frame):
Armin Ronacherfdf95302008-05-11 22:20:51 +02001351 self.write('%s((' % (self.environment.autoescape and
1352 'markup_join' or 'unicode_join'))
Armin Ronacherd1342312008-04-28 12:20:12 +02001353 for arg in node.nodes:
1354 self.visit(arg, frame)
1355 self.write(', ')
1356 self.write('))')
1357
Armin Ronachere791c2a2008-04-07 18:39:54 +02001358 def visit_Compare(self, node, frame):
1359 self.visit(node.expr, frame)
1360 for op in node.ops:
1361 self.visit(op, frame)
1362
1363 def visit_Operand(self, node, frame):
1364 self.write(' %s ' % operators[node.op])
1365 self.visit(node.expr, frame)
1366
Armin Ronacher6dc6f292008-06-12 08:50:07 +02001367 def visit_Getattr(self, node, frame):
1368 self.write('environment.getattr(')
1369 self.visit(node.node, frame)
1370 self.write(', %r)' % node.attr)
1371
1372 def visit_Getitem(self, node, frame):
Armin Ronacher5c3c4702008-09-12 23:12:49 +02001373 # slices bypass the environment getitem method.
1374 if isinstance(node.arg, nodes.Slice):
Armin Ronacher8efc5222008-04-08 14:47:40 +02001375 self.visit(node.node, frame)
1376 self.write('[')
1377 self.visit(node.arg, frame)
1378 self.write(']')
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001379 else:
Armin Ronacher6dc6f292008-06-12 08:50:07 +02001380 self.write('environment.getitem(')
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001381 self.visit(node.node, frame)
1382 self.write(', ')
1383 self.visit(node.arg, frame)
1384 self.write(')')
Armin Ronacher8efc5222008-04-08 14:47:40 +02001385
1386 def visit_Slice(self, node, frame):
1387 if node.start is not None:
1388 self.visit(node.start, frame)
1389 self.write(':')
1390 if node.stop is not None:
1391 self.visit(node.stop, frame)
1392 if node.step is not None:
1393 self.write(':')
1394 self.visit(node.step, frame)
1395
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001396 def visit_Filter(self, node, frame):
Armin Ronacherb9e78752008-05-10 23:36:28 +02001397 self.write(self.filters[node.name] + '(')
Christoph Hack80909862008-04-14 01:35:10 +02001398 func = self.environment.filters.get(node.name)
Armin Ronacher0611e492008-04-25 23:44:14 +02001399 if func is None:
Armin Ronachere2244882008-05-19 09:25:57 +02001400 self.fail('no filter named %r' % node.name, node.lineno)
Christoph Hack80909862008-04-14 01:35:10 +02001401 if getattr(func, 'contextfilter', False):
1402 self.write('context, ')
Armin Ronacher9a027f42008-04-17 11:13:40 +02001403 elif getattr(func, 'environmentfilter', False):
1404 self.write('environment, ')
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001405
1406 # if the filter node is None we are inside a filter block
1407 # and want to write to the current buffer
Armin Ronacher3da90312008-05-23 16:37:28 +02001408 if node.node is not None:
Armin Ronacherfa865fb2008-04-12 22:11:53 +02001409 self.visit(node.node, frame)
Armin Ronacher3da90312008-05-23 16:37:28 +02001410 elif self.environment.autoescape:
1411 self.write('Markup(concat(%s))' % frame.buffer)
1412 else:
1413 self.write('concat(%s)' % frame.buffer)
Armin Ronacherd55ab532008-04-09 16:13:39 +02001414 self.signature(node, frame)
1415 self.write(')')
Armin Ronacher8efc5222008-04-08 14:47:40 +02001416
1417 def visit_Test(self, node, frame):
Armin Ronacherb9e78752008-05-10 23:36:28 +02001418 self.write(self.tests[node.name] + '(')
Armin Ronacher0611e492008-04-25 23:44:14 +02001419 if node.name not in self.environment.tests:
Armin Ronachere2244882008-05-19 09:25:57 +02001420 self.fail('no test named %r' % node.name, node.lineno)
Armin Ronacher8efc5222008-04-08 14:47:40 +02001421 self.visit(node.node, frame)
1422 self.signature(node, frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001423 self.write(')')
Armin Ronacher8efc5222008-04-08 14:47:40 +02001424
Armin Ronacher3d8b7842008-04-13 13:16:50 +02001425 def visit_CondExpr(self, node, frame):
Armin Ronacher547d0b62008-07-04 16:35:10 +02001426 def write_expr2():
1427 if node.expr2 is not None:
1428 return self.visit(node.expr2, frame)
1429 self.write('environment.undefined(%r)' % ('the inline if-'
1430 'expression on %s evaluated to false and '
1431 'no else section was defined.' % self.position(node)))
1432
Armin Ronacher3d8b7842008-04-13 13:16:50 +02001433 if not have_condexpr:
1434 self.write('((')
1435 self.visit(node.test, frame)
1436 self.write(') and (')
1437 self.visit(node.expr1, frame)
1438 self.write(',) or (')
Armin Ronacher547d0b62008-07-04 16:35:10 +02001439 write_expr2()
Armin Ronacher3d8b7842008-04-13 13:16:50 +02001440 self.write(',))[0]')
1441 else:
1442 self.write('(')
1443 self.visit(node.expr1, frame)
1444 self.write(' if ')
1445 self.visit(node.test, frame)
1446 self.write(' else ')
Armin Ronacher547d0b62008-07-04 16:35:10 +02001447 write_expr2()
Armin Ronacher3d8b7842008-04-13 13:16:50 +02001448 self.write(')')
1449
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001450 def visit_Call(self, node, frame, forward_caller=False):
Armin Ronacherc63243e2008-04-14 22:53:58 +02001451 if self.environment.sandboxed:
Armin Ronacherfd310492008-05-25 00:16:51 +02001452 self.write('environment.call(context, ')
1453 else:
1454 self.write('context.call(')
Armin Ronacher8efc5222008-04-08 14:47:40 +02001455 self.visit(node.node, frame)
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001456 extra_kwargs = forward_caller and {'caller': 'caller'} or None
Armin Ronacherfd310492008-05-25 00:16:51 +02001457 self.signature(node, frame, extra_kwargs)
Armin Ronacher8efc5222008-04-08 14:47:40 +02001458 self.write(')')
1459
1460 def visit_Keyword(self, node, frame):
Armin Ronacher2e9396b2008-04-16 14:21:57 +02001461 self.write(node.key + '=')
Armin Ronacher8efc5222008-04-08 14:47:40 +02001462 self.visit(node.value, frame)
Armin Ronachered1e0d42008-05-18 20:25:28 +02001463
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001464 # -- Unused nodes for extensions
Armin Ronachered1e0d42008-05-18 20:25:28 +02001465
1466 def visit_MarkSafe(self, node, frame):
1467 self.write('Markup(')
1468 self.visit(node.expr, frame)
1469 self.write(')')
1470
1471 def visit_EnvironmentAttribute(self, node, frame):
1472 self.write('environment.' + node.name)
1473
1474 def visit_ExtensionAttribute(self, node, frame):
Armin Ronacher6df604e2008-05-23 22:18:38 +02001475 self.write('environment.extensions[%r].%s' % (node.identifier, node.name))
Armin Ronachered1e0d42008-05-18 20:25:28 +02001476
1477 def visit_ImportedName(self, node, frame):
1478 self.write(self.import_aliases[node.importname])
1479
1480 def visit_InternalName(self, node, frame):
1481 self.write(node.name)
1482
Armin Ronacher6df604e2008-05-23 22:18:38 +02001483 def visit_ContextReference(self, node, frame):
1484 self.write('context')
1485
Armin Ronachered1e0d42008-05-18 20:25:28 +02001486 def visit_Continue(self, node, frame):
1487 self.writeline('continue', node)
1488
1489 def visit_Break(self, node, frame):
1490 self.writeline('break', node)
Armin Ronacher271a0eb2009-02-11 22:49:08 +01001491
1492 def visit_Scope(self, node, frame):
1493 scope_frame = frame.inner()
1494 scope_frame.inspect(node.iter_child_nodes())
1495 aliases = self.push_scope(scope_frame)
1496 self.pull_locals(scope_frame)
1497 self.blockvisit(node.body, scope_frame)
1498 self.pop_scope(aliases, scope_frame)