blob: e43c3620843c3312eb965492925fb27c9cf50a70 [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 Ronacher71082072008-04-12 14:19:36 +0200441 def signature(self, node, frame, have_comma=True, extra_kwargs=None):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200442 """Writes a function call to the stream for the current node.
443 Per default it will write a leading comma but this can be
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200444 disabled by setting have_comma to False. The extra keyword
445 arguments may not include python keywords otherwise a syntax
446 error could occour. The extra keyword arguments should be given
447 as python dict.
Armin Ronacherfed44b52008-04-13 19:42:53 +0200448 """
Armin Ronacher8efc5222008-04-08 14:47:40 +0200449 have_comma = have_comma and [True] or []
450 def touch_comma():
451 if have_comma:
452 self.write(', ')
453 else:
454 have_comma.append(True)
455
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200456 # if any of the given keyword arguments is a python keyword
457 # we have to make sure that no invalid call is created.
458 kwarg_workaround = False
459 for kwarg in chain((x.key for x in node.kwargs), extra_kwargs or ()):
460 if iskeyword(kwarg):
461 kwarg_workaround = True
462 break
463
Armin Ronacher8efc5222008-04-08 14:47:40 +0200464 for arg in node.args:
465 touch_comma()
466 self.visit(arg, frame)
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200467
468 if not kwarg_workaround:
469 for kwarg in node.kwargs:
470 touch_comma()
471 self.visit(kwarg, frame)
472 if extra_kwargs is not None:
473 for key, value in extra_kwargs.iteritems():
474 touch_comma()
475 self.write('%s=%s' % (key, value))
Armin Ronacher8efc5222008-04-08 14:47:40 +0200476 if node.dyn_args:
477 touch_comma()
Armin Ronacher71082072008-04-12 14:19:36 +0200478 self.write('*')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200479 self.visit(node.dyn_args, frame)
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200480
481 if kwarg_workaround:
482 touch_comma()
483 if node.dyn_kwargs is not None:
484 self.write('**dict({')
485 else:
486 self.write('**{')
487 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 Ronacher8efc5222008-04-08 14:47:40 +0200502 touch_comma()
Armin Ronacher71082072008-04-12 14:19:36 +0200503 self.write('**')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200504 self.visit(node.dyn_kwargs, frame)
505
Armin Ronacherc9705c22008-04-27 21:28:03 +0200506 def pull_locals(self, frame):
507 """Pull all the references identifiers into the local scope."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200508 for name in frame.identifiers.undeclared:
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200509 self.writeline('l_%s = context.resolve(%r)' % (name, name))
Armin Ronacherc9705c22008-04-27 21:28:03 +0200510
511 def pull_dependencies(self, nodes):
512 """Pull all the dependencies."""
513 visitor = DependencyFinderVisitor()
514 for node in nodes:
515 visitor.visit(node)
Armin Ronacherb9e78752008-05-10 23:36:28 +0200516 for dependency in 'filters', 'tests':
517 mapping = getattr(self, dependency)
518 for name in getattr(visitor, dependency):
519 if name not in mapping:
520 mapping[name] = self.temporary_identifier()
521 self.writeline('%s = environment.%s[%r]' %
522 (mapping[name], dependency, name))
Armin Ronachere791c2a2008-04-07 18:39:54 +0200523
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200524 def collect_shadowed(self, frame):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200525 """This function returns all the shadowed variables in a dict
526 in the form name: alias and will write the required assignments
527 into the current scope. No indentation takes place.
528 """
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200529 aliases = {}
530 for name in frame.identifiers.find_shadowed():
531 aliases[name] = ident = self.temporary_identifier()
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200532 self.writeline('%s = l_%s' % (ident, name))
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200533 return aliases
534
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200535 def restore_shadowed(self, aliases):
536 """Restore all aliases."""
537 for name, alias in aliases.iteritems():
538 self.writeline('l_%s = %s' % (name, alias))
539
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200540 def function_scoping(self, node, frame, children=None,
541 find_special=True):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200542 """In Jinja a few statements require the help of anonymous
543 functions. Those are currently macros and call blocks and in
544 the future also recursive loops. As there is currently
545 technical limitation that doesn't allow reading and writing a
546 variable in a scope where the initial value is coming from an
547 outer scope, this function tries to fall back with a common
548 error message. Additionally the frame passed is modified so
549 that the argumetns are collected and callers are looked up.
550
551 This will return the modified frame.
552 """
Armin Ronacherc9705c22008-04-27 21:28:03 +0200553 # we have to iterate twice over it, make sure that works
554 if children is None:
555 children = node.iter_child_nodes()
556 children = list(children)
Armin Ronacher71082072008-04-12 14:19:36 +0200557 func_frame = frame.inner()
Armin Ronacherc9705c22008-04-27 21:28:03 +0200558 func_frame.inspect(children, hard_scope=True)
Armin Ronacher71082072008-04-12 14:19:36 +0200559
560 # variables that are undeclared (accessed before declaration) and
561 # declared locally *and* part of an outside scope raise a template
562 # assertion error. Reason: we can't generate reasonable code from
563 # it without aliasing all the variables. XXX: alias them ^^
564 overriden_closure_vars = (
565 func_frame.identifiers.undeclared &
566 func_frame.identifiers.declared &
567 (func_frame.identifiers.declared_locally |
568 func_frame.identifiers.declared_parameter)
569 )
570 if overriden_closure_vars:
Armin Ronachere2244882008-05-19 09:25:57 +0200571 self.fail('It\'s not possible to set and access variables '
572 'derived from an outer scope! (affects: %s' %
573 ', '.join(sorted(overriden_closure_vars)), node.lineno)
Armin Ronacher71082072008-04-12 14:19:36 +0200574
575 # remove variables from a closure from the frame's undeclared
576 # identifiers.
577 func_frame.identifiers.undeclared -= (
578 func_frame.identifiers.undeclared &
579 func_frame.identifiers.declared
580 )
581
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200582 # no special variables for this scope, abort early
583 if not find_special:
584 return func_frame
585
Armin Ronacher963f97d2008-04-25 11:44:59 +0200586 func_frame.accesses_kwargs = False
587 func_frame.accesses_varargs = False
Armin Ronacher71082072008-04-12 14:19:36 +0200588 func_frame.accesses_caller = False
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200589 func_frame.arguments = args = ['l_' + x.name for x in node.args]
Armin Ronacher71082072008-04-12 14:19:36 +0200590
Armin Ronacherc9705c22008-04-27 21:28:03 +0200591 undeclared = find_undeclared(children, ('caller', 'kwargs', 'varargs'))
592
593 if 'caller' in undeclared:
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200594 func_frame.accesses_caller = True
595 func_frame.identifiers.add_special('caller')
596 args.append('l_caller')
Armin Ronacherc9705c22008-04-27 21:28:03 +0200597 if 'kwargs' in undeclared:
Armin Ronacher963f97d2008-04-25 11:44:59 +0200598 func_frame.accesses_kwargs = True
599 func_frame.identifiers.add_special('kwargs')
600 args.append('l_kwargs')
Armin Ronacherc9705c22008-04-27 21:28:03 +0200601 if 'varargs' in undeclared:
Armin Ronacher963f97d2008-04-25 11:44:59 +0200602 func_frame.accesses_varargs = True
603 func_frame.identifiers.add_special('varargs')
604 args.append('l_varargs')
Armin Ronacher71082072008-04-12 14:19:36 +0200605 return func_frame
606
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200607 def macro_body(self, node, frame, children=None):
608 """Dump the function def of a macro or call block."""
609 frame = self.function_scoping(node, frame, children)
610 args = frame.arguments
611 self.writeline('def macro(%s):' % ', '.join(args), node)
612 self.indent()
613 self.buffer(frame)
614 self.pull_locals(frame)
615 self.blockvisit(node.body, frame)
616 self.return_buffer_contents(frame)
617 self.outdent()
618 return frame
619
620 def macro_def(self, node, frame):
621 """Dump the macro definition for the def created by macro_body."""
622 arg_tuple = ', '.join(repr(x.name) for x in node.args)
623 name = getattr(node, 'name', None)
624 if len(node.args) == 1:
625 arg_tuple += ','
626 self.write('Macro(environment, macro, %r, (%s), (' %
627 (name, arg_tuple))
628 for arg in node.defaults:
629 self.visit(arg, frame)
630 self.write(', ')
Armin Ronacher903d1682008-05-23 00:51:58 +0200631 self.write('), %r, %r, %r)' % (
632 bool(frame.accesses_kwargs),
633 bool(frame.accesses_varargs),
634 bool(frame.accesses_caller)
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200635 ))
636
637 # -- Statement Visitors
Armin Ronachere791c2a2008-04-07 18:39:54 +0200638
639 def visit_Template(self, node, frame=None):
640 assert frame is None, 'no root frame allowed'
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200641 from jinja2.runtime import __all__ as exported
Armin Ronacher709f6e52008-04-28 18:18:16 +0200642 self.writeline('from __future__ import division')
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200643 self.writeline('from jinja2.runtime import ' + ', '.join(exported))
Armin Ronacher8edbe492008-04-10 20:43:43 +0200644
Armin Ronacher75cfb862008-04-11 13:47:22 +0200645 # do we have an extends tag at all? If not, we can save some
646 # overhead by just not processing any inheritance code.
647 have_extends = node.find(nodes.Extends) is not None
648
Armin Ronacher8edbe492008-04-10 20:43:43 +0200649 # find all blocks
650 for block in node.find_all(nodes.Block):
651 if block.name in self.blocks:
Armin Ronachere2244882008-05-19 09:25:57 +0200652 self.fail('block %r defined twice' % block.name, block.lineno)
Armin Ronacher8edbe492008-04-10 20:43:43 +0200653 self.blocks[block.name] = block
Armin Ronachere791c2a2008-04-07 18:39:54 +0200654
Armin Ronacher023b5e92008-05-08 11:03:10 +0200655 # find all imports and import them
656 for import_ in node.find_all(nodes.ImportedName):
657 if import_.importname not in self.import_aliases:
658 imp = import_.importname
659 self.import_aliases[imp] = alias = self.temporary_identifier()
660 if '.' in imp:
661 module, obj = imp.rsplit('.', 1)
662 self.writeline('from %s import %s as %s' %
663 (module, obj, alias))
664 else:
665 self.writeline('import %s as %s' % (imp, alias))
666
667 # add the load name
Armin Ronacherdc02b642008-05-15 22:47:27 +0200668 self.writeline('name = %r' % self.name)
Armin Ronacher023b5e92008-05-08 11:03:10 +0200669
Armin Ronacher8efc5222008-04-08 14:47:40 +0200670 # generate the root render function.
Armin Ronacher32a910f2008-04-26 23:21:03 +0200671 self.writeline('def root(context, environment=environment):', extra=1)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200672
673 # process the root
Armin Ronachere791c2a2008-04-07 18:39:54 +0200674 frame = Frame()
Armin Ronacherc9705c22008-04-27 21:28:03 +0200675 frame.inspect(node.body)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200676 frame.toplevel = frame.rootlevel = True
Armin Ronacherf059ec12008-04-11 22:21:00 +0200677 self.indent()
Armin Ronacherc9705c22008-04-27 21:28:03 +0200678 if have_extends:
679 self.writeline('parent_template = None')
Armin Ronacherc9705c22008-04-27 21:28:03 +0200680 if 'self' in find_undeclared(node.body, ('self',)):
681 frame.identifiers.add_special('self')
682 self.writeline('l_self = TemplateReference(context)')
Armin Ronacher6df604e2008-05-23 22:18:38 +0200683 self.pull_locals(frame)
684 self.pull_dependencies(node.body)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200685 self.blockvisit(node.body, frame)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200686 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200687
Armin Ronacher8efc5222008-04-08 14:47:40 +0200688 # make sure that the parent root is called.
Armin Ronacher75cfb862008-04-11 13:47:22 +0200689 if have_extends:
690 if not self.has_known_extends:
691 self.indent()
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200692 self.writeline('if parent_template is not None:')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200693 self.indent()
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200694 self.writeline('for event in parent_template.'
Armin Ronacher771c7502008-05-18 23:14:14 +0200695 '_root_render_func(context):')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200696 self.indent()
697 self.writeline('yield event')
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200698 self.outdent(2 + (not self.has_known_extends))
Armin Ronachere791c2a2008-04-07 18:39:54 +0200699
700 # at this point we now have the blocks collected and can visit them too.
701 for name, block in self.blocks.iteritems():
702 block_frame = Frame()
Armin Ronacherc9705c22008-04-27 21:28:03 +0200703 block_frame.inspect(block.body)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200704 block_frame.block = name
Armin Ronacherd4c64f72008-04-11 17:15:29 +0200705 self.writeline('def block_%s(context, environment=environment):'
706 % name, block, 1)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200707 self.indent()
708 undeclared = find_undeclared(block.body, ('self', 'super'))
709 if 'self' in undeclared:
710 block_frame.identifiers.add_special('self')
711 self.writeline('l_self = TemplateReference(context)')
712 if 'super' in undeclared:
713 block_frame.identifiers.add_special('super')
714 self.writeline('l_super = context.super(%r, '
715 'block_%s)' % (name, name))
Armin Ronachere791c2a2008-04-07 18:39:54 +0200716 self.pull_locals(block_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200717 self.pull_dependencies(block.body)
Armin Ronacher625215e2008-04-13 16:31:08 +0200718 self.blockvisit(block.body, block_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200719 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200720
Armin Ronacher75cfb862008-04-11 13:47:22 +0200721 self.writeline('blocks = {%s}' % ', '.join('%r: block_%s' % (x, x)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200722 for x in self.blocks),
723 extra=1)
724
725 # add a function that returns the debug info
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200726 self.writeline('debug_info = %r' % '&'.join('%s=%s' % x for x
727 in self.debug_info))
Armin Ronacher75cfb862008-04-11 13:47:22 +0200728
Armin Ronachere791c2a2008-04-07 18:39:54 +0200729 def visit_Block(self, node, frame):
730 """Call a block and register it for the template."""
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200731 level = 1
Armin Ronacher75cfb862008-04-11 13:47:22 +0200732 if frame.toplevel:
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200733 # if we know that we are a child template, there is no need to
734 # check if we are one
735 if self.has_known_extends:
736 return
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200737 if self.extends_so_far > 0:
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200738 self.writeline('if parent_template is None:')
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200739 self.indent()
740 level += 1
Armin Ronacher83fbc0f2008-05-15 12:22:28 +0200741 self.writeline('for event in context.blocks[%r][0](context):' %
Armin Ronacherc9705c22008-04-27 21:28:03 +0200742 node.name, node)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200743 self.indent()
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200744 self.simple_write('event', frame)
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200745 self.outdent(level)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200746
747 def visit_Extends(self, node, frame):
748 """Calls the extender."""
Armin Ronacher8efc5222008-04-08 14:47:40 +0200749 if not frame.toplevel:
Armin Ronachere2244882008-05-19 09:25:57 +0200750 self.fail('cannot use extend from a non top-level scope',
751 node.lineno)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200752
Armin Ronacher7fb38972008-04-11 13:54:28 +0200753 # if the number of extends statements in general is zero so
754 # far, we don't have to add a check if something extended
755 # the template before this one.
756 if self.extends_so_far > 0:
Armin Ronacher75cfb862008-04-11 13:47:22 +0200757
Armin Ronacher7fb38972008-04-11 13:54:28 +0200758 # if we have a known extends we just add a template runtime
759 # error into the generated code. We could catch that at compile
760 # time too, but i welcome it not to confuse users by throwing the
761 # same error at different times just "because we can".
762 if not self.has_known_extends:
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200763 self.writeline('if parent_template is not None:')
Armin Ronacher7fb38972008-04-11 13:54:28 +0200764 self.indent()
765 self.writeline('raise TemplateRuntimeError(%r)' %
766 'extended multiple times')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200767
Armin Ronacher7fb38972008-04-11 13:54:28 +0200768 # if we have a known extends already we don't need that code here
769 # as we know that the template execution will end here.
770 if self.has_known_extends:
771 raise CompilerExit()
772 self.outdent()
773
Armin Ronacher9d42abf2008-05-14 18:10:41 +0200774 self.writeline('parent_template = environment.get_template(', node)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200775 self.visit(node.template, frame)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200776 self.write(', %r)' % self.name)
777 self.writeline('for name, parent_block in parent_template.'
778 'blocks.iteritems():')
779 self.indent()
780 self.writeline('context.blocks.setdefault(name, []).'
Armin Ronacher83fbc0f2008-05-15 12:22:28 +0200781 'append(parent_block)')
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200782 self.outdent()
Armin Ronacher75cfb862008-04-11 13:47:22 +0200783
784 # if this extends statement was in the root level we can take
785 # advantage of that information and simplify the generated code
786 # in the top level from this point onwards
Armin Ronacher27069d72008-05-11 19:48:12 +0200787 if frame.rootlevel:
788 self.has_known_extends = True
Armin Ronachere791c2a2008-04-07 18:39:54 +0200789
Armin Ronacher7fb38972008-04-11 13:54:28 +0200790 # and now we have one more
791 self.extends_so_far += 1
792
Armin Ronacherf059ec12008-04-11 22:21:00 +0200793 def visit_Include(self, node, frame):
794 """Handles includes."""
Armin Ronacherea847c52008-05-02 20:04:32 +0200795 if node.with_context:
796 self.writeline('template = environment.get_template(', node)
797 self.visit(node.template, frame)
798 self.write(', %r)' % self.name)
Armin Ronacher771c7502008-05-18 23:14:14 +0200799 self.writeline('for event in template._root_render_func('
Armin Ronacherea847c52008-05-02 20:04:32 +0200800 'template.new_context(context.parent, True)):')
801 else:
802 self.writeline('for event in environment.get_template(', node)
803 self.visit(node.template, frame)
Armin Ronacher771c7502008-05-18 23:14:14 +0200804 self.write(', %r).module._body_stream:' %
Armin Ronacherea847c52008-05-02 20:04:32 +0200805 self.name)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200806 self.indent()
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200807 self.simple_write('event', frame)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200808 self.outdent()
809
Armin Ronacher0611e492008-04-25 23:44:14 +0200810 def visit_Import(self, node, frame):
811 """Visit regular imports."""
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200812 self.writeline('l_%s = ' % node.target, node)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200813 if frame.toplevel:
Armin Ronacher53042292008-04-26 18:30:19 +0200814 self.write('context.vars[%r] = ' % node.target)
Armin Ronacher0611e492008-04-25 23:44:14 +0200815 self.write('environment.get_template(')
816 self.visit(node.template, frame)
Armin Ronacherea847c52008-05-02 20:04:32 +0200817 self.write(', %r).' % self.name)
818 if node.with_context:
819 self.write('make_module(context.parent, True)')
820 else:
821 self.write('module')
Armin Ronacher903d1682008-05-23 00:51:58 +0200822 if frame.toplevel and not node.target.startswith('_'):
Armin Ronacher53042292008-04-26 18:30:19 +0200823 self.writeline('context.exported_vars.discard(%r)' % node.target)
Armin Ronacher0611e492008-04-25 23:44:14 +0200824
825 def visit_FromImport(self, node, frame):
826 """Visit named imports."""
827 self.newline(node)
828 self.write('included_template = environment.get_template(')
829 self.visit(node.template, frame)
Armin Ronacherea847c52008-05-02 20:04:32 +0200830 self.write(', %r).' % self.name)
831 if node.with_context:
832 self.write('make_module(context.parent, True)')
833 else:
834 self.write('module')
Armin Ronachera78d2762008-05-15 23:18:07 +0200835
836 var_names = []
837 discarded_names = []
Armin Ronacher0611e492008-04-25 23:44:14 +0200838 for name in node.names:
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200839 if isinstance(name, tuple):
840 name, alias = name
841 else:
842 alias = name
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200843 self.writeline('l_%s = getattr(included_template, '
844 '%r, missing)' % (alias, name))
845 self.writeline('if l_%s is missing:' % alias)
Armin Ronacher0611e492008-04-25 23:44:14 +0200846 self.indent()
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200847 self.writeline('l_%s = environment.undefined(%r %% '
Armin Ronacherdc02b642008-05-15 22:47:27 +0200848 'included_template.__name__, '
Armin Ronacher0a2ac692008-05-13 01:03:08 +0200849 'name=%r)' %
Armin Ronacherd1ff8582008-05-11 00:30:43 +0200850 (alias, 'the template %r does not export '
Armin Ronacher0a2ac692008-05-13 01:03:08 +0200851 'the requested name ' + repr(name), name))
Armin Ronacher0611e492008-04-25 23:44:14 +0200852 self.outdent()
853 if frame.toplevel:
Armin Ronachera78d2762008-05-15 23:18:07 +0200854 var_names.append(alias)
Armin Ronacher903d1682008-05-23 00:51:58 +0200855 if not alias.startswith('_'):
Armin Ronachera78d2762008-05-15 23:18:07 +0200856 discarded_names.append(alias)
857
858 if var_names:
859 if len(var_names) == 1:
860 name = var_names[0]
861 self.writeline('context.vars[%r] = l_%s' % (name, name))
862 else:
863 self.writeline('context.vars.update({%s})' % ', '.join(
864 '%r: l_%s' % (name, name) for name in var_names
865 ))
866 if discarded_names:
867 if len(discarded_names) == 1:
868 self.writeline('context.exported_vars.discard(%r)' %
869 discarded_names[0])
870 else:
871 self.writeline('context.exported_vars.difference_'
872 'update((%s))' % ', '.join(map(repr, discarded_names)))
Armin Ronacherf059ec12008-04-11 22:21:00 +0200873
Armin Ronachere791c2a2008-04-07 18:39:54 +0200874 def visit_For(self, node, frame):
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200875 # when calculating the nodes for the inner frame we have to exclude
876 # the iterator contents from it
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200877 children = node.iter_child_nodes(exclude=('iter',))
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200878 if node.recursive:
879 loop_frame = self.function_scoping(node, frame, children,
880 find_special=False)
881 else:
882 loop_frame = frame.inner()
883 loop_frame.inspect(children)
884
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200885 # try to figure out if we have an extended loop. An extended loop
886 # is necessary if the loop is in recursive mode if the special loop
887 # variable is accessed in the body.
888 extended_loop = node.recursive or 'loop' in \
889 find_undeclared(node.iter_child_nodes(
890 only=('body',)), ('loop',))
891
892 # make sure the loop variable is a special one and raise a template
893 # assertion error if a loop tries to write to loop
894 loop_frame.identifiers.add_special('loop')
895 for name in node.find_all(nodes.Name):
896 if name.ctx == 'store' and name.name == 'loop':
897 self.fail('Can\'t assign to special loop variable '
898 'in for-loop target', name.lineno)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200899
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200900 # if we don't have an recursive loop we have to find the shadowed
901 # variables at that point
902 if not node.recursive:
903 aliases = self.collect_shadowed(loop_frame)
904
905 # otherwise we set up a buffer and add a function def
906 else:
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200907 self.writeline('def loop(reciter, loop_render_func):', node)
908 self.indent()
Armin Ronachered1e0d42008-05-18 20:25:28 +0200909 self.buffer(loop_frame)
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200910 aliases = {}
911
Armin Ronacherc9705c22008-04-27 21:28:03 +0200912 self.pull_locals(loop_frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200913 if node.else_:
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200914 iteration_indicator = self.temporary_identifier()
915 self.writeline('%s = 1' % iteration_indicator)
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200916
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200917 # Create a fake parent loop if the else or test section of a
918 # loop is accessing the special loop variable and no parent loop
919 # exists.
920 if 'loop' not in aliases and 'loop' in find_undeclared(
921 node.iter_child_nodes(only=('else_', 'test')), ('loop',)):
922 self.writeline("l_loop = environment.undefined(%r, name='loop')" %
923 "'loop' is undefined. the filter section of a loop as well " \
924 "as the else block doesn't have access to the special 'loop' "
925 "variable of the current loop. Because there is no parent "
926 "loop it's undefined.")
927
928 self.writeline('for ', node)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200929 self.visit(node.target, loop_frame)
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200930 self.write(extended_loop and ', l_loop in LoopContext(' or ' in ')
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200931
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200932 # if we have an extened loop and a node test, we filter in the
933 # "outer frame".
934 if extended_loop and node.test is not None:
935 self.write('(')
936 self.visit(node.target, loop_frame)
937 self.write(' for ')
938 self.visit(node.target, loop_frame)
939 self.write(' in ')
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200940 if node.recursive:
941 self.write('reciter')
942 else:
943 self.visit(node.iter, loop_frame)
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200944 self.write(' if (')
945 test_frame = loop_frame.copy()
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200946 self.visit(node.test, test_frame)
947 self.write('))')
948
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200949 elif node.recursive:
950 self.write('reciter')
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200951 else:
952 self.visit(node.iter, loop_frame)
953
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200954 if node.recursive:
955 self.write(', recurse=loop_render_func):')
956 else:
957 self.write(extended_loop and '):' or ':')
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200958
959 # tests in not extended loops become a continue
960 if not extended_loop and node.test is not None:
961 self.indent()
Armin Ronacher47a506f2008-05-06 12:17:23 +0200962 self.writeline('if not ')
Armin Ronacher32a910f2008-04-26 23:21:03 +0200963 self.visit(node.test, loop_frame)
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200964 self.write(':')
965 self.indent()
966 self.writeline('continue')
967 self.outdent(2)
968
Armin Ronacherc9705c22008-04-27 21:28:03 +0200969 self.indent()
Armin Ronacherbe4ae242008-04-18 09:49:08 +0200970 self.blockvisit(node.body, loop_frame, force_generator=True)
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200971 if node.else_:
972 self.writeline('%s = 0' % iteration_indicator)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200973 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200974
975 if node.else_:
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200976 self.writeline('if %s:' % iteration_indicator)
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200977 self.indent()
Armin Ronacher625215e2008-04-13 16:31:08 +0200978 self.blockvisit(node.else_, loop_frame, force_generator=False)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200979 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200980
Armin Ronacherd4c64f72008-04-11 17:15:29 +0200981 # reset the aliases if there are any.
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200982 self.restore_shadowed(aliases)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200983
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200984 # if the node was recursive we have to return the buffer contents
985 # and start the iteration code
986 if node.recursive:
Armin Ronachered1e0d42008-05-18 20:25:28 +0200987 self.return_buffer_contents(loop_frame)
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200988 self.outdent()
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200989 self.start_write(frame, node)
990 self.write('loop(')
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200991 self.visit(node.iter, frame)
992 self.write(', loop)')
Armin Ronachera2eb77d2008-05-22 20:28:21 +0200993 self.end_write(frame)
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200994
Armin Ronachere791c2a2008-04-07 18:39:54 +0200995 def visit_If(self, node, frame):
Armin Ronacher75cfb862008-04-11 13:47:22 +0200996 if_frame = frame.soft()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200997 self.writeline('if ', node)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200998 self.visit(node.test, if_frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200999 self.write(':')
Armin Ronacherc9705c22008-04-27 21:28:03 +02001000 self.indent()
Armin Ronacher75cfb862008-04-11 13:47:22 +02001001 self.blockvisit(node.body, if_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +02001002 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +02001003 if node.else_:
1004 self.writeline('else:')
Armin Ronacherc9705c22008-04-27 21:28:03 +02001005 self.indent()
Armin Ronacher75cfb862008-04-11 13:47:22 +02001006 self.blockvisit(node.else_, if_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +02001007 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +02001008
Armin Ronacher8efc5222008-04-08 14:47:40 +02001009 def visit_Macro(self, node, frame):
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001010 macro_frame = self.macro_body(node, frame)
Armin Ronacher8efc5222008-04-08 14:47:40 +02001011 self.newline()
1012 if frame.toplevel:
Armin Ronacher903d1682008-05-23 00:51:58 +02001013 if not node.name.startswith('_'):
Armin Ronacherc9705c22008-04-27 21:28:03 +02001014 self.write('context.exported_vars.add(%r)' % node.name)
Armin Ronacher32a910f2008-04-26 23:21:03 +02001015 self.writeline('context.vars[%r] = ' % node.name)
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001016 self.write('l_%s = ' % node.name)
1017 self.macro_def(node, macro_frame)
Armin Ronacher71082072008-04-12 14:19:36 +02001018
1019 def visit_CallBlock(self, node, frame):
Armin Ronacher3da90312008-05-23 16:37:28 +02001020 children = node.iter_child_nodes(exclude=('call',))
1021 call_frame = self.macro_body(node, frame, children)
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001022 self.writeline('caller = ')
1023 self.macro_def(node, call_frame)
1024 self.start_write(frame, node)
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001025 self.visit_Call(node.call, call_frame, forward_caller=True)
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001026 self.end_write(frame)
Armin Ronacherfa865fb2008-04-12 22:11:53 +02001027
1028 def visit_FilterBlock(self, node, frame):
1029 filter_frame = frame.inner()
1030 filter_frame.inspect(node.iter_child_nodes())
Armin Ronacherfa865fb2008-04-12 22:11:53 +02001031 aliases = self.collect_shadowed(filter_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +02001032 self.pull_locals(filter_frame)
Armin Ronachered1e0d42008-05-18 20:25:28 +02001033 self.buffer(filter_frame)
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001034 self.blockvisit(node.body, filter_frame, force_generator=False)
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001035 self.start_write(frame, node)
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001036 self.visit_Filter(node.filter, filter_frame)
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001037 self.end_write(frame)
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001038 self.restore_shadowed(aliases)
Armin Ronacher8efc5222008-04-08 14:47:40 +02001039
Armin Ronachere791c2a2008-04-07 18:39:54 +02001040 def visit_ExprStmt(self, node, frame):
1041 self.newline(node)
Armin Ronacher6ce170c2008-04-25 12:32:36 +02001042 self.visit(node.node, frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001043
1044 def visit_Output(self, node, frame):
Armin Ronacher75cfb862008-04-11 13:47:22 +02001045 # if we have a known extends statement, we don't output anything
Armin Ronacher7a52df82008-04-11 13:58:22 +02001046 if self.has_known_extends and frame.toplevel:
Armin Ronacher75cfb862008-04-11 13:47:22 +02001047 return
Armin Ronachere791c2a2008-04-07 18:39:54 +02001048
Armin Ronacher75cfb862008-04-11 13:47:22 +02001049 self.newline(node)
Armin Ronacher8edbe492008-04-10 20:43:43 +02001050
Armin Ronacher7fb38972008-04-11 13:54:28 +02001051 # if we are in the toplevel scope and there was already an extends
1052 # statement we have to add a check that disables our yield(s) here
1053 # so that they don't appear in the output.
1054 outdent_later = False
1055 if frame.toplevel and self.extends_so_far != 0:
Armin Ronacher203bfcb2008-04-24 21:54:44 +02001056 self.writeline('if parent_template is None:')
Armin Ronacher75cfb862008-04-11 13:47:22 +02001057 self.indent()
Armin Ronacher7fb38972008-04-11 13:54:28 +02001058 outdent_later = True
Armin Ronacher75cfb862008-04-11 13:47:22 +02001059
Armin Ronachere791c2a2008-04-07 18:39:54 +02001060 # try to evaluate as many chunks as possible into a static
1061 # string at compile time.
1062 body = []
1063 for child in node.nodes:
1064 try:
Armin Ronacher9cf95912008-05-24 19:54:43 +02001065 const = child.as_const()
1066 except nodes.Impossible:
1067 body.append(child)
1068 continue
1069 try:
1070 if self.environment.autoescape:
1071 if hasattr(const, '__html__'):
1072 const = const.__html__()
1073 else:
1074 const = escape(const)
1075 const = unicode(const)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001076 except:
Armin Ronacher9cf95912008-05-24 19:54:43 +02001077 # if something goes wrong here we evaluate the node
1078 # at runtime for easier debugging
Armin Ronachere791c2a2008-04-07 18:39:54 +02001079 body.append(child)
1080 continue
1081 if body and isinstance(body[-1], list):
1082 body[-1].append(const)
1083 else:
1084 body.append([const])
1085
Armin Ronachered1e0d42008-05-18 20:25:28 +02001086 # if we have less than 3 nodes or a buffer we yield or extend/append
1087 if len(body) < 3 or frame.buffer is not None:
Armin Ronacher32a910f2008-04-26 23:21:03 +02001088 if frame.buffer is not None:
Armin Ronacher1e1e8902008-05-11 23:21:16 +02001089 # for one item we append, for more we extend
1090 if len(body) == 1:
1091 self.writeline('%s.append(' % frame.buffer)
1092 else:
1093 self.writeline('%s.extend((' % frame.buffer)
Armin Ronacher1f627ff2008-05-15 13:23:26 +02001094 self.indent()
Armin Ronachere791c2a2008-04-07 18:39:54 +02001095 for item in body:
1096 if isinstance(item, list):
Armin Ronacherde6bf712008-04-26 01:44:14 +02001097 val = repr(concat(item))
Armin Ronacherfa865fb2008-04-12 22:11:53 +02001098 if frame.buffer is None:
1099 self.writeline('yield ' + val)
1100 else:
Armin Ronacher1f627ff2008-05-15 13:23:26 +02001101 self.writeline(val + ', ')
Armin Ronachere791c2a2008-04-07 18:39:54 +02001102 else:
Armin Ronacherfa865fb2008-04-12 22:11:53 +02001103 if frame.buffer is None:
Armin Ronachered1e0d42008-05-18 20:25:28 +02001104 self.writeline('yield ', item)
Armin Ronacher1f627ff2008-05-15 13:23:26 +02001105 else:
1106 self.newline(item)
Armin Ronacherd1342312008-04-28 12:20:12 +02001107 close = 1
1108 if self.environment.autoescape:
1109 self.write('escape(')
1110 else:
1111 self.write('unicode(')
1112 if self.environment.finalize is not None:
1113 self.write('environment.finalize(')
1114 close += 1
Armin Ronachere791c2a2008-04-07 18:39:54 +02001115 self.visit(item, frame)
Armin Ronacherd1342312008-04-28 12:20:12 +02001116 self.write(')' * close)
Armin Ronacher32a910f2008-04-26 23:21:03 +02001117 if frame.buffer is not None:
1118 self.write(', ')
1119 if frame.buffer is not None:
Armin Ronacher1e1e8902008-05-11 23:21:16 +02001120 # close the open parentheses
Armin Ronacher1f627ff2008-05-15 13:23:26 +02001121 self.outdent()
1122 self.writeline(len(body) == 1 and ')' or '))')
Armin Ronachere791c2a2008-04-07 18:39:54 +02001123
1124 # otherwise we create a format string as this is faster in that case
1125 else:
1126 format = []
1127 arguments = []
1128 for item in body:
1129 if isinstance(item, list):
Armin Ronacherde6bf712008-04-26 01:44:14 +02001130 format.append(concat(item).replace('%', '%%'))
Armin Ronachere791c2a2008-04-07 18:39:54 +02001131 else:
1132 format.append('%s')
1133 arguments.append(item)
Armin Ronachered1e0d42008-05-18 20:25:28 +02001134 self.writeline('yield ')
Armin Ronacherde6bf712008-04-26 01:44:14 +02001135 self.write(repr(concat(format)) + ' % (')
Armin Ronachere791c2a2008-04-07 18:39:54 +02001136 idx = -1
Armin Ronachera7f016d2008-05-16 00:22:40 +02001137 self.indent()
Armin Ronacher8e8d0712008-04-16 23:10:49 +02001138 for argument in arguments:
Armin Ronachered1e0d42008-05-18 20:25:28 +02001139 self.newline(argument)
Armin Ronacherd1342312008-04-28 12:20:12 +02001140 close = 0
1141 if self.environment.autoescape:
1142 self.write('escape(')
1143 close += 1
1144 if self.environment.finalize is not None:
1145 self.write('environment.finalize(')
1146 close += 1
Armin Ronachere791c2a2008-04-07 18:39:54 +02001147 self.visit(argument, frame)
Armin Ronacher1f627ff2008-05-15 13:23:26 +02001148 self.write(')' * close + ', ')
Armin Ronachera7f016d2008-05-16 00:22:40 +02001149 self.outdent()
1150 self.writeline(')')
Armin Ronachere791c2a2008-04-07 18:39:54 +02001151
Armin Ronacher7fb38972008-04-11 13:54:28 +02001152 if outdent_later:
Armin Ronacher75cfb862008-04-11 13:47:22 +02001153 self.outdent()
1154
Armin Ronacher8efc5222008-04-08 14:47:40 +02001155 def visit_Assign(self, node, frame):
1156 self.newline(node)
1157 # toplevel assignments however go into the local namespace and
1158 # the current template's context. We create a copy of the frame
1159 # here and add a set so that the Name visitor can add the assigned
1160 # names here.
1161 if frame.toplevel:
1162 assignment_frame = frame.copy()
1163 assignment_frame.assigned_names = set()
1164 else:
1165 assignment_frame = frame
1166 self.visit(node.target, assignment_frame)
1167 self.write(' = ')
1168 self.visit(node.node, frame)
Armin Ronacher9706fab2008-04-08 18:49:56 +02001169
1170 # make sure toplevel assignments are added to the context.
Armin Ronacher8efc5222008-04-08 14:47:40 +02001171 if frame.toplevel:
Armin Ronacher69e12db2008-05-12 09:00:03 +02001172 public_names = [x for x in assignment_frame.assigned_names
Armin Ronacher903d1682008-05-23 00:51:58 +02001173 if not x.startswith('_')]
Armin Ronacher69e12db2008-05-12 09:00:03 +02001174 if len(assignment_frame.assigned_names) == 1:
1175 name = iter(assignment_frame.assigned_names).next()
Armin Ronacherd1ff8582008-05-11 00:30:43 +02001176 self.writeline('context.vars[%r] = l_%s' % (name, name))
Armin Ronacher69e12db2008-05-12 09:00:03 +02001177 else:
1178 self.writeline('context.vars.update({')
1179 for idx, name in enumerate(assignment_frame.assigned_names):
1180 if idx:
1181 self.write(', ')
1182 self.write('%r: l_%s' % (name, name))
1183 self.write('})')
1184 if public_names:
1185 if len(public_names) == 1:
1186 self.writeline('context.exported_vars.add(%r)' %
1187 public_names[0])
1188 else:
1189 self.writeline('context.exported_vars.update((%s))' %
1190 ', '.join(map(repr, public_names)))
Armin Ronacher8efc5222008-04-08 14:47:40 +02001191
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001192 # -- Expression Visitors
1193
Armin Ronachere791c2a2008-04-07 18:39:54 +02001194 def visit_Name(self, node, frame):
Armin Ronacherc9705c22008-04-27 21:28:03 +02001195 if node.ctx == 'store' and frame.toplevel:
1196 frame.assigned_names.add(node.name)
Armin Ronacherd1ff8582008-05-11 00:30:43 +02001197 self.write('l_' + node.name)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001198
1199 def visit_Const(self, node, frame):
1200 val = node.value
1201 if isinstance(val, float):
Armin Ronachere791c2a2008-04-07 18:39:54 +02001202 self.write(str(val))
1203 else:
1204 self.write(repr(val))
1205
Armin Ronacher8efc5222008-04-08 14:47:40 +02001206 def visit_Tuple(self, node, frame):
1207 self.write('(')
1208 idx = -1
1209 for idx, item in enumerate(node.items):
1210 if idx:
1211 self.write(', ')
1212 self.visit(item, frame)
1213 self.write(idx == 0 and ',)' or ')')
1214
Armin Ronacher8edbe492008-04-10 20:43:43 +02001215 def visit_List(self, node, frame):
1216 self.write('[')
1217 for idx, item in enumerate(node.items):
1218 if idx:
1219 self.write(', ')
1220 self.visit(item, frame)
1221 self.write(']')
1222
1223 def visit_Dict(self, node, frame):
1224 self.write('{')
1225 for idx, item in enumerate(node.items):
1226 if idx:
1227 self.write(', ')
1228 self.visit(item.key, frame)
1229 self.write(': ')
1230 self.visit(item.value, frame)
1231 self.write('}')
1232
Armin Ronachere791c2a2008-04-07 18:39:54 +02001233 def binop(operator):
1234 def visitor(self, node, frame):
1235 self.write('(')
1236 self.visit(node.left, frame)
1237 self.write(' %s ' % operator)
1238 self.visit(node.right, frame)
1239 self.write(')')
1240 return visitor
1241
1242 def uaop(operator):
1243 def visitor(self, node, frame):
1244 self.write('(' + operator)
Armin Ronacher9a822052008-04-17 18:44:07 +02001245 self.visit(node.node, frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001246 self.write(')')
1247 return visitor
1248
1249 visit_Add = binop('+')
1250 visit_Sub = binop('-')
1251 visit_Mul = binop('*')
1252 visit_Div = binop('/')
1253 visit_FloorDiv = binop('//')
1254 visit_Pow = binop('**')
1255 visit_Mod = binop('%')
1256 visit_And = binop('and')
1257 visit_Or = binop('or')
1258 visit_Pos = uaop('+')
1259 visit_Neg = uaop('-')
1260 visit_Not = uaop('not ')
1261 del binop, uaop
1262
Armin Ronacherd1342312008-04-28 12:20:12 +02001263 def visit_Concat(self, node, frame):
Armin Ronacherfdf95302008-05-11 22:20:51 +02001264 self.write('%s((' % (self.environment.autoescape and
1265 'markup_join' or 'unicode_join'))
Armin Ronacherd1342312008-04-28 12:20:12 +02001266 for arg in node.nodes:
1267 self.visit(arg, frame)
1268 self.write(', ')
1269 self.write('))')
1270
Armin Ronachere791c2a2008-04-07 18:39:54 +02001271 def visit_Compare(self, node, frame):
1272 self.visit(node.expr, frame)
1273 for op in node.ops:
1274 self.visit(op, frame)
1275
1276 def visit_Operand(self, node, frame):
1277 self.write(' %s ' % operators[node.op])
1278 self.visit(node.expr, frame)
1279
1280 def visit_Subscript(self, node, frame):
Armin Ronacher08a6a3b2008-05-13 15:35:47 +02001281 # slices or integer subscriptions bypass the subscribe
1282 # method if we can determine that at compile time.
1283 if isinstance(node.arg, nodes.Slice) or \
1284 (isinstance(node.arg, nodes.Const) and
1285 isinstance(node.arg.value, (int, long))):
Armin Ronacher8efc5222008-04-08 14:47:40 +02001286 self.visit(node.node, frame)
1287 self.write('[')
1288 self.visit(node.arg, frame)
1289 self.write(']')
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001290 else:
1291 self.write('environment.subscribe(')
1292 self.visit(node.node, frame)
1293 self.write(', ')
1294 self.visit(node.arg, frame)
1295 self.write(')')
Armin Ronacher8efc5222008-04-08 14:47:40 +02001296
1297 def visit_Slice(self, node, frame):
1298 if node.start is not None:
1299 self.visit(node.start, frame)
1300 self.write(':')
1301 if node.stop is not None:
1302 self.visit(node.stop, frame)
1303 if node.step is not None:
1304 self.write(':')
1305 self.visit(node.step, frame)
1306
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001307 def visit_Filter(self, node, frame):
Armin Ronacherb9e78752008-05-10 23:36:28 +02001308 self.write(self.filters[node.name] + '(')
Christoph Hack80909862008-04-14 01:35:10 +02001309 func = self.environment.filters.get(node.name)
Armin Ronacher0611e492008-04-25 23:44:14 +02001310 if func is None:
Armin Ronachere2244882008-05-19 09:25:57 +02001311 self.fail('no filter named %r' % node.name, node.lineno)
Christoph Hack80909862008-04-14 01:35:10 +02001312 if getattr(func, 'contextfilter', False):
1313 self.write('context, ')
Armin Ronacher9a027f42008-04-17 11:13:40 +02001314 elif getattr(func, 'environmentfilter', False):
1315 self.write('environment, ')
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001316
1317 # if the filter node is None we are inside a filter block
1318 # and want to write to the current buffer
Armin Ronacher3da90312008-05-23 16:37:28 +02001319 if node.node is not None:
Armin Ronacherfa865fb2008-04-12 22:11:53 +02001320 self.visit(node.node, frame)
Armin Ronacher3da90312008-05-23 16:37:28 +02001321 elif self.environment.autoescape:
1322 self.write('Markup(concat(%s))' % frame.buffer)
1323 else:
1324 self.write('concat(%s)' % frame.buffer)
Armin Ronacherd55ab532008-04-09 16:13:39 +02001325 self.signature(node, frame)
1326 self.write(')')
Armin Ronacher8efc5222008-04-08 14:47:40 +02001327
1328 def visit_Test(self, node, frame):
Armin Ronacherb9e78752008-05-10 23:36:28 +02001329 self.write(self.tests[node.name] + '(')
Armin Ronacher0611e492008-04-25 23:44:14 +02001330 if node.name not in self.environment.tests:
Armin Ronachere2244882008-05-19 09:25:57 +02001331 self.fail('no test named %r' % node.name, node.lineno)
Armin Ronacher8efc5222008-04-08 14:47:40 +02001332 self.visit(node.node, frame)
1333 self.signature(node, frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001334 self.write(')')
Armin Ronacher8efc5222008-04-08 14:47:40 +02001335
Armin Ronacher3d8b7842008-04-13 13:16:50 +02001336 def visit_CondExpr(self, node, frame):
1337 if not have_condexpr:
1338 self.write('((')
1339 self.visit(node.test, frame)
1340 self.write(') and (')
1341 self.visit(node.expr1, frame)
1342 self.write(',) or (')
1343 self.visit(node.expr2, frame)
1344 self.write(',))[0]')
1345 else:
1346 self.write('(')
1347 self.visit(node.expr1, frame)
1348 self.write(' if ')
1349 self.visit(node.test, frame)
1350 self.write(' else ')
1351 self.visit(node.expr2, frame)
1352 self.write(')')
1353
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001354 def visit_Call(self, node, frame, forward_caller=False):
Armin Ronacherc63243e2008-04-14 22:53:58 +02001355 if self.environment.sandboxed:
1356 self.write('environment.call(')
Armin Ronacher8efc5222008-04-08 14:47:40 +02001357 self.visit(node.node, frame)
Armin Ronacherc63243e2008-04-14 22:53:58 +02001358 self.write(self.environment.sandboxed and ', ' or '(')
Armin Ronacher105f0dc2008-05-23 16:12:47 +02001359 extra_kwargs = forward_caller and {'caller': 'caller'} or None
Armin Ronacher71082072008-04-12 14:19:36 +02001360 self.signature(node, frame, False, extra_kwargs)
Armin Ronacher8efc5222008-04-08 14:47:40 +02001361 self.write(')')
1362
1363 def visit_Keyword(self, node, frame):
Armin Ronacher2e9396b2008-04-16 14:21:57 +02001364 self.write(node.key + '=')
Armin Ronacher8efc5222008-04-08 14:47:40 +02001365 self.visit(node.value, frame)
Armin Ronachered1e0d42008-05-18 20:25:28 +02001366
Armin Ronachera2eb77d2008-05-22 20:28:21 +02001367 # -- Unused nodes for extensions
Armin Ronachered1e0d42008-05-18 20:25:28 +02001368
1369 def visit_MarkSafe(self, node, frame):
1370 self.write('Markup(')
1371 self.visit(node.expr, frame)
1372 self.write(')')
1373
1374 def visit_EnvironmentAttribute(self, node, frame):
1375 self.write('environment.' + node.name)
1376
1377 def visit_ExtensionAttribute(self, node, frame):
Armin Ronacher6df604e2008-05-23 22:18:38 +02001378 self.write('environment.extensions[%r].%s' % (node.identifier, node.name))
Armin Ronachered1e0d42008-05-18 20:25:28 +02001379
1380 def visit_ImportedName(self, node, frame):
1381 self.write(self.import_aliases[node.importname])
1382
1383 def visit_InternalName(self, node, frame):
1384 self.write(node.name)
1385
Armin Ronacher6df604e2008-05-23 22:18:38 +02001386 def visit_ContextReference(self, node, frame):
1387 self.write('context')
1388
Armin Ronachered1e0d42008-05-18 20:25:28 +02001389 def visit_Continue(self, node, frame):
1390 self.writeline('continue', node)
1391
1392 def visit_Break(self, node, frame):
1393 self.writeline('break', node)