blob: e16617e93ca4aa115ae38dfeee94d325690061e5 [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
Armin Ronacher3d8b7842008-04-13 13:16:50 +020032try:
33 exec '(0 if 0 else 0)'
34except SyntaxError:
35 have_condexpr = False
36else:
37 have_condexpr = True
38
39
Christoph Hack65642a52008-04-08 14:46:56 +020040def generate(node, environment, filename, stream=None):
Armin Ronacherbcb7c532008-04-11 16:30:34 +020041 """Generate the python source for a node tree."""
Armin Ronachere791c2a2008-04-07 18:39:54 +020042 is_child = node.find(nodes.Extends) is not None
Christoph Hack65642a52008-04-08 14:46:56 +020043 generator = CodeGenerator(environment, is_child, filename, stream)
Armin Ronachere791c2a2008-04-07 18:39:54 +020044 generator.visit(node)
45 if stream is None:
46 return generator.stream.getvalue()
47
48
Armin Ronacher4dfc9752008-04-09 15:03:29 +020049def has_safe_repr(value):
50 """Does the node have a safe representation?"""
Armin Ronacherd55ab532008-04-09 16:13:39 +020051 if value is None or value is NotImplemented or value is Ellipsis:
Armin Ronacher4dfc9752008-04-09 15:03:29 +020052 return True
Armin Ronacherd55ab532008-04-09 16:13:39 +020053 if isinstance(value, (bool, int, long, float, complex, basestring,
54 StaticLoopContext)):
Armin Ronacher4dfc9752008-04-09 15:03:29 +020055 return True
Armin Ronacherd55ab532008-04-09 16:13:39 +020056 if isinstance(value, (tuple, list, set, frozenset)):
Armin Ronacher4dfc9752008-04-09 15:03:29 +020057 for item in value:
58 if not has_safe_repr(item):
59 return False
60 return True
61 elif isinstance(value, dict):
62 for key, value in value.iteritems():
63 if not has_safe_repr(key):
64 return False
65 if not has_safe_repr(value):
66 return False
67 return True
68 return False
69
70
Armin Ronachere791c2a2008-04-07 18:39:54 +020071class Identifiers(object):
72 """Tracks the status of identifiers in frames."""
73
74 def __init__(self):
75 # variables that are known to be declared (probably from outer
76 # frames or because they are special for the frame)
77 self.declared = set()
78
79 # names that are accessed without being explicitly declared by
80 # this one or any of the outer scopes. Names can appear both in
81 # declared and undeclared.
82 self.undeclared = set()
83
84 # names that are declared locally
85 self.declared_locally = set()
86
87 # names that are declared by parameters
88 self.declared_parameter = set()
89
Armin Ronacherf059ec12008-04-11 22:21:00 +020090 # filters/tests that are referenced
Armin Ronacherd4c64f72008-04-11 17:15:29 +020091 self.filters = set()
Armin Ronacherf059ec12008-04-11 22:21:00 +020092 self.tests = set()
Christoph Hack65642a52008-04-08 14:46:56 +020093
Armin Ronachere791c2a2008-04-07 18:39:54 +020094 def add_special(self, name):
95 """Register a special name like `loop`."""
96 self.undeclared.discard(name)
97 self.declared.add(name)
98
Armin Ronacher4f62a9f2008-04-08 18:09:13 +020099 def is_declared(self, name, local_only=False):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200100 """Check if a name is declared in this or an outer scope."""
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200101 if name in self.declared_locally or name in self.declared_parameter:
102 return True
103 if local_only:
104 return False
105 return name in self.declared
Armin Ronachere791c2a2008-04-07 18:39:54 +0200106
107 def find_shadowed(self):
108 """Find all the shadowed names."""
109 return self.declared & (self.declared_locally | self.declared_parameter)
110
111
112class Frame(object):
Armin Ronacher75cfb862008-04-11 13:47:22 +0200113 """Holds compile time information for us."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200114
115 def __init__(self, parent=None):
116 self.identifiers = Identifiers()
Armin Ronacher75cfb862008-04-11 13:47:22 +0200117 # a toplevel frame is the root + soft frames such as if conditions.
Armin Ronacher8efc5222008-04-08 14:47:40 +0200118 self.toplevel = False
Armin Ronacher75cfb862008-04-11 13:47:22 +0200119 # the root frame is basically just the outermost frame, so no if
120 # conditions. This information is used to optimize inheritance
121 # situations.
122 self.rootlevel = False
Armin Ronachere791c2a2008-04-07 18:39:54 +0200123 self.parent = parent
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200124 self.buffer = None
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200125 self.name_overrides = {}
Armin Ronacher8efc5222008-04-08 14:47:40 +0200126 self.block = parent and parent.block or None
Armin Ronachere791c2a2008-04-07 18:39:54 +0200127 if parent is not None:
128 self.identifiers.declared.update(
129 parent.identifiers.declared |
Armin Ronachere791c2a2008-04-07 18:39:54 +0200130 parent.identifiers.declared_locally |
131 parent.identifiers.declared_parameter
132 )
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200133 self.buffer = parent.buffer
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200134 self.name_overrides = parent.name_overrides.copy()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200135
Armin Ronacher8efc5222008-04-08 14:47:40 +0200136 def copy(self):
137 """Create a copy of the current one."""
138 rv = copy(self)
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200139 rv.identifiers = copy(self.identifiers)
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200140 rv.name_overrides = self.name_overrides.copy()
Armin Ronacher8efc5222008-04-08 14:47:40 +0200141 return rv
142
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200143 def inspect(self, nodes, hard_scope=False):
144 """Walk the node and check for identifiers. If the scope
145 is hard (eg: enforce on a python level) overrides from outer
146 scopes are tracked differently.
147 """
148 visitor = FrameIdentifierVisitor(self.identifiers, hard_scope)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200149 for node in nodes:
150 visitor.visit(node)
151
152 def inner(self):
153 """Return an inner frame."""
154 return Frame(self)
155
Armin Ronacher75cfb862008-04-11 13:47:22 +0200156 def soft(self):
157 """Return a soft frame. A soft frame may not be modified as
158 standalone thing as it shares the resources with the frame it
159 was created of, but it's not a rootlevel frame any longer.
160 """
161 rv = copy(self)
162 rv.rootlevel = False
163 return rv
164
Armin Ronachere791c2a2008-04-07 18:39:54 +0200165
166class FrameIdentifierVisitor(NodeVisitor):
167 """A visitor for `Frame.inspect`."""
168
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200169 def __init__(self, identifiers, hard_scope):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200170 self.identifiers = identifiers
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200171 self.hard_scope = hard_scope
Armin Ronachere791c2a2008-04-07 18:39:54 +0200172
173 def visit_Name(self, node):
174 """All assignments to names go through this function."""
175 if node.ctx in ('store', 'param'):
176 self.identifiers.declared_locally.add(node.name)
177 elif node.ctx == 'load':
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200178 if not self.identifiers.is_declared(node.name, self.hard_scope):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200179 self.identifiers.undeclared.add(node.name)
180
Armin Ronacherd55ab532008-04-09 16:13:39 +0200181 def visit_Filter(self, node):
Armin Ronacher449167d2008-04-11 17:55:05 +0200182 self.generic_visit(node)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200183 self.identifiers.filters.add(node.name)
184
185 def visit_Test(self, node):
186 self.generic_visit(node)
187 self.identifiers.tests.add(node.name)
Christoph Hack65642a52008-04-08 14:46:56 +0200188
Armin Ronachere791c2a2008-04-07 18:39:54 +0200189 def visit_Macro(self, node):
190 """Macros set local."""
191 self.identifiers.declared_locally.add(node.name)
192
Armin Ronacherf059ec12008-04-11 22:21:00 +0200193 def visit_Include(self, node):
194 """Some includes set local."""
195 self.generic_visit(node)
196 if node.target is not None:
197 self.identifiers.declared_locally.add(node.target)
198
Armin Ronacherebe55aa2008-04-10 20:51:23 +0200199 def visit_Assign(self, node):
200 """Visit assignments in the correct order."""
201 self.visit(node.node)
202 self.visit(node.target)
203
Armin Ronachere791c2a2008-04-07 18:39:54 +0200204 # stop traversing at instructions that have their own scope.
Armin Ronacher8efc5222008-04-08 14:47:40 +0200205 visit_Block = visit_CallBlock = visit_FilterBlock = \
Armin Ronachere791c2a2008-04-07 18:39:54 +0200206 visit_For = lambda s, n: None
207
208
Armin Ronacher75cfb862008-04-11 13:47:22 +0200209class CompilerExit(Exception):
210 """Raised if the compiler encountered a situation where it just
211 doesn't make sense to further process the code. Any block that
212 raises such an exception is not further processed."""
213
214
Armin Ronachere791c2a2008-04-07 18:39:54 +0200215class CodeGenerator(NodeVisitor):
216
Christoph Hack65642a52008-04-08 14:46:56 +0200217 def __init__(self, environment, is_child, filename, stream=None):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200218 if stream is None:
219 stream = StringIO()
Christoph Hack65642a52008-04-08 14:46:56 +0200220 self.environment = environment
Armin Ronachere791c2a2008-04-07 18:39:54 +0200221 self.is_child = is_child
222 self.filename = filename
223 self.stream = stream
224 self.blocks = {}
225 self.indentation = 0
226 self.new_lines = 0
227 self.last_identifier = 0
Armin Ronacher7fb38972008-04-11 13:54:28 +0200228 self.extends_so_far = 0
Armin Ronacher75cfb862008-04-11 13:47:22 +0200229 self.has_known_extends = False
Armin Ronachere791c2a2008-04-07 18:39:54 +0200230 self._last_line = 0
231 self._first_write = True
232
233 def temporary_identifier(self):
234 self.last_identifier += 1
235 return 't%d' % self.last_identifier
236
237 def indent(self):
238 self.indentation += 1
239
Armin Ronacher8efc5222008-04-08 14:47:40 +0200240 def outdent(self, step=1):
241 self.indentation -= step
Armin Ronachere791c2a2008-04-07 18:39:54 +0200242
243 def blockvisit(self, nodes, frame, force_generator=False):
244 self.indent()
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200245 if force_generator and frame.buffer is None:
Armin Ronachere791c2a2008-04-07 18:39:54 +0200246 self.writeline('if 0: yield None')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200247 try:
248 for node in nodes:
249 self.visit(node, frame)
250 except CompilerExit:
251 pass
Armin Ronachere791c2a2008-04-07 18:39:54 +0200252 self.outdent()
253
254 def write(self, x):
255 if self.new_lines:
256 if not self._first_write:
257 self.stream.write('\n' * self.new_lines)
258 self._first_write = False
259 self.stream.write(' ' * self.indentation)
260 self.new_lines = 0
261 self.stream.write(x)
262
263 def writeline(self, x, node=None, extra=0):
264 self.newline(node, extra)
265 self.write(x)
266
267 def newline(self, node=None, extra=0):
268 self.new_lines = max(self.new_lines, 1 + extra)
269 if node is not None and node.lineno != self._last_line:
270 self.write('# line: %s' % node.lineno)
271 self.new_lines = 1
272 self._last_line = node.lineno
273
Armin Ronacher71082072008-04-12 14:19:36 +0200274 def signature(self, node, frame, have_comma=True, extra_kwargs=None):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200275 have_comma = have_comma and [True] or []
276 def touch_comma():
277 if have_comma:
278 self.write(', ')
279 else:
280 have_comma.append(True)
281
282 for arg in node.args:
283 touch_comma()
284 self.visit(arg, frame)
285 for kwarg in node.kwargs:
286 touch_comma()
287 self.visit(kwarg, frame)
Armin Ronacher71082072008-04-12 14:19:36 +0200288 if extra_kwargs is not None:
289 touch_comma()
290 self.write(extra_kwargs)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200291 if node.dyn_args:
292 touch_comma()
Armin Ronacher71082072008-04-12 14:19:36 +0200293 self.write('*')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200294 self.visit(node.dyn_args, frame)
295 if node.dyn_kwargs:
296 touch_comma()
Armin Ronacher71082072008-04-12 14:19:36 +0200297 self.write('**')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200298 self.visit(node.dyn_kwargs, frame)
299
Armin Ronachere791c2a2008-04-07 18:39:54 +0200300 def pull_locals(self, frame, no_indent=False):
301 if not no_indent:
302 self.indent()
303 for name in frame.identifiers.undeclared:
304 self.writeline('l_%s = context[%r]' % (name, name))
Armin Ronacherd4c64f72008-04-11 17:15:29 +0200305 for name in frame.identifiers.filters:
306 self.writeline('f_%s = environment.filters[%r]' % (name, name))
Armin Ronacherf059ec12008-04-11 22:21:00 +0200307 for name in frame.identifiers.tests:
308 self.writeline('t_%s = environment.tests[%r]' % (name, name))
Armin Ronachere791c2a2008-04-07 18:39:54 +0200309 if not no_indent:
310 self.outdent()
311
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200312 def collect_shadowed(self, frame):
313 # make sure we "backup" overridden, local identifiers
314 # TODO: we should probably optimize this and check if the
315 # identifier is in use afterwards.
316 aliases = {}
317 for name in frame.identifiers.find_shadowed():
318 aliases[name] = ident = self.temporary_identifier()
319 self.writeline('%s = l_%s' % (ident, name))
320 return aliases
321
Armin Ronacher71082072008-04-12 14:19:36 +0200322 def function_scoping(self, node, frame):
323 func_frame = frame.inner()
324 func_frame.inspect(node.iter_child_nodes(), hard_scope=True)
325
326 # variables that are undeclared (accessed before declaration) and
327 # declared locally *and* part of an outside scope raise a template
328 # assertion error. Reason: we can't generate reasonable code from
329 # it without aliasing all the variables. XXX: alias them ^^
330 overriden_closure_vars = (
331 func_frame.identifiers.undeclared &
332 func_frame.identifiers.declared &
333 (func_frame.identifiers.declared_locally |
334 func_frame.identifiers.declared_parameter)
335 )
336 if overriden_closure_vars:
337 vars = ', '.join(sorted(overriden_closure_vars))
338 raise TemplateAssertionError('It\'s not possible to set and '
339 'access variables derived from '
340 'an outer scope! (affects: %s' %
341 vars, node.lineno, self.filename)
342
343 # remove variables from a closure from the frame's undeclared
344 # identifiers.
345 func_frame.identifiers.undeclared -= (
346 func_frame.identifiers.undeclared &
347 func_frame.identifiers.declared
348 )
349
350 func_frame.accesses_arguments = False
351 func_frame.accesses_caller = False
352 func_frame.arguments = args = ['l_' + x.name for x in node.args]
353
354 if 'arguments' in func_frame.identifiers.undeclared:
355 func_frame.accesses_arguments = True
356 func_frame.identifiers.add_special('arguments')
357 args.append('l_arguments')
358 if 'caller' in func_frame.identifiers.undeclared:
359 func_frame.accesses_caller = True
360 func_frame.identifiers.add_special('caller')
361 args.append('l_caller')
362 return func_frame
363
Armin Ronachere791c2a2008-04-07 18:39:54 +0200364 # -- Visitors
365
366 def visit_Template(self, node, frame=None):
367 assert frame is None, 'no root frame allowed'
368 self.writeline('from jinja2.runtime import *')
369 self.writeline('filename = %r' % self.filename)
Armin Ronacher8edbe492008-04-10 20:43:43 +0200370
Armin Ronacher75cfb862008-04-11 13:47:22 +0200371 # do we have an extends tag at all? If not, we can save some
372 # overhead by just not processing any inheritance code.
373 have_extends = node.find(nodes.Extends) is not None
374
Armin Ronacher8edbe492008-04-10 20:43:43 +0200375 # find all blocks
376 for block in node.find_all(nodes.Block):
377 if block.name in self.blocks:
378 raise TemplateAssertionError('block %r defined twice' %
379 block.name, block.lineno,
380 self.filename)
381 self.blocks[block.name] = block
Armin Ronachere791c2a2008-04-07 18:39:54 +0200382
Armin Ronacher8efc5222008-04-08 14:47:40 +0200383 # generate the root render function.
Armin Ronacherf059ec12008-04-11 22:21:00 +0200384 self.writeline('def root(globals, environment=environment'
385 ', standalone=False):', extra=1)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200386 self.indent()
Armin Ronacherf059ec12008-04-11 22:21:00 +0200387 self.writeline('context = TemplateContext(globals, %r, blocks'
388 ', standalone)' % self.filename)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200389 if have_extends:
390 self.writeline('parent_root = None')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200391 self.outdent()
Armin Ronacher75cfb862008-04-11 13:47:22 +0200392
393 # process the root
Armin Ronachere791c2a2008-04-07 18:39:54 +0200394 frame = Frame()
395 frame.inspect(node.body)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200396 frame.toplevel = frame.rootlevel = True
Armin Ronachere791c2a2008-04-07 18:39:54 +0200397 self.pull_locals(frame)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200398 self.indent()
399 self.writeline('yield context')
400 self.outdent()
401 self.blockvisit(node.body, frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200402
Armin Ronacher8efc5222008-04-08 14:47:40 +0200403 # make sure that the parent root is called.
Armin Ronacher75cfb862008-04-11 13:47:22 +0200404 if have_extends:
405 if not self.has_known_extends:
406 self.indent()
407 self.writeline('if parent_root is not None:')
408 self.indent()
Armin Ronacherf059ec12008-04-11 22:21:00 +0200409 self.writeline('stream = parent_root(context)')
410 self.writeline('stream.next()')
411 self.writeline('for event in stream:')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200412 self.indent()
413 self.writeline('yield event')
Armin Ronacher7a52df82008-04-11 13:58:22 +0200414 self.outdent(1 + self.has_known_extends)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200415
416 # at this point we now have the blocks collected and can visit them too.
417 for name, block in self.blocks.iteritems():
418 block_frame = Frame()
419 block_frame.inspect(block.body)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200420 block_frame.block = name
Armin Ronacherd4c64f72008-04-11 17:15:29 +0200421 self.writeline('def block_%s(context, environment=environment):'
422 % name, block, 1)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200423 self.pull_locals(block_frame)
424 self.blockvisit(block.body, block_frame, True)
425
Armin Ronacher75cfb862008-04-11 13:47:22 +0200426 self.writeline('blocks = {%s}' % ', '.join('%r: block_%s' % (x, x)
427 for x in self.blocks), extra=1)
428
Armin Ronachere791c2a2008-04-07 18:39:54 +0200429 def visit_Block(self, node, frame):
430 """Call a block and register it for the template."""
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200431 level = 1
Armin Ronacher75cfb862008-04-11 13:47:22 +0200432 if frame.toplevel:
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200433 # if we know that we are a child template, there is no need to
434 # check if we are one
435 if self.has_known_extends:
436 return
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200437 if self.extends_so_far > 0:
438 self.writeline('if parent_root is None:')
439 self.indent()
440 level += 1
441 self.writeline('for event in context.blocks[%r][-1](context):' % node.name)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200442 self.indent()
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200443 if frame.buffer is None:
444 self.writeline('yield event')
445 else:
446 self.writeline('%s.append(event)' % frame.buffer)
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200447 self.outdent(level)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200448
449 def visit_Extends(self, node, frame):
450 """Calls the extender."""
Armin Ronacher8efc5222008-04-08 14:47:40 +0200451 if not frame.toplevel:
452 raise TemplateAssertionError('cannot use extend from a non '
453 'top-level scope', node.lineno,
454 self.filename)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200455
Armin Ronacher7fb38972008-04-11 13:54:28 +0200456 # if the number of extends statements in general is zero so
457 # far, we don't have to add a check if something extended
458 # the template before this one.
459 if self.extends_so_far > 0:
Armin Ronacher75cfb862008-04-11 13:47:22 +0200460
Armin Ronacher7fb38972008-04-11 13:54:28 +0200461 # if we have a known extends we just add a template runtime
462 # error into the generated code. We could catch that at compile
463 # time too, but i welcome it not to confuse users by throwing the
464 # same error at different times just "because we can".
465 if not self.has_known_extends:
466 self.writeline('if parent_root is not None:')
467 self.indent()
468 self.writeline('raise TemplateRuntimeError(%r)' %
469 'extended multiple times')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200470
Armin Ronacher7fb38972008-04-11 13:54:28 +0200471 # if we have a known extends already we don't need that code here
472 # as we know that the template execution will end here.
473 if self.has_known_extends:
474 raise CompilerExit()
475 self.outdent()
476
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200477 self.writeline('parent_root = environment.get_template(', node, 1)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200478 self.visit(node.template, frame)
Armin Ronacher41ef36f2008-04-11 19:55:08 +0200479 self.write(', %r).root_render_func' % self.filename)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200480
481 # if this extends statement was in the root level we can take
482 # advantage of that information and simplify the generated code
483 # in the top level from this point onwards
484 self.has_known_extends = True
Armin Ronachere791c2a2008-04-07 18:39:54 +0200485
Armin Ronacher7fb38972008-04-11 13:54:28 +0200486 # and now we have one more
487 self.extends_so_far += 1
488
Armin Ronacherf059ec12008-04-11 22:21:00 +0200489 def visit_Include(self, node, frame):
490 """Handles includes."""
491 # simpled include is include into a variable. This kind of
492 # include works the same on every level, so we handle it first.
493 if node.target is not None:
494 self.writeline('l_%s = ' % node.target, node)
495 if frame.toplevel:
496 self.write('context[%r] = ' % node.target)
497 self.write('IncludedTemplate(environment, context, ')
498 self.visit(node.template, frame)
499 self.write(')')
500 return
501
502 self.writeline('included_stream = environment.get_template(', node)
503 self.visit(node.template, frame)
504 self.write(').root_render_func(context, standalone=True)')
505 self.writeline('included_context = included_stream.next()')
506 self.writeline('for event in included_stream:')
507 self.indent()
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200508 if frame.buffer is None:
509 self.writeline('yield event')
510 else:
511 self.writeline('%s.append(event)' % frame.buffer)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200512 self.outdent()
513
514 # if we have a toplevel include the exported variables are copied
515 # into the current context without exporting them. context.udpate
516 # does *not* mark the variables as exported
517 if frame.toplevel:
518 self.writeline('context.update(included_context.get_exported())')
519
Armin Ronachere791c2a2008-04-07 18:39:54 +0200520 def visit_For(self, node, frame):
521 loop_frame = frame.inner()
522 loop_frame.inspect(node.iter_child_nodes())
Armin Ronachere791c2a2008-04-07 18:39:54 +0200523 extended_loop = bool(node.else_) or \
524 'loop' in loop_frame.identifiers.undeclared
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200525 if extended_loop:
526 loop_frame.identifiers.add_special('loop')
Armin Ronachere791c2a2008-04-07 18:39:54 +0200527
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200528 aliases = self.collect_shadowed(loop_frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200529 self.pull_locals(loop_frame, True)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200530 if node.else_:
531 self.writeline('l_loop = None')
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200532
533 self.newline(node)
534 self.writeline('for ')
Armin Ronachere791c2a2008-04-07 18:39:54 +0200535 self.visit(node.target, loop_frame)
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200536 self.write(extended_loop and ', l_loop in LoopContext(' or ' in ')
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200537
538 # the expression pointing to the parent loop. We make the
539 # undefined a bit more debug friendly at the same time.
540 parent_loop = 'loop' in aliases and aliases['loop'] \
541 or "Undefined('loop', extra=%r)" % \
542 'the filter section of a loop as well as the ' \
543 'else block doesn\'t have access to the special ' \
544 "'loop' variable of the current loop. Because " \
545 'there is no parent loop it\'s undefined.'
546
547 # if we have an extened loop and a node test, we filter in the
548 # "outer frame".
549 if extended_loop and node.test is not None:
550 self.write('(')
551 self.visit(node.target, loop_frame)
552 self.write(' for ')
553 self.visit(node.target, loop_frame)
554 self.write(' in ')
555 self.visit(node.iter, loop_frame)
556 self.write(' if (')
557 test_frame = loop_frame.copy()
558 test_frame.name_overrides['loop'] = parent_loop
559 self.visit(node.test, test_frame)
560 self.write('))')
561
562 else:
563 self.visit(node.iter, loop_frame)
564
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200565 if 'loop' in aliases:
566 self.write(', ' + aliases['loop'])
Armin Ronachere791c2a2008-04-07 18:39:54 +0200567 self.write(extended_loop and '):' or ':')
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200568
569 # tests in not extended loops become a continue
570 if not extended_loop and node.test is not None:
571 self.indent()
572 self.writeline('if ')
573 self.visit(node.test)
574 self.write(':')
575 self.indent()
576 self.writeline('continue')
577 self.outdent(2)
578
Armin Ronachere791c2a2008-04-07 18:39:54 +0200579 self.blockvisit(node.body, loop_frame)
580
581 if node.else_:
582 self.writeline('if l_loop is None:')
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200583 self.indent()
584 self.writeline('l_loop = ' + parent_loop)
585 self.outdent()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200586 self.blockvisit(node.else_, loop_frame)
587
Armin Ronacherd4c64f72008-04-11 17:15:29 +0200588 # reset the aliases if there are any.
Armin Ronachere791c2a2008-04-07 18:39:54 +0200589 for name, alias in aliases.iteritems():
Armin Ronacher8efc5222008-04-08 14:47:40 +0200590 self.writeline('l_%s = %s' % (name, alias))
Armin Ronachere791c2a2008-04-07 18:39:54 +0200591
592 def visit_If(self, node, frame):
Armin Ronacher75cfb862008-04-11 13:47:22 +0200593 if_frame = frame.soft()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200594 self.writeline('if ', node)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200595 self.visit(node.test, if_frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200596 self.write(':')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200597 self.blockvisit(node.body, if_frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200598 if node.else_:
599 self.writeline('else:')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200600 self.blockvisit(node.else_, if_frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200601
Armin Ronacher8efc5222008-04-08 14:47:40 +0200602 def visit_Macro(self, node, frame):
Armin Ronacher71082072008-04-12 14:19:36 +0200603 macro_frame = self.function_scoping(node, frame)
604 args = macro_frame.arguments
Armin Ronacher8efc5222008-04-08 14:47:40 +0200605 self.writeline('def macro(%s):' % ', '.join(args), node)
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200606 self.pull_locals(macro_frame)
Armin Ronacher71082072008-04-12 14:19:36 +0200607 self.blockvisit(node.body, macro_frame, True)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200608 self.newline()
609 if frame.toplevel:
610 self.write('context[%r] = ' % node.name)
611 arg_tuple = ', '.join(repr(x.name) for x in node.args)
612 if len(node.args) == 1:
613 arg_tuple += ','
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200614 self.write('l_%s = Macro(macro, %r, (%s), (' % (node.name, node.name,
615 arg_tuple))
616 for arg in node.defaults:
617 self.visit(arg)
618 self.write(', ')
Armin Ronacher00d5d212008-04-13 01:10:18 +0200619 self.write('), %s, %s)' % (
620 macro_frame.accesses_arguments and '1' or '0',
621 macro_frame.accesses_caller and '1' or '0'
Armin Ronacher71082072008-04-12 14:19:36 +0200622 ))
623
624 def visit_CallBlock(self, node, frame):
625 call_frame = self.function_scoping(node, frame)
626 args = call_frame.arguments
627 self.writeline('def call(%s):' % ', '.join(args), node)
628 self.blockvisit(node.body, call_frame, node)
629 arg_tuple = ', '.join(repr(x.name) for x in node.args)
630 if len(node.args) == 1:
631 arg_tuple += ','
632 self.writeline('caller = Macro(call, None, (%s), (' % arg_tuple)
633 for arg in node.defaults:
634 self.visit(arg)
635 self.write(', ')
Armin Ronacher00d5d212008-04-13 01:10:18 +0200636 self.write('), %s, 0)' % (call_frame.accesses_arguments and '1' or '0'))
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200637 if frame.buffer is None:
638 self.writeline('yield ', node)
639 else:
640 self.writeline('%s.append(' % frame.buffer, node)
Armin Ronacher71082072008-04-12 14:19:36 +0200641 self.visit_Call(node.call, call_frame, extra_kwargs='caller=caller')
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200642 if frame.buffer is not None:
643 self.write(')')
644
645 def visit_FilterBlock(self, node, frame):
646 filter_frame = frame.inner()
647 filter_frame.inspect(node.iter_child_nodes())
648
649 aliases = self.collect_shadowed(filter_frame)
650 self.pull_locals(filter_frame, True)
651 filter_frame.buffer = buf = self.temporary_identifier()
652
653 self.writeline('%s = []' % buf, node)
654 for child in node.body:
655 self.visit(child, filter_frame)
656
657 if frame.buffer is None:
658 self.writeline('yield ', node)
659 else:
660 self.writeline('%s.append(' % frame.buffer, node)
661 self.visit_Filter(node.filter, filter_frame, "u''.join(%s)" % buf)
662 if frame.buffer is not None:
663 self.write(')')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200664
Armin Ronachere791c2a2008-04-07 18:39:54 +0200665 def visit_ExprStmt(self, node, frame):
666 self.newline(node)
667 self.visit(node, frame)
668
669 def visit_Output(self, node, frame):
Armin Ronacher75cfb862008-04-11 13:47:22 +0200670 # if we have a known extends statement, we don't output anything
Armin Ronacher7a52df82008-04-11 13:58:22 +0200671 if self.has_known_extends and frame.toplevel:
Armin Ronacher75cfb862008-04-11 13:47:22 +0200672 return
Armin Ronachere791c2a2008-04-07 18:39:54 +0200673
Armin Ronacher75cfb862008-04-11 13:47:22 +0200674 self.newline(node)
Armin Ronacher8edbe492008-04-10 20:43:43 +0200675 if self.environment.finalize is unicode:
676 finalizer = 'unicode'
Armin Ronacherf059ec12008-04-11 22:21:00 +0200677 have_finalizer = False
Armin Ronacher8edbe492008-04-10 20:43:43 +0200678 else:
679 finalizer = 'context.finalize'
Armin Ronacherf059ec12008-04-11 22:21:00 +0200680 have_finalizer = False
Armin Ronacher8edbe492008-04-10 20:43:43 +0200681
Armin Ronacher7fb38972008-04-11 13:54:28 +0200682 # if we are in the toplevel scope and there was already an extends
683 # statement we have to add a check that disables our yield(s) here
684 # so that they don't appear in the output.
685 outdent_later = False
686 if frame.toplevel and self.extends_so_far != 0:
Armin Ronacher75cfb862008-04-11 13:47:22 +0200687 self.writeline('if parent_root is None:')
688 self.indent()
Armin Ronacher7fb38972008-04-11 13:54:28 +0200689 outdent_later = True
Armin Ronacher75cfb862008-04-11 13:47:22 +0200690
Armin Ronachere791c2a2008-04-07 18:39:54 +0200691 # try to evaluate as many chunks as possible into a static
692 # string at compile time.
693 body = []
694 for child in node.nodes:
695 try:
696 const = unicode(child.as_const())
697 except:
698 body.append(child)
699 continue
700 if body and isinstance(body[-1], list):
701 body[-1].append(const)
702 else:
703 body.append([const])
704
705 # if we have less than 3 nodes we just yield them
706 if len(body) < 3:
707 for item in body:
708 if isinstance(item, list):
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200709 val = repr(u''.join(item))
710 if frame.buffer is None:
711 self.writeline('yield ' + val)
712 else:
713 self.writeline('%s.append(%s)' % (frame.buffer, val))
Armin Ronachere791c2a2008-04-07 18:39:54 +0200714 else:
715 self.newline(item)
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200716 if frame.buffer is None:
717 self.write('yield ')
718 else:
719 self.write('%s.append(' % frame.buffer)
720 self.write(finalizer + '(')
Armin Ronachere791c2a2008-04-07 18:39:54 +0200721 self.visit(item, frame)
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200722 self.write(')' * (1 + (frame.buffer is not None)))
Armin Ronachere791c2a2008-04-07 18:39:54 +0200723
724 # otherwise we create a format string as this is faster in that case
725 else:
726 format = []
727 arguments = []
728 for item in body:
729 if isinstance(item, list):
730 format.append(u''.join(item).replace('%', '%%'))
731 else:
732 format.append('%s')
733 arguments.append(item)
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200734 if frame.buffer is None:
735 self.writeline('yield ')
736 else:
737 self.writeline('%s.append(' % frame.buffer)
738 self.write(repr(u''.join(format)) + ' % (')
Armin Ronachere791c2a2008-04-07 18:39:54 +0200739 idx = -1
740 for idx, argument in enumerate(arguments):
741 if idx:
742 self.write(', ')
Armin Ronacherf059ec12008-04-11 22:21:00 +0200743 if have_finalizer:
Armin Ronacher8edbe492008-04-10 20:43:43 +0200744 self.write('(')
Armin Ronachere791c2a2008-04-07 18:39:54 +0200745 self.visit(argument, frame)
Armin Ronacherf059ec12008-04-11 22:21:00 +0200746 if have_finalizer:
Armin Ronacher8edbe492008-04-10 20:43:43 +0200747 self.write(')')
Armin Ronachere791c2a2008-04-07 18:39:54 +0200748 self.write(idx == 0 and ',)' or ')')
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200749 if frame.buffer is not None:
750 self.write(')')
Armin Ronachere791c2a2008-04-07 18:39:54 +0200751
Armin Ronacher7fb38972008-04-11 13:54:28 +0200752 if outdent_later:
Armin Ronacher75cfb862008-04-11 13:47:22 +0200753 self.outdent()
754
Armin Ronacher8efc5222008-04-08 14:47:40 +0200755 def visit_Assign(self, node, frame):
756 self.newline(node)
757 # toplevel assignments however go into the local namespace and
758 # the current template's context. We create a copy of the frame
759 # here and add a set so that the Name visitor can add the assigned
760 # names here.
761 if frame.toplevel:
762 assignment_frame = frame.copy()
763 assignment_frame.assigned_names = set()
764 else:
765 assignment_frame = frame
766 self.visit(node.target, assignment_frame)
767 self.write(' = ')
768 self.visit(node.node, frame)
Armin Ronacher9706fab2008-04-08 18:49:56 +0200769
770 # make sure toplevel assignments are added to the context.
Armin Ronacher8efc5222008-04-08 14:47:40 +0200771 if frame.toplevel:
772 for name in assignment_frame.assigned_names:
773 self.writeline('context[%r] = l_%s' % (name, name))
774
Armin Ronachere791c2a2008-04-07 18:39:54 +0200775 def visit_Name(self, node, frame):
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200776 if node.ctx == 'store':
777 if frame.toplevel:
778 frame.assigned_names.add(node.name)
779 frame.name_overrides.pop(node.name, None)
780 elif node.ctx == 'load':
781 if node.name in frame.name_overrides:
782 self.write(frame.name_overrides[node.name])
783 return
Armin Ronachere791c2a2008-04-07 18:39:54 +0200784 self.write('l_' + node.name)
785
786 def visit_Const(self, node, frame):
787 val = node.value
788 if isinstance(val, float):
789 # XXX: add checks for infinity and nan
790 self.write(str(val))
791 else:
792 self.write(repr(val))
793
Armin Ronacher8efc5222008-04-08 14:47:40 +0200794 def visit_Tuple(self, node, frame):
795 self.write('(')
796 idx = -1
797 for idx, item in enumerate(node.items):
798 if idx:
799 self.write(', ')
800 self.visit(item, frame)
801 self.write(idx == 0 and ',)' or ')')
802
Armin Ronacher8edbe492008-04-10 20:43:43 +0200803 def visit_List(self, node, frame):
804 self.write('[')
805 for idx, item in enumerate(node.items):
806 if idx:
807 self.write(', ')
808 self.visit(item, frame)
809 self.write(']')
810
811 def visit_Dict(self, node, frame):
812 self.write('{')
813 for idx, item in enumerate(node.items):
814 if idx:
815 self.write(', ')
816 self.visit(item.key, frame)
817 self.write(': ')
818 self.visit(item.value, frame)
819 self.write('}')
820
Armin Ronachere791c2a2008-04-07 18:39:54 +0200821 def binop(operator):
822 def visitor(self, node, frame):
823 self.write('(')
824 self.visit(node.left, frame)
825 self.write(' %s ' % operator)
826 self.visit(node.right, frame)
827 self.write(')')
828 return visitor
829
830 def uaop(operator):
831 def visitor(self, node, frame):
832 self.write('(' + operator)
833 self.visit(node.node)
834 self.write(')')
835 return visitor
836
837 visit_Add = binop('+')
838 visit_Sub = binop('-')
839 visit_Mul = binop('*')
840 visit_Div = binop('/')
841 visit_FloorDiv = binop('//')
842 visit_Pow = binop('**')
843 visit_Mod = binop('%')
844 visit_And = binop('and')
845 visit_Or = binop('or')
846 visit_Pos = uaop('+')
847 visit_Neg = uaop('-')
848 visit_Not = uaop('not ')
849 del binop, uaop
850
851 def visit_Compare(self, node, frame):
852 self.visit(node.expr, frame)
853 for op in node.ops:
854 self.visit(op, frame)
855
856 def visit_Operand(self, node, frame):
857 self.write(' %s ' % operators[node.op])
858 self.visit(node.expr, frame)
859
860 def visit_Subscript(self, node, frame):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200861 if isinstance(node.arg, nodes.Slice):
862 self.visit(node.node, frame)
863 self.write('[')
864 self.visit(node.arg, frame)
865 self.write(']')
866 return
867 try:
868 const = node.arg.as_const()
869 have_const = True
870 except nodes.Impossible:
871 have_const = False
872 if have_const:
873 if isinstance(const, (int, long, float)):
874 self.visit(node.node, frame)
875 self.write('[%s]' % const)
876 return
877 self.write('subscribe(')
Armin Ronachere791c2a2008-04-07 18:39:54 +0200878 self.visit(node.node, frame)
879 self.write(', ')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200880 if have_const:
881 self.write(repr(const))
882 else:
883 self.visit(node.arg, frame)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200884 self.write(')')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200885
886 def visit_Slice(self, node, frame):
887 if node.start is not None:
888 self.visit(node.start, frame)
889 self.write(':')
890 if node.stop is not None:
891 self.visit(node.stop, frame)
892 if node.step is not None:
893 self.write(':')
894 self.visit(node.step, frame)
895
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200896 def visit_Filter(self, node, frame, initial=None):
Armin Ronacherd4c64f72008-04-11 17:15:29 +0200897 self.write('f_%s(' % node.name)
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200898 if initial is not None:
899 self.write(initial)
900 else:
901 func = self.environment.filters.get(node.name)
902 if getattr(func, 'contextfilter', False):
903 self.write('context, ')
904 self.visit(node.node, frame)
Armin Ronacherd55ab532008-04-09 16:13:39 +0200905 self.signature(node, frame)
906 self.write(')')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200907
908 def visit_Test(self, node, frame):
Armin Ronacherf059ec12008-04-11 22:21:00 +0200909 self.write('t_%s(' % node.name)
910 func = self.environment.tests.get(node.name)
911 if getattr(func, 'contexttest', False):
912 self.write('context, ')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200913 self.visit(node.node, frame)
914 self.signature(node, frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200915 self.write(')')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200916
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200917 def visit_CondExpr(self, node, frame):
918 if not have_condexpr:
919 self.write('((')
920 self.visit(node.test, frame)
921 self.write(') and (')
922 self.visit(node.expr1, frame)
923 self.write(',) or (')
924 self.visit(node.expr2, frame)
925 self.write(',))[0]')
926 else:
927 self.write('(')
928 self.visit(node.expr1, frame)
929 self.write(' if ')
930 self.visit(node.test, frame)
931 self.write(' else ')
932 self.visit(node.expr2, frame)
933 self.write(')')
934
Armin Ronacher71082072008-04-12 14:19:36 +0200935 def visit_Call(self, node, frame, extra_kwargs=None):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200936 self.visit(node.node, frame)
937 self.write('(')
Armin Ronacher71082072008-04-12 14:19:36 +0200938 self.signature(node, frame, False, extra_kwargs)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200939 self.write(')')
940
941 def visit_Keyword(self, node, frame):
942 self.visit(node.key, frame)
943 self.write('=')
944 self.visit(node.value, frame)