blob: effa6d4adad454bff547d033dd9cbcb55e2ea587 [file] [log] [blame]
Armin Ronacher07bc6842008-03-31 14:18:49 +02001# -*- coding: utf-8 -*-
2"""
3 jinja2.nodes
4 ~~~~~~~~~~~~
5
6 This module implements additional nodes derived from the ast base node.
7
8 It also provides some node tree helper functions like `in_lineno` and
9 `get_nodes` used by the parser and translator in order to normalize
10 python and jinja nodes.
11
Armin Ronacher4f7d2d52008-04-22 10:40:26 +020012 :copyright: 2008 by Armin Ronacher.
Armin Ronacher07bc6842008-03-31 14:18:49 +020013 :license: BSD, see LICENSE for more details.
14"""
15import operator
Armin Ronacher7ceced52008-05-03 10:15:31 +020016from copy import copy
Armin Ronacher07bc6842008-03-31 14:18:49 +020017from itertools import chain, izip
Armin Ronacher82b3f3d2008-03-31 20:01:08 +020018from collections import deque
Armin Ronacherd84ec462008-04-29 13:43:16 +020019from jinja2.utils import Markup
Armin Ronacher07bc6842008-03-31 14:18:49 +020020
21
22_binop_to_func = {
23 '*': operator.mul,
24 '/': operator.truediv,
25 '//': operator.floordiv,
26 '**': operator.pow,
27 '%': operator.mod,
28 '+': operator.add,
29 '-': operator.sub
30}
31
32_uaop_to_func = {
33 'not': operator.not_,
34 '+': operator.pos,
35 '-': operator.neg
36}
37
Armin Ronacher625215e2008-04-13 16:31:08 +020038_cmpop_to_func = {
39 'eq': operator.eq,
40 'ne': operator.ne,
41 'gt': operator.gt,
42 'gteq': operator.ge,
43 'lt': operator.lt,
44 'lteq': operator.le,
Armin Ronacherb5124e62008-04-25 00:36:14 +020045 'in': lambda a, b: a in b,
46 'notin': lambda a, b: a not in b
Armin Ronacher625215e2008-04-13 16:31:08 +020047}
48
Armin Ronacher07bc6842008-03-31 14:18:49 +020049
50class Impossible(Exception):
Armin Ronacher8efc5222008-04-08 14:47:40 +020051 """Raised if the node could not perform a requested action."""
Armin Ronacher07bc6842008-03-31 14:18:49 +020052
53
54class NodeType(type):
Armin Ronacher8efc5222008-04-08 14:47:40 +020055 """A metaclass for nodes that handles the field and attribute
56 inheritance. fields and attributes from the parent class are
57 automatically forwarded to the child."""
Armin Ronacher07bc6842008-03-31 14:18:49 +020058
59 def __new__(cls, name, bases, d):
Armin Ronachere791c2a2008-04-07 18:39:54 +020060 for attr in 'fields', 'attributes':
Armin Ronacher07bc6842008-03-31 14:18:49 +020061 storage = []
Armin Ronacher7324eb82008-04-21 07:55:52 +020062 storage.extend(getattr(bases[0], attr, ()))
Armin Ronacher07bc6842008-03-31 14:18:49 +020063 storage.extend(d.get(attr, ()))
Armin Ronacher7324eb82008-04-21 07:55:52 +020064 assert len(bases) == 1, 'multiple inheritance not allowed'
65 assert len(storage) == len(set(storage)), 'layout conflict'
Armin Ronacher07bc6842008-03-31 14:18:49 +020066 d[attr] = tuple(storage)
Armin Ronacher023b5e92008-05-08 11:03:10 +020067 d.setdefault('abstract', False)
Armin Ronacher7324eb82008-04-21 07:55:52 +020068 return type.__new__(cls, name, bases, d)
Armin Ronacher07bc6842008-03-31 14:18:49 +020069
70
71class Node(object):
Armin Ronacher023b5e92008-05-08 11:03:10 +020072 """Baseclass for all Jinja2 nodes. There are a number of nodes available
73 of different types. There are three major types:
74
75 - :class:`Stmt`: statements
76 - :class:`Expr`: expressions
77 - :class:`Helper`: helper nodes
78 - :class:`Template`: the outermost wrapper node
79
80 All nodes have fields and attributes. Fields may be other nodes, lists,
81 or arbitrary values. Fields are passed to the constructor as regular
82 positional arguments, attributes as keyword arguments. Each node has
83 two attributes: `lineno` (the line number of the node) and `environment`.
84 The `environment` attribute is set at the end of the parsing process for
85 all nodes automatically.
86 """
Armin Ronacher07bc6842008-03-31 14:18:49 +020087 __metaclass__ = NodeType
Armin Ronachere791c2a2008-04-07 18:39:54 +020088 fields = ()
Armin Ronacherd55ab532008-04-09 16:13:39 +020089 attributes = ('lineno', 'environment')
Armin Ronacher023b5e92008-05-08 11:03:10 +020090 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +020091
Armin Ronacher023b5e92008-05-08 11:03:10 +020092 def __init__(self, *fields, **attributes):
Armin Ronacher69e12db2008-05-12 09:00:03 +020093 if self.abstract:
94 raise TypeError('abstract nodes are not instanciable')
Armin Ronacher023b5e92008-05-08 11:03:10 +020095 if fields:
96 if len(fields) != len(self.fields):
Armin Ronachere791c2a2008-04-07 18:39:54 +020097 if not self.fields:
Armin Ronacher07bc6842008-03-31 14:18:49 +020098 raise TypeError('%r takes 0 arguments' %
99 self.__class__.__name__)
100 raise TypeError('%r takes 0 or %d argument%s' % (
101 self.__class__.__name__,
Armin Ronachere791c2a2008-04-07 18:39:54 +0200102 len(self.fields),
103 len(self.fields) != 1 and 's' or ''
Armin Ronacher07bc6842008-03-31 14:18:49 +0200104 ))
Armin Ronacher023b5e92008-05-08 11:03:10 +0200105 for name, arg in izip(self.fields, fields):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200106 setattr(self, name, arg)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200107 for attr in self.attributes:
Armin Ronacher023b5e92008-05-08 11:03:10 +0200108 setattr(self, attr, attributes.pop(attr, None))
109 if attributes:
110 raise TypeError('unknown attribute %r' %
111 iter(attributes).next())
Armin Ronacher07bc6842008-03-31 14:18:49 +0200112
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200113 def iter_fields(self, exclude=None, only=None):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200114 """This method iterates over all fields that are defined and yields
Armin Ronacher3da90312008-05-23 16:37:28 +0200115 ``(key, value)`` tuples. Per default all fields are returned, but
116 it's possible to limit that to some fields by providing the `only`
117 parameter or to exclude some using the `exclude` parameter. Both
118 should be sets or tuples of field names.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200119 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200120 for name in self.fields:
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200121 if (exclude is only is None) or \
122 (exclude is not None and name not in exclude) or \
123 (only is not None and name in only):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200124 try:
125 yield name, getattr(self, name)
126 except AttributeError:
127 pass
Armin Ronacher07bc6842008-03-31 14:18:49 +0200128
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200129 def iter_child_nodes(self, exclude=None, only=None):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200130 """Iterates over all direct child nodes of the node. This iterates
131 over all fields and yields the values of they are nodes. If the value
132 of a field is a list all the nodes in that list are returned.
133 """
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200134 for field, item in self.iter_fields(exclude, only):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200135 if isinstance(item, list):
136 for n in item:
137 if isinstance(n, Node):
138 yield n
139 elif isinstance(item, Node):
140 yield item
141
Armin Ronachere791c2a2008-04-07 18:39:54 +0200142 def find(self, node_type):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200143 """Find the first node of a given type. If no such node exists the
144 return value is `None`.
145 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200146 for result in self.find_all(node_type):
147 return result
148
149 def find_all(self, node_type):
150 """Find all the nodes of a given type."""
151 for child in self.iter_child_nodes():
152 if isinstance(child, node_type):
153 yield child
154 for result in child.find_all(node_type):
155 yield result
156
Armin Ronacher0ecb8592008-04-09 16:29:47 +0200157 def copy(self):
158 """Return a deep copy of the node."""
159 result = object.__new__(self.__class__)
160 for field, value in self.iter_fields():
161 if isinstance(value, Node):
162 new_value = value.copy()
163 elif isinstance(value, list):
164 new_value = []
Armin Ronacherd436e982008-04-09 16:31:20 +0200165 for item in value:
Armin Ronacher0ecb8592008-04-09 16:29:47 +0200166 if isinstance(item, Node):
167 item = item.copy()
168 else:
169 item = copy(item)
170 new_value.append(item)
171 else:
Armin Ronacherd436e982008-04-09 16:31:20 +0200172 new_value = copy(value)
Armin Ronacher0ecb8592008-04-09 16:29:47 +0200173 setattr(result, field, new_value)
174 for attr in self.attributes:
175 try:
176 setattr(result, attr, getattr(self, attr))
177 except AttributeError:
178 pass
179 return result
180
Armin Ronachere791c2a2008-04-07 18:39:54 +0200181 def set_ctx(self, ctx):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200182 """Reset the context of a node and all child nodes. Per default the
183 parser will all generate nodes that have a 'load' context as it's the
184 most common one. This method is used in the parser to set assignment
185 targets and other nodes to a store context.
Armin Ronachere791c2a2008-04-07 18:39:54 +0200186 """
187 todo = deque([self])
188 while todo:
189 node = todo.popleft()
190 if 'ctx' in node.fields:
191 node.ctx = ctx
192 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200193 return self
Armin Ronachere791c2a2008-04-07 18:39:54 +0200194
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200195 def set_lineno(self, lineno, override=False):
196 """Set the line numbers of the node and children."""
197 todo = deque([self])
198 while todo:
199 node = todo.popleft()
200 if 'lineno' in node.attributes:
201 if node.lineno is None or override:
202 node.lineno = lineno
203 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200204 return self
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200205
Armin Ronacherd55ab532008-04-09 16:13:39 +0200206 def set_environment(self, environment):
207 """Set the environment for all nodes."""
208 todo = deque([self])
209 while todo:
210 node = todo.popleft()
211 node.environment = environment
212 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200213 return self
Armin Ronacherd55ab532008-04-09 16:13:39 +0200214
Armin Ronacher69e12db2008-05-12 09:00:03 +0200215 def __eq__(self, other):
Armin Ronacherb3a1fcf2008-05-15 11:04:14 +0200216 return type(self) is type(other) and \
217 tuple(self.iter_fields()) == tuple(other.iter_fields())
Armin Ronacher69e12db2008-05-12 09:00:03 +0200218
219 def __ne__(self, other):
220 return not self.__eq__(other)
221
Armin Ronacher07bc6842008-03-31 14:18:49 +0200222 def __repr__(self):
223 return '%s(%s)' % (
224 self.__class__.__name__,
225 ', '.join('%s=%r' % (arg, getattr(self, arg, None)) for
Armin Ronachere791c2a2008-04-07 18:39:54 +0200226 arg in self.fields)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200227 )
228
229
230class Stmt(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200231 """Base node for all statements."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200232 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200233
234
235class Helper(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200236 """Nodes that exist in a specific context only."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200237 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200238
239
240class Template(Node):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200241 """Node that represents a template. This must be the outermost node that
242 is passed to the compiler.
243 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200244 fields = ('body',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200245
246
247class Output(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200248 """A node that holds multiple expressions which are then printed out.
249 This is used both for the `print` statement and the regular template data.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200250 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200251 fields = ('nodes',)
252
Armin Ronacher07bc6842008-03-31 14:18:49 +0200253
254class Extends(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200255 """Represents an extends statement."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200256 fields = ('template',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200257
258
259class For(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200260 """The for loop. `target` is the target for the iteration (usually a
261 :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list
262 of nodes that are used as loop-body, and `else_` a list of nodes for the
263 `else` block. If no else node exists it has to be an empty list.
264
265 For filtered nodes an expression can be stored as `test`, otherwise `None`.
266 """
Armin Ronacherfdf95302008-05-11 22:20:51 +0200267 fields = ('target', 'iter', 'body', 'else_', 'test', 'recursive')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200268
269
270class If(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200271 """If `test` is true, `body` is rendered, else `else_`."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200272 fields = ('test', 'body', 'else_')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200273
274
275class Macro(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200276 """A macro definition. `name` is the name of the macro, `args` a list of
277 arguments and `defaults` a list of defaults if there are any. `body` is
278 a list of nodes for the macro body.
279 """
Armin Ronacher8efc5222008-04-08 14:47:40 +0200280 fields = ('name', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200281
282
283class CallBlock(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200284 """Like a macro without a name but a call instead. `call` is called with
285 the unnamed macro as `caller` argument this node holds.
286 """
Armin Ronacherc9705c22008-04-27 21:28:03 +0200287 fields = ('call', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200288
289
290class Set(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200291 """Allows defining own variables."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200292 fields = ('name', 'expr')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200293
294
295class FilterBlock(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200296 """Node for filter sections."""
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200297 fields = ('body', 'filter')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200298
299
300class Block(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200301 """A node that represents a block."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200302 fields = ('name', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200303
304
305class Include(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200306 """A node that represents the include tag."""
Armin Ronacherea847c52008-05-02 20:04:32 +0200307 fields = ('template', 'with_context')
Armin Ronacher0611e492008-04-25 23:44:14 +0200308
309
310class Import(Stmt):
311 """A node that represents the import tag."""
Armin Ronacherea847c52008-05-02 20:04:32 +0200312 fields = ('template', 'target', 'with_context')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200313
314
Armin Ronacher0611e492008-04-25 23:44:14 +0200315class FromImport(Stmt):
316 """A node that represents the from import tag. It's important to not
317 pass unsafe names to the name attribute. The compiler translates the
318 attribute lookups directly into getattr calls and does *not* use the
Armin Ronacherb9388772008-06-25 20:43:18 +0200319 subscript callback of the interface. As exported variables may not
Armin Ronacher0611e492008-04-25 23:44:14 +0200320 start with double underscores (which the parser asserts) this is not a
321 problem for regular Jinja code, but if this node is used in an extension
322 extra care must be taken.
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200323
324 The list of names may contain tuples if aliases are wanted.
Armin Ronacher0611e492008-04-25 23:44:14 +0200325 """
Armin Ronacherea847c52008-05-02 20:04:32 +0200326 fields = ('template', 'names', 'with_context')
Armin Ronacher0611e492008-04-25 23:44:14 +0200327
328
Armin Ronacher07bc6842008-03-31 14:18:49 +0200329class ExprStmt(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200330 """A statement that evaluates an expression and discards the result."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200331 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200332
333
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200334class Assign(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200335 """Assigns an expression to a target."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200336 fields = ('target', 'node')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200337
338
Armin Ronacher07bc6842008-03-31 14:18:49 +0200339class Expr(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200340 """Baseclass for all expressions."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200341 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200342
343 def as_const(self):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200344 """Return the value of the expression as constant or raise
Armin Ronacher023b5e92008-05-08 11:03:10 +0200345 :exc:`Impossible` if this was not possible:
346
347 >>> Add(Const(23), Const(42)).as_const()
348 65
349 >>> Add(Const(23), Name('var', 'load')).as_const()
350 Traceback (most recent call last):
351 ...
352 Impossible
353
354 This requires the `environment` attribute of all nodes to be
355 set to the environment that created the nodes.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200356 """
357 raise Impossible()
358
359 def can_assign(self):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200360 """Check if it's possible to assign something to this node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200361 return False
362
363
364class BinExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200365 """Baseclass for all binary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200366 fields = ('left', 'right')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200367 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200368 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200369
370 def as_const(self):
371 f = _binop_to_func[self.operator]
372 try:
373 return f(self.left.as_const(), self.right.as_const())
374 except:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200375 raise Impossible()
376
377
378class UnaryExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200379 """Baseclass for all unary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200380 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200381 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200382 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200383
384 def as_const(self):
385 f = _uaop_to_func[self.operator]
386 try:
387 return f(self.node.as_const())
388 except:
389 raise Impossible()
390
391
392class Name(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200393 """Looks up a name or stores a value in a name.
394 The `ctx` of the node can be one of the following values:
395
396 - `store`: store a value in the name
397 - `load`: load that name
398 - `param`: like `store` but if the name was defined as function parameter.
399 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200400 fields = ('name', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200401
402 def can_assign(self):
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200403 return self.name not in ('true', 'false', 'none',
404 'True', 'False', 'None')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200405
406
407class Literal(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200408 """Baseclass for literals."""
Armin Ronacher69e12db2008-05-12 09:00:03 +0200409 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200410
411
412class Const(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200413 """All constant values. The parser will return this node for simple
414 constants such as ``42`` or ``"foo"`` but it can be used to store more
415 complex values such as lists too. Only constants with a safe
416 representation (objects where ``eval(repr(x)) == x`` is true).
417 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200418 fields = ('value',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200419
420 def as_const(self):
421 return self.value
422
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200423 @classmethod
Armin Ronacherd55ab532008-04-09 16:13:39 +0200424 def from_untrusted(cls, value, lineno=None, environment=None):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200425 """Return a const object if the value is representable as
426 constant value in the generated code, otherwise it will raise
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200427 an `Impossible` exception.
428 """
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200429 from compiler import has_safe_repr
430 if not has_safe_repr(value):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200431 raise Impossible()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200432 return cls(value, lineno=lineno, environment=environment)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200433
Armin Ronacher07bc6842008-03-31 14:18:49 +0200434
Armin Ronacher5411ce72008-05-25 11:36:22 +0200435class TemplateData(Literal):
436 """A constant template string."""
437 fields = ('data',)
438
439 def as_const(self):
440 if self.environment.autoescape:
441 return Markup(self.data)
442 return self.data
443
444
Armin Ronacher07bc6842008-03-31 14:18:49 +0200445class Tuple(Literal):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200446 """For loop unpacking and some other things like multiple arguments
Armin Ronacher023b5e92008-05-08 11:03:10 +0200447 for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
448 is used for loading the names or storing.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200449 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200450 fields = ('items', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200451
452 def as_const(self):
453 return tuple(x.as_const() for x in self.items)
454
455 def can_assign(self):
456 for item in self.items:
457 if not item.can_assign():
458 return False
459 return True
460
461
462class List(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200463 """Any list literal such as ``[1, 2, 3]``"""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200464 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200465
466 def as_const(self):
467 return [x.as_const() for x in self.items]
468
469
470class Dict(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200471 """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
472 :class:`Pair` nodes.
473 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200474 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200475
476 def as_const(self):
477 return dict(x.as_const() for x in self.items)
478
479
480class Pair(Helper):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200481 """A key, value pair for dicts."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200482 fields = ('key', 'value')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200483
484 def as_const(self):
485 return self.key.as_const(), self.value.as_const()
486
487
Armin Ronacher8efc5222008-04-08 14:47:40 +0200488class Keyword(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200489 """A key, value pair for keyword arguments where key is a string."""
Armin Ronacher8efc5222008-04-08 14:47:40 +0200490 fields = ('key', 'value')
491
492
Armin Ronacher07bc6842008-03-31 14:18:49 +0200493class CondExpr(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200494 """A conditional expression (inline if expression). (``{{
495 foo if bar else baz }}``)
496 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200497 fields = ('test', 'expr1', 'expr2')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200498
499 def as_const(self):
500 if self.test.as_const():
501 return self.expr1.as_const()
Armin Ronacher547d0b62008-07-04 16:35:10 +0200502
503 # if we evaluate to an undefined object, we better do that at runtime
504 if self.expr2 is None:
505 raise Impossible()
506
Armin Ronacher07bc6842008-03-31 14:18:49 +0200507 return self.expr2.as_const()
508
509
510class Filter(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200511 """This node applies a filter on an expression. `name` is the name of
512 the filter, the rest of the fields are the same as for :class:`Call`.
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200513
514 If the `node` of a filter is `None` the contents of the last buffer are
515 filtered. Buffers are created by macros and filter blocks.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200516 """
Armin Ronacherd55ab532008-04-09 16:13:39 +0200517 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200518
Armin Ronacher00d5d212008-04-13 01:10:18 +0200519 def as_const(self, obj=None):
520 if self.node is obj is None:
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200521 raise Impossible()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200522 filter = self.environment.filters.get(self.name)
523 if filter is None or getattr(filter, 'contextfilter', False):
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200524 raise Impossible()
Armin Ronacher00d5d212008-04-13 01:10:18 +0200525 if obj is None:
526 obj = self.node.as_const()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200527 args = [x.as_const() for x in self.args]
Armin Ronacher9a027f42008-04-17 11:13:40 +0200528 if getattr(filter, 'environmentfilter', False):
529 args.insert(0, self.environment)
Armin Ronacherd55ab532008-04-09 16:13:39 +0200530 kwargs = dict(x.as_const() for x in self.kwargs)
531 if self.dyn_args is not None:
532 try:
533 args.extend(self.dyn_args.as_const())
534 except:
535 raise Impossible()
536 if self.dyn_kwargs is not None:
537 try:
538 kwargs.update(self.dyn_kwargs.as_const())
539 except:
540 raise Impossible()
541 try:
542 return filter(obj, *args, **kwargs)
543 except:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200544 raise Impossible()
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200545
546
Armin Ronacher07bc6842008-03-31 14:18:49 +0200547class Test(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200548 """Applies a test on an expression. `name` is the name of the test, the
549 rest of the fields are the same as for :class:`Call`.
550 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200551 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200552
553
554class Call(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200555 """Calls an expression. `args` is a list of arguments, `kwargs` a list
556 of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
557 and `dyn_kwargs` has to be either `None` or a node that is used as
558 node for dynamic positional (``*args``) or keyword (``**kwargs``)
559 arguments.
560 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200561 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200562
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200563 def as_const(self):
564 obj = self.node.as_const()
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200565
566 # don't evaluate context functions
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200567 args = [x.as_const() for x in self.args]
Armin Ronacherfd310492008-05-25 00:16:51 +0200568 if getattr(obj, 'contextfunction', False):
569 raise Impossible()
570 elif getattr(obj, 'environmentfunction', False):
571 args.insert(0, self.environment)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200572
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200573 kwargs = dict(x.as_const() for x in self.kwargs)
574 if self.dyn_args is not None:
575 try:
576 args.extend(self.dyn_args.as_const())
577 except:
578 raise Impossible()
579 if self.dyn_kwargs is not None:
580 try:
Armin Ronacherd55ab532008-04-09 16:13:39 +0200581 kwargs.update(self.dyn_kwargs.as_const())
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200582 except:
583 raise Impossible()
584 try:
585 return obj(*args, **kwargs)
586 except:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200587 raise Impossible()
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200588
Armin Ronacher07bc6842008-03-31 14:18:49 +0200589
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200590class Getitem(Expr):
Armin Ronacherb9388772008-06-25 20:43:18 +0200591 """Get an attribute or item from an expression and prefer the item."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200592 fields = ('node', 'arg', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200593
594 def as_const(self):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200595 if self.ctx != 'load':
596 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200597 try:
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200598 return self.environment.getitem(self.node.as_const(),
599 self.arg.as_const())
600 except:
601 raise Impossible()
602
603 def can_assign(self):
604 return False
605
606
607class Getattr(Expr):
Armin Ronacherb9388772008-06-25 20:43:18 +0200608 """Get an attribute or item from an expression that is a ascii-only
609 bytestring and prefer the attribute.
610 """
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200611 fields = ('node', 'attr', 'ctx')
612
613 def as_const(self):
614 if self.ctx != 'load':
615 raise Impossible()
616 try:
617 return self.environment.getattr(self.node.as_const(), arg)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200618 except:
619 raise Impossible()
620
621 def can_assign(self):
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200622 return False
Armin Ronacher07bc6842008-03-31 14:18:49 +0200623
624
625class Slice(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200626 """Represents a slice object. This must only be used as argument for
627 :class:`Subscript`.
628 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200629 fields = ('start', 'stop', 'step')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200630
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200631 def as_const(self):
632 def const(obj):
633 if obj is None:
634 return obj
635 return obj.as_const()
636 return slice(const(self.start), const(self.stop), const(self.step))
637
Armin Ronacher07bc6842008-03-31 14:18:49 +0200638
639class Concat(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200640 """Concatenates the list of expressions provided after converting them to
641 unicode.
642 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200643 fields = ('nodes',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200644
645 def as_const(self):
646 return ''.join(unicode(x.as_const()) for x in self.nodes)
647
648
649class Compare(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200650 """Compares an expression with some other expressions. `ops` must be a
651 list of :class:`Operand`\s.
652 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200653 fields = ('expr', 'ops')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200654
Armin Ronacher625215e2008-04-13 16:31:08 +0200655 def as_const(self):
656 result = value = self.expr.as_const()
Armin Ronacherb5124e62008-04-25 00:36:14 +0200657 try:
658 for op in self.ops:
659 new_value = op.expr.as_const()
660 result = _cmpop_to_func[op.op](value, new_value)
661 value = new_value
662 except:
663 raise Impossible()
Armin Ronacher625215e2008-04-13 16:31:08 +0200664 return result
665
Armin Ronacher07bc6842008-03-31 14:18:49 +0200666
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200667class Operand(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200668 """Holds an operator and an expression."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200669 fields = ('op', 'expr')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200670
Armin Ronacher023b5e92008-05-08 11:03:10 +0200671if __debug__:
672 Operand.__doc__ += '\nThe following operators are available: ' + \
673 ', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
674 set(_uaop_to_func) | set(_cmpop_to_func)))
675
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200676
Armin Ronacher07bc6842008-03-31 14:18:49 +0200677class Mul(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200678 """Multiplies the left with the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200679 operator = '*'
680
681
682class Div(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200683 """Divides the left by the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200684 operator = '/'
685
686
687class FloorDiv(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200688 """Divides the left by the right node and truncates conver the
689 result into an integer by truncating.
690 """
Armin Ronacher07bc6842008-03-31 14:18:49 +0200691 operator = '//'
692
693
694class Add(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200695 """Add the left to the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200696 operator = '+'
697
698
699class Sub(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200700 """Substract the right from the left node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200701 operator = '-'
702
703
704class Mod(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200705 """Left modulo right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200706 operator = '%'
707
708
709class Pow(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200710 """Left to the power of right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200711 operator = '**'
712
713
714class And(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200715 """Short circuited AND."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200716 operator = 'and'
717
718 def as_const(self):
719 return self.left.as_const() and self.right.as_const()
720
721
722class Or(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200723 """Short circuited OR."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200724 operator = 'or'
725
726 def as_const(self):
727 return self.left.as_const() or self.right.as_const()
728
729
730class Not(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200731 """Negate the expression."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200732 operator = 'not'
733
734
Armin Ronachere791c2a2008-04-07 18:39:54 +0200735class Neg(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200736 """Make the expression negative."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200737 operator = '-'
738
739
Armin Ronachere791c2a2008-04-07 18:39:54 +0200740class Pos(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200741 """Make the expression positive (noop for most expressions)"""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200742 operator = '+'
Armin Ronacher023b5e92008-05-08 11:03:10 +0200743
744
745# Helpers for extensions
746
747
748class EnvironmentAttribute(Expr):
749 """Loads an attribute from the environment object. This is useful for
750 extensions that want to call a callback stored on the environment.
751 """
752 fields = ('name',)
753
754
755class ExtensionAttribute(Expr):
756 """Returns the attribute of an extension bound to the environment.
757 The identifier is the identifier of the :class:`Extension`.
Armin Ronacherb9e78752008-05-10 23:36:28 +0200758
759 This node is usually constructed by calling the
760 :meth:`~jinja2.ext.Extension.attr` method on an extension.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200761 """
Armin Ronacher6df604e2008-05-23 22:18:38 +0200762 fields = ('identifier', 'name')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200763
764
765class ImportedName(Expr):
766 """If created with an import name the import name is returned on node
767 access. For example ``ImportedName('cgi.escape')`` returns the `escape`
768 function from the cgi module on evaluation. Imports are optimized by the
769 compiler so there is no need to assign them to local variables.
770 """
771 fields = ('importname',)
772
773
774class InternalName(Expr):
775 """An internal name in the compiler. You cannot create these nodes
Armin Ronacher762079c2008-05-08 23:57:56 +0200776 yourself but the parser provides a
777 :meth:`~jinja2.parser.Parser.free_identifier` method that creates
Armin Ronacher023b5e92008-05-08 11:03:10 +0200778 a new identifier for you. This identifier is not available from the
779 template and is not threated specially by the compiler.
780 """
781 fields = ('name',)
782
783 def __init__(self):
784 raise TypeError('Can\'t create internal names. Use the '
785 '`free_identifier` method on a parser.')
786
787
788class MarkSafe(Expr):
789 """Mark the wrapped expression as safe (wrap it as `Markup`)."""
790 fields = ('expr',)
791
792 def as_const(self):
793 return Markup(self.expr.as_const())
794
795
Armin Ronacher6df604e2008-05-23 22:18:38 +0200796class ContextReference(Expr):
797 """Returns the current template context."""
798
799
Armin Ronachered1e0d42008-05-18 20:25:28 +0200800class Continue(Stmt):
801 """Continue a loop."""
802
803
804class Break(Stmt):
805 """Break a loop."""
806
807
Armin Ronacher8a1d27f2008-05-19 08:37:19 +0200808# make sure nobody creates custom nodes
809def _failing_new(*args, **kwargs):
810 raise TypeError('can\'t create custom node types')
811NodeType.__new__ = staticmethod(_failing_new); del _failing_new