blob: 2631c450440eb74fbc42f1a821095342a308a50d [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 Ronacher32a910f2008-04-26 23:21:03 +020011from time import time
Armin Ronacher8efc5222008-04-08 14:47:40 +020012from copy import copy
Armin Ronachere791c2a2008-04-07 18:39:54 +020013from random import randrange
Armin Ronacher2feed1d2008-04-26 16:26:52 +020014from keyword import iskeyword
Armin Ronachere791c2a2008-04-07 18:39:54 +020015from cStringIO import StringIO
Armin Ronacher2feed1d2008-04-26 16:26:52 +020016from itertools import chain
Armin Ronachere791c2a2008-04-07 18:39:54 +020017from jinja2 import nodes
18from jinja2.visitor import NodeVisitor, NodeTransformer
19from jinja2.exceptions import TemplateAssertionError
Armin Ronacher32a910f2008-04-26 23:21:03 +020020from jinja2.runtime import concat
Armin Ronacher5236d8c2008-04-17 11:23:16 +020021from jinja2.utils import Markup
Armin Ronachere791c2a2008-04-07 18:39:54 +020022
23
24operators = {
25 'eq': '==',
26 'ne': '!=',
27 'gt': '>',
28 'gteq': '>=',
29 'lt': '<',
30 'lteq': '<=',
31 'in': 'in',
32 'notin': 'not in'
33}
34
Armin Ronacher3d8b7842008-04-13 13:16:50 +020035try:
36 exec '(0 if 0 else 0)'
37except SyntaxError:
38 have_condexpr = False
39else:
40 have_condexpr = True
41
42
Armin Ronacher8e8d0712008-04-16 23:10:49 +020043def generate(node, environment, name, filename, stream=None):
Armin Ronacherbcb7c532008-04-11 16:30:34 +020044 """Generate the python source for a node tree."""
Armin Ronacher8e8d0712008-04-16 23:10:49 +020045 generator = CodeGenerator(environment, name, filename, stream)
Armin Ronachere791c2a2008-04-07 18:39:54 +020046 generator.visit(node)
47 if stream is None:
48 return generator.stream.getvalue()
49
50
Armin Ronacher4dfc9752008-04-09 15:03:29 +020051def has_safe_repr(value):
52 """Does the node have a safe representation?"""
Armin Ronacherd55ab532008-04-09 16:13:39 +020053 if value is None or value is NotImplemented or value is Ellipsis:
Armin Ronacher4dfc9752008-04-09 15:03:29 +020054 return True
Armin Ronacherd55ab532008-04-09 16:13:39 +020055 if isinstance(value, (bool, int, long, float, complex, basestring,
Armin Ronacher32a910f2008-04-26 23:21:03 +020056 xrange, Markup)):
Armin Ronacher4dfc9752008-04-09 15:03:29 +020057 return True
Armin Ronacherd55ab532008-04-09 16:13:39 +020058 if isinstance(value, (tuple, list, set, frozenset)):
Armin Ronacher4dfc9752008-04-09 15:03:29 +020059 for item in value:
60 if not has_safe_repr(item):
61 return False
62 return True
63 elif isinstance(value, dict):
64 for key, value in value.iteritems():
65 if not has_safe_repr(key):
66 return False
67 if not has_safe_repr(value):
68 return False
69 return True
70 return False
71
72
Armin Ronacherc9705c22008-04-27 21:28:03 +020073def find_undeclared(nodes, names):
74 """Check if the names passed are accessed undeclared. The return value
75 is a set of all the undeclared names from the sequence of names found.
76 """
77 visitor = UndeclaredNameVisitor(names)
78 try:
79 for node in nodes:
80 visitor.visit(node)
81 except VisitorExit:
82 pass
83 return visitor.undeclared
84
85
Armin Ronachere791c2a2008-04-07 18:39:54 +020086class Identifiers(object):
87 """Tracks the status of identifiers in frames."""
88
89 def __init__(self):
90 # variables that are known to be declared (probably from outer
91 # frames or because they are special for the frame)
92 self.declared = set()
93
Armin Ronacher10f3ba22008-04-18 11:30:37 +020094 # undeclared variables from outer scopes
95 self.outer_undeclared = set()
96
Armin Ronachere791c2a2008-04-07 18:39:54 +020097 # names that are accessed without being explicitly declared by
98 # this one or any of the outer scopes. Names can appear both in
99 # declared and undeclared.
100 self.undeclared = set()
101
102 # names that are declared locally
103 self.declared_locally = set()
104
105 # names that are declared by parameters
106 self.declared_parameter = set()
107
108 def add_special(self, name):
109 """Register a special name like `loop`."""
110 self.undeclared.discard(name)
111 self.declared.add(name)
112
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200113 def is_declared(self, name, local_only=False):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200114 """Check if a name is declared in this or an outer scope."""
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200115 if name in self.declared_locally or name in self.declared_parameter:
116 return True
117 if local_only:
118 return False
119 return name in self.declared
Armin Ronachere791c2a2008-04-07 18:39:54 +0200120
121 def find_shadowed(self):
122 """Find all the shadowed names."""
Armin Ronacher10f3ba22008-04-18 11:30:37 +0200123 return (self.declared | self.outer_undeclared) & \
124 (self.declared_locally | self.declared_parameter)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200125
126
127class Frame(object):
Armin Ronacher75cfb862008-04-11 13:47:22 +0200128 """Holds compile time information for us."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200129
130 def __init__(self, parent=None):
131 self.identifiers = Identifiers()
Armin Ronacherfed44b52008-04-13 19:42:53 +0200132
Armin Ronacher75cfb862008-04-11 13:47:22 +0200133 # a toplevel frame is the root + soft frames such as if conditions.
Armin Ronacher8efc5222008-04-08 14:47:40 +0200134 self.toplevel = False
Armin Ronacherfed44b52008-04-13 19:42:53 +0200135
Armin Ronacher75cfb862008-04-11 13:47:22 +0200136 # the root frame is basically just the outermost frame, so no if
137 # conditions. This information is used to optimize inheritance
138 # situations.
139 self.rootlevel = False
Armin Ronacherfed44b52008-04-13 19:42:53 +0200140
141 # inside some tags we are using a buffer rather than yield statements.
142 # this for example affects {% filter %} or {% macro %}. If a frame
143 # is buffered this variable points to the name of the list used as
144 # buffer.
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200145 self.buffer = None
Armin Ronacherfed44b52008-04-13 19:42:53 +0200146
Armin Ronacherfed44b52008-04-13 19:42:53 +0200147 # the name of the block we're in, otherwise None.
Armin Ronacher8efc5222008-04-08 14:47:40 +0200148 self.block = parent and parent.block or None
Armin Ronacherfed44b52008-04-13 19:42:53 +0200149
150 # the parent of this frame
151 self.parent = parent
152
Armin Ronachere791c2a2008-04-07 18:39:54 +0200153 if parent is not None:
154 self.identifiers.declared.update(
155 parent.identifiers.declared |
Armin Ronachere791c2a2008-04-07 18:39:54 +0200156 parent.identifiers.declared_locally |
157 parent.identifiers.declared_parameter
158 )
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 Ronacherc9705c22008-04-27 21:28:03 +0200248 if node.ctx in ('store', 'param'):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200249 self.identifiers.declared_locally.add(node.name)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200250 elif node.ctx == 'load' and not \
251 self.identifiers.is_declared(node.name, self.hard_scope):
252 self.identifiers.undeclared.add(node.name)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200253
Armin Ronacherc9705c22008-04-27 21:28:03 +0200254 def visit_Macro(self, node):
255 self.generic_visit(node)
256 self.identifiers.declared_locally.add(node.name)
Armin Ronacher0611e492008-04-25 23:44:14 +0200257
Armin Ronacherc9705c22008-04-27 21:28:03 +0200258 def visit_Import(self, node):
259 self.generic_visit(node)
260 self.identifiers.declared_locally.add(node.target)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200261
Armin Ronacherc9705c22008-04-27 21:28:03 +0200262 def visit_FromImport(self, node):
263 self.generic_visit(node)
264 for name in node.names:
265 if isinstance(name, tuple):
266 self.identifiers.declared_locally.add(name[1])
267 else:
268 self.identifiers.declared_locally.add(name)
269
270 def visit_Assign(self, node):
Armin Ronacherebe55aa2008-04-10 20:51:23 +0200271 """Visit assignments in the correct order."""
Armin Ronacherc9705c22008-04-27 21:28:03 +0200272 self.visit(node.node)
273 self.visit(node.target)
Armin Ronacherebe55aa2008-04-10 20:51:23 +0200274
Armin Ronacherc9705c22008-04-27 21:28:03 +0200275 def visit_For(self, node):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200276 """Visiting stops at for blocks. However the block sequence
277 is visited as part of the outer scope.
278 """
Armin Ronacherc9705c22008-04-27 21:28:03 +0200279 self.visit(node.iter)
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200280
Armin Ronacherc9705c22008-04-27 21:28:03 +0200281 def visit_CallBlock(self, node):
282 for child in node.iter_child_nodes(exclude=('body',)):
283 self.visit(child)
284
285 def visit_FilterBlock(self, node):
286 self.visit(node.filter)
287
288 def visit_Block(self, node):
289 """Stop visiting at blocks."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200290
291
Armin Ronacher75cfb862008-04-11 13:47:22 +0200292class CompilerExit(Exception):
293 """Raised if the compiler encountered a situation where it just
294 doesn't make sense to further process the code. Any block that
Armin Ronacher0611e492008-04-25 23:44:14 +0200295 raises such an exception is not further processed.
296 """
Armin Ronacher75cfb862008-04-11 13:47:22 +0200297
298
Armin Ronachere791c2a2008-04-07 18:39:54 +0200299class CodeGenerator(NodeVisitor):
300
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200301 def __init__(self, environment, name, filename, stream=None):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200302 if stream is None:
303 stream = StringIO()
Christoph Hack65642a52008-04-08 14:46:56 +0200304 self.environment = environment
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200305 self.name = name
Armin Ronachere791c2a2008-04-07 18:39:54 +0200306 self.filename = filename
307 self.stream = stream
Armin Ronacherfed44b52008-04-13 19:42:53 +0200308
309 # a registry for all blocks. Because blocks are moved out
310 # into the global python scope they are registered here
Armin Ronachere791c2a2008-04-07 18:39:54 +0200311 self.blocks = {}
Armin Ronacherfed44b52008-04-13 19:42:53 +0200312
313 # the number of extends statements so far
Armin Ronacher7fb38972008-04-11 13:54:28 +0200314 self.extends_so_far = 0
Armin Ronacherfed44b52008-04-13 19:42:53 +0200315
316 # some templates have a rootlevel extends. In this case we
317 # can safely assume that we're a child template and do some
318 # more optimizations.
Armin Ronacher75cfb862008-04-11 13:47:22 +0200319 self.has_known_extends = False
Armin Ronacherfed44b52008-04-13 19:42:53 +0200320
Armin Ronacherba3757b2008-04-16 19:43:16 +0200321 # the current line number
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200322 self.code_lineno = 1
Armin Ronacherba3757b2008-04-16 19:43:16 +0200323
324 # the debug information
325 self.debug_info = []
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200326 self._write_debug_info = None
Armin Ronacherba3757b2008-04-16 19:43:16 +0200327
Armin Ronacherfed44b52008-04-13 19:42:53 +0200328 # the number of new lines before the next write()
329 self._new_lines = 0
330
331 # the line number of the last written statement
Armin Ronachere791c2a2008-04-07 18:39:54 +0200332 self._last_line = 0
Armin Ronacherfed44b52008-04-13 19:42:53 +0200333
334 # true if nothing was written so far.
Armin Ronachere791c2a2008-04-07 18:39:54 +0200335 self._first_write = True
336
Armin Ronacherfed44b52008-04-13 19:42:53 +0200337 # used by the `temporary_identifier` method to get new
338 # unique, temporary identifier
339 self._last_identifier = 0
340
341 # the current indentation
342 self._indentation = 0
343
Armin Ronachere791c2a2008-04-07 18:39:54 +0200344 def temporary_identifier(self):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200345 """Get a new unique identifier."""
346 self._last_identifier += 1
347 return 't%d' % self._last_identifier
Armin Ronachere791c2a2008-04-07 18:39:54 +0200348
349 def indent(self):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200350 """Indent by one."""
351 self._indentation += 1
Armin Ronachere791c2a2008-04-07 18:39:54 +0200352
Armin Ronacher8efc5222008-04-08 14:47:40 +0200353 def outdent(self, step=1):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200354 """Outdent by step."""
355 self._indentation -= step
Armin Ronachere791c2a2008-04-07 18:39:54 +0200356
Armin Ronacherc9705c22008-04-27 21:28:03 +0200357 def blockvisit(self, nodes, frame, force_generator=True):
358 """Visit a list of nodes as block in a frame. If the current frame
359 is no buffer a dummy ``if 0: yield None`` is written automatically
360 unless the force_generator parameter is set to False.
Armin Ronacherfed44b52008-04-13 19:42:53 +0200361 """
Armin Ronacher625215e2008-04-13 16:31:08 +0200362 if frame.buffer is None and force_generator:
Armin Ronachere791c2a2008-04-07 18:39:54 +0200363 self.writeline('if 0: yield None')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200364 try:
365 for node in nodes:
366 self.visit(node, frame)
367 except CompilerExit:
368 pass
Armin Ronachere791c2a2008-04-07 18:39:54 +0200369
370 def write(self, x):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200371 """Write a string into the output stream."""
372 if self._new_lines:
Armin Ronachere791c2a2008-04-07 18:39:54 +0200373 if not self._first_write:
Armin Ronacherfed44b52008-04-13 19:42:53 +0200374 self.stream.write('\n' * self._new_lines)
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200375 self.code_lineno += self._new_lines
376 if self._write_debug_info is not None:
377 self.debug_info.append((self._write_debug_info,
378 self.code_lineno))
379 self._write_debug_info = None
Armin Ronachere791c2a2008-04-07 18:39:54 +0200380 self._first_write = False
Armin Ronacherfed44b52008-04-13 19:42:53 +0200381 self.stream.write(' ' * self._indentation)
382 self._new_lines = 0
Armin Ronachere791c2a2008-04-07 18:39:54 +0200383 self.stream.write(x)
384
385 def writeline(self, x, node=None, extra=0):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200386 """Combination of newline and write."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200387 self.newline(node, extra)
388 self.write(x)
389
390 def newline(self, node=None, extra=0):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200391 """Add one or more newlines before the next write."""
392 self._new_lines = max(self._new_lines, 1 + extra)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200393 if node is not None and node.lineno != self._last_line:
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200394 self._write_debug_info = node.lineno
395 self._last_line = node.lineno
Armin Ronachere791c2a2008-04-07 18:39:54 +0200396
Armin Ronacher71082072008-04-12 14:19:36 +0200397 def signature(self, node, frame, have_comma=True, extra_kwargs=None):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200398 """Writes a function call to the stream for the current node.
399 Per default it will write a leading comma but this can be
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200400 disabled by setting have_comma to False. The extra keyword
401 arguments may not include python keywords otherwise a syntax
402 error could occour. The extra keyword arguments should be given
403 as python dict.
Armin Ronacherfed44b52008-04-13 19:42:53 +0200404 """
Armin Ronacher8efc5222008-04-08 14:47:40 +0200405 have_comma = have_comma and [True] or []
406 def touch_comma():
407 if have_comma:
408 self.write(', ')
409 else:
410 have_comma.append(True)
411
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200412 # if any of the given keyword arguments is a python keyword
413 # we have to make sure that no invalid call is created.
414 kwarg_workaround = False
415 for kwarg in chain((x.key for x in node.kwargs), extra_kwargs or ()):
416 if iskeyword(kwarg):
417 kwarg_workaround = True
418 break
419
Armin Ronacher8efc5222008-04-08 14:47:40 +0200420 for arg in node.args:
421 touch_comma()
422 self.visit(arg, frame)
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200423
424 if not kwarg_workaround:
425 for kwarg in node.kwargs:
426 touch_comma()
427 self.visit(kwarg, frame)
428 if extra_kwargs is not None:
429 for key, value in extra_kwargs.iteritems():
430 touch_comma()
431 self.write('%s=%s' % (key, value))
Armin Ronacher8efc5222008-04-08 14:47:40 +0200432 if node.dyn_args:
433 touch_comma()
Armin Ronacher71082072008-04-12 14:19:36 +0200434 self.write('*')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200435 self.visit(node.dyn_args, frame)
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200436
437 if kwarg_workaround:
438 touch_comma()
439 if node.dyn_kwargs is not None:
440 self.write('**dict({')
441 else:
442 self.write('**{')
443 for kwarg in node.kwargs:
444 self.write('%r: ' % kwarg.key)
445 self.visit(kwarg.value, frame)
446 self.write(', ')
447 if extra_kwargs is not None:
448 for key, value in extra_kwargs.iteritems():
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200449 self.write('%r: %s, ' % (key, value))
450 if node.dyn_kwargs is not None:
451 self.write('}, **')
452 self.visit(node.dyn_kwargs, frame)
453 self.write(')')
454 else:
455 self.write('}')
456
457 elif node.dyn_kwargs is not None:
Armin Ronacher8efc5222008-04-08 14:47:40 +0200458 touch_comma()
Armin Ronacher71082072008-04-12 14:19:36 +0200459 self.write('**')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200460 self.visit(node.dyn_kwargs, frame)
461
Armin Ronacherc9705c22008-04-27 21:28:03 +0200462 def pull_locals(self, frame):
463 """Pull all the references identifiers into the local scope."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200464 for name in frame.identifiers.undeclared:
465 self.writeline('l_%s = context[%r]' % (name, name))
Armin Ronacherc9705c22008-04-27 21:28:03 +0200466
467 def pull_dependencies(self, nodes):
468 """Pull all the dependencies."""
469 visitor = DependencyFinderVisitor()
470 for node in nodes:
471 visitor.visit(node)
472 for name in visitor.filters:
Armin Ronacherd4c64f72008-04-11 17:15:29 +0200473 self.writeline('f_%s = environment.filters[%r]' % (name, name))
Armin Ronacherc9705c22008-04-27 21:28:03 +0200474 for name in visitor.tests:
Armin Ronacherf059ec12008-04-11 22:21:00 +0200475 self.writeline('t_%s = environment.tests[%r]' % (name, name))
Armin Ronachere791c2a2008-04-07 18:39:54 +0200476
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200477 def collect_shadowed(self, frame):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200478 """This function returns all the shadowed variables in a dict
479 in the form name: alias and will write the required assignments
480 into the current scope. No indentation takes place.
481 """
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200482 # make sure we "backup" overridden, local identifiers
483 # TODO: we should probably optimize this and check if the
484 # identifier is in use afterwards.
485 aliases = {}
486 for name in frame.identifiers.find_shadowed():
487 aliases[name] = ident = self.temporary_identifier()
488 self.writeline('%s = l_%s' % (ident, name))
489 return aliases
490
Armin Ronacherc9705c22008-04-27 21:28:03 +0200491 def function_scoping(self, node, frame, children=None):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200492 """In Jinja a few statements require the help of anonymous
493 functions. Those are currently macros and call blocks and in
494 the future also recursive loops. As there is currently
495 technical limitation that doesn't allow reading and writing a
496 variable in a scope where the initial value is coming from an
497 outer scope, this function tries to fall back with a common
498 error message. Additionally the frame passed is modified so
499 that the argumetns are collected and callers are looked up.
500
501 This will return the modified frame.
502 """
Armin Ronacherc9705c22008-04-27 21:28:03 +0200503 # we have to iterate twice over it, make sure that works
504 if children is None:
505 children = node.iter_child_nodes()
506 children = list(children)
Armin Ronacher71082072008-04-12 14:19:36 +0200507 func_frame = frame.inner()
Armin Ronacherc9705c22008-04-27 21:28:03 +0200508 func_frame.inspect(children, hard_scope=True)
Armin Ronacher71082072008-04-12 14:19:36 +0200509
510 # variables that are undeclared (accessed before declaration) and
511 # declared locally *and* part of an outside scope raise a template
512 # assertion error. Reason: we can't generate reasonable code from
513 # it without aliasing all the variables. XXX: alias them ^^
514 overriden_closure_vars = (
515 func_frame.identifiers.undeclared &
516 func_frame.identifiers.declared &
517 (func_frame.identifiers.declared_locally |
518 func_frame.identifiers.declared_parameter)
519 )
520 if overriden_closure_vars:
521 vars = ', '.join(sorted(overriden_closure_vars))
522 raise TemplateAssertionError('It\'s not possible to set and '
523 'access variables derived from '
524 'an outer scope! (affects: %s' %
Armin Ronacher68f77672008-04-17 11:50:39 +0200525 vars, node.lineno, self.name)
Armin Ronacher71082072008-04-12 14:19:36 +0200526
527 # remove variables from a closure from the frame's undeclared
528 # identifiers.
529 func_frame.identifiers.undeclared -= (
530 func_frame.identifiers.undeclared &
531 func_frame.identifiers.declared
532 )
533
Armin Ronacher963f97d2008-04-25 11:44:59 +0200534 func_frame.accesses_kwargs = False
535 func_frame.accesses_varargs = False
Armin Ronacher71082072008-04-12 14:19:36 +0200536 func_frame.accesses_caller = False
537 func_frame.arguments = args = ['l_' + x.name for x in node.args]
538
Armin Ronacherc9705c22008-04-27 21:28:03 +0200539 undeclared = find_undeclared(children, ('caller', 'kwargs', 'varargs'))
540
541 if 'caller' in undeclared:
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200542 func_frame.accesses_caller = True
543 func_frame.identifiers.add_special('caller')
544 args.append('l_caller')
Armin Ronacherc9705c22008-04-27 21:28:03 +0200545 if 'kwargs' in undeclared:
Armin Ronacher963f97d2008-04-25 11:44:59 +0200546 func_frame.accesses_kwargs = True
547 func_frame.identifiers.add_special('kwargs')
548 args.append('l_kwargs')
Armin Ronacherc9705c22008-04-27 21:28:03 +0200549 if 'varargs' in undeclared:
Armin Ronacher963f97d2008-04-25 11:44:59 +0200550 func_frame.accesses_varargs = True
551 func_frame.identifiers.add_special('varargs')
552 args.append('l_varargs')
Armin Ronacher71082072008-04-12 14:19:36 +0200553 return func_frame
554
Armin Ronachere791c2a2008-04-07 18:39:54 +0200555 # -- Visitors
556
557 def visit_Template(self, node, frame=None):
558 assert frame is None, 'no root frame allowed'
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200559 from jinja2.runtime import __all__ as exported
560 self.writeline('from jinja2.runtime import ' + ', '.join(exported))
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200561 self.writeline('name = %r' % self.name)
Armin Ronacher8edbe492008-04-10 20:43:43 +0200562
Armin Ronacher75cfb862008-04-11 13:47:22 +0200563 # do we have an extends tag at all? If not, we can save some
564 # overhead by just not processing any inheritance code.
565 have_extends = node.find(nodes.Extends) is not None
566
Armin Ronacher8edbe492008-04-10 20:43:43 +0200567 # find all blocks
568 for block in node.find_all(nodes.Block):
569 if block.name in self.blocks:
570 raise TemplateAssertionError('block %r defined twice' %
571 block.name, block.lineno,
Armin Ronacher68f77672008-04-17 11:50:39 +0200572 self.name)
Armin Ronacher8edbe492008-04-10 20:43:43 +0200573 self.blocks[block.name] = block
Armin Ronachere791c2a2008-04-07 18:39:54 +0200574
Armin Ronacher8efc5222008-04-08 14:47:40 +0200575 # generate the root render function.
Armin Ronacher32a910f2008-04-26 23:21:03 +0200576 self.writeline('def root(context, environment=environment):', extra=1)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200577
578 # process the root
Armin Ronachere791c2a2008-04-07 18:39:54 +0200579 frame = Frame()
Armin Ronacherc9705c22008-04-27 21:28:03 +0200580 frame.inspect(node.body)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200581 frame.toplevel = frame.rootlevel = True
Armin Ronacherf059ec12008-04-11 22:21:00 +0200582 self.indent()
Armin Ronacherc9705c22008-04-27 21:28:03 +0200583 if have_extends:
584 self.writeline('parent_template = None')
585 self.pull_locals(frame)
586 self.pull_dependencies(node.body)
587 if 'self' in find_undeclared(node.body, ('self',)):
588 frame.identifiers.add_special('self')
589 self.writeline('l_self = TemplateReference(context)')
590 self.blockvisit(node.body, frame)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200591 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200592
Armin Ronacher8efc5222008-04-08 14:47:40 +0200593 # make sure that the parent root is called.
Armin Ronacher75cfb862008-04-11 13:47:22 +0200594 if have_extends:
595 if not self.has_known_extends:
596 self.indent()
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200597 self.writeline('if parent_template is not None:')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200598 self.indent()
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200599 self.writeline('for event in parent_template.'
600 'root_render_func(context):')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200601 self.indent()
602 self.writeline('yield event')
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200603 self.outdent(2 + (not self.has_known_extends))
Armin Ronachere791c2a2008-04-07 18:39:54 +0200604
605 # at this point we now have the blocks collected and can visit them too.
606 for name, block in self.blocks.iteritems():
607 block_frame = Frame()
Armin Ronacherc9705c22008-04-27 21:28:03 +0200608 block_frame.inspect(block.body)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200609 block_frame.block = name
Armin Ronacherd4c64f72008-04-11 17:15:29 +0200610 self.writeline('def block_%s(context, environment=environment):'
611 % name, block, 1)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200612 self.indent()
613 undeclared = find_undeclared(block.body, ('self', 'super'))
614 if 'self' in undeclared:
615 block_frame.identifiers.add_special('self')
616 self.writeline('l_self = TemplateReference(context)')
617 if 'super' in undeclared:
618 block_frame.identifiers.add_special('super')
619 self.writeline('l_super = context.super(%r, '
620 'block_%s)' % (name, name))
Armin Ronachere791c2a2008-04-07 18:39:54 +0200621 self.pull_locals(block_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200622 self.pull_dependencies(block.body)
Armin Ronacher625215e2008-04-13 16:31:08 +0200623 self.blockvisit(block.body, block_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200624 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200625
Armin Ronacher75cfb862008-04-11 13:47:22 +0200626 self.writeline('blocks = {%s}' % ', '.join('%r: block_%s' % (x, x)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200627 for x in self.blocks),
628 extra=1)
629
630 # add a function that returns the debug info
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200631 self.writeline('debug_info = %r' % '&'.join('%s=%s' % x for x
632 in self.debug_info))
Armin Ronacher75cfb862008-04-11 13:47:22 +0200633
Armin Ronachere791c2a2008-04-07 18:39:54 +0200634 def visit_Block(self, node, frame):
635 """Call a block and register it for the template."""
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200636 level = 1
Armin Ronacher75cfb862008-04-11 13:47:22 +0200637 if frame.toplevel:
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200638 # if we know that we are a child template, there is no need to
639 # check if we are one
640 if self.has_known_extends:
641 return
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200642 if self.extends_so_far > 0:
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200643 self.writeline('if parent_template is None:')
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200644 self.indent()
645 level += 1
Armin Ronacherc9705c22008-04-27 21:28:03 +0200646 self.writeline('for event in context.blocks[%r][-1](context):' %
647 node.name, node)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200648 self.indent()
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200649 if frame.buffer is None:
650 self.writeline('yield event')
651 else:
652 self.writeline('%s.append(event)' % frame.buffer)
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200653 self.outdent(level)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200654
655 def visit_Extends(self, node, frame):
656 """Calls the extender."""
Armin Ronacher8efc5222008-04-08 14:47:40 +0200657 if not frame.toplevel:
658 raise TemplateAssertionError('cannot use extend from a non '
659 'top-level scope', node.lineno,
Armin Ronacher68f77672008-04-17 11:50:39 +0200660 self.name)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200661
Armin Ronacher7fb38972008-04-11 13:54:28 +0200662 # if the number of extends statements in general is zero so
663 # far, we don't have to add a check if something extended
664 # the template before this one.
665 if self.extends_so_far > 0:
Armin Ronacher75cfb862008-04-11 13:47:22 +0200666
Armin Ronacher7fb38972008-04-11 13:54:28 +0200667 # if we have a known extends we just add a template runtime
668 # error into the generated code. We could catch that at compile
669 # time too, but i welcome it not to confuse users by throwing the
670 # same error at different times just "because we can".
671 if not self.has_known_extends:
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200672 self.writeline('if parent_template is not None:')
Armin Ronacher7fb38972008-04-11 13:54:28 +0200673 self.indent()
674 self.writeline('raise TemplateRuntimeError(%r)' %
675 'extended multiple times')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200676
Armin Ronacher7fb38972008-04-11 13:54:28 +0200677 # if we have a known extends already we don't need that code here
678 # as we know that the template execution will end here.
679 if self.has_known_extends:
680 raise CompilerExit()
681 self.outdent()
682
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200683 self.writeline('parent_template = environment.get_template(', node, 1)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200684 self.visit(node.template, frame)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200685 self.write(', %r)' % self.name)
686 self.writeline('for name, parent_block in parent_template.'
687 'blocks.iteritems():')
688 self.indent()
689 self.writeline('context.blocks.setdefault(name, []).'
690 'insert(0, parent_block)')
691 self.outdent()
Armin Ronacher75cfb862008-04-11 13:47:22 +0200692
693 # if this extends statement was in the root level we can take
694 # advantage of that information and simplify the generated code
695 # in the top level from this point onwards
696 self.has_known_extends = True
Armin Ronachere791c2a2008-04-07 18:39:54 +0200697
Armin Ronacher7fb38972008-04-11 13:54:28 +0200698 # and now we have one more
699 self.extends_so_far += 1
700
Armin Ronacherf059ec12008-04-11 22:21:00 +0200701 def visit_Include(self, node, frame):
702 """Handles includes."""
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200703 self.writeline('included_template = environment.get_template(', node)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200704 self.visit(node.template, frame)
Armin Ronacher963f97d2008-04-25 11:44:59 +0200705 self.write(', %r)' % self.name)
Armin Ronacher0611e492008-04-25 23:44:14 +0200706 self.writeline('for event in included_template.root_render_func('
Armin Ronacherc9705c22008-04-27 21:28:03 +0200707 'included_template.new_context(context.parent, True)):')
Armin Ronacherf059ec12008-04-11 22:21:00 +0200708 self.indent()
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200709 if frame.buffer is None:
710 self.writeline('yield event')
711 else:
712 self.writeline('%s.append(event)' % frame.buffer)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200713 self.outdent()
714
Armin Ronacher0611e492008-04-25 23:44:14 +0200715 def visit_Import(self, node, frame):
716 """Visit regular imports."""
717 self.writeline('l_%s = ' % node.target, node)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200718 if frame.toplevel:
Armin Ronacher53042292008-04-26 18:30:19 +0200719 self.write('context.vars[%r] = ' % node.target)
Armin Ronacher0611e492008-04-25 23:44:14 +0200720 self.write('environment.get_template(')
721 self.visit(node.template, frame)
722 self.write(', %r).include(context)' % self.name)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200723 if frame.toplevel and not node.target.startswith('__'):
Armin Ronacher53042292008-04-26 18:30:19 +0200724 self.writeline('context.exported_vars.discard(%r)' % node.target)
Armin Ronacher0611e492008-04-25 23:44:14 +0200725
726 def visit_FromImport(self, node, frame):
727 """Visit named imports."""
728 self.newline(node)
729 self.write('included_template = environment.get_template(')
730 self.visit(node.template, frame)
731 self.write(', %r).include(context)' % self.name)
732 for name in node.names:
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200733 if isinstance(name, tuple):
734 name, alias = name
735 else:
736 alias = name
Armin Ronacher0611e492008-04-25 23:44:14 +0200737 self.writeline('l_%s = getattr(included_template, '
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200738 '%r, missing)' % (alias, name))
739 self.writeline('if l_%s is missing:' % alias)
Armin Ronacher0611e492008-04-25 23:44:14 +0200740 self.indent()
741 self.writeline('l_%s = environment.undefined(%r %% '
742 'included_template.name)' %
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200743 (alias, 'the template %r does not export '
Armin Ronacher0611e492008-04-25 23:44:14 +0200744 'the requested name ' + repr(name)))
745 self.outdent()
746 if frame.toplevel:
Armin Ronacher53042292008-04-26 18:30:19 +0200747 self.writeline('context.vars[%r] = l_%s' % (alias, alias))
Armin Ronacherc9705c22008-04-27 21:28:03 +0200748 if not alias.startswith('__'):
749 self.writeline('context.exported_vars.discard(%r)' % alias)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200750
Armin Ronachere791c2a2008-04-07 18:39:54 +0200751 def visit_For(self, node, frame):
752 loop_frame = frame.inner()
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200753 loop_frame.inspect(node.iter_child_nodes(exclude=('iter',)))
Armin Ronachere791c2a2008-04-07 18:39:54 +0200754 extended_loop = bool(node.else_) or \
755 'loop' in loop_frame.identifiers.undeclared
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200756 if extended_loop:
757 loop_frame.identifiers.add_special('loop')
Armin Ronachere791c2a2008-04-07 18:39:54 +0200758
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200759 aliases = self.collect_shadowed(loop_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200760 self.pull_locals(loop_frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200761 if node.else_:
762 self.writeline('l_loop = None')
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200763
764 self.newline(node)
765 self.writeline('for ')
Armin Ronachere791c2a2008-04-07 18:39:54 +0200766 self.visit(node.target, loop_frame)
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200767 self.write(extended_loop and ', l_loop in LoopContext(' or ' in ')
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200768
769 # the expression pointing to the parent loop. We make the
770 # undefined a bit more debug friendly at the same time.
771 parent_loop = 'loop' in aliases and aliases['loop'] \
Armin Ronacherbe4ae242008-04-18 09:49:08 +0200772 or "environment.undefined(%r)" % "'loop' is undefined. " \
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200773 'the filter section of a loop as well as the ' \
774 'else block doesn\'t have access to the special ' \
775 "'loop' variable of the current loop. Because " \
776 'there is no parent loop it\'s undefined.'
777
778 # if we have an extened loop and a node test, we filter in the
779 # "outer frame".
780 if extended_loop and node.test is not None:
781 self.write('(')
782 self.visit(node.target, loop_frame)
783 self.write(' for ')
784 self.visit(node.target, loop_frame)
785 self.write(' in ')
786 self.visit(node.iter, loop_frame)
787 self.write(' if (')
788 test_frame = loop_frame.copy()
Armin Ronacherc9705c22008-04-27 21:28:03 +0200789 self.writeline('l_loop = ' + parent_loop)
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200790 self.visit(node.test, test_frame)
791 self.write('))')
792
793 else:
794 self.visit(node.iter, loop_frame)
795
Armin Ronachere791c2a2008-04-07 18:39:54 +0200796 self.write(extended_loop and '):' or ':')
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200797
798 # tests in not extended loops become a continue
799 if not extended_loop and node.test is not None:
800 self.indent()
801 self.writeline('if ')
Armin Ronacher32a910f2008-04-26 23:21:03 +0200802 self.visit(node.test, loop_frame)
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200803 self.write(':')
804 self.indent()
805 self.writeline('continue')
806 self.outdent(2)
807
Armin Ronacherc9705c22008-04-27 21:28:03 +0200808 self.indent()
Armin Ronacherbe4ae242008-04-18 09:49:08 +0200809 self.blockvisit(node.body, loop_frame, force_generator=True)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200810 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200811
812 if node.else_:
813 self.writeline('if l_loop is None:')
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200814 self.indent()
815 self.writeline('l_loop = ' + parent_loop)
Armin Ronacher625215e2008-04-13 16:31:08 +0200816 self.blockvisit(node.else_, loop_frame, force_generator=False)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200817 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200818
Armin Ronacherd4c64f72008-04-11 17:15:29 +0200819 # reset the aliases if there are any.
Armin Ronachere791c2a2008-04-07 18:39:54 +0200820 for name, alias in aliases.iteritems():
Armin Ronacher8efc5222008-04-08 14:47:40 +0200821 self.writeline('l_%s = %s' % (name, alias))
Armin Ronachere791c2a2008-04-07 18:39:54 +0200822
823 def visit_If(self, node, frame):
Armin Ronacher75cfb862008-04-11 13:47:22 +0200824 if_frame = frame.soft()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200825 self.writeline('if ', node)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200826 self.visit(node.test, if_frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200827 self.write(':')
Armin Ronacherc9705c22008-04-27 21:28:03 +0200828 self.indent()
Armin Ronacher75cfb862008-04-11 13:47:22 +0200829 self.blockvisit(node.body, if_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200830 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200831 if node.else_:
832 self.writeline('else:')
Armin Ronacherc9705c22008-04-27 21:28:03 +0200833 self.indent()
Armin Ronacher75cfb862008-04-11 13:47:22 +0200834 self.blockvisit(node.else_, if_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200835 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200836
Armin Ronacher8efc5222008-04-08 14:47:40 +0200837 def visit_Macro(self, node, frame):
Armin Ronacher71082072008-04-12 14:19:36 +0200838 macro_frame = self.function_scoping(node, frame)
839 args = macro_frame.arguments
Armin Ronacher8efc5222008-04-08 14:47:40 +0200840 self.writeline('def macro(%s):' % ', '.join(args), node)
Armin Ronacher625215e2008-04-13 16:31:08 +0200841 macro_frame.buffer = buf = self.temporary_identifier()
842 self.indent()
Armin Ronacherc9705c22008-04-27 21:28:03 +0200843 self.pull_locals(macro_frame)
Armin Ronacher625215e2008-04-13 16:31:08 +0200844 self.writeline('%s = []' % buf)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200845 self.blockvisit(node.body, macro_frame)
Armin Ronacherd1342312008-04-28 12:20:12 +0200846 if self.environment.autoescape:
847 self.writeline('return Markup(concat(%s))' % buf)
848 else:
849 self.writeline("return concat(%s)" % buf)
Armin Ronacher625215e2008-04-13 16:31:08 +0200850 self.outdent()
Armin Ronacher8efc5222008-04-08 14:47:40 +0200851 self.newline()
852 if frame.toplevel:
Armin Ronacherc9705c22008-04-27 21:28:03 +0200853 if not node.name.startswith('__'):
854 self.write('context.exported_vars.add(%r)' % node.name)
Armin Ronacher32a910f2008-04-26 23:21:03 +0200855 self.writeline('context.vars[%r] = ' % node.name)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200856 arg_tuple = ', '.join(repr(x.name) for x in node.args)
857 if len(node.args) == 1:
858 arg_tuple += ','
Armin Ronacherc63243e2008-04-14 22:53:58 +0200859 self.write('l_%s = Macro(environment, macro, %r, (%s), (' %
860 (node.name, node.name, arg_tuple))
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200861 for arg in node.defaults:
Armin Ronacher625215e2008-04-13 16:31:08 +0200862 self.visit(arg, macro_frame)
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200863 self.write(', ')
Armin Ronacher963f97d2008-04-25 11:44:59 +0200864 self.write('), %s, %s, %s)' % (
865 macro_frame.accesses_kwargs and '1' or '0',
866 macro_frame.accesses_varargs and '1' or '0',
Armin Ronacher00d5d212008-04-13 01:10:18 +0200867 macro_frame.accesses_caller and '1' or '0'
Armin Ronacher71082072008-04-12 14:19:36 +0200868 ))
869
870 def visit_CallBlock(self, node, frame):
Armin Ronacherc9705c22008-04-27 21:28:03 +0200871 call_frame = self.function_scoping(node, frame, node.iter_child_nodes
872 (exclude=('call',)))
Armin Ronacher71082072008-04-12 14:19:36 +0200873 args = call_frame.arguments
874 self.writeline('def call(%s):' % ', '.join(args), node)
Armin Ronacher625215e2008-04-13 16:31:08 +0200875 call_frame.buffer = buf = self.temporary_identifier()
876 self.indent()
Armin Ronacherc9705c22008-04-27 21:28:03 +0200877 self.pull_locals(call_frame)
Armin Ronacher625215e2008-04-13 16:31:08 +0200878 self.writeline('%s = []' % buf)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200879 self.blockvisit(node.body, call_frame)
Armin Ronacherd1342312008-04-28 12:20:12 +0200880 if self.environment.autoescape:
881 self.writeline("return Markup(concat(%s))" % buf)
882 else:
883 self.writeline('return concat(%s)' % buf)
Armin Ronacher625215e2008-04-13 16:31:08 +0200884 self.outdent()
Armin Ronacher71082072008-04-12 14:19:36 +0200885 arg_tuple = ', '.join(repr(x.name) for x in node.args)
886 if len(node.args) == 1:
887 arg_tuple += ','
Armin Ronacherc63243e2008-04-14 22:53:58 +0200888 self.writeline('caller = Macro(environment, call, None, (%s), (' %
889 arg_tuple)
Armin Ronacher71082072008-04-12 14:19:36 +0200890 for arg in node.defaults:
Armin Ronacherc9705c22008-04-27 21:28:03 +0200891 self.visit(arg, call_frame)
Armin Ronacher71082072008-04-12 14:19:36 +0200892 self.write(', ')
Armin Ronacher963f97d2008-04-25 11:44:59 +0200893 self.write('), %s, %s, 0)' % (
894 call_frame.accesses_kwargs and '1' or '0',
895 call_frame.accesses_varargs and '1' or '0'
896 ))
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200897 if frame.buffer is None:
898 self.writeline('yield ', node)
899 else:
900 self.writeline('%s.append(' % frame.buffer, node)
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200901 self.visit_Call(node.call, call_frame,
902 extra_kwargs={'caller': 'caller'})
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200903 if frame.buffer is not None:
904 self.write(')')
905
906 def visit_FilterBlock(self, node, frame):
907 filter_frame = frame.inner()
908 filter_frame.inspect(node.iter_child_nodes())
909
910 aliases = self.collect_shadowed(filter_frame)
Armin Ronacherc9705c22008-04-27 21:28:03 +0200911 self.pull_locals(filter_frame)
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200912 filter_frame.buffer = buf = self.temporary_identifier()
913
914 self.writeline('%s = []' % buf, node)
915 for child in node.body:
916 self.visit(child, filter_frame)
917
918 if frame.buffer is None:
919 self.writeline('yield ', node)
920 else:
921 self.writeline('%s.append(' % frame.buffer, node)
Armin Ronacherde6bf712008-04-26 01:44:14 +0200922 self.visit_Filter(node.filter, filter_frame, 'concat(%s)' % buf)
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200923 if frame.buffer is not None:
924 self.write(')')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200925
Armin Ronachere791c2a2008-04-07 18:39:54 +0200926 def visit_ExprStmt(self, node, frame):
927 self.newline(node)
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200928 self.visit(node.node, frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200929
930 def visit_Output(self, node, frame):
Armin Ronacher75cfb862008-04-11 13:47:22 +0200931 # if we have a known extends statement, we don't output anything
Armin Ronacher7a52df82008-04-11 13:58:22 +0200932 if self.has_known_extends and frame.toplevel:
Armin Ronacher75cfb862008-04-11 13:47:22 +0200933 return
Armin Ronachere791c2a2008-04-07 18:39:54 +0200934
Armin Ronacher75cfb862008-04-11 13:47:22 +0200935 self.newline(node)
Armin Ronacher8edbe492008-04-10 20:43:43 +0200936
Armin Ronacher7fb38972008-04-11 13:54:28 +0200937 # if we are in the toplevel scope and there was already an extends
938 # statement we have to add a check that disables our yield(s) here
939 # so that they don't appear in the output.
940 outdent_later = False
941 if frame.toplevel and self.extends_so_far != 0:
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200942 self.writeline('if parent_template is None:')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200943 self.indent()
Armin Ronacher7fb38972008-04-11 13:54:28 +0200944 outdent_later = True
Armin Ronacher75cfb862008-04-11 13:47:22 +0200945
Armin Ronachere791c2a2008-04-07 18:39:54 +0200946 # try to evaluate as many chunks as possible into a static
947 # string at compile time.
948 body = []
949 for child in node.nodes:
950 try:
951 const = unicode(child.as_const())
952 except:
953 body.append(child)
954 continue
955 if body and isinstance(body[-1], list):
956 body[-1].append(const)
957 else:
958 body.append([const])
959
Armin Ronacher32a910f2008-04-26 23:21:03 +0200960 # if we have less than 3 nodes or less than 6 and a buffer we
961 # yield or extend
962 if len(body) < 3 or (frame.buffer is not None and len(body) < 6):
963 if frame.buffer is not None:
964 self.writeline('%s.extend((' % frame.buffer)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200965 for item in body:
966 if isinstance(item, list):
Armin Ronacherde6bf712008-04-26 01:44:14 +0200967 val = repr(concat(item))
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200968 if frame.buffer is None:
969 self.writeline('yield ' + val)
970 else:
Armin Ronacher32a910f2008-04-26 23:21:03 +0200971 self.write(val + ', ')
Armin Ronachere791c2a2008-04-07 18:39:54 +0200972 else:
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200973 if frame.buffer is None:
Armin Ronacher32a910f2008-04-26 23:21:03 +0200974 self.writeline('yield ')
Armin Ronacherd1342312008-04-28 12:20:12 +0200975 close = 1
976 if self.environment.autoescape:
977 self.write('escape(')
978 else:
979 self.write('unicode(')
980 if self.environment.finalize is not None:
981 self.write('environment.finalize(')
982 close += 1
Armin Ronachere791c2a2008-04-07 18:39:54 +0200983 self.visit(item, frame)
Armin Ronacherd1342312008-04-28 12:20:12 +0200984 self.write(')' * close)
Armin Ronacher32a910f2008-04-26 23:21:03 +0200985 if frame.buffer is not None:
986 self.write(', ')
987 if frame.buffer is not None:
988 self.write('))')
Armin Ronachere791c2a2008-04-07 18:39:54 +0200989
990 # otherwise we create a format string as this is faster in that case
991 else:
992 format = []
993 arguments = []
994 for item in body:
995 if isinstance(item, list):
Armin Ronacherde6bf712008-04-26 01:44:14 +0200996 format.append(concat(item).replace('%', '%%'))
Armin Ronachere791c2a2008-04-07 18:39:54 +0200997 else:
998 format.append('%s')
999 arguments.append(item)
Armin Ronacherfa865fb2008-04-12 22:11:53 +02001000 if frame.buffer is None:
1001 self.writeline('yield ')
1002 else:
1003 self.writeline('%s.append(' % frame.buffer)
Armin Ronacherde6bf712008-04-26 01:44:14 +02001004 self.write(repr(concat(format)) + ' % (')
Armin Ronachere791c2a2008-04-07 18:39:54 +02001005 idx = -1
Armin Ronacher8e8d0712008-04-16 23:10:49 +02001006 self.indent()
1007 for argument in arguments:
1008 self.newline(argument)
Armin Ronacherd1342312008-04-28 12:20:12 +02001009 close = 0
1010 if self.environment.autoescape:
1011 self.write('escape(')
1012 close += 1
1013 if self.environment.finalize is not None:
1014 self.write('environment.finalize(')
1015 close += 1
Armin Ronachere791c2a2008-04-07 18:39:54 +02001016 self.visit(argument, frame)
Armin Ronacherd1342312008-04-28 12:20:12 +02001017 self.write(')' * close + ',')
Armin Ronacher8e8d0712008-04-16 23:10:49 +02001018 self.outdent()
1019 self.writeline(')')
Armin Ronacherfa865fb2008-04-12 22:11:53 +02001020 if frame.buffer is not None:
1021 self.write(')')
Armin Ronachere791c2a2008-04-07 18:39:54 +02001022
Armin Ronacher7fb38972008-04-11 13:54:28 +02001023 if outdent_later:
Armin Ronacher75cfb862008-04-11 13:47:22 +02001024 self.outdent()
1025
Armin Ronacher8efc5222008-04-08 14:47:40 +02001026 def visit_Assign(self, node, frame):
1027 self.newline(node)
1028 # toplevel assignments however go into the local namespace and
1029 # the current template's context. We create a copy of the frame
1030 # here and add a set so that the Name visitor can add the assigned
1031 # names here.
1032 if frame.toplevel:
1033 assignment_frame = frame.copy()
1034 assignment_frame.assigned_names = set()
1035 else:
1036 assignment_frame = frame
1037 self.visit(node.target, assignment_frame)
1038 self.write(' = ')
1039 self.visit(node.node, frame)
Armin Ronacher9706fab2008-04-08 18:49:56 +02001040
1041 # make sure toplevel assignments are added to the context.
Armin Ronacher8efc5222008-04-08 14:47:40 +02001042 if frame.toplevel:
1043 for name in assignment_frame.assigned_names:
Armin Ronacher32a910f2008-04-26 23:21:03 +02001044 self.writeline('context.vars[%r] = l_%s' % (name, name))
Armin Ronacherc9705c22008-04-27 21:28:03 +02001045 if not name.startswith('__'):
1046 self.writeline('context.exported_vars.add(%r)' % name)
Armin Ronacher8efc5222008-04-08 14:47:40 +02001047
Armin Ronachere791c2a2008-04-07 18:39:54 +02001048 def visit_Name(self, node, frame):
Armin Ronacherc9705c22008-04-27 21:28:03 +02001049 if node.ctx == 'store' and frame.toplevel:
1050 frame.assigned_names.add(node.name)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001051 self.write('l_' + node.name)
1052
1053 def visit_Const(self, node, frame):
1054 val = node.value
1055 if isinstance(val, float):
1056 # XXX: add checks for infinity and nan
1057 self.write(str(val))
1058 else:
1059 self.write(repr(val))
1060
Armin Ronacher8efc5222008-04-08 14:47:40 +02001061 def visit_Tuple(self, node, frame):
1062 self.write('(')
1063 idx = -1
1064 for idx, item in enumerate(node.items):
1065 if idx:
1066 self.write(', ')
1067 self.visit(item, frame)
1068 self.write(idx == 0 and ',)' or ')')
1069
Armin Ronacher8edbe492008-04-10 20:43:43 +02001070 def visit_List(self, node, frame):
1071 self.write('[')
1072 for idx, item in enumerate(node.items):
1073 if idx:
1074 self.write(', ')
1075 self.visit(item, frame)
1076 self.write(']')
1077
1078 def visit_Dict(self, node, frame):
1079 self.write('{')
1080 for idx, item in enumerate(node.items):
1081 if idx:
1082 self.write(', ')
1083 self.visit(item.key, frame)
1084 self.write(': ')
1085 self.visit(item.value, frame)
1086 self.write('}')
1087
Armin Ronachere791c2a2008-04-07 18:39:54 +02001088 def binop(operator):
1089 def visitor(self, node, frame):
1090 self.write('(')
1091 self.visit(node.left, frame)
1092 self.write(' %s ' % operator)
1093 self.visit(node.right, frame)
1094 self.write(')')
1095 return visitor
1096
1097 def uaop(operator):
1098 def visitor(self, node, frame):
1099 self.write('(' + operator)
Armin Ronacher9a822052008-04-17 18:44:07 +02001100 self.visit(node.node, frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001101 self.write(')')
1102 return visitor
1103
1104 visit_Add = binop('+')
1105 visit_Sub = binop('-')
1106 visit_Mul = binop('*')
1107 visit_Div = binop('/')
1108 visit_FloorDiv = binop('//')
1109 visit_Pow = binop('**')
1110 visit_Mod = binop('%')
1111 visit_And = binop('and')
1112 visit_Or = binop('or')
1113 visit_Pos = uaop('+')
1114 visit_Neg = uaop('-')
1115 visit_Not = uaop('not ')
1116 del binop, uaop
1117
Armin Ronacherd1342312008-04-28 12:20:12 +02001118 def visit_Concat(self, node, frame):
1119 self.write('join((')
1120 for arg in node.nodes:
1121 self.visit(arg, frame)
1122 self.write(', ')
1123 self.write('))')
1124
Armin Ronachere791c2a2008-04-07 18:39:54 +02001125 def visit_Compare(self, node, frame):
1126 self.visit(node.expr, frame)
1127 for op in node.ops:
1128 self.visit(op, frame)
1129
1130 def visit_Operand(self, node, frame):
1131 self.write(' %s ' % operators[node.op])
1132 self.visit(node.expr, frame)
1133
1134 def visit_Subscript(self, node, frame):
Armin Ronacher8efc5222008-04-08 14:47:40 +02001135 if isinstance(node.arg, nodes.Slice):
1136 self.visit(node.node, frame)
1137 self.write('[')
1138 self.visit(node.arg, frame)
1139 self.write(']')
1140 return
1141 try:
1142 const = node.arg.as_const()
1143 have_const = True
1144 except nodes.Impossible:
1145 have_const = False
Armin Ronacherc63243e2008-04-14 22:53:58 +02001146 self.write('environment.subscribe(')
Armin Ronachere791c2a2008-04-07 18:39:54 +02001147 self.visit(node.node, frame)
1148 self.write(', ')
Armin Ronacher8efc5222008-04-08 14:47:40 +02001149 if have_const:
1150 self.write(repr(const))
1151 else:
1152 self.visit(node.arg, frame)
Armin Ronacher4dfc9752008-04-09 15:03:29 +02001153 self.write(')')
Armin Ronacher8efc5222008-04-08 14:47:40 +02001154
1155 def visit_Slice(self, node, frame):
1156 if node.start is not None:
1157 self.visit(node.start, frame)
1158 self.write(':')
1159 if node.stop is not None:
1160 self.visit(node.stop, frame)
1161 if node.step is not None:
1162 self.write(':')
1163 self.visit(node.step, frame)
1164
Armin Ronacherfa865fb2008-04-12 22:11:53 +02001165 def visit_Filter(self, node, frame, initial=None):
Armin Ronacherd4c64f72008-04-11 17:15:29 +02001166 self.write('f_%s(' % node.name)
Christoph Hack80909862008-04-14 01:35:10 +02001167 func = self.environment.filters.get(node.name)
Armin Ronacher0611e492008-04-25 23:44:14 +02001168 if func is None:
1169 raise TemplateAssertionError('no filter named %r' % node.name,
1170 node.lineno, self.filename)
Christoph Hack80909862008-04-14 01:35:10 +02001171 if getattr(func, 'contextfilter', False):
1172 self.write('context, ')
Armin Ronacher9a027f42008-04-17 11:13:40 +02001173 elif getattr(func, 'environmentfilter', False):
1174 self.write('environment, ')
Christoph Hack80909862008-04-14 01:35:10 +02001175 if isinstance(node.node, nodes.Filter):
1176 self.visit_Filter(node.node, frame, initial)
1177 elif node.node is None:
Armin Ronacherfa865fb2008-04-12 22:11:53 +02001178 self.write(initial)
1179 else:
Armin Ronacherfa865fb2008-04-12 22:11:53 +02001180 self.visit(node.node, frame)
Armin Ronacherd55ab532008-04-09 16:13:39 +02001181 self.signature(node, frame)
1182 self.write(')')
Armin Ronacher8efc5222008-04-08 14:47:40 +02001183
1184 def visit_Test(self, node, frame):
Armin Ronacherf059ec12008-04-11 22:21:00 +02001185 self.write('t_%s(' % node.name)
Armin Ronacher0611e492008-04-25 23:44:14 +02001186 if node.name not in self.environment.tests:
1187 raise TemplateAssertionError('no test named %r' % node.name,
1188 node.lineno, self.filename)
Armin Ronacher8efc5222008-04-08 14:47:40 +02001189 self.visit(node.node, frame)
1190 self.signature(node, frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +02001191 self.write(')')
Armin Ronacher8efc5222008-04-08 14:47:40 +02001192
Armin Ronacher3d8b7842008-04-13 13:16:50 +02001193 def visit_CondExpr(self, node, frame):
1194 if not have_condexpr:
1195 self.write('((')
1196 self.visit(node.test, frame)
1197 self.write(') and (')
1198 self.visit(node.expr1, frame)
1199 self.write(',) or (')
1200 self.visit(node.expr2, frame)
1201 self.write(',))[0]')
1202 else:
1203 self.write('(')
1204 self.visit(node.expr1, frame)
1205 self.write(' if ')
1206 self.visit(node.test, frame)
1207 self.write(' else ')
1208 self.visit(node.expr2, frame)
1209 self.write(')')
1210
Armin Ronacher71082072008-04-12 14:19:36 +02001211 def visit_Call(self, node, frame, extra_kwargs=None):
Armin Ronacherc63243e2008-04-14 22:53:58 +02001212 if self.environment.sandboxed:
1213 self.write('environment.call(')
Armin Ronacher8efc5222008-04-08 14:47:40 +02001214 self.visit(node.node, frame)
Armin Ronacherc63243e2008-04-14 22:53:58 +02001215 self.write(self.environment.sandboxed and ', ' or '(')
Armin Ronacher71082072008-04-12 14:19:36 +02001216 self.signature(node, frame, False, extra_kwargs)
Armin Ronacher8efc5222008-04-08 14:47:40 +02001217 self.write(')')
1218
1219 def visit_Keyword(self, node, frame):
Armin Ronacher2e9396b2008-04-16 14:21:57 +02001220 self.write(node.key + '=')
Armin Ronacher8efc5222008-04-08 14:47:40 +02001221 self.visit(node.value, frame)