blob: 9eb54606db217224e5a7aa217919196ec9a41036 [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
319 subscribe callback of the interface. As exported variables may not
320 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 Ronachere791c2a2008-04-07 18:39:54 +0200403 return self.name not in ('true', 'false', 'none')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200404
405
406class Literal(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200407 """Baseclass for literals."""
Armin Ronacher69e12db2008-05-12 09:00:03 +0200408 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200409
410
411class Const(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200412 """All constant values. The parser will return this node for simple
413 constants such as ``42`` or ``"foo"`` but it can be used to store more
414 complex values such as lists too. Only constants with a safe
415 representation (objects where ``eval(repr(x)) == x`` is true).
416 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200417 fields = ('value',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200418
419 def as_const(self):
420 return self.value
421
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200422 @classmethod
Armin Ronacherd55ab532008-04-09 16:13:39 +0200423 def from_untrusted(cls, value, lineno=None, environment=None):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200424 """Return a const object if the value is representable as
425 constant value in the generated code, otherwise it will raise
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200426 an `Impossible` exception.
427 """
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200428 from compiler import has_safe_repr
429 if not has_safe_repr(value):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200430 raise Impossible()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200431 return cls(value, lineno=lineno, environment=environment)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200432
Armin Ronacher07bc6842008-03-31 14:18:49 +0200433
434class Tuple(Literal):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200435 """For loop unpacking and some other things like multiple arguments
Armin Ronacher023b5e92008-05-08 11:03:10 +0200436 for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
437 is used for loading the names or storing.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200438 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200439 fields = ('items', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200440
441 def as_const(self):
442 return tuple(x.as_const() for x in self.items)
443
444 def can_assign(self):
445 for item in self.items:
446 if not item.can_assign():
447 return False
448 return True
449
450
451class List(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200452 """Any list literal such as ``[1, 2, 3]``"""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200453 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200454
455 def as_const(self):
456 return [x.as_const() for x in self.items]
457
458
459class Dict(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200460 """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
461 :class:`Pair` nodes.
462 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200463 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200464
465 def as_const(self):
466 return dict(x.as_const() for x in self.items)
467
468
469class Pair(Helper):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200470 """A key, value pair for dicts."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200471 fields = ('key', 'value')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200472
473 def as_const(self):
474 return self.key.as_const(), self.value.as_const()
475
476
Armin Ronacher8efc5222008-04-08 14:47:40 +0200477class Keyword(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200478 """A key, value pair for keyword arguments where key is a string."""
Armin Ronacher8efc5222008-04-08 14:47:40 +0200479 fields = ('key', 'value')
480
481
Armin Ronacher07bc6842008-03-31 14:18:49 +0200482class CondExpr(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200483 """A conditional expression (inline if expression). (``{{
484 foo if bar else baz }}``)
485 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200486 fields = ('test', 'expr1', 'expr2')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200487
488 def as_const(self):
489 if self.test.as_const():
490 return self.expr1.as_const()
491 return self.expr2.as_const()
492
493
494class Filter(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200495 """This node applies a filter on an expression. `name` is the name of
496 the filter, the rest of the fields are the same as for :class:`Call`.
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200497
498 If the `node` of a filter is `None` the contents of the last buffer are
499 filtered. Buffers are created by macros and filter blocks.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200500 """
Armin Ronacherd55ab532008-04-09 16:13:39 +0200501 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200502
Armin Ronacher00d5d212008-04-13 01:10:18 +0200503 def as_const(self, obj=None):
504 if self.node is obj is None:
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200505 raise Impossible()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200506 filter = self.environment.filters.get(self.name)
507 if filter is None or getattr(filter, 'contextfilter', False):
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200508 raise Impossible()
Armin Ronacher00d5d212008-04-13 01:10:18 +0200509 if obj is None:
510 obj = self.node.as_const()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200511 args = [x.as_const() for x in self.args]
Armin Ronacher9a027f42008-04-17 11:13:40 +0200512 if getattr(filter, 'environmentfilter', False):
513 args.insert(0, self.environment)
Armin Ronacherd55ab532008-04-09 16:13:39 +0200514 kwargs = dict(x.as_const() for x in self.kwargs)
515 if self.dyn_args is not None:
516 try:
517 args.extend(self.dyn_args.as_const())
518 except:
519 raise Impossible()
520 if self.dyn_kwargs is not None:
521 try:
522 kwargs.update(self.dyn_kwargs.as_const())
523 except:
524 raise Impossible()
525 try:
526 return filter(obj, *args, **kwargs)
527 except:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200528 raise Impossible()
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200529
530
Armin Ronacher07bc6842008-03-31 14:18:49 +0200531class Test(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200532 """Applies a test on an expression. `name` is the name of the test, the
533 rest of the fields are the same as for :class:`Call`.
534 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200535 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200536
537
538class Call(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200539 """Calls an expression. `args` is a list of arguments, `kwargs` a list
540 of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
541 and `dyn_kwargs` has to be either `None` or a node that is used as
542 node for dynamic positional (``*args``) or keyword (``**kwargs``)
543 arguments.
544 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200545 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200546
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200547 def as_const(self):
548 obj = self.node.as_const()
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200549
550 # don't evaluate context functions
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200551 args = [x.as_const() for x in self.args]
Armin Ronacherfd310492008-05-25 00:16:51 +0200552 if getattr(obj, 'contextfunction', False):
553 raise Impossible()
554 elif getattr(obj, 'environmentfunction', False):
555 args.insert(0, self.environment)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200556
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200557 kwargs = dict(x.as_const() for x in self.kwargs)
558 if self.dyn_args is not None:
559 try:
560 args.extend(self.dyn_args.as_const())
561 except:
562 raise Impossible()
563 if self.dyn_kwargs is not None:
564 try:
Armin Ronacherd55ab532008-04-09 16:13:39 +0200565 kwargs.update(self.dyn_kwargs.as_const())
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200566 except:
567 raise Impossible()
568 try:
569 return obj(*args, **kwargs)
570 except:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200571 raise Impossible()
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200572
Armin Ronacher07bc6842008-03-31 14:18:49 +0200573
574class Subscript(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200575 """Subscribe an expression by an argument. This node performs a dict
576 and an attribute lookup on the object whatever succeeds.
577 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200578 fields = ('node', 'arg', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200579
580 def as_const(self):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200581 if self.ctx != 'load':
582 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200583 try:
Benjamin Wieganda3152742008-04-28 18:07:52 +0200584 return self.environment.subscribe(self.node.as_const(),
585 self.arg.as_const())
Armin Ronacher07bc6842008-03-31 14:18:49 +0200586 except:
587 raise Impossible()
588
589 def can_assign(self):
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200590 return False
Armin Ronacher07bc6842008-03-31 14:18:49 +0200591
592
593class Slice(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200594 """Represents a slice object. This must only be used as argument for
595 :class:`Subscript`.
596 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200597 fields = ('start', 'stop', 'step')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200598
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200599 def as_const(self):
600 def const(obj):
601 if obj is None:
602 return obj
603 return obj.as_const()
604 return slice(const(self.start), const(self.stop), const(self.step))
605
Armin Ronacher07bc6842008-03-31 14:18:49 +0200606
607class Concat(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200608 """Concatenates the list of expressions provided after converting them to
609 unicode.
610 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200611 fields = ('nodes',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200612
613 def as_const(self):
614 return ''.join(unicode(x.as_const()) for x in self.nodes)
615
616
617class Compare(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200618 """Compares an expression with some other expressions. `ops` must be a
619 list of :class:`Operand`\s.
620 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200621 fields = ('expr', 'ops')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200622
Armin Ronacher625215e2008-04-13 16:31:08 +0200623 def as_const(self):
624 result = value = self.expr.as_const()
Armin Ronacherb5124e62008-04-25 00:36:14 +0200625 try:
626 for op in self.ops:
627 new_value = op.expr.as_const()
628 result = _cmpop_to_func[op.op](value, new_value)
629 value = new_value
630 except:
631 raise Impossible()
Armin Ronacher625215e2008-04-13 16:31:08 +0200632 return result
633
Armin Ronacher07bc6842008-03-31 14:18:49 +0200634
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200635class Operand(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200636 """Holds an operator and an expression."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200637 fields = ('op', 'expr')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200638
Armin Ronacher023b5e92008-05-08 11:03:10 +0200639if __debug__:
640 Operand.__doc__ += '\nThe following operators are available: ' + \
641 ', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
642 set(_uaop_to_func) | set(_cmpop_to_func)))
643
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200644
Armin Ronacher07bc6842008-03-31 14:18:49 +0200645class Mul(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200646 """Multiplies the left with the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200647 operator = '*'
648
649
650class Div(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200651 """Divides the left by the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200652 operator = '/'
653
654
655class FloorDiv(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200656 """Divides the left by the right node and truncates conver the
657 result into an integer by truncating.
658 """
Armin Ronacher07bc6842008-03-31 14:18:49 +0200659 operator = '//'
660
661
662class Add(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200663 """Add the left to the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200664 operator = '+'
665
666
667class Sub(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200668 """Substract the right from the left node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200669 operator = '-'
670
671
672class Mod(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200673 """Left modulo right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200674 operator = '%'
675
676
677class Pow(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200678 """Left to the power of right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200679 operator = '**'
680
681
682class And(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200683 """Short circuited AND."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200684 operator = 'and'
685
686 def as_const(self):
687 return self.left.as_const() and self.right.as_const()
688
689
690class Or(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200691 """Short circuited OR."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200692 operator = 'or'
693
694 def as_const(self):
695 return self.left.as_const() or self.right.as_const()
696
697
698class Not(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200699 """Negate the expression."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200700 operator = 'not'
701
702
Armin Ronachere791c2a2008-04-07 18:39:54 +0200703class Neg(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200704 """Make the expression negative."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200705 operator = '-'
706
707
Armin Ronachere791c2a2008-04-07 18:39:54 +0200708class Pos(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200709 """Make the expression positive (noop for most expressions)"""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200710 operator = '+'
Armin Ronacher023b5e92008-05-08 11:03:10 +0200711
712
713# Helpers for extensions
714
715
716class EnvironmentAttribute(Expr):
717 """Loads an attribute from the environment object. This is useful for
718 extensions that want to call a callback stored on the environment.
719 """
720 fields = ('name',)
721
722
723class ExtensionAttribute(Expr):
724 """Returns the attribute of an extension bound to the environment.
725 The identifier is the identifier of the :class:`Extension`.
Armin Ronacherb9e78752008-05-10 23:36:28 +0200726
727 This node is usually constructed by calling the
728 :meth:`~jinja2.ext.Extension.attr` method on an extension.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200729 """
Armin Ronacher6df604e2008-05-23 22:18:38 +0200730 fields = ('identifier', 'name')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200731
732
733class ImportedName(Expr):
734 """If created with an import name the import name is returned on node
735 access. For example ``ImportedName('cgi.escape')`` returns the `escape`
736 function from the cgi module on evaluation. Imports are optimized by the
737 compiler so there is no need to assign them to local variables.
738 """
739 fields = ('importname',)
740
741
742class InternalName(Expr):
743 """An internal name in the compiler. You cannot create these nodes
Armin Ronacher762079c2008-05-08 23:57:56 +0200744 yourself but the parser provides a
745 :meth:`~jinja2.parser.Parser.free_identifier` method that creates
Armin Ronacher023b5e92008-05-08 11:03:10 +0200746 a new identifier for you. This identifier is not available from the
747 template and is not threated specially by the compiler.
748 """
749 fields = ('name',)
750
751 def __init__(self):
752 raise TypeError('Can\'t create internal names. Use the '
753 '`free_identifier` method on a parser.')
754
755
756class MarkSafe(Expr):
757 """Mark the wrapped expression as safe (wrap it as `Markup`)."""
758 fields = ('expr',)
759
760 def as_const(self):
761 return Markup(self.expr.as_const())
762
763
Armin Ronacher6df604e2008-05-23 22:18:38 +0200764class ContextReference(Expr):
765 """Returns the current template context."""
766
767
Armin Ronachered1e0d42008-05-18 20:25:28 +0200768class Continue(Stmt):
769 """Continue a loop."""
770
771
772class Break(Stmt):
773 """Break a loop."""
774
775
Armin Ronacher8a1d27f2008-05-19 08:37:19 +0200776# make sure nobody creates custom nodes
777def _failing_new(*args, **kwargs):
778 raise TypeError('can\'t create custom node types')
779NodeType.__new__ = staticmethod(_failing_new); del _failing_new