blob: e17aa1de80023cff06323340fad221adf9d350b3 [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
8 :copyright: Copyright 2008 by Armin Ronacher.
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 Ronacherff53c782008-08-13 18:55:50 +0200118 def find_shadowed(self, extra=()):
119 """Find all the shadowed names. extra is an iterable of variables
120 that may be defined with `add_special` which may occour scoped.
121 """
Armin Ronacher10f3ba22008-04-18 11:30:37 +0200122 return (self.declared | self.outer_undeclared) & \
Armin Ronacherff53c782008-08-13 18:55:50 +0200123 (self.declared_locally | self.declared_parameter) | \
124 set(x for x in extra if self.is_declared(x))
Armin Ronachere791c2a2008-04-07 18:39:54 +0200125
126
127class Frame(object):
Armin Ronacher75cfb862008-04-11 13:47:22 +0200128 """Holds compile time information for us."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200129
130 def __init__(self, parent=None):
131 self.identifiers = Identifiers()
Armin Ronacherfed44b52008-04-13 19:42:53 +0200132
Armin Ronacher75cfb862008-04-11 13:47:22 +0200133 # a toplevel frame is the root + soft frames such as if conditions.
Armin Ronacher8efc5222008-04-08 14:47:40 +0200134 self.toplevel = False
Armin Ronacherfed44b52008-04-13 19:42:53 +0200135
Armin Ronacher75cfb862008-04-11 13:47:22 +0200136 # the root frame is basically just the outermost frame, so no if
137 # conditions. This information is used to optimize inheritance
138 # situations.
139 self.rootlevel = False
Armin Ronacherfed44b52008-04-13 19:42:53 +0200140
Armin Ronacher79668952008-09-23 22:52:46 +0200141 # in some dynamic inheritance situations the compiler needs to add
142 # write tests around output statements.
143 self.require_output_check = parent and parent.require_output_check
Armin Ronacherf40c8842008-09-17 18:51:26 +0200144
Armin Ronacherfed44b52008-04-13 19:42:53 +0200145 # inside some tags we are using a buffer rather than yield statements.
146 # this for example affects {% filter %} or {% macro %}. If a frame
147 # is buffered this variable points to the name of the list used as
148 # buffer.
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200149 self.buffer = None
Armin Ronacherfed44b52008-04-13 19:42:53 +0200150
Armin Ronacherfed44b52008-04-13 19:42:53 +0200151 # the name of the block we're in, otherwise None.
Armin Ronacher8efc5222008-04-08 14:47:40 +0200152 self.block = parent and parent.block or None
Armin Ronacherfed44b52008-04-13 19:42:53 +0200153
154 # the parent of this frame
155 self.parent = parent
156
Armin Ronachere791c2a2008-04-07 18:39:54 +0200157 if parent is not None:
158 self.identifiers.declared.update(
159 parent.identifiers.declared |
Armin Ronachere791c2a2008-04-07 18:39:54 +0200160 parent.identifiers.declared_locally |
Armin Ronacherb3a1fcf2008-05-15 11:04:14 +0200161 parent.identifiers.declared_parameter |
162 parent.identifiers.undeclared
Armin Ronachere791c2a2008-04-07 18:39:54 +0200163 )
Armin Ronacher10f3ba22008-04-18 11:30:37 +0200164 self.identifiers.outer_undeclared.update(
165 parent.identifiers.undeclared -
166 self.identifiers.declared
167 )
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200168 self.buffer = parent.buffer
Armin Ronachere791c2a2008-04-07 18:39:54 +0200169
Armin Ronacher8efc5222008-04-08 14:47:40 +0200170 def copy(self):
171 """Create a copy of the current one."""
Armin Ronacher9a0078d2008-08-13 18:24:17 +0200172 rv = object.__new__(self.__class__)
173 rv.__dict__.update(self.__dict__)
174 rv.identifiers = object.__new__(self.identifiers.__class__)
175 rv.identifiers.__dict__.update(self.identifiers.__dict__)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200176 return rv
177
Armin Ronacherc9705c22008-04-27 21:28:03 +0200178 def inspect(self, nodes, hard_scope=False):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200179 """Walk the node and check for identifiers. If the scope is hard (eg:
180 enforce on a python level) overrides from outer scopes are tracked
181 differently.
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200182 """
183 visitor = FrameIdentifierVisitor(self.identifiers, hard_scope)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200184 for node in nodes:
Armin Ronacherc9705c22008-04-27 21:28:03 +0200185 visitor.visit(node)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200186
187 def inner(self):
188 """Return an inner frame."""
189 return Frame(self)
190
Armin Ronacher75cfb862008-04-11 13:47:22 +0200191 def soft(self):
192 """Return a soft frame. A soft frame may not be modified as
193 standalone thing as it shares the resources with the frame it
194 was created of, but it's not a rootlevel frame any longer.
195 """
Armin Ronacher9a0078d2008-08-13 18:24:17 +0200196 rv = self.copy()
Armin Ronacher75cfb862008-04-11 13:47:22 +0200197 rv.rootlevel = False
198 return rv
199
Armin Ronacher9a0078d2008-08-13 18:24:17 +0200200 __copy__ = copy
201
Armin Ronachere791c2a2008-04-07 18:39:54 +0200202
Armin Ronacherc9705c22008-04-27 21:28:03 +0200203class VisitorExit(RuntimeError):
204 """Exception used by the `UndeclaredNameVisitor` to signal a stop."""
205
206
207class DependencyFinderVisitor(NodeVisitor):
208 """A visitor that collects filter and test calls."""
209
210 def __init__(self):
211 self.filters = set()
212 self.tests = set()
213
214 def visit_Filter(self, node):
215 self.generic_visit(node)
216 self.filters.add(node.name)
217
218 def visit_Test(self, node):
219 self.generic_visit(node)
220 self.tests.add(node.name)
221
222 def visit_Block(self, node):
223 """Stop visiting at blocks."""
224
225
226class UndeclaredNameVisitor(NodeVisitor):
227 """A visitor that checks if a name is accessed without being
228 declared. This is different from the frame visitor as it will
229 not stop at closure frames.
230 """
231
232 def __init__(self, names):
233 self.names = set(names)
234 self.undeclared = set()
235
236 def visit_Name(self, node):
237 if node.ctx == 'load' and node.name in self.names:
238 self.undeclared.add(node.name)
239 if self.undeclared == self.names:
240 raise VisitorExit()
241 else:
242 self.names.discard(node.name)
243
244 def visit_Block(self, node):
245 """Stop visiting a blocks."""
246
247
Armin Ronachere791c2a2008-04-07 18:39:54 +0200248class FrameIdentifierVisitor(NodeVisitor):
249 """A visitor for `Frame.inspect`."""
250
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200251 def __init__(self, identifiers, hard_scope):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200252 self.identifiers = identifiers
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200253 self.hard_scope = hard_scope
Armin Ronachere791c2a2008-04-07 18:39:54 +0200254
Armin Ronacherc9705c22008-04-27 21:28:03 +0200255 def visit_Name(self, node):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200256 """All assignments to names go through this function."""
Armin Ronachere9411b42008-05-15 16:22:07 +0200257 if node.ctx == 'store':
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200258 self.identifiers.declared_locally.add(node.name)
Armin Ronachere9411b42008-05-15 16:22:07 +0200259 elif node.ctx == 'param':
260 self.identifiers.declared_parameter.add(node.name)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200261 elif node.ctx == 'load' and not \
262 self.identifiers.is_declared(node.name, self.hard_scope):
263 self.identifiers.undeclared.add(node.name)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200264
Armin Ronacherc9705c22008-04-27 21:28:03 +0200265 def visit_Macro(self, node):
Armin Ronacherc9705c22008-04-27 21:28:03 +0200266 self.identifiers.declared_locally.add(node.name)
Armin Ronacher0611e492008-04-25 23:44:14 +0200267
Armin Ronacherc9705c22008-04-27 21:28:03 +0200268 def visit_Import(self, node):
269 self.generic_visit(node)
270 self.identifiers.declared_locally.add(node.target)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200271
Armin Ronacherc9705c22008-04-27 21:28:03 +0200272 def visit_FromImport(self, node):
273 self.generic_visit(node)
274 for name in node.names:
275 if isinstance(name, tuple):
276 self.identifiers.declared_locally.add(name[1])
277 else:
278 self.identifiers.declared_locally.add(name)
279
280 def visit_Assign(self, node):
Armin Ronacherebe55aa2008-04-10 20:51:23 +0200281 """Visit assignments in the correct order."""
Armin Ronacherc9705c22008-04-27 21:28:03 +0200282 self.visit(node.node)
283 self.visit(node.target)
Armin Ronacherebe55aa2008-04-10 20:51:23 +0200284
Armin Ronacherc9705c22008-04-27 21:28:03 +0200285 def visit_For(self, node):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200286 """Visiting stops at for blocks. However the block sequence
287 is visited as part of the outer scope.
288 """
Armin Ronacherc9705c22008-04-27 21:28:03 +0200289 self.visit(node.iter)
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200290
Armin Ronacherc9705c22008-04-27 21:28:03 +0200291 def visit_CallBlock(self, node):
292 for child in node.iter_child_nodes(exclude=('body',)):
293 self.visit(child)
294
295 def visit_FilterBlock(self, node):
296 self.visit(node.filter)
297
298 def visit_Block(self, node):
299 """Stop visiting at blocks."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200300
301
Armin Ronacher75cfb862008-04-11 13:47:22 +0200302class CompilerExit(Exception):
303 """Raised if the compiler encountered a situation where it just
304 doesn't make sense to further process the code. Any block that
Armin Ronacher0611e492008-04-25 23:44:14 +0200305 raises such an exception is not further processed.
306 """
Armin Ronacher75cfb862008-04-11 13:47:22 +0200307
308
Armin Ronachere791c2a2008-04-07 18:39:54 +0200309class CodeGenerator(NodeVisitor):
310
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200311 def __init__(self, environment, name, filename, stream=None):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200312 if stream is None:
313 stream = StringIO()
Christoph Hack65642a52008-04-08 14:46:56 +0200314 self.environment = environment
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200315 self.name = name
Armin Ronachere791c2a2008-04-07 18:39:54 +0200316 self.filename = filename
317 self.stream = stream
Armin Ronacherfed44b52008-04-13 19:42:53 +0200318
Armin Ronacher023b5e92008-05-08 11:03:10 +0200319 # aliases for imports
320 self.import_aliases = {}
321
Armin Ronacherfed44b52008-04-13 19:42:53 +0200322 # a registry for all blocks. Because blocks are moved out
323 # into the global python scope they are registered here
Armin Ronachere791c2a2008-04-07 18:39:54 +0200324 self.blocks = {}
Armin Ronacherfed44b52008-04-13 19:42:53 +0200325
326 # the number of extends statements so far
Armin Ronacher7fb38972008-04-11 13:54:28 +0200327 self.extends_so_far = 0
Armin Ronacherfed44b52008-04-13 19:42:53 +0200328
329 # some templates have a rootlevel extends. In this case we
330 # can safely assume that we're a child template and do some
331 # more optimizations.
Armin Ronacher75cfb862008-04-11 13:47:22 +0200332 self.has_known_extends = False
Armin Ronacherfed44b52008-04-13 19:42:53 +0200333
Armin Ronacherba3757b2008-04-16 19:43:16 +0200334 # the current line number
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200335 self.code_lineno = 1
Armin Ronacherba3757b2008-04-16 19:43:16 +0200336
Armin Ronacherb9e78752008-05-10 23:36:28 +0200337 # registry of all filters and tests (global, not block local)
338 self.tests = {}
339 self.filters = {}
340
Armin Ronacherba3757b2008-04-16 19:43:16 +0200341 # the debug information
342 self.debug_info = []
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200343 self._write_debug_info = None
Armin Ronacherba3757b2008-04-16 19:43:16 +0200344
Armin Ronacherfed44b52008-04-13 19:42:53 +0200345 # the number of new lines before the next write()
346 self._new_lines = 0
347
348 # the line number of the last written statement
Armin Ronachere791c2a2008-04-07 18:39:54 +0200349 self._last_line = 0
Armin Ronacherfed44b52008-04-13 19:42:53 +0200350
351 # true if nothing was written so far.
Armin Ronachere791c2a2008-04-07 18:39:54 +0200352 self._first_write = True
353
Armin Ronacherfed44b52008-04-13 19:42:53 +0200354 # used by the `temporary_identifier` method to get new
355 # unique, temporary identifier
356 self._last_identifier = 0
357
358 # the current indentation
359 self._indentation = 0
360
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200361 # -- Various compilation helpers
362
Armin Ronachere2244882008-05-19 09:25:57 +0200363 def fail(self, msg, lineno):
364 """Fail with a `TemplateAssertionError`."""
365 raise TemplateAssertionError(msg, lineno, self.name, self.filename)
366
Armin Ronachere791c2a2008-04-07 18:39:54 +0200367 def temporary_identifier(self):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200368 """Get a new unique identifier."""
369 self._last_identifier += 1
Armin Ronacher8a1d27f2008-05-19 08:37:19 +0200370 return 't_%d' % self._last_identifier
Armin Ronachere791c2a2008-04-07 18:39:54 +0200371
Armin Ronachered1e0d42008-05-18 20:25:28 +0200372 def buffer(self, frame):
373 """Enable buffering for the frame from that point onwards."""
Armin Ronachere2244882008-05-19 09:25:57 +0200374 frame.buffer = self.temporary_identifier()
375 self.writeline('%s = []' % frame.buffer)
Armin Ronachered1e0d42008-05-18 20:25:28 +0200376
377 def return_buffer_contents(self, frame):
378 """Return the buffer contents of the frame."""
379 if self.environment.autoescape:
380 self.writeline('return Markup(concat(%s))' % frame.buffer)
381 else:
382 self.writeline('return concat(%s)' % frame.buffer)
383
Armin Ronachere791c2a2008-04-07 18:39:54 +0200384 def indent(self):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200385 """Indent by one."""
386 self._indentation += 1
Armin Ronachere791c2a2008-04-07 18:39:54 +0200387
Armin Ronacher8efc5222008-04-08 14:47:40 +0200388 def outdent(self, step=1):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200389 """Outdent by step."""
390 self._indentation -= step
Armin Ronachere791c2a2008-04-07 18:39:54 +0200391
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200392 def start_write(self, frame, node=None):
393 """Yield or write into the frame buffer."""
394 if frame.buffer is None:
395 self.writeline('yield ', node)
396 else:
397 self.writeline('%s.append(' % frame.buffer, node)
398
399 def end_write(self, frame):
400 """End the writing process started by `start_write`."""
401 if frame.buffer is not None:
402 self.write(')')
403
404 def simple_write(self, s, frame, node=None):
405 """Simple shortcut for start_write + write + end_write."""
406 self.start_write(frame, node)
407 self.write(s)
408 self.end_write(frame)
409
Armin Ronacherf40c8842008-09-17 18:51:26 +0200410 def blockvisit(self, nodes, frame):
Armin Ronacherc9705c22008-04-27 21:28:03 +0200411 """Visit a list of nodes as block in a frame. If the current frame
412 is no buffer a dummy ``if 0: yield None`` is written automatically
413 unless the force_generator parameter is set to False.
Armin Ronacherfed44b52008-04-13 19:42:53 +0200414 """
Armin Ronacherf40c8842008-09-17 18:51:26 +0200415 if frame.buffer is None:
Armin Ronachere791c2a2008-04-07 18:39:54 +0200416 self.writeline('if 0: yield None')
Armin Ronacherf40c8842008-09-17 18:51:26 +0200417 else:
418 self.writeline('pass')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200419 try:
420 for node in nodes:
421 self.visit(node, frame)
422 except CompilerExit:
423 pass
Armin Ronachere791c2a2008-04-07 18:39:54 +0200424
425 def write(self, x):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200426 """Write a string into the output stream."""
427 if self._new_lines:
Armin Ronachere791c2a2008-04-07 18:39:54 +0200428 if not self._first_write:
Armin Ronacherfed44b52008-04-13 19:42:53 +0200429 self.stream.write('\n' * self._new_lines)
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200430 self.code_lineno += self._new_lines
431 if self._write_debug_info is not None:
432 self.debug_info.append((self._write_debug_info,
433 self.code_lineno))
434 self._write_debug_info = None
Armin Ronachere791c2a2008-04-07 18:39:54 +0200435 self._first_write = False
Armin Ronacherfed44b52008-04-13 19:42:53 +0200436 self.stream.write(' ' * self._indentation)
437 self._new_lines = 0
Armin Ronachere791c2a2008-04-07 18:39:54 +0200438 self.stream.write(x)
439
440 def writeline(self, x, node=None, extra=0):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200441 """Combination of newline and write."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200442 self.newline(node, extra)
443 self.write(x)
444
445 def newline(self, node=None, extra=0):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200446 """Add one or more newlines before the next write."""
447 self._new_lines = max(self._new_lines, 1 + extra)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200448 if node is not None and node.lineno != self._last_line:
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200449 self._write_debug_info = node.lineno
450 self._last_line = node.lineno
Armin Ronachere791c2a2008-04-07 18:39:54 +0200451
Armin Ronacherfd310492008-05-25 00:16:51 +0200452 def signature(self, node, frame, extra_kwargs=None):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200453 """Writes a function call to the stream for the current node.
Armin Ronacherfd310492008-05-25 00:16:51 +0200454 A leading comma is added automatically. The extra keyword
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200455 arguments may not include python keywords otherwise a syntax
456 error could occour. The extra keyword arguments should be given
457 as python dict.
Armin Ronacherfed44b52008-04-13 19:42:53 +0200458 """
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200459 # if any of the given keyword arguments is a python keyword
460 # we have to make sure that no invalid call is created.
461 kwarg_workaround = False
462 for kwarg in chain((x.key for x in node.kwargs), extra_kwargs or ()):
Armin Ronacher9a0078d2008-08-13 18:24:17 +0200463 if is_python_keyword(kwarg):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200464 kwarg_workaround = True
465 break
466
Armin Ronacher8efc5222008-04-08 14:47:40 +0200467 for arg in node.args:
Armin Ronacherfd310492008-05-25 00:16:51 +0200468 self.write(', ')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200469 self.visit(arg, frame)
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200470
471 if not kwarg_workaround:
472 for kwarg in node.kwargs:
Armin Ronacherfd310492008-05-25 00:16:51 +0200473 self.write(', ')
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200474 self.visit(kwarg, frame)
475 if extra_kwargs is not None:
476 for key, value in extra_kwargs.iteritems():
Armin Ronacherfd310492008-05-25 00:16:51 +0200477 self.write(', %s=%s' % (key, value))
Armin Ronacher8efc5222008-04-08 14:47:40 +0200478 if node.dyn_args:
Armin Ronacherfd310492008-05-25 00:16:51 +0200479 self.write(', *')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200480 self.visit(node.dyn_args, frame)
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200481
482 if kwarg_workaround:
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200483 if node.dyn_kwargs is not None:
Armin Ronacherfd310492008-05-25 00:16:51 +0200484 self.write(', **dict({')
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200485 else:
Armin Ronacherfd310492008-05-25 00:16:51 +0200486 self.write(', **{')
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200487 for kwarg in node.kwargs:
488 self.write('%r: ' % kwarg.key)
489 self.visit(kwarg.value, frame)
490 self.write(', ')
491 if extra_kwargs is not None:
492 for key, value in extra_kwargs.iteritems():
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200493 self.write('%r: %s, ' % (key, value))
494 if node.dyn_kwargs is not None:
495 self.write('}, **')
496 self.visit(node.dyn_kwargs, frame)
497 self.write(')')
498 else:
499 self.write('}')
500
501 elif node.dyn_kwargs is not None:
Armin Ronacherfd310492008-05-25 00:16:51 +0200502 self.write(', **')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200503 self.visit(node.dyn_kwargs, frame)
504
Armin Ronacherc9705c22008-04-27 21:28:03 +0200505 def pull_locals(self, frame):
506 """Pull all the references identifiers into the local scope."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200507 for name in frame.identifiers.undeclared:
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200508 self.writeline('l_%s = context.resolve(%r)' % (name, name))
Armin Ronacherc9705c22008-04-27 21:28:03 +0200509
510 def pull_dependencies(self, nodes):
511 """Pull all the dependencies."""
512 visitor = DependencyFinderVisitor()
513 for node in nodes:
514 visitor.visit(node)
Armin Ronacherb9e78752008-05-10 23:36:28 +0200515 for dependency in 'filters', 'tests':
516 mapping = getattr(self, dependency)
517 for name in getattr(visitor, dependency):
518 if name not in mapping:
519 mapping[name] = self.temporary_identifier()
520 self.writeline('%s = environment.%s[%r]' %
521 (mapping[name], dependency, name))
Armin Ronachere791c2a2008-04-07 18:39:54 +0200522
Armin Ronacher673aa882008-10-04 18:06:57 +0200523 def push_scope(self, frame, extra_vars=()):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200524 """This function returns all the shadowed variables in a dict
525 in the form name: alias and will write the required assignments
526 into the current scope. No indentation takes place.
Armin Ronacherff53c782008-08-13 18:55:50 +0200527
Armin Ronacher673aa882008-10-04 18:06:57 +0200528 This also predefines locally declared variables from the loop
529 body because under some circumstances it may be the case that
530
Armin Ronacherff53c782008-08-13 18:55:50 +0200531 `extra_vars` is passed to `Identifiers.find_shadowed`.
Armin Ronacherfed44b52008-04-13 19:42:53 +0200532 """
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200533 aliases = {}
Armin Ronacherff53c782008-08-13 18:55:50 +0200534 for name in frame.identifiers.find_shadowed(extra_vars):
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200535 aliases[name] = ident = self.temporary_identifier()
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200536 self.writeline('%s = l_%s' % (ident, name))
Armin Ronacher673aa882008-10-04 18:06:57 +0200537 to_declare = set()
538 for name in frame.identifiers.declared_locally:
539 if name not in aliases:
540 to_declare.add('l_' + name)
541 if to_declare:
542 self.writeline(' = '.join(to_declare) + ' = missing')
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200543 return aliases
544
Armin Ronacher673aa882008-10-04 18:06:57 +0200545 def pop_scope(self, aliases, frame):
546 """Restore all aliases and delete unused variables."""
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200547 for name, alias in aliases.iteritems():
548 self.writeline('l_%s = %s' % (name, alias))
Armin Ronacher673aa882008-10-04 18:06:57 +0200549 to_delete = set()
550 for name in frame.identifiers.declared_locally:
551 if name not in aliases:
552 to_delete.add('l_' + name)
553 if to_delete:
554 self.writeline('del ' + ', '.join(to_delete))
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200555
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200556 def function_scoping(self, node, frame, children=None,
557 find_special=True):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200558 """In Jinja a few statements require the help of anonymous
559 functions. Those are currently macros and call blocks and in
560 the future also recursive loops. As there is currently
561 technical limitation that doesn't allow reading and writing a
562 variable in a scope where the initial value is coming from an
563 outer scope, this function tries to fall back with a common
564 error message. Additionally the frame passed is modified so
565 that the argumetns are collected and callers are looked up.
566
567 This will return the modified frame.
568 """
Armin Ronacherc9705c22008-04-27 21:28:03 +0200569 # we have to iterate twice over it, make sure that works
570 if children is None:
571 children = node.iter_child_nodes()
572 children = list(children)
Armin Ronacher71082072008-04-12 14:19:36 +0200573 func_frame = frame.inner()
Armin Ronacherc9705c22008-04-27 21:28:03 +0200574 func_frame.inspect(children, hard_scope=True)
Armin Ronacher71082072008-04-12 14:19:36 +0200575
576 # variables that are undeclared (accessed before declaration) and
577 # declared locally *and* part of an outside scope raise a template
578 # assertion error. Reason: we can't generate reasonable code from
579 # it without aliasing all the variables. XXX: alias them ^^
580 overriden_closure_vars = (
581 func_frame.identifiers.undeclared &
582 func_frame.identifiers.declared &
583 (func_frame.identifiers.declared_locally |
584 func_frame.identifiers.declared_parameter)
585 )
586 if overriden_closure_vars:
Armin Ronachere2244882008-05-19 09:25:57 +0200587 self.fail('It\'s not possible to set and access variables '
588 'derived from an outer scope! (affects: %s' %
589 ', '.join(sorted(overriden_closure_vars)), node.lineno)
Armin Ronacher71082072008-04-12 14:19:36 +0200590
591 # remove variables from a closure from the frame's undeclared
592 # identifiers.
593 func_frame.identifiers.undeclared -= (
594 func_frame.identifiers.undeclared &
595 func_frame.identifiers.declared
596 )
597
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200598 # no special variables for this scope, abort early
599 if not find_special:
600 return func_frame
601
Armin Ronacher963f97d2008-04-25 11:44:59 +0200602 func_frame.accesses_kwargs = False
603 func_frame.accesses_varargs = False
Armin Ronacher71082072008-04-12 14:19:36 +0200604 func_frame.accesses_caller = False
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200605 func_frame.arguments = args = ['l_' + x.name for x in node.args]
Armin Ronacher71082072008-04-12 14:19:36 +0200606
Armin Ronacherc9705c22008-04-27 21:28:03 +0200607 undeclared = find_undeclared(children, ('caller', 'kwargs', 'varargs'))
608
609 if 'caller' in undeclared:
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200610 func_frame.accesses_caller = True
611 func_frame.identifiers.add_special('caller')
612 args.append('l_caller')
Armin Ronacherc9705c22008-04-27 21:28:03 +0200613 if 'kwargs' in undeclared:
Armin Ronacher963f97d2008-04-25 11:44:59 +0200614 func_frame.accesses_kwargs = True
615 func_frame.identifiers.add_special('kwargs')
616 args.append('l_kwargs')
Armin Ronacherc9705c22008-04-27 21:28:03 +0200617 if 'varargs' in undeclared:
Armin Ronacher963f97d2008-04-25 11:44:59 +0200618 func_frame.accesses_varargs = True
619 func_frame.identifiers.add_special('varargs')
620 args.append('l_varargs')
Armin Ronacher71082072008-04-12 14:19:36 +0200621 return func_frame
622
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200623 def macro_body(self, node, frame, children=None):
624 """Dump the function def of a macro or call block."""
625 frame = self.function_scoping(node, frame, children)
Armin Ronachere308bf22008-10-30 19:18:45 +0100626 # macros are delayed, they never require output checks
627 frame.require_output_check = False
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200628 args = frame.arguments
629 self.writeline('def macro(%s):' % ', '.join(args), node)
630 self.indent()
631 self.buffer(frame)
632 self.pull_locals(frame)
633 self.blockvisit(node.body, frame)
634 self.return_buffer_contents(frame)
635 self.outdent()
636 return frame
637
638 def macro_def(self, node, frame):
639 """Dump the macro definition for the def created by macro_body."""
640 arg_tuple = ', '.join(repr(x.name) for x in node.args)
641 name = getattr(node, 'name', None)
642 if len(node.args) == 1:
643 arg_tuple += ','
644 self.write('Macro(environment, macro, %r, (%s), (' %
645 (name, arg_tuple))
646 for arg in node.defaults:
647 self.visit(arg, frame)
648 self.write(', ')
Armin Ronacher903d1682008-05-23 00:51:58 +0200649 self.write('), %r, %r, %r)' % (
650 bool(frame.accesses_kwargs),
651 bool(frame.accesses_varargs),
652 bool(frame.accesses_caller)
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200653 ))
654
Armin Ronacher547d0b62008-07-04 16:35:10 +0200655 def position(self, node):
656 """Return a human readable position for the node."""
657 rv = 'line %d' % node.lineno
658 if self.name is not None:
Armin Ronachercebd8382008-12-25 18:33:46 +0100659 rv += ' in ' + repr(self.name)
Armin Ronacher547d0b62008-07-04 16:35:10 +0200660 return rv
661
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200662 # -- Statement Visitors
Armin Ronachere791c2a2008-04-07 18:39:54 +0200663
664 def visit_Template(self, node, frame=None):
665 assert frame is None, 'no root frame allowed'
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200666 from jinja2.runtime import __all__ as exported
Armin Ronacher709f6e52008-04-28 18:18:16 +0200667 self.writeline('from __future__ import division')
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200668 self.writeline('from jinja2.runtime import ' + ', '.join(exported))
Armin Ronacher8edbe492008-04-10 20:43:43 +0200669
Armin Ronacher75cfb862008-04-11 13:47:22 +0200670 # do we have an extends tag at all? If not, we can save some
671 # overhead by just not processing any inheritance code.
672 have_extends = node.find(nodes.Extends) is not None
673
Armin Ronacher8edbe492008-04-10 20:43:43 +0200674 # find all blocks
675 for block in node.find_all(nodes.Block):
676 if block.name in self.blocks:
Armin Ronachere2244882008-05-19 09:25:57 +0200677 self.fail('block %r defined twice' % block.name, block.lineno)
Armin Ronacher8edbe492008-04-10 20:43:43 +0200678 self.blocks[block.name] = block
Armin Ronachere791c2a2008-04-07 18:39:54 +0200679
Armin Ronacher023b5e92008-05-08 11:03:10 +0200680 # find all imports and import them
681 for import_ in node.find_all(nodes.ImportedName):
682 if import_.importname not in self.import_aliases:
683 imp = import_.importname
684 self.import_aliases[imp] = alias = self.temporary_identifier()
685 if '.' in imp:
686 module, obj = imp.rsplit('.', 1)
687 self.writeline('from %s import %s as %s' %
688 (module, obj, alias))
689 else:
690 self.writeline('import %s as %s' % (imp, alias))
691
692 # add the load name
Armin Ronacherdc02b642008-05-15 22:47:27 +0200693 self.writeline('name = %r' % self.name)
Armin Ronacher023b5e92008-05-08 11:03:10 +0200694
Armin Ronacher8efc5222008-04-08 14:47:40 +0200695 # generate the root render function.
Armin Ronacher32a910f2008-04-26 23:21:03 +0200696 self.writeline('def root(context, environment=environment):', extra=1)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200697
698 # process the root
Armin Ronachere791c2a2008-04-07 18:39:54 +0200699 frame = Frame()
Armin Ronacherc9705c22008-04-27 21:28:03 +0200700 frame.inspect(node.body)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200701 frame.toplevel = frame.rootlevel = True
Armin Ronacher79668952008-09-23 22:52:46 +0200702 frame.require_output_check = have_extends and not self.has_known_extends
Armin Ronacherf059ec12008-04-11 22:21:00 +0200703 self.indent()
Armin Ronacherc9705c22008-04-27 21:28:03 +0200704 if have_extends:
705 self.writeline('parent_template = None')
Armin Ronacherc9705c22008-04-27 21:28:03 +0200706 if 'self' in find_undeclared(node.body, ('self',)):
707 frame.identifiers.add_special('self')
708 self.writeline('l_self = TemplateReference(context)')
Armin Ronacher6df604e2008-05-23 22:18:38 +0200709 self.pull_locals(frame)
710 self.pull_dependencies(node.body)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200711 self.blockvisit(node.body, frame)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200712 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200713
Armin Ronacher8efc5222008-04-08 14:47:40 +0200714 # make sure that the parent root is called.
Armin Ronacher75cfb862008-04-11 13:47:22 +0200715 if have_extends:
716 if not self.has_known_extends:
717 self.indent()
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200718 self.writeline('if parent_template is not None:')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200719 self.indent()
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200720 self.writeline('for event in parent_template.'
Armin Ronacher5411ce72008-05-25 11:36:22 +0200721 'root_render_func(context):')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200722 self.indent()
723 self.writeline('yield event')
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200724 self.outdent(2 + (not self.has_known_extends))
Armin Ronachere791c2a2008-04-07 18:39:54 +0200725
726 # at this point we now have the blocks collected and can visit them too.
727 for name, block in self.blocks.iteritems():
728 block_frame = Frame()
Armin Ronacherc9705c22008-04-27 21:28:03 +0200729 block_frame.inspect(block.body)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200730 block_frame.block = name
Armin Ronacherd4c64f72008-04-11 17:15:29 +0200731 self.writeline('def block_%s(context, environment=environment):'
732 % name, block, 1)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200733 self.indent()
734 undeclared = find_undeclared(block.body, ('self', 'super'))
735 if 'self' in undeclared:
736 block_frame.identifiers.add_special('self')
737 self.writeline('l_self = TemplateReference(context)')
738 if 'super' in undeclared:
739 block_frame.identifiers.add_special('super')
740 self.writeline('l_super = context.super(%r, '
741 'block_%s)' % (name, name))
Armin Ronachere791c2a2008-04-07 18:39:54 +0200742 self.pull_locals(block_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200743 self.pull_dependencies(block.body)
Armin Ronacher625215e2008-04-13 16:31:08 +0200744 self.blockvisit(block.body, block_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200745 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200746
Armin Ronacher75cfb862008-04-11 13:47:22 +0200747 self.writeline('blocks = {%s}' % ', '.join('%r: block_%s' % (x, x)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200748 for x in self.blocks),
749 extra=1)
750
751 # add a function that returns the debug info
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200752 self.writeline('debug_info = %r' % '&'.join('%s=%s' % x for x
753 in self.debug_info))
Armin Ronacher75cfb862008-04-11 13:47:22 +0200754
Armin Ronachere791c2a2008-04-07 18:39:54 +0200755 def visit_Block(self, node, frame):
756 """Call a block and register it for the template."""
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200757 level = 1
Armin Ronacher75cfb862008-04-11 13:47:22 +0200758 if frame.toplevel:
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200759 # if we know that we are a child template, there is no need to
760 # check if we are one
761 if self.has_known_extends:
762 return
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200763 if self.extends_so_far > 0:
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200764 self.writeline('if parent_template is None:')
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200765 self.indent()
766 level += 1
Armin Ronacher83fbc0f2008-05-15 12:22:28 +0200767 self.writeline('for event in context.blocks[%r][0](context):' %
Armin Ronacherc9705c22008-04-27 21:28:03 +0200768 node.name, node)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200769 self.indent()
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200770 self.simple_write('event', frame)
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200771 self.outdent(level)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200772
773 def visit_Extends(self, node, frame):
774 """Calls the extender."""
Armin Ronacher8efc5222008-04-08 14:47:40 +0200775 if not frame.toplevel:
Armin Ronachere2244882008-05-19 09:25:57 +0200776 self.fail('cannot use extend from a non top-level scope',
777 node.lineno)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200778
Armin Ronacher7fb38972008-04-11 13:54:28 +0200779 # if the number of extends statements in general is zero so
780 # far, we don't have to add a check if something extended
781 # the template before this one.
782 if self.extends_so_far > 0:
Armin Ronacher75cfb862008-04-11 13:47:22 +0200783
Armin Ronacher7fb38972008-04-11 13:54:28 +0200784 # if we have a known extends we just add a template runtime
785 # error into the generated code. We could catch that at compile
786 # time too, but i welcome it not to confuse users by throwing the
787 # same error at different times just "because we can".
788 if not self.has_known_extends:
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200789 self.writeline('if parent_template is not None:')
Armin Ronacher7fb38972008-04-11 13:54:28 +0200790 self.indent()
791 self.writeline('raise TemplateRuntimeError(%r)' %
792 'extended multiple times')
Armin Ronacher79668952008-09-23 22:52:46 +0200793 self.outdent()
Armin Ronacher75cfb862008-04-11 13:47:22 +0200794
Armin Ronacher7fb38972008-04-11 13:54:28 +0200795 # if we have a known extends already we don't need that code here
796 # as we know that the template execution will end here.
797 if self.has_known_extends:
798 raise CompilerExit()
Armin Ronacher7fb38972008-04-11 13:54:28 +0200799
Armin Ronacher9d42abf2008-05-14 18:10:41 +0200800 self.writeline('parent_template = environment.get_template(', node)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200801 self.visit(node.template, frame)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200802 self.write(', %r)' % self.name)
803 self.writeline('for name, parent_block in parent_template.'
804 'blocks.iteritems():')
805 self.indent()
806 self.writeline('context.blocks.setdefault(name, []).'
Armin Ronacher83fbc0f2008-05-15 12:22:28 +0200807 'append(parent_block)')
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200808 self.outdent()
Armin Ronacher75cfb862008-04-11 13:47:22 +0200809
810 # if this extends statement was in the root level we can take
811 # advantage of that information and simplify the generated code
812 # in the top level from this point onwards
Armin Ronacher27069d72008-05-11 19:48:12 +0200813 if frame.rootlevel:
814 self.has_known_extends = True
Armin Ronachere791c2a2008-04-07 18:39:54 +0200815
Armin Ronacher7fb38972008-04-11 13:54:28 +0200816 # and now we have one more
817 self.extends_so_far += 1
818
Armin Ronacherf059ec12008-04-11 22:21:00 +0200819 def visit_Include(self, node, frame):
820 """Handles includes."""
Armin Ronacher37f58ce2008-12-27 13:10:38 +0100821 if node.ignore_missing:
822 self.writeline('try:')
823 self.indent()
824 self.writeline('template = environment.get_template(', node)
825 self.visit(node.template, frame)
826 self.write(', %r)' % self.name)
827 if node.ignore_missing:
828 self.outdent()
829 self.writeline('except TemplateNotFound:')
830 self.indent()
831 self.writeline('pass')
832 self.outdent()
833 self.writeline('else:')
834 self.indent()
835
Armin Ronacherea847c52008-05-02 20:04:32 +0200836 if node.with_context:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200837 self.writeline('for event in template.root_render_func('
Armin Ronacher673aa882008-10-04 18:06:57 +0200838 'template.new_context(context.parent, True, '
839 'locals())):')
Armin Ronacherea847c52008-05-02 20:04:32 +0200840 else:
Armin Ronacher37f58ce2008-12-27 13:10:38 +0100841 self.writeline('for event in template.module._body_stream:')
842
Armin Ronacherf059ec12008-04-11 22:21:00 +0200843 self.indent()
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200844 self.simple_write('event', frame)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200845 self.outdent()
846
Armin Ronacher37f58ce2008-12-27 13:10:38 +0100847 if node.ignore_missing:
848 self.outdent()
849
Armin Ronacher0611e492008-04-25 23:44:14 +0200850 def visit_Import(self, node, frame):
851 """Visit regular imports."""
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200852 self.writeline('l_%s = ' % node.target, node)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200853 if frame.toplevel:
Armin Ronacher53042292008-04-26 18:30:19 +0200854 self.write('context.vars[%r] = ' % node.target)
Armin Ronacher0611e492008-04-25 23:44:14 +0200855 self.write('environment.get_template(')
856 self.visit(node.template, frame)
Armin Ronacherea847c52008-05-02 20:04:32 +0200857 self.write(', %r).' % self.name)
858 if node.with_context:
Armin Ronacher673aa882008-10-04 18:06:57 +0200859 self.write('make_module(context.parent, True, locals())')
Armin Ronacherea847c52008-05-02 20:04:32 +0200860 else:
861 self.write('module')
Armin Ronacher903d1682008-05-23 00:51:58 +0200862 if frame.toplevel and not node.target.startswith('_'):
Armin Ronacher53042292008-04-26 18:30:19 +0200863 self.writeline('context.exported_vars.discard(%r)' % node.target)
Armin Ronacher0611e492008-04-25 23:44:14 +0200864
865 def visit_FromImport(self, node, frame):
866 """Visit named imports."""
867 self.newline(node)
868 self.write('included_template = environment.get_template(')
869 self.visit(node.template, frame)
Armin Ronacherea847c52008-05-02 20:04:32 +0200870 self.write(', %r).' % self.name)
871 if node.with_context:
872 self.write('make_module(context.parent, True)')
873 else:
874 self.write('module')
Armin Ronachera78d2762008-05-15 23:18:07 +0200875
876 var_names = []
877 discarded_names = []
Armin Ronacher0611e492008-04-25 23:44:14 +0200878 for name in node.names:
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200879 if isinstance(name, tuple):
880 name, alias = name
881 else:
882 alias = name
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200883 self.writeline('l_%s = getattr(included_template, '
884 '%r, missing)' % (alias, name))
885 self.writeline('if l_%s is missing:' % alias)
Armin Ronacher0611e492008-04-25 23:44:14 +0200886 self.indent()
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200887 self.writeline('l_%s = environment.undefined(%r %% '
Armin Ronacherdc02b642008-05-15 22:47:27 +0200888 'included_template.__name__, '
Armin Ronacher0a2ac692008-05-13 01:03:08 +0200889 'name=%r)' %
Armin Ronacher547d0b62008-07-04 16:35:10 +0200890 (alias, 'the template %%r (imported on %s) does '
891 'not export the requested name %s' % (
892 self.position(node),
893 repr(name)
894 ), name))
Armin Ronacher0611e492008-04-25 23:44:14 +0200895 self.outdent()
896 if frame.toplevel:
Armin Ronachera78d2762008-05-15 23:18:07 +0200897 var_names.append(alias)
Armin Ronacher903d1682008-05-23 00:51:58 +0200898 if not alias.startswith('_'):
Armin Ronachera78d2762008-05-15 23:18:07 +0200899 discarded_names.append(alias)
900
901 if var_names:
902 if len(var_names) == 1:
903 name = var_names[0]
904 self.writeline('context.vars[%r] = l_%s' % (name, name))
905 else:
906 self.writeline('context.vars.update({%s})' % ', '.join(
907 '%r: l_%s' % (name, name) for name in var_names
908 ))
909 if discarded_names:
910 if len(discarded_names) == 1:
911 self.writeline('context.exported_vars.discard(%r)' %
912 discarded_names[0])
913 else:
914 self.writeline('context.exported_vars.difference_'
915 'update((%s))' % ', '.join(map(repr, discarded_names)))
Armin Ronacherf059ec12008-04-11 22:21:00 +0200916
Armin Ronachere791c2a2008-04-07 18:39:54 +0200917 def visit_For(self, node, frame):
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200918 # when calculating the nodes for the inner frame we have to exclude
919 # the iterator contents from it
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200920 children = node.iter_child_nodes(exclude=('iter',))
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200921 if node.recursive:
922 loop_frame = self.function_scoping(node, frame, children,
923 find_special=False)
924 else:
925 loop_frame = frame.inner()
926 loop_frame.inspect(children)
927
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200928 # try to figure out if we have an extended loop. An extended loop
929 # is necessary if the loop is in recursive mode if the special loop
930 # variable is accessed in the body.
931 extended_loop = node.recursive or 'loop' in \
932 find_undeclared(node.iter_child_nodes(
933 only=('body',)), ('loop',))
934
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200935 # if we don't have an recursive loop we have to find the shadowed
Armin Ronacherff53c782008-08-13 18:55:50 +0200936 # variables at that point. Because loops can be nested but the loop
937 # variable is a special one we have to enforce aliasing for it.
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200938 if not node.recursive:
Armin Ronacher673aa882008-10-04 18:06:57 +0200939 aliases = self.push_scope(loop_frame, ('loop',))
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200940
941 # otherwise we set up a buffer and add a function def
942 else:
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200943 self.writeline('def loop(reciter, loop_render_func):', node)
944 self.indent()
Armin Ronachered1e0d42008-05-18 20:25:28 +0200945 self.buffer(loop_frame)
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200946 aliases = {}
947
Armin Ronacherff53c782008-08-13 18:55:50 +0200948 # make sure the loop variable is a special one and raise a template
949 # assertion error if a loop tries to write to loop
Armin Ronacher833a3b52008-08-14 12:31:12 +0200950 if extended_loop:
951 loop_frame.identifiers.add_special('loop')
Armin Ronacherff53c782008-08-13 18:55:50 +0200952 for name in node.find_all(nodes.Name):
953 if name.ctx == 'store' and name.name == 'loop':
954 self.fail('Can\'t assign to special loop variable '
955 'in for-loop target', name.lineno)
956
Armin Ronacherc9705c22008-04-27 21:28:03 +0200957 self.pull_locals(loop_frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200958 if node.else_:
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200959 iteration_indicator = self.temporary_identifier()
960 self.writeline('%s = 1' % iteration_indicator)
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200961
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200962 # Create a fake parent loop if the else or test section of a
963 # loop is accessing the special loop variable and no parent loop
964 # exists.
965 if 'loop' not in aliases and 'loop' in find_undeclared(
966 node.iter_child_nodes(only=('else_', 'test')), ('loop',)):
967 self.writeline("l_loop = environment.undefined(%r, name='loop')" %
Armin Ronacher547d0b62008-07-04 16:35:10 +0200968 ("'loop' is undefined. the filter section of a loop as well "
969 "as the else block doesn't have access to the special 'loop'"
970 " variable of the current loop. Because there is no parent "
971 "loop it's undefined. Happened in loop on %s" %
972 self.position(node)))
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200973
974 self.writeline('for ', node)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200975 self.visit(node.target, loop_frame)
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200976 self.write(extended_loop and ', l_loop in LoopContext(' or ' in ')
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200977
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200978 # if we have an extened loop and a node test, we filter in the
979 # "outer frame".
980 if extended_loop and node.test is not None:
981 self.write('(')
982 self.visit(node.target, loop_frame)
983 self.write(' for ')
984 self.visit(node.target, loop_frame)
985 self.write(' in ')
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200986 if node.recursive:
987 self.write('reciter')
988 else:
989 self.visit(node.iter, loop_frame)
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200990 self.write(' if (')
991 test_frame = loop_frame.copy()
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200992 self.visit(node.test, test_frame)
993 self.write('))')
994
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200995 elif node.recursive:
996 self.write('reciter')
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200997 else:
998 self.visit(node.iter, loop_frame)
999
Armin Ronacher1e1e8902008-05-11 23:21:16 +02001000 if node.recursive:
1001 self.write(', recurse=loop_render_func):')
1002 else:
1003 self.write(extended_loop and '):' or ':')
Armin Ronacher3d8b7842008-04-13 13:16:50 +02001004
1005 # tests in not extended loops become a continue
1006 if not extended_loop and node.test is not None:
1007 self.indent()
Armin Ronacher47a506f2008-05-06 12:17:23 +02001008 self.writeline('if not ')
Armin Ronacher32a910f2008-04-26 23:21:03 +02001009 self.visit(node.test, loop_frame)
Armin Ronacher3d8b7842008-04-13 13:16:50 +02001010 self.write(':')
1011 self.indent()
1012 self.writeline('continue')
1013 self.outdent(2)
1014
Armin Ronacherc9705c22008-04-27 21:28:03 +02001015 self.indent()
Armin Ronacherf40c8842008-09-17 18:51:26 +02001016 self.blockvisit(node.body, loop_frame)
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001017 if node.else_:
1018 self.writeline('%s = 0' % iteration_indicator)
Armin Ronacherc9705c22008-04-27 21:28:03 +02001019 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +02001020
1021 if node.else_:
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001022 self.writeline('if %s:' % iteration_indicator)
Armin Ronacher3d8b7842008-04-13 13:16:50 +02001023 self.indent()
Armin Ronacherf40c8842008-09-17 18:51:26 +02001024 self.blockvisit(node.else_, loop_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +02001025 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +02001026
Armin Ronacherd4c64f72008-04-11 17:15:29 +02001027 # reset the aliases if there are any.
Armin Ronachercebd8382008-12-25 18:33:46 +01001028 if not node.recursive:
1029 self.pop_scope(aliases, loop_frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001030
Armin Ronacher1e1e8902008-05-11 23:21:16 +02001031 # if the node was recursive we have to return the buffer contents
1032 # and start the iteration code
1033 if node.recursive:
Armin Ronachered1e0d42008-05-18 20:25:28 +02001034 self.return_buffer_contents(loop_frame)
Armin Ronacher1e1e8902008-05-11 23:21:16 +02001035 self.outdent()
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001036 self.start_write(frame, node)
1037 self.write('loop(')
Armin Ronacher1e1e8902008-05-11 23:21:16 +02001038 self.visit(node.iter, frame)
1039 self.write(', loop)')
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001040 self.end_write(frame)
Armin Ronacher1e1e8902008-05-11 23:21:16 +02001041
Armin Ronachere791c2a2008-04-07 18:39:54 +02001042 def visit_If(self, node, frame):
Armin Ronacher75cfb862008-04-11 13:47:22 +02001043 if_frame = frame.soft()
Armin Ronachere791c2a2008-04-07 18:39:54 +02001044 self.writeline('if ', node)
Armin Ronacher75cfb862008-04-11 13:47:22 +02001045 self.visit(node.test, if_frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001046 self.write(':')
Armin Ronacherc9705c22008-04-27 21:28:03 +02001047 self.indent()
Armin Ronacher75cfb862008-04-11 13:47:22 +02001048 self.blockvisit(node.body, if_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +02001049 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +02001050 if node.else_:
1051 self.writeline('else:')
Armin Ronacherc9705c22008-04-27 21:28:03 +02001052 self.indent()
Armin Ronacher75cfb862008-04-11 13:47:22 +02001053 self.blockvisit(node.else_, if_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +02001054 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +02001055
Armin Ronacher8efc5222008-04-08 14:47:40 +02001056 def visit_Macro(self, node, frame):
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001057 macro_frame = self.macro_body(node, frame)
Armin Ronacher8efc5222008-04-08 14:47:40 +02001058 self.newline()
1059 if frame.toplevel:
Armin Ronacher903d1682008-05-23 00:51:58 +02001060 if not node.name.startswith('_'):
Armin Ronacherc9705c22008-04-27 21:28:03 +02001061 self.write('context.exported_vars.add(%r)' % node.name)
Armin Ronacher32a910f2008-04-26 23:21:03 +02001062 self.writeline('context.vars[%r] = ' % node.name)
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001063 self.write('l_%s = ' % node.name)
1064 self.macro_def(node, macro_frame)
Armin Ronacher71082072008-04-12 14:19:36 +02001065
1066 def visit_CallBlock(self, node, frame):
Armin Ronacher3da90312008-05-23 16:37:28 +02001067 children = node.iter_child_nodes(exclude=('call',))
1068 call_frame = self.macro_body(node, frame, children)
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001069 self.writeline('caller = ')
1070 self.macro_def(node, call_frame)
1071 self.start_write(frame, node)
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001072 self.visit_Call(node.call, call_frame, forward_caller=True)
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001073 self.end_write(frame)
Armin Ronacherfa865fb2008-04-12 22:11:53 +02001074
1075 def visit_FilterBlock(self, node, frame):
1076 filter_frame = frame.inner()
1077 filter_frame.inspect(node.iter_child_nodes())
Armin Ronacher673aa882008-10-04 18:06:57 +02001078 aliases = self.push_scope(filter_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +02001079 self.pull_locals(filter_frame)
Armin Ronachered1e0d42008-05-18 20:25:28 +02001080 self.buffer(filter_frame)
Armin Ronacherf40c8842008-09-17 18:51:26 +02001081 self.blockvisit(node.body, filter_frame)
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001082 self.start_write(frame, node)
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001083 self.visit_Filter(node.filter, filter_frame)
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001084 self.end_write(frame)
Armin Ronacher673aa882008-10-04 18:06:57 +02001085 self.pop_scope(aliases, filter_frame)
Armin Ronacher8efc5222008-04-08 14:47:40 +02001086
Armin Ronachere791c2a2008-04-07 18:39:54 +02001087 def visit_ExprStmt(self, node, frame):
1088 self.newline(node)
Armin Ronacher6ce170c2008-04-25 12:32:36 +02001089 self.visit(node.node, frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001090
1091 def visit_Output(self, node, frame):
Armin Ronacher75cfb862008-04-11 13:47:22 +02001092 # if we have a known extends statement, we don't output anything
Armin Ronacher79668952008-09-23 22:52:46 +02001093 # if we are in a require_output_check section
1094 if self.has_known_extends and frame.require_output_check:
Armin Ronacher75cfb862008-04-11 13:47:22 +02001095 return
Armin Ronachere791c2a2008-04-07 18:39:54 +02001096
Armin Ronacher665bfb82008-07-14 13:41:46 +02001097 if self.environment.finalize:
1098 finalize = lambda x: unicode(self.environment.finalize(x))
1099 else:
1100 finalize = unicode
1101
Armin Ronacher75cfb862008-04-11 13:47:22 +02001102 self.newline(node)
Armin Ronacher8edbe492008-04-10 20:43:43 +02001103
Armin Ronacher79668952008-09-23 22:52:46 +02001104 # if we are inside a frame that requires output checking, we do so
Armin Ronacher7fb38972008-04-11 13:54:28 +02001105 outdent_later = False
Armin Ronacher79668952008-09-23 22:52:46 +02001106 if frame.require_output_check:
Armin Ronacher203bfcb2008-04-24 21:54:44 +02001107 self.writeline('if parent_template is None:')
Armin Ronacher75cfb862008-04-11 13:47:22 +02001108 self.indent()
Armin Ronacher7fb38972008-04-11 13:54:28 +02001109 outdent_later = True
Armin Ronacher75cfb862008-04-11 13:47:22 +02001110
Armin Ronachere791c2a2008-04-07 18:39:54 +02001111 # try to evaluate as many chunks as possible into a static
1112 # string at compile time.
1113 body = []
1114 for child in node.nodes:
1115 try:
Armin Ronacher9cf95912008-05-24 19:54:43 +02001116 const = child.as_const()
1117 except nodes.Impossible:
1118 body.append(child)
1119 continue
1120 try:
1121 if self.environment.autoescape:
1122 if hasattr(const, '__html__'):
1123 const = const.__html__()
1124 else:
1125 const = escape(const)
Armin Ronacher665bfb82008-07-14 13:41:46 +02001126 const = finalize(const)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001127 except:
Armin Ronacher9cf95912008-05-24 19:54:43 +02001128 # if something goes wrong here we evaluate the node
1129 # at runtime for easier debugging
Armin Ronachere791c2a2008-04-07 18:39:54 +02001130 body.append(child)
1131 continue
1132 if body and isinstance(body[-1], list):
1133 body[-1].append(const)
1134 else:
1135 body.append([const])
1136
Armin Ronachered1e0d42008-05-18 20:25:28 +02001137 # if we have less than 3 nodes or a buffer we yield or extend/append
1138 if len(body) < 3 or frame.buffer is not None:
Armin Ronacher32a910f2008-04-26 23:21:03 +02001139 if frame.buffer is not None:
Armin Ronacher1e1e8902008-05-11 23:21:16 +02001140 # for one item we append, for more we extend
1141 if len(body) == 1:
1142 self.writeline('%s.append(' % frame.buffer)
1143 else:
1144 self.writeline('%s.extend((' % frame.buffer)
Armin Ronacher1f627ff2008-05-15 13:23:26 +02001145 self.indent()
Armin Ronachere791c2a2008-04-07 18:39:54 +02001146 for item in body:
1147 if isinstance(item, list):
Armin Ronacherde6bf712008-04-26 01:44:14 +02001148 val = repr(concat(item))
Armin Ronacherfa865fb2008-04-12 22:11:53 +02001149 if frame.buffer is None:
1150 self.writeline('yield ' + val)
1151 else:
Armin Ronacher1f627ff2008-05-15 13:23:26 +02001152 self.writeline(val + ', ')
Armin Ronachere791c2a2008-04-07 18:39:54 +02001153 else:
Armin Ronacherfa865fb2008-04-12 22:11:53 +02001154 if frame.buffer is None:
Armin Ronachered1e0d42008-05-18 20:25:28 +02001155 self.writeline('yield ', item)
Armin Ronacher1f627ff2008-05-15 13:23:26 +02001156 else:
1157 self.newline(item)
Armin Ronacherd1342312008-04-28 12:20:12 +02001158 close = 1
1159 if self.environment.autoescape:
1160 self.write('escape(')
1161 else:
1162 self.write('unicode(')
1163 if self.environment.finalize is not None:
1164 self.write('environment.finalize(')
1165 close += 1
Armin Ronachere791c2a2008-04-07 18:39:54 +02001166 self.visit(item, frame)
Armin Ronacherd1342312008-04-28 12:20:12 +02001167 self.write(')' * close)
Armin Ronacher32a910f2008-04-26 23:21:03 +02001168 if frame.buffer is not None:
1169 self.write(', ')
1170 if frame.buffer is not None:
Armin Ronacher1e1e8902008-05-11 23:21:16 +02001171 # close the open parentheses
Armin Ronacher1f627ff2008-05-15 13:23:26 +02001172 self.outdent()
1173 self.writeline(len(body) == 1 and ')' or '))')
Armin Ronachere791c2a2008-04-07 18:39:54 +02001174
1175 # otherwise we create a format string as this is faster in that case
1176 else:
1177 format = []
1178 arguments = []
1179 for item in body:
1180 if isinstance(item, list):
Armin Ronacherde6bf712008-04-26 01:44:14 +02001181 format.append(concat(item).replace('%', '%%'))
Armin Ronachere791c2a2008-04-07 18:39:54 +02001182 else:
1183 format.append('%s')
1184 arguments.append(item)
Armin Ronachered1e0d42008-05-18 20:25:28 +02001185 self.writeline('yield ')
Armin Ronacherde6bf712008-04-26 01:44:14 +02001186 self.write(repr(concat(format)) + ' % (')
Armin Ronachere791c2a2008-04-07 18:39:54 +02001187 idx = -1
Armin Ronachera7f016d2008-05-16 00:22:40 +02001188 self.indent()
Armin Ronacher8e8d0712008-04-16 23:10:49 +02001189 for argument in arguments:
Armin Ronachered1e0d42008-05-18 20:25:28 +02001190 self.newline(argument)
Armin Ronacherd1342312008-04-28 12:20:12 +02001191 close = 0
1192 if self.environment.autoescape:
1193 self.write('escape(')
1194 close += 1
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(argument, frame)
Armin Ronacher1f627ff2008-05-15 13:23:26 +02001199 self.write(')' * close + ', ')
Armin Ronachera7f016d2008-05-16 00:22:40 +02001200 self.outdent()
1201 self.writeline(')')
Armin Ronachere791c2a2008-04-07 18:39:54 +02001202
Armin Ronacher7fb38972008-04-11 13:54:28 +02001203 if outdent_later:
Armin Ronacher75cfb862008-04-11 13:47:22 +02001204 self.outdent()
1205
Armin Ronacher8efc5222008-04-08 14:47:40 +02001206 def visit_Assign(self, node, frame):
1207 self.newline(node)
1208 # toplevel assignments however go into the local namespace and
1209 # the current template's context. We create a copy of the frame
1210 # here and add a set so that the Name visitor can add the assigned
1211 # names here.
1212 if frame.toplevel:
1213 assignment_frame = frame.copy()
1214 assignment_frame.assigned_names = set()
1215 else:
1216 assignment_frame = frame
1217 self.visit(node.target, assignment_frame)
1218 self.write(' = ')
1219 self.visit(node.node, frame)
Armin Ronacher9706fab2008-04-08 18:49:56 +02001220
1221 # make sure toplevel assignments are added to the context.
Armin Ronacher8efc5222008-04-08 14:47:40 +02001222 if frame.toplevel:
Armin Ronacher69e12db2008-05-12 09:00:03 +02001223 public_names = [x for x in assignment_frame.assigned_names
Armin Ronacher903d1682008-05-23 00:51:58 +02001224 if not x.startswith('_')]
Armin Ronacher69e12db2008-05-12 09:00:03 +02001225 if len(assignment_frame.assigned_names) == 1:
1226 name = iter(assignment_frame.assigned_names).next()
Armin Ronacherd1ff8582008-05-11 00:30:43 +02001227 self.writeline('context.vars[%r] = l_%s' % (name, name))
Armin Ronacher69e12db2008-05-12 09:00:03 +02001228 else:
1229 self.writeline('context.vars.update({')
1230 for idx, name in enumerate(assignment_frame.assigned_names):
1231 if idx:
1232 self.write(', ')
1233 self.write('%r: l_%s' % (name, name))
1234 self.write('})')
1235 if public_names:
1236 if len(public_names) == 1:
1237 self.writeline('context.exported_vars.add(%r)' %
1238 public_names[0])
1239 else:
1240 self.writeline('context.exported_vars.update((%s))' %
1241 ', '.join(map(repr, public_names)))
Armin Ronacher8efc5222008-04-08 14:47:40 +02001242
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001243 # -- Expression Visitors
1244
Armin Ronachere791c2a2008-04-07 18:39:54 +02001245 def visit_Name(self, node, frame):
Armin Ronacherc9705c22008-04-27 21:28:03 +02001246 if node.ctx == 'store' and frame.toplevel:
1247 frame.assigned_names.add(node.name)
Armin Ronacherd1ff8582008-05-11 00:30:43 +02001248 self.write('l_' + node.name)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001249
1250 def visit_Const(self, node, frame):
1251 val = node.value
1252 if isinstance(val, float):
Armin Ronachere791c2a2008-04-07 18:39:54 +02001253 self.write(str(val))
1254 else:
1255 self.write(repr(val))
1256
Armin Ronacher5411ce72008-05-25 11:36:22 +02001257 def visit_TemplateData(self, node, frame):
1258 self.write(repr(node.as_const()))
1259
Armin Ronacher8efc5222008-04-08 14:47:40 +02001260 def visit_Tuple(self, node, frame):
1261 self.write('(')
1262 idx = -1
1263 for idx, item in enumerate(node.items):
1264 if idx:
1265 self.write(', ')
1266 self.visit(item, frame)
1267 self.write(idx == 0 and ',)' or ')')
1268
Armin Ronacher8edbe492008-04-10 20:43:43 +02001269 def visit_List(self, node, frame):
1270 self.write('[')
1271 for idx, item in enumerate(node.items):
1272 if idx:
1273 self.write(', ')
1274 self.visit(item, frame)
1275 self.write(']')
1276
1277 def visit_Dict(self, node, frame):
1278 self.write('{')
1279 for idx, item in enumerate(node.items):
1280 if idx:
1281 self.write(', ')
1282 self.visit(item.key, frame)
1283 self.write(': ')
1284 self.visit(item.value, frame)
1285 self.write('}')
1286
Armin Ronachere791c2a2008-04-07 18:39:54 +02001287 def binop(operator):
1288 def visitor(self, node, frame):
1289 self.write('(')
1290 self.visit(node.left, frame)
1291 self.write(' %s ' % operator)
1292 self.visit(node.right, frame)
1293 self.write(')')
1294 return visitor
1295
1296 def uaop(operator):
1297 def visitor(self, node, frame):
1298 self.write('(' + operator)
Armin Ronacher9a822052008-04-17 18:44:07 +02001299 self.visit(node.node, frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001300 self.write(')')
1301 return visitor
1302
1303 visit_Add = binop('+')
1304 visit_Sub = binop('-')
1305 visit_Mul = binop('*')
1306 visit_Div = binop('/')
1307 visit_FloorDiv = binop('//')
1308 visit_Pow = binop('**')
1309 visit_Mod = binop('%')
1310 visit_And = binop('and')
1311 visit_Or = binop('or')
1312 visit_Pos = uaop('+')
1313 visit_Neg = uaop('-')
1314 visit_Not = uaop('not ')
1315 del binop, uaop
1316
Armin Ronacherd1342312008-04-28 12:20:12 +02001317 def visit_Concat(self, node, frame):
Armin Ronacherfdf95302008-05-11 22:20:51 +02001318 self.write('%s((' % (self.environment.autoescape and
1319 'markup_join' or 'unicode_join'))
Armin Ronacherd1342312008-04-28 12:20:12 +02001320 for arg in node.nodes:
1321 self.visit(arg, frame)
1322 self.write(', ')
1323 self.write('))')
1324
Armin Ronachere791c2a2008-04-07 18:39:54 +02001325 def visit_Compare(self, node, frame):
1326 self.visit(node.expr, frame)
1327 for op in node.ops:
1328 self.visit(op, frame)
1329
1330 def visit_Operand(self, node, frame):
1331 self.write(' %s ' % operators[node.op])
1332 self.visit(node.expr, frame)
1333
Armin Ronacher6dc6f292008-06-12 08:50:07 +02001334 def visit_Getattr(self, node, frame):
1335 self.write('environment.getattr(')
1336 self.visit(node.node, frame)
1337 self.write(', %r)' % node.attr)
1338
1339 def visit_Getitem(self, node, frame):
Armin Ronacher5c3c4702008-09-12 23:12:49 +02001340 # slices bypass the environment getitem method.
1341 if isinstance(node.arg, nodes.Slice):
Armin Ronacher8efc5222008-04-08 14:47:40 +02001342 self.visit(node.node, frame)
1343 self.write('[')
1344 self.visit(node.arg, frame)
1345 self.write(']')
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001346 else:
Armin Ronacher6dc6f292008-06-12 08:50:07 +02001347 self.write('environment.getitem(')
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001348 self.visit(node.node, frame)
1349 self.write(', ')
1350 self.visit(node.arg, frame)
1351 self.write(')')
Armin Ronacher8efc5222008-04-08 14:47:40 +02001352
1353 def visit_Slice(self, node, frame):
1354 if node.start is not None:
1355 self.visit(node.start, frame)
1356 self.write(':')
1357 if node.stop is not None:
1358 self.visit(node.stop, frame)
1359 if node.step is not None:
1360 self.write(':')
1361 self.visit(node.step, frame)
1362
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001363 def visit_Filter(self, node, frame):
Armin Ronacherb9e78752008-05-10 23:36:28 +02001364 self.write(self.filters[node.name] + '(')
Christoph Hack80909862008-04-14 01:35:10 +02001365 func = self.environment.filters.get(node.name)
Armin Ronacher0611e492008-04-25 23:44:14 +02001366 if func is None:
Armin Ronachere2244882008-05-19 09:25:57 +02001367 self.fail('no filter named %r' % node.name, node.lineno)
Christoph Hack80909862008-04-14 01:35:10 +02001368 if getattr(func, 'contextfilter', False):
1369 self.write('context, ')
Armin Ronacher9a027f42008-04-17 11:13:40 +02001370 elif getattr(func, 'environmentfilter', False):
1371 self.write('environment, ')
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001372
1373 # if the filter node is None we are inside a filter block
1374 # and want to write to the current buffer
Armin Ronacher3da90312008-05-23 16:37:28 +02001375 if node.node is not None:
Armin Ronacherfa865fb2008-04-12 22:11:53 +02001376 self.visit(node.node, frame)
Armin Ronacher3da90312008-05-23 16:37:28 +02001377 elif self.environment.autoescape:
1378 self.write('Markup(concat(%s))' % frame.buffer)
1379 else:
1380 self.write('concat(%s)' % frame.buffer)
Armin Ronacherd55ab532008-04-09 16:13:39 +02001381 self.signature(node, frame)
1382 self.write(')')
Armin Ronacher8efc5222008-04-08 14:47:40 +02001383
1384 def visit_Test(self, node, frame):
Armin Ronacherb9e78752008-05-10 23:36:28 +02001385 self.write(self.tests[node.name] + '(')
Armin Ronacher0611e492008-04-25 23:44:14 +02001386 if node.name not in self.environment.tests:
Armin Ronachere2244882008-05-19 09:25:57 +02001387 self.fail('no test named %r' % node.name, node.lineno)
Armin Ronacher8efc5222008-04-08 14:47:40 +02001388 self.visit(node.node, frame)
1389 self.signature(node, frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001390 self.write(')')
Armin Ronacher8efc5222008-04-08 14:47:40 +02001391
Armin Ronacher3d8b7842008-04-13 13:16:50 +02001392 def visit_CondExpr(self, node, frame):
Armin Ronacher547d0b62008-07-04 16:35:10 +02001393 def write_expr2():
1394 if node.expr2 is not None:
1395 return self.visit(node.expr2, frame)
1396 self.write('environment.undefined(%r)' % ('the inline if-'
1397 'expression on %s evaluated to false and '
1398 'no else section was defined.' % self.position(node)))
1399
Armin Ronacher3d8b7842008-04-13 13:16:50 +02001400 if not have_condexpr:
1401 self.write('((')
1402 self.visit(node.test, frame)
1403 self.write(') and (')
1404 self.visit(node.expr1, frame)
1405 self.write(',) or (')
Armin Ronacher547d0b62008-07-04 16:35:10 +02001406 write_expr2()
Armin Ronacher3d8b7842008-04-13 13:16:50 +02001407 self.write(',))[0]')
1408 else:
1409 self.write('(')
1410 self.visit(node.expr1, frame)
1411 self.write(' if ')
1412 self.visit(node.test, frame)
1413 self.write(' else ')
Armin Ronacher547d0b62008-07-04 16:35:10 +02001414 write_expr2()
Armin Ronacher3d8b7842008-04-13 13:16:50 +02001415 self.write(')')
1416
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001417 def visit_Call(self, node, frame, forward_caller=False):
Armin Ronacherc63243e2008-04-14 22:53:58 +02001418 if self.environment.sandboxed:
Armin Ronacherfd310492008-05-25 00:16:51 +02001419 self.write('environment.call(context, ')
1420 else:
1421 self.write('context.call(')
Armin Ronacher8efc5222008-04-08 14:47:40 +02001422 self.visit(node.node, frame)
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001423 extra_kwargs = forward_caller and {'caller': 'caller'} or None
Armin Ronacherfd310492008-05-25 00:16:51 +02001424 self.signature(node, frame, extra_kwargs)
Armin Ronacher8efc5222008-04-08 14:47:40 +02001425 self.write(')')
1426
1427 def visit_Keyword(self, node, frame):
Armin Ronacher2e9396b2008-04-16 14:21:57 +02001428 self.write(node.key + '=')
Armin Ronacher8efc5222008-04-08 14:47:40 +02001429 self.visit(node.value, frame)
Armin Ronachered1e0d42008-05-18 20:25:28 +02001430
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001431 # -- Unused nodes for extensions
Armin Ronachered1e0d42008-05-18 20:25:28 +02001432
1433 def visit_MarkSafe(self, node, frame):
1434 self.write('Markup(')
1435 self.visit(node.expr, frame)
1436 self.write(')')
1437
1438 def visit_EnvironmentAttribute(self, node, frame):
1439 self.write('environment.' + node.name)
1440
1441 def visit_ExtensionAttribute(self, node, frame):
Armin Ronacher6df604e2008-05-23 22:18:38 +02001442 self.write('environment.extensions[%r].%s' % (node.identifier, node.name))
Armin Ronachered1e0d42008-05-18 20:25:28 +02001443
1444 def visit_ImportedName(self, node, frame):
1445 self.write(self.import_aliases[node.importname])
1446
1447 def visit_InternalName(self, node, frame):
1448 self.write(node.name)
1449
Armin Ronacher6df604e2008-05-23 22:18:38 +02001450 def visit_ContextReference(self, node, frame):
1451 self.write('context')
1452
Armin Ronachered1e0d42008-05-18 20:25:28 +02001453 def visit_Continue(self, node, frame):
1454 self.writeline('continue', node)
1455
1456 def visit_Break(self, node, frame):
1457 self.writeline('break', node)