blob: 83e07e69b507d7ea5c964bfba5ed06c9539bb73b [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 Ronachere791c2a2008-04-07 18:39:54 +020012from random import randrange
Armin Ronachere791c2a2008-04-07 18:39:54 +020013from cStringIO import StringIO
14from jinja2 import nodes
15from jinja2.visitor import NodeVisitor, NodeTransformer
16from jinja2.exceptions import TemplateAssertionError
Armin Ronacher4dfc9752008-04-09 15:03:29 +020017from jinja2.runtime import StaticLoopContext
Armin Ronachere791c2a2008-04-07 18:39:54 +020018
19
20operators = {
21 'eq': '==',
22 'ne': '!=',
23 'gt': '>',
24 'gteq': '>=',
25 'lt': '<',
26 'lteq': '<=',
27 'in': 'in',
28 'notin': 'not in'
29}
30
31
Christoph Hack65642a52008-04-08 14:46:56 +020032def generate(node, environment, filename, stream=None):
Armin Ronacherbcb7c532008-04-11 16:30:34 +020033 """Generate the python source for a node tree."""
Armin Ronachere791c2a2008-04-07 18:39:54 +020034 is_child = node.find(nodes.Extends) is not None
Christoph Hack65642a52008-04-08 14:46:56 +020035 generator = CodeGenerator(environment, is_child, filename, stream)
Armin Ronachere791c2a2008-04-07 18:39:54 +020036 generator.visit(node)
37 if stream is None:
38 return generator.stream.getvalue()
39
40
Armin Ronacher4dfc9752008-04-09 15:03:29 +020041def has_safe_repr(value):
42 """Does the node have a safe representation?"""
Armin Ronacherd55ab532008-04-09 16:13:39 +020043 if value is None or value is NotImplemented or value is Ellipsis:
Armin Ronacher4dfc9752008-04-09 15:03:29 +020044 return True
Armin Ronacherd55ab532008-04-09 16:13:39 +020045 if isinstance(value, (bool, int, long, float, complex, basestring,
46 StaticLoopContext)):
Armin Ronacher4dfc9752008-04-09 15:03:29 +020047 return True
Armin Ronacherd55ab532008-04-09 16:13:39 +020048 if isinstance(value, (tuple, list, set, frozenset)):
Armin Ronacher4dfc9752008-04-09 15:03:29 +020049 for item in value:
50 if not has_safe_repr(item):
51 return False
52 return True
53 elif isinstance(value, dict):
54 for key, value in value.iteritems():
55 if not has_safe_repr(key):
56 return False
57 if not has_safe_repr(value):
58 return False
59 return True
60 return False
61
62
Armin Ronachere791c2a2008-04-07 18:39:54 +020063class Identifiers(object):
64 """Tracks the status of identifiers in frames."""
65
66 def __init__(self):
67 # variables that are known to be declared (probably from outer
68 # frames or because they are special for the frame)
69 self.declared = set()
70
71 # names that are accessed without being explicitly declared by
72 # this one or any of the outer scopes. Names can appear both in
73 # declared and undeclared.
74 self.undeclared = set()
75
76 # names that are declared locally
77 self.declared_locally = set()
78
79 # names that are declared by parameters
80 self.declared_parameter = set()
81
Armin Ronacherf059ec12008-04-11 22:21:00 +020082 # filters/tests that are referenced
Armin Ronacherd4c64f72008-04-11 17:15:29 +020083 self.filters = set()
Armin Ronacherf059ec12008-04-11 22:21:00 +020084 self.tests = set()
Christoph Hack65642a52008-04-08 14:46:56 +020085
Armin Ronachere791c2a2008-04-07 18:39:54 +020086 def add_special(self, name):
87 """Register a special name like `loop`."""
88 self.undeclared.discard(name)
89 self.declared.add(name)
90
Armin Ronacher4f62a9f2008-04-08 18:09:13 +020091 def is_declared(self, name, local_only=False):
Armin Ronachere791c2a2008-04-07 18:39:54 +020092 """Check if a name is declared in this or an outer scope."""
Armin Ronacher4f62a9f2008-04-08 18:09:13 +020093 if name in self.declared_locally or name in self.declared_parameter:
94 return True
95 if local_only:
96 return False
97 return name in self.declared
Armin Ronachere791c2a2008-04-07 18:39:54 +020098
99 def find_shadowed(self):
100 """Find all the shadowed names."""
101 return self.declared & (self.declared_locally | self.declared_parameter)
102
103
104class Frame(object):
Armin Ronacher75cfb862008-04-11 13:47:22 +0200105 """Holds compile time information for us."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200106
107 def __init__(self, parent=None):
108 self.identifiers = Identifiers()
Armin Ronacher75cfb862008-04-11 13:47:22 +0200109 # a toplevel frame is the root + soft frames such as if conditions.
Armin Ronacher8efc5222008-04-08 14:47:40 +0200110 self.toplevel = False
Armin Ronacher75cfb862008-04-11 13:47:22 +0200111 # the root frame is basically just the outermost frame, so no if
112 # conditions. This information is used to optimize inheritance
113 # situations.
114 self.rootlevel = False
Armin Ronachere791c2a2008-04-07 18:39:54 +0200115 self.parent = parent
Armin Ronacher8efc5222008-04-08 14:47:40 +0200116 self.block = parent and parent.block or None
Armin Ronachere791c2a2008-04-07 18:39:54 +0200117 if parent is not None:
118 self.identifiers.declared.update(
119 parent.identifiers.declared |
Armin Ronachere791c2a2008-04-07 18:39:54 +0200120 parent.identifiers.declared_locally |
121 parent.identifiers.declared_parameter
122 )
123
Armin Ronacher8efc5222008-04-08 14:47:40 +0200124 def copy(self):
125 """Create a copy of the current one."""
126 rv = copy(self)
127 rv.identifiers = copy(self)
128 return rv
129
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200130 def inspect(self, nodes, hard_scope=False):
131 """Walk the node and check for identifiers. If the scope
132 is hard (eg: enforce on a python level) overrides from outer
133 scopes are tracked differently.
134 """
135 visitor = FrameIdentifierVisitor(self.identifiers, hard_scope)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200136 for node in nodes:
137 visitor.visit(node)
138
139 def inner(self):
140 """Return an inner frame."""
141 return Frame(self)
142
Armin Ronacher75cfb862008-04-11 13:47:22 +0200143 def soft(self):
144 """Return a soft frame. A soft frame may not be modified as
145 standalone thing as it shares the resources with the frame it
146 was created of, but it's not a rootlevel frame any longer.
147 """
148 rv = copy(self)
149 rv.rootlevel = False
150 return rv
151
Armin Ronachere791c2a2008-04-07 18:39:54 +0200152
153class FrameIdentifierVisitor(NodeVisitor):
154 """A visitor for `Frame.inspect`."""
155
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200156 def __init__(self, identifiers, hard_scope):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200157 self.identifiers = identifiers
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200158 self.hard_scope = hard_scope
Armin Ronachere791c2a2008-04-07 18:39:54 +0200159
160 def visit_Name(self, node):
161 """All assignments to names go through this function."""
162 if node.ctx in ('store', 'param'):
163 self.identifiers.declared_locally.add(node.name)
164 elif node.ctx == 'load':
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200165 if not self.identifiers.is_declared(node.name, self.hard_scope):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200166 self.identifiers.undeclared.add(node.name)
167
Armin Ronacherd55ab532008-04-09 16:13:39 +0200168 def visit_Filter(self, node):
Armin Ronacher449167d2008-04-11 17:55:05 +0200169 self.generic_visit(node)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200170 self.identifiers.filters.add(node.name)
171
172 def visit_Test(self, node):
173 self.generic_visit(node)
174 self.identifiers.tests.add(node.name)
Christoph Hack65642a52008-04-08 14:46:56 +0200175
Armin Ronachere791c2a2008-04-07 18:39:54 +0200176 def visit_Macro(self, node):
177 """Macros set local."""
178 self.identifiers.declared_locally.add(node.name)
179
Armin Ronacherf059ec12008-04-11 22:21:00 +0200180 def visit_Include(self, node):
181 """Some includes set local."""
182 self.generic_visit(node)
183 if node.target is not None:
184 self.identifiers.declared_locally.add(node.target)
185
Armin Ronacherebe55aa2008-04-10 20:51:23 +0200186 def visit_Assign(self, node):
187 """Visit assignments in the correct order."""
188 self.visit(node.node)
189 self.visit(node.target)
190
Armin Ronachere791c2a2008-04-07 18:39:54 +0200191 # stop traversing at instructions that have their own scope.
Armin Ronacher8efc5222008-04-08 14:47:40 +0200192 visit_Block = visit_CallBlock = visit_FilterBlock = \
Armin Ronachere791c2a2008-04-07 18:39:54 +0200193 visit_For = lambda s, n: None
194
195
Armin Ronacher75cfb862008-04-11 13:47:22 +0200196class CompilerExit(Exception):
197 """Raised if the compiler encountered a situation where it just
198 doesn't make sense to further process the code. Any block that
199 raises such an exception is not further processed."""
200
201
Armin Ronachere791c2a2008-04-07 18:39:54 +0200202class CodeGenerator(NodeVisitor):
203
Christoph Hack65642a52008-04-08 14:46:56 +0200204 def __init__(self, environment, is_child, filename, stream=None):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200205 if stream is None:
206 stream = StringIO()
Christoph Hack65642a52008-04-08 14:46:56 +0200207 self.environment = environment
Armin Ronachere791c2a2008-04-07 18:39:54 +0200208 self.is_child = is_child
209 self.filename = filename
210 self.stream = stream
211 self.blocks = {}
212 self.indentation = 0
213 self.new_lines = 0
214 self.last_identifier = 0
Armin Ronacher7fb38972008-04-11 13:54:28 +0200215 self.extends_so_far = 0
Armin Ronacher75cfb862008-04-11 13:47:22 +0200216 self.has_known_extends = False
Armin Ronachere791c2a2008-04-07 18:39:54 +0200217 self._last_line = 0
218 self._first_write = True
219
220 def temporary_identifier(self):
221 self.last_identifier += 1
222 return 't%d' % self.last_identifier
223
224 def indent(self):
225 self.indentation += 1
226
Armin Ronacher8efc5222008-04-08 14:47:40 +0200227 def outdent(self, step=1):
228 self.indentation -= step
Armin Ronachere791c2a2008-04-07 18:39:54 +0200229
230 def blockvisit(self, nodes, frame, force_generator=False):
231 self.indent()
232 if force_generator:
233 self.writeline('if 0: yield None')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200234 try:
235 for node in nodes:
236 self.visit(node, frame)
237 except CompilerExit:
238 pass
Armin Ronachere791c2a2008-04-07 18:39:54 +0200239 self.outdent()
240
241 def write(self, x):
242 if self.new_lines:
243 if not self._first_write:
244 self.stream.write('\n' * self.new_lines)
245 self._first_write = False
246 self.stream.write(' ' * self.indentation)
247 self.new_lines = 0
248 self.stream.write(x)
249
250 def writeline(self, x, node=None, extra=0):
251 self.newline(node, extra)
252 self.write(x)
253
254 def newline(self, node=None, extra=0):
255 self.new_lines = max(self.new_lines, 1 + extra)
256 if node is not None and node.lineno != self._last_line:
257 self.write('# line: %s' % node.lineno)
258 self.new_lines = 1
259 self._last_line = node.lineno
260
Armin Ronacher71082072008-04-12 14:19:36 +0200261 def signature(self, node, frame, have_comma=True, extra_kwargs=None):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200262 have_comma = have_comma and [True] or []
263 def touch_comma():
264 if have_comma:
265 self.write(', ')
266 else:
267 have_comma.append(True)
268
269 for arg in node.args:
270 touch_comma()
271 self.visit(arg, frame)
272 for kwarg in node.kwargs:
273 touch_comma()
274 self.visit(kwarg, frame)
Armin Ronacher71082072008-04-12 14:19:36 +0200275 if extra_kwargs is not None:
276 touch_comma()
277 self.write(extra_kwargs)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200278 if node.dyn_args:
279 touch_comma()
Armin Ronacher71082072008-04-12 14:19:36 +0200280 self.write('*')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200281 self.visit(node.dyn_args, frame)
282 if node.dyn_kwargs:
283 touch_comma()
Armin Ronacher71082072008-04-12 14:19:36 +0200284 self.write('**')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200285 self.visit(node.dyn_kwargs, frame)
286
Armin Ronachere791c2a2008-04-07 18:39:54 +0200287 def pull_locals(self, frame, no_indent=False):
288 if not no_indent:
289 self.indent()
290 for name in frame.identifiers.undeclared:
291 self.writeline('l_%s = context[%r]' % (name, name))
Armin Ronacherd4c64f72008-04-11 17:15:29 +0200292 for name in frame.identifiers.filters:
293 self.writeline('f_%s = environment.filters[%r]' % (name, name))
Armin Ronacherf059ec12008-04-11 22:21:00 +0200294 for name in frame.identifiers.tests:
295 self.writeline('t_%s = environment.tests[%r]' % (name, name))
Armin Ronachere791c2a2008-04-07 18:39:54 +0200296 if not no_indent:
297 self.outdent()
298
Armin Ronacher71082072008-04-12 14:19:36 +0200299 def function_scoping(self, node, frame):
300 func_frame = frame.inner()
301 func_frame.inspect(node.iter_child_nodes(), hard_scope=True)
302
303 # variables that are undeclared (accessed before declaration) and
304 # declared locally *and* part of an outside scope raise a template
305 # assertion error. Reason: we can't generate reasonable code from
306 # it without aliasing all the variables. XXX: alias them ^^
307 overriden_closure_vars = (
308 func_frame.identifiers.undeclared &
309 func_frame.identifiers.declared &
310 (func_frame.identifiers.declared_locally |
311 func_frame.identifiers.declared_parameter)
312 )
313 if overriden_closure_vars:
314 vars = ', '.join(sorted(overriden_closure_vars))
315 raise TemplateAssertionError('It\'s not possible to set and '
316 'access variables derived from '
317 'an outer scope! (affects: %s' %
318 vars, node.lineno, self.filename)
319
320 # remove variables from a closure from the frame's undeclared
321 # identifiers.
322 func_frame.identifiers.undeclared -= (
323 func_frame.identifiers.undeclared &
324 func_frame.identifiers.declared
325 )
326
327 func_frame.accesses_arguments = False
328 func_frame.accesses_caller = False
329 func_frame.arguments = args = ['l_' + x.name for x in node.args]
330
331 if 'arguments' in func_frame.identifiers.undeclared:
332 func_frame.accesses_arguments = True
333 func_frame.identifiers.add_special('arguments')
334 args.append('l_arguments')
335 if 'caller' in func_frame.identifiers.undeclared:
336 func_frame.accesses_caller = True
337 func_frame.identifiers.add_special('caller')
338 args.append('l_caller')
339 return func_frame
340
Armin Ronachere791c2a2008-04-07 18:39:54 +0200341 # -- Visitors
342
343 def visit_Template(self, node, frame=None):
344 assert frame is None, 'no root frame allowed'
345 self.writeline('from jinja2.runtime import *')
346 self.writeline('filename = %r' % self.filename)
Armin Ronacher8edbe492008-04-10 20:43:43 +0200347
Armin Ronacher75cfb862008-04-11 13:47:22 +0200348 # do we have an extends tag at all? If not, we can save some
349 # overhead by just not processing any inheritance code.
350 have_extends = node.find(nodes.Extends) is not None
351
Armin Ronacher8edbe492008-04-10 20:43:43 +0200352 # find all blocks
353 for block in node.find_all(nodes.Block):
354 if block.name in self.blocks:
355 raise TemplateAssertionError('block %r defined twice' %
356 block.name, block.lineno,
357 self.filename)
358 self.blocks[block.name] = block
Armin Ronachere791c2a2008-04-07 18:39:54 +0200359
Armin Ronacher8efc5222008-04-08 14:47:40 +0200360 # generate the root render function.
Armin Ronacherf059ec12008-04-11 22:21:00 +0200361 self.writeline('def root(globals, environment=environment'
362 ', standalone=False):', extra=1)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200363 self.indent()
Armin Ronacherf059ec12008-04-11 22:21:00 +0200364 self.writeline('context = TemplateContext(globals, %r, blocks'
365 ', standalone)' % self.filename)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200366 if have_extends:
367 self.writeline('parent_root = None')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200368 self.outdent()
Armin Ronacher75cfb862008-04-11 13:47:22 +0200369
370 # process the root
Armin Ronachere791c2a2008-04-07 18:39:54 +0200371 frame = Frame()
372 frame.inspect(node.body)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200373 frame.toplevel = frame.rootlevel = True
Armin Ronachere791c2a2008-04-07 18:39:54 +0200374 self.pull_locals(frame)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200375 self.indent()
376 self.writeline('yield context')
377 self.outdent()
378 self.blockvisit(node.body, frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200379
Armin Ronacher8efc5222008-04-08 14:47:40 +0200380 # make sure that the parent root is called.
Armin Ronacher75cfb862008-04-11 13:47:22 +0200381 if have_extends:
382 if not self.has_known_extends:
383 self.indent()
384 self.writeline('if parent_root is not None:')
385 self.indent()
Armin Ronacherf059ec12008-04-11 22:21:00 +0200386 self.writeline('stream = parent_root(context)')
387 self.writeline('stream.next()')
388 self.writeline('for event in stream:')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200389 self.indent()
390 self.writeline('yield event')
Armin Ronacher7a52df82008-04-11 13:58:22 +0200391 self.outdent(1 + self.has_known_extends)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200392
393 # at this point we now have the blocks collected and can visit them too.
394 for name, block in self.blocks.iteritems():
395 block_frame = Frame()
396 block_frame.inspect(block.body)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200397 block_frame.block = name
Armin Ronacherd4c64f72008-04-11 17:15:29 +0200398 self.writeline('def block_%s(context, environment=environment):'
399 % name, block, 1)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200400 self.pull_locals(block_frame)
401 self.blockvisit(block.body, block_frame, True)
402
Armin Ronacher75cfb862008-04-11 13:47:22 +0200403 self.writeline('blocks = {%s}' % ', '.join('%r: block_%s' % (x, x)
404 for x in self.blocks), extra=1)
405
Armin Ronachere791c2a2008-04-07 18:39:54 +0200406 def visit_Block(self, node, frame):
407 """Call a block and register it for the template."""
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200408 level = 1
Armin Ronacher75cfb862008-04-11 13:47:22 +0200409 if frame.toplevel:
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200410 # if we know that we are a child template, there is no need to
411 # check if we are one
412 if self.has_known_extends:
413 return
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200414 if self.extends_so_far > 0:
415 self.writeline('if parent_root is None:')
416 self.indent()
417 level += 1
418 self.writeline('for event in context.blocks[%r][-1](context):' % node.name)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200419 self.indent()
420 self.writeline('yield event')
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200421 self.outdent(level)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200422
423 def visit_Extends(self, node, frame):
424 """Calls the extender."""
Armin Ronacher8efc5222008-04-08 14:47:40 +0200425 if not frame.toplevel:
426 raise TemplateAssertionError('cannot use extend from a non '
427 'top-level scope', node.lineno,
428 self.filename)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200429
Armin Ronacher7fb38972008-04-11 13:54:28 +0200430 # if the number of extends statements in general is zero so
431 # far, we don't have to add a check if something extended
432 # the template before this one.
433 if self.extends_so_far > 0:
Armin Ronacher75cfb862008-04-11 13:47:22 +0200434
Armin Ronacher7fb38972008-04-11 13:54:28 +0200435 # if we have a known extends we just add a template runtime
436 # error into the generated code. We could catch that at compile
437 # time too, but i welcome it not to confuse users by throwing the
438 # same error at different times just "because we can".
439 if not self.has_known_extends:
440 self.writeline('if parent_root is not None:')
441 self.indent()
442 self.writeline('raise TemplateRuntimeError(%r)' %
443 'extended multiple times')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200444
Armin Ronacher7fb38972008-04-11 13:54:28 +0200445 # if we have a known extends already we don't need that code here
446 # as we know that the template execution will end here.
447 if self.has_known_extends:
448 raise CompilerExit()
449 self.outdent()
450
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200451 self.writeline('parent_root = environment.get_template(', node, 1)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200452 self.visit(node.template, frame)
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200453 self.write(', %r).root_render_func' % self.filename)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200454
455 # if this extends statement was in the root level we can take
456 # advantage of that information and simplify the generated code
457 # in the top level from this point onwards
458 self.has_known_extends = True
Armin Ronachere791c2a2008-04-07 18:39:54 +0200459
Armin Ronacher7fb38972008-04-11 13:54:28 +0200460 # and now we have one more
461 self.extends_so_far += 1
462
Armin Ronacherf059ec12008-04-11 22:21:00 +0200463 def visit_Include(self, node, frame):
464 """Handles includes."""
465 # simpled include is include into a variable. This kind of
466 # include works the same on every level, so we handle it first.
467 if node.target is not None:
468 self.writeline('l_%s = ' % node.target, node)
469 if frame.toplevel:
470 self.write('context[%r] = ' % node.target)
471 self.write('IncludedTemplate(environment, context, ')
472 self.visit(node.template, frame)
473 self.write(')')
474 return
475
476 self.writeline('included_stream = environment.get_template(', node)
477 self.visit(node.template, frame)
478 self.write(').root_render_func(context, standalone=True)')
479 self.writeline('included_context = included_stream.next()')
480 self.writeline('for event in included_stream:')
481 self.indent()
482 self.writeline('yield event')
483 self.outdent()
484
485 # if we have a toplevel include the exported variables are copied
486 # into the current context without exporting them. context.udpate
487 # does *not* mark the variables as exported
488 if frame.toplevel:
489 self.writeline('context.update(included_context.get_exported())')
490
Armin Ronachere791c2a2008-04-07 18:39:54 +0200491 def visit_For(self, node, frame):
492 loop_frame = frame.inner()
493 loop_frame.inspect(node.iter_child_nodes())
Armin Ronachere791c2a2008-04-07 18:39:54 +0200494 extended_loop = bool(node.else_) or \
495 'loop' in loop_frame.identifiers.undeclared
Armin Ronacher8efc5222008-04-08 14:47:40 +0200496 loop_frame.identifiers.add_special('loop')
Armin Ronachere791c2a2008-04-07 18:39:54 +0200497
498 # make sure we "backup" overridden, local identifiers
499 # TODO: we should probably optimize this and check if the
500 # identifier is in use afterwards.
501 aliases = {}
502 for name in loop_frame.identifiers.find_shadowed():
503 aliases[name] = ident = self.temporary_identifier()
504 self.writeline('%s = l_%s' % (ident, name))
505
506 self.pull_locals(loop_frame, True)
507
508 self.newline(node)
509 if node.else_:
510 self.writeline('l_loop = None')
511 self.write('for ')
512 self.visit(node.target, loop_frame)
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200513 self.write(extended_loop and ', l_loop in LoopContext(' or ' in ')
Armin Ronachere791c2a2008-04-07 18:39:54 +0200514 self.visit(node.iter, loop_frame)
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200515 if 'loop' in aliases:
516 self.write(', ' + aliases['loop'])
Armin Ronachere791c2a2008-04-07 18:39:54 +0200517 self.write(extended_loop and '):' or ':')
518 self.blockvisit(node.body, loop_frame)
519
520 if node.else_:
521 self.writeline('if l_loop is None:')
522 self.blockvisit(node.else_, loop_frame)
523
Armin Ronacherd4c64f72008-04-11 17:15:29 +0200524 # reset the aliases if there are any.
Armin Ronachere791c2a2008-04-07 18:39:54 +0200525 for name, alias in aliases.iteritems():
Armin Ronacher8efc5222008-04-08 14:47:40 +0200526 self.writeline('l_%s = %s' % (name, alias))
Armin Ronachere791c2a2008-04-07 18:39:54 +0200527
528 def visit_If(self, node, frame):
Armin Ronacher75cfb862008-04-11 13:47:22 +0200529 if_frame = frame.soft()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200530 self.writeline('if ', node)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200531 self.visit(node.test, if_frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200532 self.write(':')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200533 self.blockvisit(node.body, if_frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200534 if node.else_:
535 self.writeline('else:')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200536 self.blockvisit(node.else_, if_frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200537
Armin Ronacher8efc5222008-04-08 14:47:40 +0200538 def visit_Macro(self, node, frame):
Armin Ronacher71082072008-04-12 14:19:36 +0200539 macro_frame = self.function_scoping(node, frame)
540 args = macro_frame.arguments
Armin Ronacher8efc5222008-04-08 14:47:40 +0200541 self.writeline('def macro(%s):' % ', '.join(args), node)
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200542 self.pull_locals(macro_frame)
Armin Ronacher71082072008-04-12 14:19:36 +0200543 self.blockvisit(node.body, macro_frame, True)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200544 self.newline()
545 if frame.toplevel:
546 self.write('context[%r] = ' % node.name)
547 arg_tuple = ', '.join(repr(x.name) for x in node.args)
548 if len(node.args) == 1:
549 arg_tuple += ','
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200550 self.write('l_%s = Macro(macro, %r, (%s), (' % (node.name, node.name,
551 arg_tuple))
552 for arg in node.defaults:
553 self.visit(arg)
554 self.write(', ')
Armin Ronacher71082072008-04-12 14:19:36 +0200555 self.write('), %r, %r)' % (
556 macro_frame.accesses_arguments,
557 macro_frame.accesses_caller
558 ))
559
560 def visit_CallBlock(self, node, frame):
561 call_frame = self.function_scoping(node, frame)
562 args = call_frame.arguments
563 self.writeline('def call(%s):' % ', '.join(args), node)
564 self.blockvisit(node.body, call_frame, node)
565 arg_tuple = ', '.join(repr(x.name) for x in node.args)
566 if len(node.args) == 1:
567 arg_tuple += ','
568 self.writeline('caller = Macro(call, None, (%s), (' % arg_tuple)
569 for arg in node.defaults:
570 self.visit(arg)
571 self.write(', ')
572 self.write('), %r, False)' % call_frame.accesses_arguments)
573 self.writeline('yield ', node)
574 self.visit_Call(node.call, call_frame, extra_kwargs='caller=caller')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200575
Armin Ronachere791c2a2008-04-07 18:39:54 +0200576 def visit_ExprStmt(self, node, frame):
577 self.newline(node)
578 self.visit(node, frame)
579
580 def visit_Output(self, node, frame):
Armin Ronacher75cfb862008-04-11 13:47:22 +0200581 # if we have a known extends statement, we don't output anything
Armin Ronacher7a52df82008-04-11 13:58:22 +0200582 if self.has_known_extends and frame.toplevel:
Armin Ronacher75cfb862008-04-11 13:47:22 +0200583 return
Armin Ronachere791c2a2008-04-07 18:39:54 +0200584
Armin Ronacher75cfb862008-04-11 13:47:22 +0200585 self.newline(node)
Armin Ronacher8edbe492008-04-10 20:43:43 +0200586 if self.environment.finalize is unicode:
587 finalizer = 'unicode'
Armin Ronacherf059ec12008-04-11 22:21:00 +0200588 have_finalizer = False
Armin Ronacher8edbe492008-04-10 20:43:43 +0200589 else:
590 finalizer = 'context.finalize'
Armin Ronacherf059ec12008-04-11 22:21:00 +0200591 have_finalizer = False
Armin Ronacher8edbe492008-04-10 20:43:43 +0200592
Armin Ronacher7fb38972008-04-11 13:54:28 +0200593 # if we are in the toplevel scope and there was already an extends
594 # statement we have to add a check that disables our yield(s) here
595 # so that they don't appear in the output.
596 outdent_later = False
597 if frame.toplevel and self.extends_so_far != 0:
Armin Ronacher75cfb862008-04-11 13:47:22 +0200598 self.writeline('if parent_root is None:')
599 self.indent()
Armin Ronacher7fb38972008-04-11 13:54:28 +0200600 outdent_later = True
Armin Ronacher75cfb862008-04-11 13:47:22 +0200601
Armin Ronachere791c2a2008-04-07 18:39:54 +0200602 # try to evaluate as many chunks as possible into a static
603 # string at compile time.
604 body = []
605 for child in node.nodes:
606 try:
607 const = unicode(child.as_const())
608 except:
609 body.append(child)
610 continue
611 if body and isinstance(body[-1], list):
612 body[-1].append(const)
613 else:
614 body.append([const])
615
616 # if we have less than 3 nodes we just yield them
617 if len(body) < 3:
618 for item in body:
619 if isinstance(item, list):
620 self.writeline('yield %s' % repr(u''.join(item)))
621 else:
622 self.newline(item)
Armin Ronacher8edbe492008-04-10 20:43:43 +0200623 self.write('yield %s(' % finalizer)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200624 self.visit(item, frame)
625 self.write(')')
626
627 # otherwise we create a format string as this is faster in that case
628 else:
629 format = []
630 arguments = []
631 for item in body:
632 if isinstance(item, list):
633 format.append(u''.join(item).replace('%', '%%'))
634 else:
635 format.append('%s')
636 arguments.append(item)
637 self.writeline('yield %r %% (' % u''.join(format))
638 idx = -1
639 for idx, argument in enumerate(arguments):
640 if idx:
641 self.write(', ')
Armin Ronacherf059ec12008-04-11 22:21:00 +0200642 if have_finalizer:
Armin Ronacher8edbe492008-04-10 20:43:43 +0200643 self.write('(')
Armin Ronachere791c2a2008-04-07 18:39:54 +0200644 self.visit(argument, frame)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200645 if have_finalizer:
Armin Ronacher8edbe492008-04-10 20:43:43 +0200646 self.write(')')
Armin Ronachere791c2a2008-04-07 18:39:54 +0200647 self.write(idx == 0 and ',)' or ')')
648
Armin Ronacher7fb38972008-04-11 13:54:28 +0200649 if outdent_later:
Armin Ronacher75cfb862008-04-11 13:47:22 +0200650 self.outdent()
651
Armin Ronacher8efc5222008-04-08 14:47:40 +0200652 def visit_Assign(self, node, frame):
653 self.newline(node)
654 # toplevel assignments however go into the local namespace and
655 # the current template's context. We create a copy of the frame
656 # here and add a set so that the Name visitor can add the assigned
657 # names here.
658 if frame.toplevel:
659 assignment_frame = frame.copy()
660 assignment_frame.assigned_names = set()
661 else:
662 assignment_frame = frame
663 self.visit(node.target, assignment_frame)
664 self.write(' = ')
665 self.visit(node.node, frame)
Armin Ronacher9706fab2008-04-08 18:49:56 +0200666
667 # make sure toplevel assignments are added to the context.
Armin Ronacher8efc5222008-04-08 14:47:40 +0200668 if frame.toplevel:
669 for name in assignment_frame.assigned_names:
670 self.writeline('context[%r] = l_%s' % (name, name))
671
Armin Ronachere791c2a2008-04-07 18:39:54 +0200672 def visit_Name(self, node, frame):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200673 if frame.toplevel and node.ctx == 'store':
674 frame.assigned_names.add(node.name)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200675 self.write('l_' + node.name)
676
677 def visit_Const(self, node, frame):
678 val = node.value
679 if isinstance(val, float):
680 # XXX: add checks for infinity and nan
681 self.write(str(val))
682 else:
683 self.write(repr(val))
684
Armin Ronacher8efc5222008-04-08 14:47:40 +0200685 def visit_Tuple(self, node, frame):
686 self.write('(')
687 idx = -1
688 for idx, item in enumerate(node.items):
689 if idx:
690 self.write(', ')
691 self.visit(item, frame)
692 self.write(idx == 0 and ',)' or ')')
693
Armin Ronacher8edbe492008-04-10 20:43:43 +0200694 def visit_List(self, node, frame):
695 self.write('[')
696 for idx, item in enumerate(node.items):
697 if idx:
698 self.write(', ')
699 self.visit(item, frame)
700 self.write(']')
701
702 def visit_Dict(self, node, frame):
703 self.write('{')
704 for idx, item in enumerate(node.items):
705 if idx:
706 self.write(', ')
707 self.visit(item.key, frame)
708 self.write(': ')
709 self.visit(item.value, frame)
710 self.write('}')
711
Armin Ronachere791c2a2008-04-07 18:39:54 +0200712 def binop(operator):
713 def visitor(self, node, frame):
714 self.write('(')
715 self.visit(node.left, frame)
716 self.write(' %s ' % operator)
717 self.visit(node.right, frame)
718 self.write(')')
719 return visitor
720
721 def uaop(operator):
722 def visitor(self, node, frame):
723 self.write('(' + operator)
724 self.visit(node.node)
725 self.write(')')
726 return visitor
727
728 visit_Add = binop('+')
729 visit_Sub = binop('-')
730 visit_Mul = binop('*')
731 visit_Div = binop('/')
732 visit_FloorDiv = binop('//')
733 visit_Pow = binop('**')
734 visit_Mod = binop('%')
735 visit_And = binop('and')
736 visit_Or = binop('or')
737 visit_Pos = uaop('+')
738 visit_Neg = uaop('-')
739 visit_Not = uaop('not ')
740 del binop, uaop
741
742 def visit_Compare(self, node, frame):
743 self.visit(node.expr, frame)
744 for op in node.ops:
745 self.visit(op, frame)
746
747 def visit_Operand(self, node, frame):
748 self.write(' %s ' % operators[node.op])
749 self.visit(node.expr, frame)
750
751 def visit_Subscript(self, node, frame):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200752 if isinstance(node.arg, nodes.Slice):
753 self.visit(node.node, frame)
754 self.write('[')
755 self.visit(node.arg, frame)
756 self.write(']')
757 return
758 try:
759 const = node.arg.as_const()
760 have_const = True
761 except nodes.Impossible:
762 have_const = False
763 if have_const:
764 if isinstance(const, (int, long, float)):
765 self.visit(node.node, frame)
766 self.write('[%s]' % const)
767 return
768 self.write('subscribe(')
Armin Ronachere791c2a2008-04-07 18:39:54 +0200769 self.visit(node.node, frame)
770 self.write(', ')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200771 if have_const:
772 self.write(repr(const))
773 else:
774 self.visit(node.arg, frame)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200775 self.write(')')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200776
777 def visit_Slice(self, node, frame):
778 if node.start is not None:
779 self.visit(node.start, frame)
780 self.write(':')
781 if node.stop is not None:
782 self.visit(node.stop, frame)
783 if node.step is not None:
784 self.write(':')
785 self.visit(node.step, frame)
786
787 def visit_Filter(self, node, frame):
Armin Ronacherd4c64f72008-04-11 17:15:29 +0200788 self.write('f_%s(' % node.name)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200789 func = self.environment.filters.get(node.name)
790 if getattr(func, 'contextfilter', False):
791 self.write('context, ')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200792 self.visit(node.node, frame)
Armin Ronacherd55ab532008-04-09 16:13:39 +0200793 self.signature(node, frame)
794 self.write(')')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200795
796 def visit_Test(self, node, frame):
Armin Ronacherf059ec12008-04-11 22:21:00 +0200797 self.write('t_%s(' % node.name)
798 func = self.environment.tests.get(node.name)
799 if getattr(func, 'contexttest', False):
800 self.write('context, ')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200801 self.visit(node.node, frame)
802 self.signature(node, frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200803 self.write(')')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200804
Armin Ronacher71082072008-04-12 14:19:36 +0200805 def visit_Call(self, node, frame, extra_kwargs=None):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200806 self.visit(node.node, frame)
807 self.write('(')
Armin Ronacher71082072008-04-12 14:19:36 +0200808 self.signature(node, frame, False, extra_kwargs)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200809 self.write(')')
810
811 def visit_Keyword(self, node, frame):
812 self.visit(node.key, frame)
813 self.write('=')
814 self.visit(node.value, frame)