blob: 75869cfdda7a72d309bb409e74f8d51c7fccf461 [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.
9 :license: GNU GPL.
10"""
Armin Ronacher8efc5222008-04-08 14:47:40 +020011from copy import copy
Armin Ronacher2feed1d2008-04-26 16:26:52 +020012from keyword import iskeyword
Armin Ronachere791c2a2008-04-07 18:39:54 +020013from cStringIO import StringIO
Armin Ronacherd1ff8582008-05-11 00:30:43 +020014from itertools import chain
Armin Ronachere791c2a2008-04-07 18:39:54 +020015from jinja2 import nodes
16from jinja2.visitor import NodeVisitor, NodeTransformer
17from jinja2.exceptions import TemplateAssertionError
Armin Ronacher9cf95912008-05-24 19:54:43 +020018from jinja2.utils import Markup, concat, escape
Armin Ronachere791c2a2008-04-07 18:39:54 +020019
20
21operators = {
22 'eq': '==',
23 'ne': '!=',
24 'gt': '>',
25 'gteq': '>=',
26 'lt': '<',
27 'lteq': '<=',
28 'in': 'in',
29 'notin': 'not in'
30}
31
Armin Ronacher3d8b7842008-04-13 13:16:50 +020032try:
33 exec '(0 if 0 else 0)'
34except SyntaxError:
35 have_condexpr = False
36else:
37 have_condexpr = True
38
39
Armin Ronacher8e8d0712008-04-16 23:10:49 +020040def generate(node, environment, name, filename, stream=None):
Armin Ronacherbcb7c532008-04-11 16:30:34 +020041 """Generate the python source for a node tree."""
Armin Ronacher023b5e92008-05-08 11:03:10 +020042 if not isinstance(node, nodes.Template):
43 raise TypeError('Can\'t compile non template nodes')
Armin Ronacher8e8d0712008-04-16 23:10:49 +020044 generator = CodeGenerator(environment, name, filename, stream)
Armin Ronachere791c2a2008-04-07 18:39:54 +020045 generator.visit(node)
46 if stream is None:
47 return generator.stream.getvalue()
48
49
Armin Ronacher4dfc9752008-04-09 15:03:29 +020050def has_safe_repr(value):
51 """Does the node have a safe representation?"""
Armin Ronacherd55ab532008-04-09 16:13:39 +020052 if value is None or value is NotImplemented or value is Ellipsis:
Armin Ronacher4dfc9752008-04-09 15:03:29 +020053 return True
Armin Ronacherd55ab532008-04-09 16:13:39 +020054 if isinstance(value, (bool, int, long, float, complex, basestring,
Armin Ronacher32a910f2008-04-26 23:21:03 +020055 xrange, Markup)):
Armin Ronacher4dfc9752008-04-09 15:03:29 +020056 return True
Armin Ronacherd55ab532008-04-09 16:13:39 +020057 if isinstance(value, (tuple, list, set, frozenset)):
Armin Ronacher4dfc9752008-04-09 15:03:29 +020058 for item in value:
59 if not has_safe_repr(item):
60 return False
61 return True
62 elif isinstance(value, dict):
63 for key, value in value.iteritems():
64 if not has_safe_repr(key):
65 return False
66 if not has_safe_repr(value):
67 return False
68 return True
69 return False
70
71
Armin Ronacherc9705c22008-04-27 21:28:03 +020072def find_undeclared(nodes, names):
73 """Check if the names passed are accessed undeclared. The return value
74 is a set of all the undeclared names from the sequence of names found.
75 """
76 visitor = UndeclaredNameVisitor(names)
77 try:
78 for node in nodes:
79 visitor.visit(node)
80 except VisitorExit:
81 pass
82 return visitor.undeclared
83
84
Armin Ronachere791c2a2008-04-07 18:39:54 +020085class Identifiers(object):
86 """Tracks the status of identifiers in frames."""
87
88 def __init__(self):
89 # variables that are known to be declared (probably from outer
90 # frames or because they are special for the frame)
91 self.declared = set()
92
Armin Ronacher10f3ba22008-04-18 11:30:37 +020093 # undeclared variables from outer scopes
94 self.outer_undeclared = set()
95
Armin Ronachere791c2a2008-04-07 18:39:54 +020096 # names that are accessed without being explicitly declared by
97 # this one or any of the outer scopes. Names can appear both in
98 # declared and undeclared.
99 self.undeclared = set()
100
101 # names that are declared locally
102 self.declared_locally = set()
103
104 # names that are declared by parameters
105 self.declared_parameter = set()
106
107 def add_special(self, name):
108 """Register a special name like `loop`."""
109 self.undeclared.discard(name)
110 self.declared.add(name)
111
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200112 def is_declared(self, name, local_only=False):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200113 """Check if a name is declared in this or an outer scope."""
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200114 if name in self.declared_locally or name in self.declared_parameter:
115 return True
116 if local_only:
117 return False
118 return name in self.declared
Armin Ronachere791c2a2008-04-07 18:39:54 +0200119
120 def find_shadowed(self):
121 """Find all the shadowed names."""
Armin Ronacher10f3ba22008-04-18 11:30:37 +0200122 return (self.declared | self.outer_undeclared) & \
123 (self.declared_locally | self.declared_parameter)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200124
125
126class Frame(object):
Armin Ronacher75cfb862008-04-11 13:47:22 +0200127 """Holds compile time information for us."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200128
129 def __init__(self, parent=None):
130 self.identifiers = Identifiers()
Armin Ronacherfed44b52008-04-13 19:42:53 +0200131
Armin Ronacher75cfb862008-04-11 13:47:22 +0200132 # a toplevel frame is the root + soft frames such as if conditions.
Armin Ronacher8efc5222008-04-08 14:47:40 +0200133 self.toplevel = False
Armin Ronacherfed44b52008-04-13 19:42:53 +0200134
Armin Ronacher75cfb862008-04-11 13:47:22 +0200135 # the root frame is basically just the outermost frame, so no if
136 # conditions. This information is used to optimize inheritance
137 # situations.
138 self.rootlevel = False
Armin Ronacherfed44b52008-04-13 19:42:53 +0200139
140 # inside some tags we are using a buffer rather than yield statements.
141 # this for example affects {% filter %} or {% macro %}. If a frame
142 # is buffered this variable points to the name of the list used as
143 # buffer.
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200144 self.buffer = None
Armin Ronacherfed44b52008-04-13 19:42:53 +0200145
Armin Ronacherfed44b52008-04-13 19:42:53 +0200146 # the name of the block we're in, otherwise None.
Armin Ronacher8efc5222008-04-08 14:47:40 +0200147 self.block = parent and parent.block or None
Armin Ronacherfed44b52008-04-13 19:42:53 +0200148
149 # 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 Ronachere791c2a2008-04-07 18:39:54 +0200155 parent.identifiers.declared_locally |
Armin Ronacherb3a1fcf2008-05-15 11:04:14 +0200156 parent.identifiers.declared_parameter |
157 parent.identifiers.undeclared
Armin Ronachere791c2a2008-04-07 18:39:54 +0200158 )
Armin Ronacher10f3ba22008-04-18 11:30:37 +0200159 self.identifiers.outer_undeclared.update(
160 parent.identifiers.undeclared -
161 self.identifiers.declared
162 )
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200163 self.buffer = parent.buffer
Armin Ronachere791c2a2008-04-07 18:39:54 +0200164
Armin Ronacher8efc5222008-04-08 14:47:40 +0200165 def copy(self):
166 """Create a copy of the current one."""
167 rv = copy(self)
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200168 rv.identifiers = copy(self.identifiers)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200169 return rv
170
Armin Ronacherc9705c22008-04-27 21:28:03 +0200171 def inspect(self, nodes, hard_scope=False):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200172 """Walk the node and check for identifiers. If the scope is hard (eg:
173 enforce on a python level) overrides from outer scopes are tracked
174 differently.
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200175 """
176 visitor = FrameIdentifierVisitor(self.identifiers, hard_scope)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200177 for node in nodes:
Armin Ronacherc9705c22008-04-27 21:28:03 +0200178 visitor.visit(node)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200179
180 def inner(self):
181 """Return an inner frame."""
182 return Frame(self)
183
Armin Ronacher75cfb862008-04-11 13:47:22 +0200184 def soft(self):
185 """Return a soft frame. A soft frame may not be modified as
186 standalone thing as it shares the resources with the frame it
187 was created of, but it's not a rootlevel frame any longer.
188 """
189 rv = copy(self)
190 rv.rootlevel = False
191 return rv
192
Armin Ronachere791c2a2008-04-07 18:39:54 +0200193
Armin Ronacherc9705c22008-04-27 21:28:03 +0200194class VisitorExit(RuntimeError):
195 """Exception used by the `UndeclaredNameVisitor` to signal a stop."""
196
197
198class DependencyFinderVisitor(NodeVisitor):
199 """A visitor that collects filter and test calls."""
200
201 def __init__(self):
202 self.filters = set()
203 self.tests = set()
204
205 def visit_Filter(self, node):
206 self.generic_visit(node)
207 self.filters.add(node.name)
208
209 def visit_Test(self, node):
210 self.generic_visit(node)
211 self.tests.add(node.name)
212
213 def visit_Block(self, node):
214 """Stop visiting at blocks."""
215
216
217class UndeclaredNameVisitor(NodeVisitor):
218 """A visitor that checks if a name is accessed without being
219 declared. This is different from the frame visitor as it will
220 not stop at closure frames.
221 """
222
223 def __init__(self, names):
224 self.names = set(names)
225 self.undeclared = set()
226
227 def visit_Name(self, node):
228 if node.ctx == 'load' and node.name in self.names:
229 self.undeclared.add(node.name)
230 if self.undeclared == self.names:
231 raise VisitorExit()
232 else:
233 self.names.discard(node.name)
234
235 def visit_Block(self, node):
236 """Stop visiting a blocks."""
237
238
Armin Ronachere791c2a2008-04-07 18:39:54 +0200239class FrameIdentifierVisitor(NodeVisitor):
240 """A visitor for `Frame.inspect`."""
241
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200242 def __init__(self, identifiers, hard_scope):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200243 self.identifiers = identifiers
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200244 self.hard_scope = hard_scope
Armin Ronachere791c2a2008-04-07 18:39:54 +0200245
Armin Ronacherc9705c22008-04-27 21:28:03 +0200246 def visit_Name(self, node):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200247 """All assignments to names go through this function."""
Armin Ronachere9411b42008-05-15 16:22:07 +0200248 if node.ctx == 'store':
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200249 self.identifiers.declared_locally.add(node.name)
Armin Ronachere9411b42008-05-15 16:22:07 +0200250 elif node.ctx == 'param':
251 self.identifiers.declared_parameter.add(node.name)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200252 elif node.ctx == 'load' and not \
253 self.identifiers.is_declared(node.name, self.hard_scope):
254 self.identifiers.undeclared.add(node.name)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200255
Armin Ronacherc9705c22008-04-27 21:28:03 +0200256 def visit_Macro(self, node):
Armin Ronacherc9705c22008-04-27 21:28:03 +0200257 self.identifiers.declared_locally.add(node.name)
Armin Ronacher0611e492008-04-25 23:44:14 +0200258
Armin Ronacherc9705c22008-04-27 21:28:03 +0200259 def visit_Import(self, node):
260 self.generic_visit(node)
261 self.identifiers.declared_locally.add(node.target)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200262
Armin Ronacherc9705c22008-04-27 21:28:03 +0200263 def visit_FromImport(self, node):
264 self.generic_visit(node)
265 for name in node.names:
266 if isinstance(name, tuple):
267 self.identifiers.declared_locally.add(name[1])
268 else:
269 self.identifiers.declared_locally.add(name)
270
271 def visit_Assign(self, node):
Armin Ronacherebe55aa2008-04-10 20:51:23 +0200272 """Visit assignments in the correct order."""
Armin Ronacherc9705c22008-04-27 21:28:03 +0200273 self.visit(node.node)
274 self.visit(node.target)
Armin Ronacherebe55aa2008-04-10 20:51:23 +0200275
Armin Ronacherc9705c22008-04-27 21:28:03 +0200276 def visit_For(self, node):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200277 """Visiting stops at for blocks. However the block sequence
278 is visited as part of the outer scope.
279 """
Armin Ronacherc9705c22008-04-27 21:28:03 +0200280 self.visit(node.iter)
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200281
Armin Ronacherc9705c22008-04-27 21:28:03 +0200282 def visit_CallBlock(self, node):
283 for child in node.iter_child_nodes(exclude=('body',)):
284 self.visit(child)
285
286 def visit_FilterBlock(self, node):
287 self.visit(node.filter)
288
289 def visit_Block(self, node):
290 """Stop visiting at blocks."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200291
292
Armin Ronacher75cfb862008-04-11 13:47:22 +0200293class CompilerExit(Exception):
294 """Raised if the compiler encountered a situation where it just
295 doesn't make sense to further process the code. Any block that
Armin Ronacher0611e492008-04-25 23:44:14 +0200296 raises such an exception is not further processed.
297 """
Armin Ronacher75cfb862008-04-11 13:47:22 +0200298
299
Armin Ronachere791c2a2008-04-07 18:39:54 +0200300class CodeGenerator(NodeVisitor):
301
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200302 def __init__(self, environment, name, filename, stream=None):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200303 if stream is None:
304 stream = StringIO()
Christoph Hack65642a52008-04-08 14:46:56 +0200305 self.environment = environment
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200306 self.name = name
Armin Ronachere791c2a2008-04-07 18:39:54 +0200307 self.filename = filename
308 self.stream = stream
Armin Ronacherfed44b52008-04-13 19:42:53 +0200309
Armin Ronacher023b5e92008-05-08 11:03:10 +0200310 # aliases for imports
311 self.import_aliases = {}
312
Armin Ronacherfed44b52008-04-13 19:42:53 +0200313 # a registry for all blocks. Because blocks are moved out
314 # into the global python scope they are registered here
Armin Ronachere791c2a2008-04-07 18:39:54 +0200315 self.blocks = {}
Armin Ronacherfed44b52008-04-13 19:42:53 +0200316
317 # the number of extends statements so far
Armin Ronacher7fb38972008-04-11 13:54:28 +0200318 self.extends_so_far = 0
Armin Ronacherfed44b52008-04-13 19:42:53 +0200319
320 # some templates have a rootlevel extends. In this case we
321 # can safely assume that we're a child template and do some
322 # more optimizations.
Armin Ronacher75cfb862008-04-11 13:47:22 +0200323 self.has_known_extends = False
Armin Ronacherfed44b52008-04-13 19:42:53 +0200324
Armin Ronacherba3757b2008-04-16 19:43:16 +0200325 # the current line number
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200326 self.code_lineno = 1
Armin Ronacherba3757b2008-04-16 19:43:16 +0200327
Armin Ronacherb9e78752008-05-10 23:36:28 +0200328 # registry of all filters and tests (global, not block local)
329 self.tests = {}
330 self.filters = {}
331
Armin Ronacherba3757b2008-04-16 19:43:16 +0200332 # the debug information
333 self.debug_info = []
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200334 self._write_debug_info = None
Armin Ronacherba3757b2008-04-16 19:43:16 +0200335
Armin Ronacherfed44b52008-04-13 19:42:53 +0200336 # the number of new lines before the next write()
337 self._new_lines = 0
338
339 # the line number of the last written statement
Armin Ronachere791c2a2008-04-07 18:39:54 +0200340 self._last_line = 0
Armin Ronacherfed44b52008-04-13 19:42:53 +0200341
342 # true if nothing was written so far.
Armin Ronachere791c2a2008-04-07 18:39:54 +0200343 self._first_write = True
344
Armin Ronacherfed44b52008-04-13 19:42:53 +0200345 # used by the `temporary_identifier` method to get new
346 # unique, temporary identifier
347 self._last_identifier = 0
348
349 # the current indentation
350 self._indentation = 0
351
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200352 # -- Various compilation helpers
353
Armin Ronachere2244882008-05-19 09:25:57 +0200354 def fail(self, msg, lineno):
355 """Fail with a `TemplateAssertionError`."""
356 raise TemplateAssertionError(msg, lineno, self.name, self.filename)
357
Armin Ronachere791c2a2008-04-07 18:39:54 +0200358 def temporary_identifier(self):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200359 """Get a new unique identifier."""
360 self._last_identifier += 1
Armin Ronacher8a1d27f2008-05-19 08:37:19 +0200361 return 't_%d' % self._last_identifier
Armin Ronachere791c2a2008-04-07 18:39:54 +0200362
Armin Ronachered1e0d42008-05-18 20:25:28 +0200363 def buffer(self, frame):
364 """Enable buffering for the frame from that point onwards."""
Armin Ronachere2244882008-05-19 09:25:57 +0200365 frame.buffer = self.temporary_identifier()
366 self.writeline('%s = []' % frame.buffer)
Armin Ronachered1e0d42008-05-18 20:25:28 +0200367
368 def return_buffer_contents(self, frame):
369 """Return the buffer contents of the frame."""
370 if self.environment.autoescape:
371 self.writeline('return Markup(concat(%s))' % frame.buffer)
372 else:
373 self.writeline('return concat(%s)' % frame.buffer)
374
Armin Ronachere791c2a2008-04-07 18:39:54 +0200375 def indent(self):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200376 """Indent by one."""
377 self._indentation += 1
Armin Ronachere791c2a2008-04-07 18:39:54 +0200378
Armin Ronacher8efc5222008-04-08 14:47:40 +0200379 def outdent(self, step=1):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200380 """Outdent by step."""
381 self._indentation -= step
Armin Ronachere791c2a2008-04-07 18:39:54 +0200382
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200383 def start_write(self, frame, node=None):
384 """Yield or write into the frame buffer."""
385 if frame.buffer is None:
386 self.writeline('yield ', node)
387 else:
388 self.writeline('%s.append(' % frame.buffer, node)
389
390 def end_write(self, frame):
391 """End the writing process started by `start_write`."""
392 if frame.buffer is not None:
393 self.write(')')
394
395 def simple_write(self, s, frame, node=None):
396 """Simple shortcut for start_write + write + end_write."""
397 self.start_write(frame, node)
398 self.write(s)
399 self.end_write(frame)
400
Armin Ronacherc9705c22008-04-27 21:28:03 +0200401 def blockvisit(self, nodes, frame, force_generator=True):
402 """Visit a list of nodes as block in a frame. If the current frame
403 is no buffer a dummy ``if 0: yield None`` is written automatically
404 unless the force_generator parameter is set to False.
Armin Ronacherfed44b52008-04-13 19:42:53 +0200405 """
Armin Ronacher625215e2008-04-13 16:31:08 +0200406 if frame.buffer is None and force_generator:
Armin Ronachere791c2a2008-04-07 18:39:54 +0200407 self.writeline('if 0: yield None')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200408 try:
409 for node in nodes:
410 self.visit(node, frame)
411 except CompilerExit:
412 pass
Armin Ronachere791c2a2008-04-07 18:39:54 +0200413
414 def write(self, x):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200415 """Write a string into the output stream."""
416 if self._new_lines:
Armin Ronachere791c2a2008-04-07 18:39:54 +0200417 if not self._first_write:
Armin Ronacherfed44b52008-04-13 19:42:53 +0200418 self.stream.write('\n' * self._new_lines)
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200419 self.code_lineno += self._new_lines
420 if self._write_debug_info is not None:
421 self.debug_info.append((self._write_debug_info,
422 self.code_lineno))
423 self._write_debug_info = None
Armin Ronachere791c2a2008-04-07 18:39:54 +0200424 self._first_write = False
Armin Ronacherfed44b52008-04-13 19:42:53 +0200425 self.stream.write(' ' * self._indentation)
426 self._new_lines = 0
Armin Ronachere791c2a2008-04-07 18:39:54 +0200427 self.stream.write(x)
428
429 def writeline(self, x, node=None, extra=0):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200430 """Combination of newline and write."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200431 self.newline(node, extra)
432 self.write(x)
433
434 def newline(self, node=None, extra=0):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200435 """Add one or more newlines before the next write."""
436 self._new_lines = max(self._new_lines, 1 + extra)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200437 if node is not None and node.lineno != self._last_line:
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200438 self._write_debug_info = node.lineno
439 self._last_line = node.lineno
Armin Ronachere791c2a2008-04-07 18:39:54 +0200440
Armin Ronacherfd310492008-05-25 00:16:51 +0200441 def signature(self, node, frame, extra_kwargs=None):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200442 """Writes a function call to the stream for the current node.
Armin Ronacherfd310492008-05-25 00:16:51 +0200443 A leading comma is added automatically. The extra keyword
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200444 arguments may not include python keywords otherwise a syntax
445 error could occour. The extra keyword arguments should be given
446 as python dict.
Armin Ronacherfed44b52008-04-13 19:42:53 +0200447 """
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200448 # if any of the given keyword arguments is a python keyword
449 # we have to make sure that no invalid call is created.
450 kwarg_workaround = False
451 for kwarg in chain((x.key for x in node.kwargs), extra_kwargs or ()):
452 if iskeyword(kwarg):
453 kwarg_workaround = True
454 break
455
Armin Ronacher8efc5222008-04-08 14:47:40 +0200456 for arg in node.args:
Armin Ronacherfd310492008-05-25 00:16:51 +0200457 self.write(', ')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200458 self.visit(arg, frame)
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200459
460 if not kwarg_workaround:
461 for kwarg in node.kwargs:
Armin Ronacherfd310492008-05-25 00:16:51 +0200462 self.write(', ')
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200463 self.visit(kwarg, frame)
464 if extra_kwargs is not None:
465 for key, value in extra_kwargs.iteritems():
Armin Ronacherfd310492008-05-25 00:16:51 +0200466 self.write(', %s=%s' % (key, value))
Armin Ronacher8efc5222008-04-08 14:47:40 +0200467 if node.dyn_args:
Armin Ronacherfd310492008-05-25 00:16:51 +0200468 self.write(', *')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200469 self.visit(node.dyn_args, frame)
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200470
471 if kwarg_workaround:
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200472 if node.dyn_kwargs is not None:
Armin Ronacherfd310492008-05-25 00:16:51 +0200473 self.write(', **dict({')
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200474 else:
Armin Ronacherfd310492008-05-25 00:16:51 +0200475 self.write(', **{')
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200476 for kwarg in node.kwargs:
477 self.write('%r: ' % kwarg.key)
478 self.visit(kwarg.value, frame)
479 self.write(', ')
480 if extra_kwargs is not None:
481 for key, value in extra_kwargs.iteritems():
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200482 self.write('%r: %s, ' % (key, value))
483 if node.dyn_kwargs is not None:
484 self.write('}, **')
485 self.visit(node.dyn_kwargs, frame)
486 self.write(')')
487 else:
488 self.write('}')
489
490 elif node.dyn_kwargs is not None:
Armin Ronacherfd310492008-05-25 00:16:51 +0200491 self.write(', **')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200492 self.visit(node.dyn_kwargs, frame)
493
Armin Ronacherc9705c22008-04-27 21:28:03 +0200494 def pull_locals(self, frame):
495 """Pull all the references identifiers into the local scope."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200496 for name in frame.identifiers.undeclared:
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200497 self.writeline('l_%s = context.resolve(%r)' % (name, name))
Armin Ronacherc9705c22008-04-27 21:28:03 +0200498
499 def pull_dependencies(self, nodes):
500 """Pull all the dependencies."""
501 visitor = DependencyFinderVisitor()
502 for node in nodes:
503 visitor.visit(node)
Armin Ronacherb9e78752008-05-10 23:36:28 +0200504 for dependency in 'filters', 'tests':
505 mapping = getattr(self, dependency)
506 for name in getattr(visitor, dependency):
507 if name not in mapping:
508 mapping[name] = self.temporary_identifier()
509 self.writeline('%s = environment.%s[%r]' %
510 (mapping[name], dependency, name))
Armin Ronachere791c2a2008-04-07 18:39:54 +0200511
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200512 def collect_shadowed(self, frame):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200513 """This function returns all the shadowed variables in a dict
514 in the form name: alias and will write the required assignments
515 into the current scope. No indentation takes place.
516 """
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200517 aliases = {}
518 for name in frame.identifiers.find_shadowed():
519 aliases[name] = ident = self.temporary_identifier()
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200520 self.writeline('%s = l_%s' % (ident, name))
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200521 return aliases
522
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200523 def restore_shadowed(self, aliases):
524 """Restore all aliases."""
525 for name, alias in aliases.iteritems():
526 self.writeline('l_%s = %s' % (name, alias))
527
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200528 def function_scoping(self, node, frame, children=None,
529 find_special=True):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200530 """In Jinja a few statements require the help of anonymous
531 functions. Those are currently macros and call blocks and in
532 the future also recursive loops. As there is currently
533 technical limitation that doesn't allow reading and writing a
534 variable in a scope where the initial value is coming from an
535 outer scope, this function tries to fall back with a common
536 error message. Additionally the frame passed is modified so
537 that the argumetns are collected and callers are looked up.
538
539 This will return the modified frame.
540 """
Armin Ronacherc9705c22008-04-27 21:28:03 +0200541 # we have to iterate twice over it, make sure that works
542 if children is None:
543 children = node.iter_child_nodes()
544 children = list(children)
Armin Ronacher71082072008-04-12 14:19:36 +0200545 func_frame = frame.inner()
Armin Ronacherc9705c22008-04-27 21:28:03 +0200546 func_frame.inspect(children, hard_scope=True)
Armin Ronacher71082072008-04-12 14:19:36 +0200547
548 # variables that are undeclared (accessed before declaration) and
549 # declared locally *and* part of an outside scope raise a template
550 # assertion error. Reason: we can't generate reasonable code from
551 # it without aliasing all the variables. XXX: alias them ^^
552 overriden_closure_vars = (
553 func_frame.identifiers.undeclared &
554 func_frame.identifiers.declared &
555 (func_frame.identifiers.declared_locally |
556 func_frame.identifiers.declared_parameter)
557 )
558 if overriden_closure_vars:
Armin Ronachere2244882008-05-19 09:25:57 +0200559 self.fail('It\'s not possible to set and access variables '
560 'derived from an outer scope! (affects: %s' %
561 ', '.join(sorted(overriden_closure_vars)), node.lineno)
Armin Ronacher71082072008-04-12 14:19:36 +0200562
563 # remove variables from a closure from the frame's undeclared
564 # identifiers.
565 func_frame.identifiers.undeclared -= (
566 func_frame.identifiers.undeclared &
567 func_frame.identifiers.declared
568 )
569
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200570 # no special variables for this scope, abort early
571 if not find_special:
572 return func_frame
573
Armin Ronacher963f97d2008-04-25 11:44:59 +0200574 func_frame.accesses_kwargs = False
575 func_frame.accesses_varargs = False
Armin Ronacher71082072008-04-12 14:19:36 +0200576 func_frame.accesses_caller = False
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200577 func_frame.arguments = args = ['l_' + x.name for x in node.args]
Armin Ronacher71082072008-04-12 14:19:36 +0200578
Armin Ronacherc9705c22008-04-27 21:28:03 +0200579 undeclared = find_undeclared(children, ('caller', 'kwargs', 'varargs'))
580
581 if 'caller' in undeclared:
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200582 func_frame.accesses_caller = True
583 func_frame.identifiers.add_special('caller')
584 args.append('l_caller')
Armin Ronacherc9705c22008-04-27 21:28:03 +0200585 if 'kwargs' in undeclared:
Armin Ronacher963f97d2008-04-25 11:44:59 +0200586 func_frame.accesses_kwargs = True
587 func_frame.identifiers.add_special('kwargs')
588 args.append('l_kwargs')
Armin Ronacherc9705c22008-04-27 21:28:03 +0200589 if 'varargs' in undeclared:
Armin Ronacher963f97d2008-04-25 11:44:59 +0200590 func_frame.accesses_varargs = True
591 func_frame.identifiers.add_special('varargs')
592 args.append('l_varargs')
Armin Ronacher71082072008-04-12 14:19:36 +0200593 return func_frame
594
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200595 def macro_body(self, node, frame, children=None):
596 """Dump the function def of a macro or call block."""
597 frame = self.function_scoping(node, frame, children)
598 args = frame.arguments
599 self.writeline('def macro(%s):' % ', '.join(args), node)
600 self.indent()
601 self.buffer(frame)
602 self.pull_locals(frame)
603 self.blockvisit(node.body, frame)
604 self.return_buffer_contents(frame)
605 self.outdent()
606 return frame
607
608 def macro_def(self, node, frame):
609 """Dump the macro definition for the def created by macro_body."""
610 arg_tuple = ', '.join(repr(x.name) for x in node.args)
611 name = getattr(node, 'name', None)
612 if len(node.args) == 1:
613 arg_tuple += ','
614 self.write('Macro(environment, macro, %r, (%s), (' %
615 (name, arg_tuple))
616 for arg in node.defaults:
617 self.visit(arg, frame)
618 self.write(', ')
Armin Ronacher903d1682008-05-23 00:51:58 +0200619 self.write('), %r, %r, %r)' % (
620 bool(frame.accesses_kwargs),
621 bool(frame.accesses_varargs),
622 bool(frame.accesses_caller)
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200623 ))
624
625 # -- Statement Visitors
Armin Ronachere791c2a2008-04-07 18:39:54 +0200626
627 def visit_Template(self, node, frame=None):
628 assert frame is None, 'no root frame allowed'
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200629 from jinja2.runtime import __all__ as exported
Armin Ronacher709f6e52008-04-28 18:18:16 +0200630 self.writeline('from __future__ import division')
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200631 self.writeline('from jinja2.runtime import ' + ', '.join(exported))
Armin Ronacher8edbe492008-04-10 20:43:43 +0200632
Armin Ronacher75cfb862008-04-11 13:47:22 +0200633 # do we have an extends tag at all? If not, we can save some
634 # overhead by just not processing any inheritance code.
635 have_extends = node.find(nodes.Extends) is not None
636
Armin Ronacher8edbe492008-04-10 20:43:43 +0200637 # find all blocks
638 for block in node.find_all(nodes.Block):
639 if block.name in self.blocks:
Armin Ronachere2244882008-05-19 09:25:57 +0200640 self.fail('block %r defined twice' % block.name, block.lineno)
Armin Ronacher8edbe492008-04-10 20:43:43 +0200641 self.blocks[block.name] = block
Armin Ronachere791c2a2008-04-07 18:39:54 +0200642
Armin Ronacher023b5e92008-05-08 11:03:10 +0200643 # find all imports and import them
644 for import_ in node.find_all(nodes.ImportedName):
645 if import_.importname not in self.import_aliases:
646 imp = import_.importname
647 self.import_aliases[imp] = alias = self.temporary_identifier()
648 if '.' in imp:
649 module, obj = imp.rsplit('.', 1)
650 self.writeline('from %s import %s as %s' %
651 (module, obj, alias))
652 else:
653 self.writeline('import %s as %s' % (imp, alias))
654
655 # add the load name
Armin Ronacherdc02b642008-05-15 22:47:27 +0200656 self.writeline('name = %r' % self.name)
Armin Ronacher023b5e92008-05-08 11:03:10 +0200657
Armin Ronacher8efc5222008-04-08 14:47:40 +0200658 # generate the root render function.
Armin Ronacher32a910f2008-04-26 23:21:03 +0200659 self.writeline('def root(context, environment=environment):', extra=1)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200660
661 # process the root
Armin Ronachere791c2a2008-04-07 18:39:54 +0200662 frame = Frame()
Armin Ronacherc9705c22008-04-27 21:28:03 +0200663 frame.inspect(node.body)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200664 frame.toplevel = frame.rootlevel = True
Armin Ronacherf059ec12008-04-11 22:21:00 +0200665 self.indent()
Armin Ronacherc9705c22008-04-27 21:28:03 +0200666 if have_extends:
667 self.writeline('parent_template = None')
Armin Ronacherc9705c22008-04-27 21:28:03 +0200668 if 'self' in find_undeclared(node.body, ('self',)):
669 frame.identifiers.add_special('self')
670 self.writeline('l_self = TemplateReference(context)')
Armin Ronacher6df604e2008-05-23 22:18:38 +0200671 self.pull_locals(frame)
672 self.pull_dependencies(node.body)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200673 self.blockvisit(node.body, frame)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200674 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200675
Armin Ronacher8efc5222008-04-08 14:47:40 +0200676 # make sure that the parent root is called.
Armin Ronacher75cfb862008-04-11 13:47:22 +0200677 if have_extends:
678 if not self.has_known_extends:
679 self.indent()
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200680 self.writeline('if parent_template is not None:')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200681 self.indent()
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200682 self.writeline('for event in parent_template.'
Armin Ronacher5411ce72008-05-25 11:36:22 +0200683 'root_render_func(context):')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200684 self.indent()
685 self.writeline('yield event')
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200686 self.outdent(2 + (not self.has_known_extends))
Armin Ronachere791c2a2008-04-07 18:39:54 +0200687
688 # at this point we now have the blocks collected and can visit them too.
689 for name, block in self.blocks.iteritems():
690 block_frame = Frame()
Armin Ronacherc9705c22008-04-27 21:28:03 +0200691 block_frame.inspect(block.body)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200692 block_frame.block = name
Armin Ronacherd4c64f72008-04-11 17:15:29 +0200693 self.writeline('def block_%s(context, environment=environment):'
694 % name, block, 1)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200695 self.indent()
696 undeclared = find_undeclared(block.body, ('self', 'super'))
697 if 'self' in undeclared:
698 block_frame.identifiers.add_special('self')
699 self.writeline('l_self = TemplateReference(context)')
700 if 'super' in undeclared:
701 block_frame.identifiers.add_special('super')
702 self.writeline('l_super = context.super(%r, '
703 'block_%s)' % (name, name))
Armin Ronachere791c2a2008-04-07 18:39:54 +0200704 self.pull_locals(block_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200705 self.pull_dependencies(block.body)
Armin Ronacher625215e2008-04-13 16:31:08 +0200706 self.blockvisit(block.body, block_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200707 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200708
Armin Ronacher75cfb862008-04-11 13:47:22 +0200709 self.writeline('blocks = {%s}' % ', '.join('%r: block_%s' % (x, x)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200710 for x in self.blocks),
711 extra=1)
712
713 # add a function that returns the debug info
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200714 self.writeline('debug_info = %r' % '&'.join('%s=%s' % x for x
715 in self.debug_info))
Armin Ronacher75cfb862008-04-11 13:47:22 +0200716
Armin Ronachere791c2a2008-04-07 18:39:54 +0200717 def visit_Block(self, node, frame):
718 """Call a block and register it for the template."""
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200719 level = 1
Armin Ronacher75cfb862008-04-11 13:47:22 +0200720 if frame.toplevel:
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200721 # if we know that we are a child template, there is no need to
722 # check if we are one
723 if self.has_known_extends:
724 return
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200725 if self.extends_so_far > 0:
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200726 self.writeline('if parent_template is None:')
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200727 self.indent()
728 level += 1
Armin Ronacher83fbc0f2008-05-15 12:22:28 +0200729 self.writeline('for event in context.blocks[%r][0](context):' %
Armin Ronacherc9705c22008-04-27 21:28:03 +0200730 node.name, node)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200731 self.indent()
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200732 self.simple_write('event', frame)
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200733 self.outdent(level)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200734
735 def visit_Extends(self, node, frame):
736 """Calls the extender."""
Armin Ronacher8efc5222008-04-08 14:47:40 +0200737 if not frame.toplevel:
Armin Ronachere2244882008-05-19 09:25:57 +0200738 self.fail('cannot use extend from a non top-level scope',
739 node.lineno)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200740
Armin Ronacher7fb38972008-04-11 13:54:28 +0200741 # if the number of extends statements in general is zero so
742 # far, we don't have to add a check if something extended
743 # the template before this one.
744 if self.extends_so_far > 0:
Armin Ronacher75cfb862008-04-11 13:47:22 +0200745
Armin Ronacher7fb38972008-04-11 13:54:28 +0200746 # if we have a known extends we just add a template runtime
747 # error into the generated code. We could catch that at compile
748 # time too, but i welcome it not to confuse users by throwing the
749 # same error at different times just "because we can".
750 if not self.has_known_extends:
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200751 self.writeline('if parent_template is not None:')
Armin Ronacher7fb38972008-04-11 13:54:28 +0200752 self.indent()
753 self.writeline('raise TemplateRuntimeError(%r)' %
754 'extended multiple times')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200755
Armin Ronacher7fb38972008-04-11 13:54:28 +0200756 # if we have a known extends already we don't need that code here
757 # as we know that the template execution will end here.
758 if self.has_known_extends:
759 raise CompilerExit()
760 self.outdent()
761
Armin Ronacher9d42abf2008-05-14 18:10:41 +0200762 self.writeline('parent_template = environment.get_template(', node)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200763 self.visit(node.template, frame)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200764 self.write(', %r)' % self.name)
765 self.writeline('for name, parent_block in parent_template.'
766 'blocks.iteritems():')
767 self.indent()
768 self.writeline('context.blocks.setdefault(name, []).'
Armin Ronacher83fbc0f2008-05-15 12:22:28 +0200769 'append(parent_block)')
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200770 self.outdent()
Armin Ronacher75cfb862008-04-11 13:47:22 +0200771
772 # if this extends statement was in the root level we can take
773 # advantage of that information and simplify the generated code
774 # in the top level from this point onwards
Armin Ronacher27069d72008-05-11 19:48:12 +0200775 if frame.rootlevel:
776 self.has_known_extends = True
Armin Ronachere791c2a2008-04-07 18:39:54 +0200777
Armin Ronacher7fb38972008-04-11 13:54:28 +0200778 # and now we have one more
779 self.extends_so_far += 1
780
Armin Ronacherf059ec12008-04-11 22:21:00 +0200781 def visit_Include(self, node, frame):
782 """Handles includes."""
Armin Ronacherea847c52008-05-02 20:04:32 +0200783 if node.with_context:
784 self.writeline('template = environment.get_template(', node)
785 self.visit(node.template, frame)
786 self.write(', %r)' % self.name)
Armin Ronacher5411ce72008-05-25 11:36:22 +0200787 self.writeline('for event in template.root_render_func('
Armin Ronacherea847c52008-05-02 20:04:32 +0200788 'template.new_context(context.parent, True)):')
789 else:
790 self.writeline('for event in environment.get_template(', node)
791 self.visit(node.template, frame)
Armin Ronacher771c7502008-05-18 23:14:14 +0200792 self.write(', %r).module._body_stream:' %
Armin Ronacherea847c52008-05-02 20:04:32 +0200793 self.name)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200794 self.indent()
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200795 self.simple_write('event', frame)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200796 self.outdent()
797
Armin Ronacher0611e492008-04-25 23:44:14 +0200798 def visit_Import(self, node, frame):
799 """Visit regular imports."""
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200800 self.writeline('l_%s = ' % node.target, node)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200801 if frame.toplevel:
Armin Ronacher53042292008-04-26 18:30:19 +0200802 self.write('context.vars[%r] = ' % node.target)
Armin Ronacher0611e492008-04-25 23:44:14 +0200803 self.write('environment.get_template(')
804 self.visit(node.template, frame)
Armin Ronacherea847c52008-05-02 20:04:32 +0200805 self.write(', %r).' % self.name)
806 if node.with_context:
807 self.write('make_module(context.parent, True)')
808 else:
809 self.write('module')
Armin Ronacher903d1682008-05-23 00:51:58 +0200810 if frame.toplevel and not node.target.startswith('_'):
Armin Ronacher53042292008-04-26 18:30:19 +0200811 self.writeline('context.exported_vars.discard(%r)' % node.target)
Armin Ronacher0611e492008-04-25 23:44:14 +0200812
813 def visit_FromImport(self, node, frame):
814 """Visit named imports."""
815 self.newline(node)
816 self.write('included_template = environment.get_template(')
817 self.visit(node.template, frame)
Armin Ronacherea847c52008-05-02 20:04:32 +0200818 self.write(', %r).' % self.name)
819 if node.with_context:
820 self.write('make_module(context.parent, True)')
821 else:
822 self.write('module')
Armin Ronachera78d2762008-05-15 23:18:07 +0200823
824 var_names = []
825 discarded_names = []
Armin Ronacher0611e492008-04-25 23:44:14 +0200826 for name in node.names:
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200827 if isinstance(name, tuple):
828 name, alias = name
829 else:
830 alias = name
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200831 self.writeline('l_%s = getattr(included_template, '
832 '%r, missing)' % (alias, name))
833 self.writeline('if l_%s is missing:' % alias)
Armin Ronacher0611e492008-04-25 23:44:14 +0200834 self.indent()
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200835 self.writeline('l_%s = environment.undefined(%r %% '
Armin Ronacherdc02b642008-05-15 22:47:27 +0200836 'included_template.__name__, '
Armin Ronacher0a2ac692008-05-13 01:03:08 +0200837 'name=%r)' %
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200838 (alias, 'the template %r does not export '
Armin Ronacher0a2ac692008-05-13 01:03:08 +0200839 'the requested name ' + repr(name), name))
Armin Ronacher0611e492008-04-25 23:44:14 +0200840 self.outdent()
841 if frame.toplevel:
Armin Ronachera78d2762008-05-15 23:18:07 +0200842 var_names.append(alias)
Armin Ronacher903d1682008-05-23 00:51:58 +0200843 if not alias.startswith('_'):
Armin Ronachera78d2762008-05-15 23:18:07 +0200844 discarded_names.append(alias)
845
846 if var_names:
847 if len(var_names) == 1:
848 name = var_names[0]
849 self.writeline('context.vars[%r] = l_%s' % (name, name))
850 else:
851 self.writeline('context.vars.update({%s})' % ', '.join(
852 '%r: l_%s' % (name, name) for name in var_names
853 ))
854 if discarded_names:
855 if len(discarded_names) == 1:
856 self.writeline('context.exported_vars.discard(%r)' %
857 discarded_names[0])
858 else:
859 self.writeline('context.exported_vars.difference_'
860 'update((%s))' % ', '.join(map(repr, discarded_names)))
Armin Ronacherf059ec12008-04-11 22:21:00 +0200861
Armin Ronachere791c2a2008-04-07 18:39:54 +0200862 def visit_For(self, node, frame):
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200863 # when calculating the nodes for the inner frame we have to exclude
864 # the iterator contents from it
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200865 children = node.iter_child_nodes(exclude=('iter',))
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200866 if node.recursive:
867 loop_frame = self.function_scoping(node, frame, children,
868 find_special=False)
869 else:
870 loop_frame = frame.inner()
871 loop_frame.inspect(children)
872
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200873 # try to figure out if we have an extended loop. An extended loop
874 # is necessary if the loop is in recursive mode if the special loop
875 # variable is accessed in the body.
876 extended_loop = node.recursive or 'loop' in \
877 find_undeclared(node.iter_child_nodes(
878 only=('body',)), ('loop',))
879
880 # make sure the loop variable is a special one and raise a template
881 # assertion error if a loop tries to write to loop
882 loop_frame.identifiers.add_special('loop')
883 for name in node.find_all(nodes.Name):
884 if name.ctx == 'store' and name.name == 'loop':
885 self.fail('Can\'t assign to special loop variable '
886 'in for-loop target', name.lineno)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200887
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200888 # if we don't have an recursive loop we have to find the shadowed
889 # variables at that point
890 if not node.recursive:
891 aliases = self.collect_shadowed(loop_frame)
892
893 # otherwise we set up a buffer and add a function def
894 else:
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200895 self.writeline('def loop(reciter, loop_render_func):', node)
896 self.indent()
Armin Ronachered1e0d42008-05-18 20:25:28 +0200897 self.buffer(loop_frame)
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200898 aliases = {}
899
Armin Ronacherc9705c22008-04-27 21:28:03 +0200900 self.pull_locals(loop_frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200901 if node.else_:
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200902 iteration_indicator = self.temporary_identifier()
903 self.writeline('%s = 1' % iteration_indicator)
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200904
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200905 # Create a fake parent loop if the else or test section of a
906 # loop is accessing the special loop variable and no parent loop
907 # exists.
908 if 'loop' not in aliases and 'loop' in find_undeclared(
909 node.iter_child_nodes(only=('else_', 'test')), ('loop',)):
910 self.writeline("l_loop = environment.undefined(%r, name='loop')" %
911 "'loop' is undefined. the filter section of a loop as well " \
912 "as the else block doesn't have access to the special 'loop' "
913 "variable of the current loop. Because there is no parent "
914 "loop it's undefined.")
915
916 self.writeline('for ', node)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200917 self.visit(node.target, loop_frame)
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200918 self.write(extended_loop and ', l_loop in LoopContext(' or ' in ')
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200919
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200920 # if we have an extened loop and a node test, we filter in the
921 # "outer frame".
922 if extended_loop and node.test is not None:
923 self.write('(')
924 self.visit(node.target, loop_frame)
925 self.write(' for ')
926 self.visit(node.target, loop_frame)
927 self.write(' in ')
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200928 if node.recursive:
929 self.write('reciter')
930 else:
931 self.visit(node.iter, loop_frame)
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200932 self.write(' if (')
933 test_frame = loop_frame.copy()
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200934 self.visit(node.test, test_frame)
935 self.write('))')
936
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200937 elif node.recursive:
938 self.write('reciter')
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200939 else:
940 self.visit(node.iter, loop_frame)
941
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200942 if node.recursive:
943 self.write(', recurse=loop_render_func):')
944 else:
945 self.write(extended_loop and '):' or ':')
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200946
947 # tests in not extended loops become a continue
948 if not extended_loop and node.test is not None:
949 self.indent()
Armin Ronacher47a506f2008-05-06 12:17:23 +0200950 self.writeline('if not ')
Armin Ronacher32a910f2008-04-26 23:21:03 +0200951 self.visit(node.test, loop_frame)
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200952 self.write(':')
953 self.indent()
954 self.writeline('continue')
955 self.outdent(2)
956
Armin Ronacherc9705c22008-04-27 21:28:03 +0200957 self.indent()
Armin Ronacherbe4ae242008-04-18 09:49:08 +0200958 self.blockvisit(node.body, loop_frame, force_generator=True)
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200959 if node.else_:
960 self.writeline('%s = 0' % iteration_indicator)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200961 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200962
963 if node.else_:
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200964 self.writeline('if %s:' % iteration_indicator)
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200965 self.indent()
Armin Ronacher625215e2008-04-13 16:31:08 +0200966 self.blockvisit(node.else_, loop_frame, force_generator=False)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200967 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200968
Armin Ronacherd4c64f72008-04-11 17:15:29 +0200969 # reset the aliases if there are any.
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200970 self.restore_shadowed(aliases)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200971
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200972 # if the node was recursive we have to return the buffer contents
973 # and start the iteration code
974 if node.recursive:
Armin Ronachered1e0d42008-05-18 20:25:28 +0200975 self.return_buffer_contents(loop_frame)
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200976 self.outdent()
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200977 self.start_write(frame, node)
978 self.write('loop(')
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200979 self.visit(node.iter, frame)
980 self.write(', loop)')
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200981 self.end_write(frame)
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200982
Armin Ronachere791c2a2008-04-07 18:39:54 +0200983 def visit_If(self, node, frame):
Armin Ronacher75cfb862008-04-11 13:47:22 +0200984 if_frame = frame.soft()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200985 self.writeline('if ', node)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200986 self.visit(node.test, if_frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200987 self.write(':')
Armin Ronacherc9705c22008-04-27 21:28:03 +0200988 self.indent()
Armin Ronacher75cfb862008-04-11 13:47:22 +0200989 self.blockvisit(node.body, if_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200990 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200991 if node.else_:
992 self.writeline('else:')
Armin Ronacherc9705c22008-04-27 21:28:03 +0200993 self.indent()
Armin Ronacher75cfb862008-04-11 13:47:22 +0200994 self.blockvisit(node.else_, if_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200995 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200996
Armin Ronacher8efc5222008-04-08 14:47:40 +0200997 def visit_Macro(self, node, frame):
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200998 macro_frame = self.macro_body(node, frame)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200999 self.newline()
1000 if frame.toplevel:
Armin Ronacher903d1682008-05-23 00:51:58 +02001001 if not node.name.startswith('_'):
Armin Ronacherc9705c22008-04-27 21:28:03 +02001002 self.write('context.exported_vars.add(%r)' % node.name)
Armin Ronacher32a910f2008-04-26 23:21:03 +02001003 self.writeline('context.vars[%r] = ' % node.name)
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001004 self.write('l_%s = ' % node.name)
1005 self.macro_def(node, macro_frame)
Armin Ronacher71082072008-04-12 14:19:36 +02001006
1007 def visit_CallBlock(self, node, frame):
Armin Ronacher3da90312008-05-23 16:37:28 +02001008 children = node.iter_child_nodes(exclude=('call',))
1009 call_frame = self.macro_body(node, frame, children)
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001010 self.writeline('caller = ')
1011 self.macro_def(node, call_frame)
1012 self.start_write(frame, node)
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001013 self.visit_Call(node.call, call_frame, forward_caller=True)
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001014 self.end_write(frame)
Armin Ronacherfa865fb2008-04-12 22:11:53 +02001015
1016 def visit_FilterBlock(self, node, frame):
1017 filter_frame = frame.inner()
1018 filter_frame.inspect(node.iter_child_nodes())
Armin Ronacherfa865fb2008-04-12 22:11:53 +02001019 aliases = self.collect_shadowed(filter_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +02001020 self.pull_locals(filter_frame)
Armin Ronachered1e0d42008-05-18 20:25:28 +02001021 self.buffer(filter_frame)
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001022 self.blockvisit(node.body, filter_frame, force_generator=False)
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001023 self.start_write(frame, node)
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001024 self.visit_Filter(node.filter, filter_frame)
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001025 self.end_write(frame)
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001026 self.restore_shadowed(aliases)
Armin Ronacher8efc5222008-04-08 14:47:40 +02001027
Armin Ronachere791c2a2008-04-07 18:39:54 +02001028 def visit_ExprStmt(self, node, frame):
1029 self.newline(node)
Armin Ronacher6ce170c2008-04-25 12:32:36 +02001030 self.visit(node.node, frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001031
1032 def visit_Output(self, node, frame):
Armin Ronacher75cfb862008-04-11 13:47:22 +02001033 # if we have a known extends statement, we don't output anything
Armin Ronacher7a52df82008-04-11 13:58:22 +02001034 if self.has_known_extends and frame.toplevel:
Armin Ronacher75cfb862008-04-11 13:47:22 +02001035 return
Armin Ronachere791c2a2008-04-07 18:39:54 +02001036
Armin Ronacher75cfb862008-04-11 13:47:22 +02001037 self.newline(node)
Armin Ronacher8edbe492008-04-10 20:43:43 +02001038
Armin Ronacher7fb38972008-04-11 13:54:28 +02001039 # if we are in the toplevel scope and there was already an extends
1040 # statement we have to add a check that disables our yield(s) here
1041 # so that they don't appear in the output.
1042 outdent_later = False
1043 if frame.toplevel and self.extends_so_far != 0:
Armin Ronacher203bfcb2008-04-24 21:54:44 +02001044 self.writeline('if parent_template is None:')
Armin Ronacher75cfb862008-04-11 13:47:22 +02001045 self.indent()
Armin Ronacher7fb38972008-04-11 13:54:28 +02001046 outdent_later = True
Armin Ronacher75cfb862008-04-11 13:47:22 +02001047
Armin Ronachere791c2a2008-04-07 18:39:54 +02001048 # try to evaluate as many chunks as possible into a static
1049 # string at compile time.
1050 body = []
1051 for child in node.nodes:
1052 try:
Armin Ronacher9cf95912008-05-24 19:54:43 +02001053 const = child.as_const()
1054 except nodes.Impossible:
1055 body.append(child)
1056 continue
1057 try:
1058 if self.environment.autoescape:
1059 if hasattr(const, '__html__'):
1060 const = const.__html__()
1061 else:
1062 const = escape(const)
1063 const = unicode(const)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001064 except:
Armin Ronacher9cf95912008-05-24 19:54:43 +02001065 # if something goes wrong here we evaluate the node
1066 # at runtime for easier debugging
Armin Ronachere791c2a2008-04-07 18:39:54 +02001067 body.append(child)
1068 continue
1069 if body and isinstance(body[-1], list):
1070 body[-1].append(const)
1071 else:
1072 body.append([const])
1073
Armin Ronachered1e0d42008-05-18 20:25:28 +02001074 # if we have less than 3 nodes or a buffer we yield or extend/append
1075 if len(body) < 3 or frame.buffer is not None:
Armin Ronacher32a910f2008-04-26 23:21:03 +02001076 if frame.buffer is not None:
Armin Ronacher1e1e8902008-05-11 23:21:16 +02001077 # for one item we append, for more we extend
1078 if len(body) == 1:
1079 self.writeline('%s.append(' % frame.buffer)
1080 else:
1081 self.writeline('%s.extend((' % frame.buffer)
Armin Ronacher1f627ff2008-05-15 13:23:26 +02001082 self.indent()
Armin Ronachere791c2a2008-04-07 18:39:54 +02001083 for item in body:
1084 if isinstance(item, list):
Armin Ronacherde6bf712008-04-26 01:44:14 +02001085 val = repr(concat(item))
Armin Ronacherfa865fb2008-04-12 22:11:53 +02001086 if frame.buffer is None:
1087 self.writeline('yield ' + val)
1088 else:
Armin Ronacher1f627ff2008-05-15 13:23:26 +02001089 self.writeline(val + ', ')
Armin Ronachere791c2a2008-04-07 18:39:54 +02001090 else:
Armin Ronacherfa865fb2008-04-12 22:11:53 +02001091 if frame.buffer is None:
Armin Ronachered1e0d42008-05-18 20:25:28 +02001092 self.writeline('yield ', item)
Armin Ronacher1f627ff2008-05-15 13:23:26 +02001093 else:
1094 self.newline(item)
Armin Ronacherd1342312008-04-28 12:20:12 +02001095 close = 1
1096 if self.environment.autoescape:
1097 self.write('escape(')
1098 else:
1099 self.write('unicode(')
1100 if self.environment.finalize is not None:
1101 self.write('environment.finalize(')
1102 close += 1
Armin Ronachere791c2a2008-04-07 18:39:54 +02001103 self.visit(item, frame)
Armin Ronacherd1342312008-04-28 12:20:12 +02001104 self.write(')' * close)
Armin Ronacher32a910f2008-04-26 23:21:03 +02001105 if frame.buffer is not None:
1106 self.write(', ')
1107 if frame.buffer is not None:
Armin Ronacher1e1e8902008-05-11 23:21:16 +02001108 # close the open parentheses
Armin Ronacher1f627ff2008-05-15 13:23:26 +02001109 self.outdent()
1110 self.writeline(len(body) == 1 and ')' or '))')
Armin Ronachere791c2a2008-04-07 18:39:54 +02001111
1112 # otherwise we create a format string as this is faster in that case
1113 else:
1114 format = []
1115 arguments = []
1116 for item in body:
1117 if isinstance(item, list):
Armin Ronacherde6bf712008-04-26 01:44:14 +02001118 format.append(concat(item).replace('%', '%%'))
Armin Ronachere791c2a2008-04-07 18:39:54 +02001119 else:
1120 format.append('%s')
1121 arguments.append(item)
Armin Ronachered1e0d42008-05-18 20:25:28 +02001122 self.writeline('yield ')
Armin Ronacherde6bf712008-04-26 01:44:14 +02001123 self.write(repr(concat(format)) + ' % (')
Armin Ronachere791c2a2008-04-07 18:39:54 +02001124 idx = -1
Armin Ronachera7f016d2008-05-16 00:22:40 +02001125 self.indent()
Armin Ronacher8e8d0712008-04-16 23:10:49 +02001126 for argument in arguments:
Armin Ronachered1e0d42008-05-18 20:25:28 +02001127 self.newline(argument)
Armin Ronacherd1342312008-04-28 12:20:12 +02001128 close = 0
1129 if self.environment.autoescape:
1130 self.write('escape(')
1131 close += 1
1132 if self.environment.finalize is not None:
1133 self.write('environment.finalize(')
1134 close += 1
Armin Ronachere791c2a2008-04-07 18:39:54 +02001135 self.visit(argument, frame)
Armin Ronacher1f627ff2008-05-15 13:23:26 +02001136 self.write(')' * close + ', ')
Armin Ronachera7f016d2008-05-16 00:22:40 +02001137 self.outdent()
1138 self.writeline(')')
Armin Ronachere791c2a2008-04-07 18:39:54 +02001139
Armin Ronacher7fb38972008-04-11 13:54:28 +02001140 if outdent_later:
Armin Ronacher75cfb862008-04-11 13:47:22 +02001141 self.outdent()
1142
Armin Ronacher8efc5222008-04-08 14:47:40 +02001143 def visit_Assign(self, node, frame):
1144 self.newline(node)
1145 # toplevel assignments however go into the local namespace and
1146 # the current template's context. We create a copy of the frame
1147 # here and add a set so that the Name visitor can add the assigned
1148 # names here.
1149 if frame.toplevel:
1150 assignment_frame = frame.copy()
1151 assignment_frame.assigned_names = set()
1152 else:
1153 assignment_frame = frame
1154 self.visit(node.target, assignment_frame)
1155 self.write(' = ')
1156 self.visit(node.node, frame)
Armin Ronacher9706fab2008-04-08 18:49:56 +02001157
1158 # make sure toplevel assignments are added to the context.
Armin Ronacher8efc5222008-04-08 14:47:40 +02001159 if frame.toplevel:
Armin Ronacher69e12db2008-05-12 09:00:03 +02001160 public_names = [x for x in assignment_frame.assigned_names
Armin Ronacher903d1682008-05-23 00:51:58 +02001161 if not x.startswith('_')]
Armin Ronacher69e12db2008-05-12 09:00:03 +02001162 if len(assignment_frame.assigned_names) == 1:
1163 name = iter(assignment_frame.assigned_names).next()
Armin Ronacherd1ff8582008-05-11 00:30:43 +02001164 self.writeline('context.vars[%r] = l_%s' % (name, name))
Armin Ronacher69e12db2008-05-12 09:00:03 +02001165 else:
1166 self.writeline('context.vars.update({')
1167 for idx, name in enumerate(assignment_frame.assigned_names):
1168 if idx:
1169 self.write(', ')
1170 self.write('%r: l_%s' % (name, name))
1171 self.write('})')
1172 if public_names:
1173 if len(public_names) == 1:
1174 self.writeline('context.exported_vars.add(%r)' %
1175 public_names[0])
1176 else:
1177 self.writeline('context.exported_vars.update((%s))' %
1178 ', '.join(map(repr, public_names)))
Armin Ronacher8efc5222008-04-08 14:47:40 +02001179
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001180 # -- Expression Visitors
1181
Armin Ronachere791c2a2008-04-07 18:39:54 +02001182 def visit_Name(self, node, frame):
Armin Ronacherc9705c22008-04-27 21:28:03 +02001183 if node.ctx == 'store' and frame.toplevel:
1184 frame.assigned_names.add(node.name)
Armin Ronacherd1ff8582008-05-11 00:30:43 +02001185 self.write('l_' + node.name)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001186
1187 def visit_Const(self, node, frame):
1188 val = node.value
1189 if isinstance(val, float):
Armin Ronachere791c2a2008-04-07 18:39:54 +02001190 self.write(str(val))
1191 else:
1192 self.write(repr(val))
1193
Armin Ronacher5411ce72008-05-25 11:36:22 +02001194 def visit_TemplateData(self, node, frame):
1195 self.write(repr(node.as_const()))
1196
Armin Ronacher8efc5222008-04-08 14:47:40 +02001197 def visit_Tuple(self, node, frame):
1198 self.write('(')
1199 idx = -1
1200 for idx, item in enumerate(node.items):
1201 if idx:
1202 self.write(', ')
1203 self.visit(item, frame)
1204 self.write(idx == 0 and ',)' or ')')
1205
Armin Ronacher8edbe492008-04-10 20:43:43 +02001206 def visit_List(self, node, frame):
1207 self.write('[')
1208 for idx, item in enumerate(node.items):
1209 if idx:
1210 self.write(', ')
1211 self.visit(item, frame)
1212 self.write(']')
1213
1214 def visit_Dict(self, node, frame):
1215 self.write('{')
1216 for idx, item in enumerate(node.items):
1217 if idx:
1218 self.write(', ')
1219 self.visit(item.key, frame)
1220 self.write(': ')
1221 self.visit(item.value, frame)
1222 self.write('}')
1223
Armin Ronachere791c2a2008-04-07 18:39:54 +02001224 def binop(operator):
1225 def visitor(self, node, frame):
1226 self.write('(')
1227 self.visit(node.left, frame)
1228 self.write(' %s ' % operator)
1229 self.visit(node.right, frame)
1230 self.write(')')
1231 return visitor
1232
1233 def uaop(operator):
1234 def visitor(self, node, frame):
1235 self.write('(' + operator)
Armin Ronacher9a822052008-04-17 18:44:07 +02001236 self.visit(node.node, frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001237 self.write(')')
1238 return visitor
1239
1240 visit_Add = binop('+')
1241 visit_Sub = binop('-')
1242 visit_Mul = binop('*')
1243 visit_Div = binop('/')
1244 visit_FloorDiv = binop('//')
1245 visit_Pow = binop('**')
1246 visit_Mod = binop('%')
1247 visit_And = binop('and')
1248 visit_Or = binop('or')
1249 visit_Pos = uaop('+')
1250 visit_Neg = uaop('-')
1251 visit_Not = uaop('not ')
1252 del binop, uaop
1253
Armin Ronacherd1342312008-04-28 12:20:12 +02001254 def visit_Concat(self, node, frame):
Armin Ronacherfdf95302008-05-11 22:20:51 +02001255 self.write('%s((' % (self.environment.autoescape and
1256 'markup_join' or 'unicode_join'))
Armin Ronacherd1342312008-04-28 12:20:12 +02001257 for arg in node.nodes:
1258 self.visit(arg, frame)
1259 self.write(', ')
1260 self.write('))')
1261
Armin Ronachere791c2a2008-04-07 18:39:54 +02001262 def visit_Compare(self, node, frame):
1263 self.visit(node.expr, frame)
1264 for op in node.ops:
1265 self.visit(op, frame)
1266
1267 def visit_Operand(self, node, frame):
1268 self.write(' %s ' % operators[node.op])
1269 self.visit(node.expr, frame)
1270
Armin Ronacher6dc6f292008-06-12 08:50:07 +02001271 def visit_Getattr(self, node, frame):
1272 self.write('environment.getattr(')
1273 self.visit(node.node, frame)
1274 self.write(', %r)' % node.attr)
1275
1276 def visit_Getitem(self, node, frame):
Armin Ronacher08a6a3b2008-05-13 15:35:47 +02001277 # slices or integer subscriptions bypass the subscribe
1278 # method if we can determine that at compile time.
1279 if isinstance(node.arg, nodes.Slice) or \
1280 (isinstance(node.arg, nodes.Const) and
1281 isinstance(node.arg.value, (int, long))):
Armin Ronacher8efc5222008-04-08 14:47:40 +02001282 self.visit(node.node, frame)
1283 self.write('[')
1284 self.visit(node.arg, frame)
1285 self.write(']')
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001286 else:
Armin Ronacher6dc6f292008-06-12 08:50:07 +02001287 self.write('environment.getitem(')
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001288 self.visit(node.node, frame)
1289 self.write(', ')
1290 self.visit(node.arg, frame)
1291 self.write(')')
Armin Ronacher8efc5222008-04-08 14:47:40 +02001292
1293 def visit_Slice(self, node, frame):
1294 if node.start is not None:
1295 self.visit(node.start, frame)
1296 self.write(':')
1297 if node.stop is not None:
1298 self.visit(node.stop, frame)
1299 if node.step is not None:
1300 self.write(':')
1301 self.visit(node.step, frame)
1302
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001303 def visit_Filter(self, node, frame):
Armin Ronacherb9e78752008-05-10 23:36:28 +02001304 self.write(self.filters[node.name] + '(')
Christoph Hack80909862008-04-14 01:35:10 +02001305 func = self.environment.filters.get(node.name)
Armin Ronacher0611e492008-04-25 23:44:14 +02001306 if func is None:
Armin Ronachere2244882008-05-19 09:25:57 +02001307 self.fail('no filter named %r' % node.name, node.lineno)
Christoph Hack80909862008-04-14 01:35:10 +02001308 if getattr(func, 'contextfilter', False):
1309 self.write('context, ')
Armin Ronacher9a027f42008-04-17 11:13:40 +02001310 elif getattr(func, 'environmentfilter', False):
1311 self.write('environment, ')
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001312
1313 # if the filter node is None we are inside a filter block
1314 # and want to write to the current buffer
Armin Ronacher3da90312008-05-23 16:37:28 +02001315 if node.node is not None:
Armin Ronacherfa865fb2008-04-12 22:11:53 +02001316 self.visit(node.node, frame)
Armin Ronacher3da90312008-05-23 16:37:28 +02001317 elif self.environment.autoescape:
1318 self.write('Markup(concat(%s))' % frame.buffer)
1319 else:
1320 self.write('concat(%s)' % frame.buffer)
Armin Ronacherd55ab532008-04-09 16:13:39 +02001321 self.signature(node, frame)
1322 self.write(')')
Armin Ronacher8efc5222008-04-08 14:47:40 +02001323
1324 def visit_Test(self, node, frame):
Armin Ronacherb9e78752008-05-10 23:36:28 +02001325 self.write(self.tests[node.name] + '(')
Armin Ronacher0611e492008-04-25 23:44:14 +02001326 if node.name not in self.environment.tests:
Armin Ronachere2244882008-05-19 09:25:57 +02001327 self.fail('no test named %r' % node.name, node.lineno)
Armin Ronacher8efc5222008-04-08 14:47:40 +02001328 self.visit(node.node, frame)
1329 self.signature(node, frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001330 self.write(')')
Armin Ronacher8efc5222008-04-08 14:47:40 +02001331
Armin Ronacher3d8b7842008-04-13 13:16:50 +02001332 def visit_CondExpr(self, node, frame):
1333 if not have_condexpr:
1334 self.write('((')
1335 self.visit(node.test, frame)
1336 self.write(') and (')
1337 self.visit(node.expr1, frame)
1338 self.write(',) or (')
1339 self.visit(node.expr2, frame)
1340 self.write(',))[0]')
1341 else:
1342 self.write('(')
1343 self.visit(node.expr1, frame)
1344 self.write(' if ')
1345 self.visit(node.test, frame)
1346 self.write(' else ')
1347 self.visit(node.expr2, frame)
1348 self.write(')')
1349
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001350 def visit_Call(self, node, frame, forward_caller=False):
Armin Ronacherc63243e2008-04-14 22:53:58 +02001351 if self.environment.sandboxed:
Armin Ronacherfd310492008-05-25 00:16:51 +02001352 self.write('environment.call(context, ')
1353 else:
1354 self.write('context.call(')
Armin Ronacher8efc5222008-04-08 14:47:40 +02001355 self.visit(node.node, frame)
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001356 extra_kwargs = forward_caller and {'caller': 'caller'} or None
Armin Ronacherfd310492008-05-25 00:16:51 +02001357 self.signature(node, frame, extra_kwargs)
Armin Ronacher8efc5222008-04-08 14:47:40 +02001358 self.write(')')
1359
1360 def visit_Keyword(self, node, frame):
Armin Ronacher2e9396b2008-04-16 14:21:57 +02001361 self.write(node.key + '=')
Armin Ronacher8efc5222008-04-08 14:47:40 +02001362 self.visit(node.value, frame)
Armin Ronachered1e0d42008-05-18 20:25:28 +02001363
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001364 # -- Unused nodes for extensions
Armin Ronachered1e0d42008-05-18 20:25:28 +02001365
1366 def visit_MarkSafe(self, node, frame):
1367 self.write('Markup(')
1368 self.visit(node.expr, frame)
1369 self.write(')')
1370
1371 def visit_EnvironmentAttribute(self, node, frame):
1372 self.write('environment.' + node.name)
1373
1374 def visit_ExtensionAttribute(self, node, frame):
Armin Ronacher6df604e2008-05-23 22:18:38 +02001375 self.write('environment.extensions[%r].%s' % (node.identifier, node.name))
Armin Ronachered1e0d42008-05-18 20:25:28 +02001376
1377 def visit_ImportedName(self, node, frame):
1378 self.write(self.import_aliases[node.importname])
1379
1380 def visit_InternalName(self, node, frame):
1381 self.write(node.name)
1382
Armin Ronacher6df604e2008-05-23 22:18:38 +02001383 def visit_ContextReference(self, node, frame):
1384 self.write('context')
1385
Armin Ronachered1e0d42008-05-18 20:25:28 +02001386 def visit_Continue(self, node, frame):
1387 self.writeline('continue', node)
1388
1389 def visit_Break(self, node, frame):
1390 self.writeline('break', node)