blob: 343449c0dab888dd4886672bdcf6f8972d4e0160 [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 Ronachere791c2a2008-04-07 18:39:54 +020033 is_child = node.find(nodes.Extends) is not None
Christoph Hack65642a52008-04-08 14:46:56 +020034 generator = CodeGenerator(environment, is_child, filename, stream)
Armin Ronachere791c2a2008-04-07 18:39:54 +020035 generator.visit(node)
36 if stream is None:
37 return generator.stream.getvalue()
38
39
Armin Ronacher4dfc9752008-04-09 15:03:29 +020040def has_safe_repr(value):
41 """Does the node have a safe representation?"""
Armin Ronacherd55ab532008-04-09 16:13:39 +020042 if value is None or value is NotImplemented or value is Ellipsis:
Armin Ronacher4dfc9752008-04-09 15:03:29 +020043 return True
Armin Ronacherd55ab532008-04-09 16:13:39 +020044 if isinstance(value, (bool, int, long, float, complex, basestring,
45 StaticLoopContext)):
Armin Ronacher4dfc9752008-04-09 15:03:29 +020046 return True
Armin Ronacherd55ab532008-04-09 16:13:39 +020047 if isinstance(value, (tuple, list, set, frozenset)):
Armin Ronacher4dfc9752008-04-09 15:03:29 +020048 for item in value:
49 if not has_safe_repr(item):
50 return False
51 return True
52 elif isinstance(value, dict):
53 for key, value in value.iteritems():
54 if not has_safe_repr(key):
55 return False
56 if not has_safe_repr(value):
57 return False
58 return True
59 return False
60
61
Armin Ronachere791c2a2008-04-07 18:39:54 +020062class Identifiers(object):
63 """Tracks the status of identifiers in frames."""
64
65 def __init__(self):
66 # variables that are known to be declared (probably from outer
67 # frames or because they are special for the frame)
68 self.declared = set()
69
70 # names that are accessed without being explicitly declared by
71 # this one or any of the outer scopes. Names can appear both in
72 # declared and undeclared.
73 self.undeclared = set()
74
75 # names that are declared locally
76 self.declared_locally = set()
77
78 # names that are declared by parameters
79 self.declared_parameter = set()
80
Christoph Hack65642a52008-04-08 14:46:56 +020081 # filters that are declared locally
82 self.declared_filter = set()
Christoph Hackacb130e2008-04-08 15:21:53 +020083 self.undeclared_filter = dict()
Christoph Hack65642a52008-04-08 14:46:56 +020084
Armin Ronachere791c2a2008-04-07 18:39:54 +020085 def add_special(self, name):
86 """Register a special name like `loop`."""
87 self.undeclared.discard(name)
88 self.declared.add(name)
89
Armin Ronacher4f62a9f2008-04-08 18:09:13 +020090 def is_declared(self, name, local_only=False):
Armin Ronachere791c2a2008-04-07 18:39:54 +020091 """Check if a name is declared in this or an outer scope."""
Armin Ronacher4f62a9f2008-04-08 18:09:13 +020092 if name in self.declared_locally or name in self.declared_parameter:
93 return True
94 if local_only:
95 return False
96 return name in self.declared
Armin Ronachere791c2a2008-04-07 18:39:54 +020097
98 def find_shadowed(self):
99 """Find all the shadowed names."""
100 return self.declared & (self.declared_locally | self.declared_parameter)
101
102
103class Frame(object):
Armin Ronacher75cfb862008-04-11 13:47:22 +0200104 """Holds compile time information for us."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200105
106 def __init__(self, parent=None):
107 self.identifiers = Identifiers()
Armin Ronacher75cfb862008-04-11 13:47:22 +0200108 # a toplevel frame is the root + soft frames such as if conditions.
Armin Ronacher8efc5222008-04-08 14:47:40 +0200109 self.toplevel = False
Armin Ronacher75cfb862008-04-11 13:47:22 +0200110 # the root frame is basically just the outermost frame, so no if
111 # conditions. This information is used to optimize inheritance
112 # situations.
113 self.rootlevel = False
Armin Ronachere791c2a2008-04-07 18:39:54 +0200114 self.parent = parent
Armin Ronacher8efc5222008-04-08 14:47:40 +0200115 self.block = parent and parent.block or None
Armin Ronachere791c2a2008-04-07 18:39:54 +0200116 if parent is not None:
117 self.identifiers.declared.update(
118 parent.identifiers.declared |
Armin Ronachere791c2a2008-04-07 18:39:54 +0200119 parent.identifiers.declared_locally |
120 parent.identifiers.declared_parameter
121 )
122
Armin Ronacher8efc5222008-04-08 14:47:40 +0200123 def copy(self):
124 """Create a copy of the current one."""
125 rv = copy(self)
126 rv.identifiers = copy(self)
127 return rv
128
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200129 def inspect(self, nodes, hard_scope=False):
130 """Walk the node and check for identifiers. If the scope
131 is hard (eg: enforce on a python level) overrides from outer
132 scopes are tracked differently.
133 """
134 visitor = FrameIdentifierVisitor(self.identifiers, hard_scope)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200135 for node in nodes:
136 visitor.visit(node)
137
138 def inner(self):
139 """Return an inner frame."""
140 return Frame(self)
141
Armin Ronacher75cfb862008-04-11 13:47:22 +0200142 def soft(self):
143 """Return a soft frame. A soft frame may not be modified as
144 standalone thing as it shares the resources with the frame it
145 was created of, but it's not a rootlevel frame any longer.
146 """
147 rv = copy(self)
148 rv.rootlevel = False
149 return rv
150
Armin Ronachere791c2a2008-04-07 18:39:54 +0200151
152class FrameIdentifierVisitor(NodeVisitor):
153 """A visitor for `Frame.inspect`."""
154
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200155 def __init__(self, identifiers, hard_scope):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200156 self.identifiers = identifiers
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200157 self.hard_scope = hard_scope
Armin Ronachere791c2a2008-04-07 18:39:54 +0200158
159 def visit_Name(self, node):
160 """All assignments to names go through this function."""
161 if node.ctx in ('store', 'param'):
162 self.identifiers.declared_locally.add(node.name)
163 elif node.ctx == 'load':
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200164 if not self.identifiers.is_declared(node.name, self.hard_scope):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200165 self.identifiers.undeclared.add(node.name)
166
Armin Ronacherd55ab532008-04-09 16:13:39 +0200167 def visit_Filter(self, node):
Christoph Hack65642a52008-04-08 14:46:56 +0200168 if not node.name in self.identifiers.declared_filter:
Christoph Hackacb130e2008-04-08 15:21:53 +0200169 uf = self.identifiers.undeclared_filter.get(node.name, 0) + 1
170 if uf > 1:
171 self.identifiers.declared_filter.add(node.name)
172 self.identifiers.undeclared_filter[node.name] = uf
Christoph Hack65642a52008-04-08 14:46:56 +0200173
Armin Ronachere791c2a2008-04-07 18:39:54 +0200174 def visit_Macro(self, node):
175 """Macros set local."""
176 self.identifiers.declared_locally.add(node.name)
177
Armin Ronacherebe55aa2008-04-10 20:51:23 +0200178 def visit_Assign(self, node):
179 """Visit assignments in the correct order."""
180 self.visit(node.node)
181 self.visit(node.target)
182
Armin Ronachere791c2a2008-04-07 18:39:54 +0200183 # stop traversing at instructions that have their own scope.
Armin Ronacher8efc5222008-04-08 14:47:40 +0200184 visit_Block = visit_CallBlock = visit_FilterBlock = \
Armin Ronachere791c2a2008-04-07 18:39:54 +0200185 visit_For = lambda s, n: None
186
187
Armin Ronacher75cfb862008-04-11 13:47:22 +0200188class CompilerExit(Exception):
189 """Raised if the compiler encountered a situation where it just
190 doesn't make sense to further process the code. Any block that
191 raises such an exception is not further processed."""
192
193
Armin Ronachere791c2a2008-04-07 18:39:54 +0200194class CodeGenerator(NodeVisitor):
195
Christoph Hack65642a52008-04-08 14:46:56 +0200196 def __init__(self, environment, is_child, filename, stream=None):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200197 if stream is None:
198 stream = StringIO()
Christoph Hack65642a52008-04-08 14:46:56 +0200199 self.environment = environment
Armin Ronachere791c2a2008-04-07 18:39:54 +0200200 self.is_child = is_child
201 self.filename = filename
202 self.stream = stream
203 self.blocks = {}
204 self.indentation = 0
205 self.new_lines = 0
206 self.last_identifier = 0
Armin Ronacher7fb38972008-04-11 13:54:28 +0200207 self.extends_so_far = 0
Armin Ronacher75cfb862008-04-11 13:47:22 +0200208 self.has_known_extends = False
Armin Ronachere791c2a2008-04-07 18:39:54 +0200209 self._last_line = 0
210 self._first_write = True
211
212 def temporary_identifier(self):
213 self.last_identifier += 1
214 return 't%d' % self.last_identifier
215
216 def indent(self):
217 self.indentation += 1
218
Armin Ronacher8efc5222008-04-08 14:47:40 +0200219 def outdent(self, step=1):
220 self.indentation -= step
Armin Ronachere791c2a2008-04-07 18:39:54 +0200221
222 def blockvisit(self, nodes, frame, force_generator=False):
223 self.indent()
224 if force_generator:
225 self.writeline('if 0: yield None')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200226 try:
227 for node in nodes:
228 self.visit(node, frame)
229 except CompilerExit:
230 pass
Armin Ronachere791c2a2008-04-07 18:39:54 +0200231 self.outdent()
232
233 def write(self, x):
234 if self.new_lines:
235 if not self._first_write:
236 self.stream.write('\n' * self.new_lines)
237 self._first_write = False
238 self.stream.write(' ' * self.indentation)
239 self.new_lines = 0
240 self.stream.write(x)
241
242 def writeline(self, x, node=None, extra=0):
243 self.newline(node, extra)
244 self.write(x)
245
246 def newline(self, node=None, extra=0):
247 self.new_lines = max(self.new_lines, 1 + extra)
248 if node is not None and node.lineno != self._last_line:
249 self.write('# line: %s' % node.lineno)
250 self.new_lines = 1
251 self._last_line = node.lineno
252
Armin Ronacher8efc5222008-04-08 14:47:40 +0200253 def signature(self, node, frame, have_comma=True):
254 have_comma = have_comma and [True] or []
255 def touch_comma():
256 if have_comma:
257 self.write(', ')
258 else:
259 have_comma.append(True)
260
261 for arg in node.args:
262 touch_comma()
263 self.visit(arg, frame)
264 for kwarg in node.kwargs:
265 touch_comma()
266 self.visit(kwarg, frame)
267 if node.dyn_args:
268 touch_comma()
269 self.visit(node.dyn_args, frame)
270 if node.dyn_kwargs:
271 touch_comma()
272 self.visit(node.dyn_kwargs, frame)
273
Armin Ronachere791c2a2008-04-07 18:39:54 +0200274 def pull_locals(self, frame, no_indent=False):
275 if not no_indent:
276 self.indent()
277 for name in frame.identifiers.undeclared:
278 self.writeline('l_%s = context[%r]' % (name, name))
Christoph Hackacb130e2008-04-08 15:21:53 +0200279 for name, count in frame.identifiers.undeclared_filter.iteritems():
280 if count > 1:
281 self.writeline('f_%s = context[%r]' % (name, name))
Armin Ronachere791c2a2008-04-07 18:39:54 +0200282 if not no_indent:
283 self.outdent()
284
285 # -- Visitors
286
287 def visit_Template(self, node, frame=None):
288 assert frame is None, 'no root frame allowed'
289 self.writeline('from jinja2.runtime import *')
290 self.writeline('filename = %r' % self.filename)
Armin Ronacher8edbe492008-04-10 20:43:43 +0200291
Armin Ronacher75cfb862008-04-11 13:47:22 +0200292 # do we have an extends tag at all? If not, we can save some
293 # overhead by just not processing any inheritance code.
294 have_extends = node.find(nodes.Extends) is not None
295
Armin Ronacher8edbe492008-04-10 20:43:43 +0200296 # find all blocks
297 for block in node.find_all(nodes.Block):
298 if block.name in self.blocks:
299 raise TemplateAssertionError('block %r defined twice' %
300 block.name, block.lineno,
301 self.filename)
302 self.blocks[block.name] = block
Armin Ronachere791c2a2008-04-07 18:39:54 +0200303
Armin Ronacher8efc5222008-04-08 14:47:40 +0200304 # generate the root render function.
Armin Ronacher75cfb862008-04-11 13:47:22 +0200305 self.writeline('def root(globals):', extra=1)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200306 self.indent()
Armin Ronacher75cfb862008-04-11 13:47:22 +0200307 self.writeline('context = TemplateContext(globals, filename, blocks)')
308 if have_extends:
309 self.writeline('parent_root = None')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200310 self.outdent()
Armin Ronacher75cfb862008-04-11 13:47:22 +0200311
312 # process the root
Armin Ronachere791c2a2008-04-07 18:39:54 +0200313 frame = Frame()
314 frame.inspect(node.body)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200315 frame.toplevel = frame.rootlevel = True
Armin Ronachere791c2a2008-04-07 18:39:54 +0200316 self.pull_locals(frame)
317 self.blockvisit(node.body, frame, True)
318
Armin Ronacher8efc5222008-04-08 14:47:40 +0200319 # make sure that the parent root is called.
Armin Ronacher75cfb862008-04-11 13:47:22 +0200320 if have_extends:
321 if not self.has_known_extends:
322 self.indent()
323 self.writeline('if parent_root is not None:')
324 self.indent()
325 self.writeline('for event in parent_root(context):')
326 self.indent()
327 self.writeline('yield event')
328 self.outdent(2 + self.has_known_extends)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200329
330 # at this point we now have the blocks collected and can visit them too.
331 for name, block in self.blocks.iteritems():
332 block_frame = Frame()
333 block_frame.inspect(block.body)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200334 block_frame.block = name
335 self.writeline('def block_%s(context):' % name, block, 1)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200336 self.pull_locals(block_frame)
337 self.blockvisit(block.body, block_frame, True)
338
Armin Ronacher75cfb862008-04-11 13:47:22 +0200339 self.writeline('blocks = {%s}' % ', '.join('%r: block_%s' % (x, x)
340 for x in self.blocks), extra=1)
341
Armin Ronachere791c2a2008-04-07 18:39:54 +0200342 def visit_Block(self, node, frame):
343 """Call a block and register it for the template."""
Armin Ronacher75cfb862008-04-11 13:47:22 +0200344 # if we know that we are a child template, there is no need to
345 # check if we are one
346 if self.has_known_extends:
347 return
348 if frame.toplevel:
349 self.writeline('if parent_root is None:')
350 self.indent()
Armin Ronacher8efc5222008-04-08 14:47:40 +0200351 self.writeline('for event in block_%s(context):' % node.name)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200352 self.indent()
353 self.writeline('yield event')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200354 self.outdent(1 + frame.toplevel)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200355
356 def visit_Extends(self, node, frame):
357 """Calls the extender."""
Armin Ronacher8efc5222008-04-08 14:47:40 +0200358 if not frame.toplevel:
359 raise TemplateAssertionError('cannot use extend from a non '
360 'top-level scope', node.lineno,
361 self.filename)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200362
Armin Ronacher7fb38972008-04-11 13:54:28 +0200363 # if the number of extends statements in general is zero so
364 # far, we don't have to add a check if something extended
365 # the template before this one.
366 if self.extends_so_far > 0:
Armin Ronacher75cfb862008-04-11 13:47:22 +0200367
Armin Ronacher7fb38972008-04-11 13:54:28 +0200368 # if we have a known extends we just add a template runtime
369 # error into the generated code. We could catch that at compile
370 # time too, but i welcome it not to confuse users by throwing the
371 # same error at different times just "because we can".
372 if not self.has_known_extends:
373 self.writeline('if parent_root is not None:')
374 self.indent()
375 self.writeline('raise TemplateRuntimeError(%r)' %
376 'extended multiple times')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200377
Armin Ronacher7fb38972008-04-11 13:54:28 +0200378 # if we have a known extends already we don't need that code here
379 # as we know that the template execution will end here.
380 if self.has_known_extends:
381 raise CompilerExit()
382 self.outdent()
383
Armin Ronacher8efc5222008-04-08 14:47:40 +0200384 self.writeline('parent_root = extends(', node, 1)
385 self.visit(node.template, frame)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200386 self.write(', context)')
387
388 # if this extends statement was in the root level we can take
389 # advantage of that information and simplify the generated code
390 # in the top level from this point onwards
391 self.has_known_extends = True
Armin Ronachere791c2a2008-04-07 18:39:54 +0200392
Armin Ronacher7fb38972008-04-11 13:54:28 +0200393 # and now we have one more
394 self.extends_so_far += 1
395
Armin Ronachere791c2a2008-04-07 18:39:54 +0200396 def visit_For(self, node, frame):
397 loop_frame = frame.inner()
398 loop_frame.inspect(node.iter_child_nodes())
Armin Ronachere791c2a2008-04-07 18:39:54 +0200399 extended_loop = bool(node.else_) or \
400 'loop' in loop_frame.identifiers.undeclared
Armin Ronacher8efc5222008-04-08 14:47:40 +0200401 loop_frame.identifiers.add_special('loop')
Armin Ronachere791c2a2008-04-07 18:39:54 +0200402
403 # make sure we "backup" overridden, local identifiers
404 # TODO: we should probably optimize this and check if the
405 # identifier is in use afterwards.
406 aliases = {}
407 for name in loop_frame.identifiers.find_shadowed():
408 aliases[name] = ident = self.temporary_identifier()
409 self.writeline('%s = l_%s' % (ident, name))
410
411 self.pull_locals(loop_frame, True)
412
413 self.newline(node)
414 if node.else_:
415 self.writeline('l_loop = None')
416 self.write('for ')
417 self.visit(node.target, loop_frame)
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200418 self.write(extended_loop and ', l_loop in LoopContext(' or ' in ')
Armin Ronachere791c2a2008-04-07 18:39:54 +0200419 self.visit(node.iter, loop_frame)
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200420 if 'loop' in aliases:
421 self.write(', ' + aliases['loop'])
Armin Ronachere791c2a2008-04-07 18:39:54 +0200422 self.write(extended_loop and '):' or ':')
423 self.blockvisit(node.body, loop_frame)
424
425 if node.else_:
426 self.writeline('if l_loop is None:')
427 self.blockvisit(node.else_, loop_frame)
428
Armin Ronacher8efc5222008-04-08 14:47:40 +0200429 # reset the aliases and clean up
430 delete = set('l_' + x for x in loop_frame.identifiers.declared_locally
431 | loop_frame.identifiers.declared_parameter)
432 if extended_loop:
433 delete.add('l_loop')
Armin Ronachere791c2a2008-04-07 18:39:54 +0200434 for name, alias in aliases.iteritems():
Armin Ronacher8efc5222008-04-08 14:47:40 +0200435 self.writeline('l_%s = %s' % (name, alias))
436 delete.add(alias)
437 delete.discard('l_' + name)
438 self.writeline('del %s' % ', '.join(delete))
Armin Ronachere791c2a2008-04-07 18:39:54 +0200439
440 def visit_If(self, node, frame):
Armin Ronacher75cfb862008-04-11 13:47:22 +0200441 if_frame = frame.soft()
Armin Ronachere791c2a2008-04-07 18:39:54 +0200442 self.writeline('if ', node)
Armin Ronacher75cfb862008-04-11 13:47:22 +0200443 self.visit(node.test, if_frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200444 self.write(':')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200445 self.blockvisit(node.body, if_frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200446 if node.else_:
447 self.writeline('else:')
Armin Ronacher75cfb862008-04-11 13:47:22 +0200448 self.blockvisit(node.else_, if_frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200449
Armin Ronacher8efc5222008-04-08 14:47:40 +0200450 def visit_Macro(self, node, frame):
451 macro_frame = frame.inner()
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200452 macro_frame.inspect(node.iter_child_nodes(), hard_scope=True)
453
454 # variables that are undeclared (accessed before declaration) and
455 # declared locally *and* part of an outside scope raise a template
456 # assertion error. Reason: we can't generate reasonable code from
457 # it without aliasing all the variables. XXX: alias them ^^
458 overriden_closure_vars = (
459 macro_frame.identifiers.undeclared &
460 macro_frame.identifiers.declared &
461 (macro_frame.identifiers.declared_locally |
462 macro_frame.identifiers.declared_parameter)
463 )
464 if overriden_closure_vars:
465 vars = ', '.join(sorted(overriden_closure_vars))
466 raise TemplateAssertionError('It\'s not possible to set and '
467 'access variables derived from '
468 'an outer scope! (affects: %s' %
469 vars, node.lineno, self.filename)
470
471 # remove variables from a closure from the frame's undeclared
472 # identifiers.
473 macro_frame.identifiers.undeclared -= (
474 macro_frame.identifiers.undeclared &
475 macro_frame.identifiers.declared
476 )
477
Armin Ronacher8efc5222008-04-08 14:47:40 +0200478 args = ['l_' + x.name for x in node.args]
479 if 'arguments' in macro_frame.identifiers.undeclared:
480 accesses_arguments = True
481 args.append('l_arguments')
482 else:
483 accesses_arguments = False
484 self.writeline('def macro(%s):' % ', '.join(args), node)
485 self.indent()
486 self.writeline('if 0: yield None')
487 self.outdent()
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200488 self.pull_locals(macro_frame)
489 self.blockvisit(node.body, macro_frame)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200490 self.newline()
491 if frame.toplevel:
492 self.write('context[%r] = ' % node.name)
493 arg_tuple = ', '.join(repr(x.name) for x in node.args)
494 if len(node.args) == 1:
495 arg_tuple += ','
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200496 self.write('l_%s = Macro(macro, %r, (%s), (' % (node.name, node.name,
497 arg_tuple))
498 for arg in node.defaults:
499 self.visit(arg)
500 self.write(', ')
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200501 self.write('), %r)' % accesses_arguments)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200502
Armin Ronachere791c2a2008-04-07 18:39:54 +0200503 def visit_ExprStmt(self, node, frame):
504 self.newline(node)
505 self.visit(node, frame)
506
507 def visit_Output(self, node, frame):
Armin Ronacher75cfb862008-04-11 13:47:22 +0200508 # if we have a known extends statement, we don't output anything
509 if self.has_known_extends:
510 return
Armin Ronachere791c2a2008-04-07 18:39:54 +0200511
Armin Ronacher75cfb862008-04-11 13:47:22 +0200512 self.newline(node)
Armin Ronacher8edbe492008-04-10 20:43:43 +0200513 if self.environment.finalize is unicode:
514 finalizer = 'unicode'
515 else:
516 finalizer = 'context.finalize'
517
Armin Ronacher7fb38972008-04-11 13:54:28 +0200518 # if we are in the toplevel scope and there was already an extends
519 # statement we have to add a check that disables our yield(s) here
520 # so that they don't appear in the output.
521 outdent_later = False
522 if frame.toplevel and self.extends_so_far != 0:
Armin Ronacher75cfb862008-04-11 13:47:22 +0200523 self.writeline('if parent_root is None:')
524 self.indent()
Armin Ronacher7fb38972008-04-11 13:54:28 +0200525 outdent_later = True
Armin Ronacher75cfb862008-04-11 13:47:22 +0200526
Armin Ronachere791c2a2008-04-07 18:39:54 +0200527 # try to evaluate as many chunks as possible into a static
528 # string at compile time.
529 body = []
530 for child in node.nodes:
531 try:
532 const = unicode(child.as_const())
533 except:
534 body.append(child)
535 continue
536 if body and isinstance(body[-1], list):
537 body[-1].append(const)
538 else:
539 body.append([const])
540
541 # if we have less than 3 nodes we just yield them
542 if len(body) < 3:
543 for item in body:
544 if isinstance(item, list):
545 self.writeline('yield %s' % repr(u''.join(item)))
546 else:
547 self.newline(item)
Armin Ronacher8edbe492008-04-10 20:43:43 +0200548 self.write('yield %s(' % finalizer)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200549 self.visit(item, frame)
550 self.write(')')
551
552 # otherwise we create a format string as this is faster in that case
553 else:
554 format = []
555 arguments = []
556 for item in body:
557 if isinstance(item, list):
558 format.append(u''.join(item).replace('%', '%%'))
559 else:
560 format.append('%s')
561 arguments.append(item)
562 self.writeline('yield %r %% (' % u''.join(format))
563 idx = -1
564 for idx, argument in enumerate(arguments):
565 if idx:
566 self.write(', ')
Armin Ronacher8edbe492008-04-10 20:43:43 +0200567 if finalizer != 'unicode':
568 self.write('(')
Armin Ronachere791c2a2008-04-07 18:39:54 +0200569 self.visit(argument, frame)
Armin Ronacher8edbe492008-04-10 20:43:43 +0200570 if finalizer != 'unicode':
571 self.write(')')
Armin Ronachere791c2a2008-04-07 18:39:54 +0200572 self.write(idx == 0 and ',)' or ')')
573
Armin Ronacher7fb38972008-04-11 13:54:28 +0200574 if outdent_later:
Armin Ronacher75cfb862008-04-11 13:47:22 +0200575 self.outdent()
576
Armin Ronacher8efc5222008-04-08 14:47:40 +0200577 def visit_Assign(self, node, frame):
578 self.newline(node)
579 # toplevel assignments however go into the local namespace and
580 # the current template's context. We create a copy of the frame
581 # here and add a set so that the Name visitor can add the assigned
582 # names here.
583 if frame.toplevel:
584 assignment_frame = frame.copy()
585 assignment_frame.assigned_names = set()
586 else:
587 assignment_frame = frame
588 self.visit(node.target, assignment_frame)
589 self.write(' = ')
590 self.visit(node.node, frame)
Armin Ronacher9706fab2008-04-08 18:49:56 +0200591
592 # make sure toplevel assignments are added to the context.
Armin Ronacher8efc5222008-04-08 14:47:40 +0200593 if frame.toplevel:
594 for name in assignment_frame.assigned_names:
595 self.writeline('context[%r] = l_%s' % (name, name))
596
Armin Ronachere791c2a2008-04-07 18:39:54 +0200597 def visit_Name(self, node, frame):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200598 if frame.toplevel and node.ctx == 'store':
599 frame.assigned_names.add(node.name)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200600 self.write('l_' + node.name)
601
602 def visit_Const(self, node, frame):
603 val = node.value
604 if isinstance(val, float):
605 # XXX: add checks for infinity and nan
606 self.write(str(val))
607 else:
608 self.write(repr(val))
609
Armin Ronacher8efc5222008-04-08 14:47:40 +0200610 def visit_Tuple(self, node, frame):
611 self.write('(')
612 idx = -1
613 for idx, item in enumerate(node.items):
614 if idx:
615 self.write(', ')
616 self.visit(item, frame)
617 self.write(idx == 0 and ',)' or ')')
618
Armin Ronacher8edbe492008-04-10 20:43:43 +0200619 def visit_List(self, node, frame):
620 self.write('[')
621 for idx, item in enumerate(node.items):
622 if idx:
623 self.write(', ')
624 self.visit(item, frame)
625 self.write(']')
626
627 def visit_Dict(self, node, frame):
628 self.write('{')
629 for idx, item in enumerate(node.items):
630 if idx:
631 self.write(', ')
632 self.visit(item.key, frame)
633 self.write(': ')
634 self.visit(item.value, frame)
635 self.write('}')
636
Armin Ronachere791c2a2008-04-07 18:39:54 +0200637 def binop(operator):
638 def visitor(self, node, frame):
639 self.write('(')
640 self.visit(node.left, frame)
641 self.write(' %s ' % operator)
642 self.visit(node.right, frame)
643 self.write(')')
644 return visitor
645
646 def uaop(operator):
647 def visitor(self, node, frame):
648 self.write('(' + operator)
649 self.visit(node.node)
650 self.write(')')
651 return visitor
652
653 visit_Add = binop('+')
654 visit_Sub = binop('-')
655 visit_Mul = binop('*')
656 visit_Div = binop('/')
657 visit_FloorDiv = binop('//')
658 visit_Pow = binop('**')
659 visit_Mod = binop('%')
660 visit_And = binop('and')
661 visit_Or = binop('or')
662 visit_Pos = uaop('+')
663 visit_Neg = uaop('-')
664 visit_Not = uaop('not ')
665 del binop, uaop
666
667 def visit_Compare(self, node, frame):
668 self.visit(node.expr, frame)
669 for op in node.ops:
670 self.visit(op, frame)
671
672 def visit_Operand(self, node, frame):
673 self.write(' %s ' % operators[node.op])
674 self.visit(node.expr, frame)
675
676 def visit_Subscript(self, node, frame):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200677 if isinstance(node.arg, nodes.Slice):
678 self.visit(node.node, frame)
679 self.write('[')
680 self.visit(node.arg, frame)
681 self.write(']')
682 return
683 try:
684 const = node.arg.as_const()
685 have_const = True
686 except nodes.Impossible:
687 have_const = False
688 if have_const:
689 if isinstance(const, (int, long, float)):
690 self.visit(node.node, frame)
691 self.write('[%s]' % const)
692 return
693 self.write('subscribe(')
Armin Ronachere791c2a2008-04-07 18:39:54 +0200694 self.visit(node.node, frame)
695 self.write(', ')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200696 if have_const:
697 self.write(repr(const))
698 else:
699 self.visit(node.arg, frame)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200700 self.write(')')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200701
702 def visit_Slice(self, node, frame):
703 if node.start is not None:
704 self.visit(node.start, frame)
705 self.write(':')
706 if node.stop is not None:
707 self.visit(node.stop, frame)
708 if node.step is not None:
709 self.write(':')
710 self.visit(node.step, frame)
711
712 def visit_Filter(self, node, frame):
Armin Ronacherd55ab532008-04-09 16:13:39 +0200713 if node.name in frame.identifiers.declared_filter:
714 self.write('f_%s(' % node.name)
715 else:
716 self.write('context.filter[%r](' % node.name)
Armin Ronacher8efc5222008-04-08 14:47:40 +0200717 self.visit(node.node, frame)
Armin Ronacherd55ab532008-04-09 16:13:39 +0200718 self.signature(node, frame)
719 self.write(')')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200720
721 def visit_Test(self, node, frame):
722 self.write('context.tests[%r](')
723 self.visit(node.node, frame)
724 self.signature(node, frame)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200725 self.write(')')
Armin Ronacher8efc5222008-04-08 14:47:40 +0200726
727 def visit_Call(self, node, frame):
728 self.visit(node.node, frame)
729 self.write('(')
730 self.signature(node, frame, False)
731 self.write(')')
732
733 def visit_Keyword(self, node, frame):
734 self.visit(node.key, frame)
735 self.write('=')
736 self.visit(node.value, frame)