blob: 0cccddf81137a02b987d7e0ea4ed302d17afb5e8 [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
Armin Ronacher5411ce72008-05-25 11:36:22 +0200434class TemplateData(Literal):
435 """A constant template string."""
436 fields = ('data',)
437
438 def as_const(self):
439 if self.environment.autoescape:
440 return Markup(self.data)
441 return self.data
442
443
Armin Ronacher07bc6842008-03-31 14:18:49 +0200444class Tuple(Literal):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200445 """For loop unpacking and some other things like multiple arguments
Armin Ronacher023b5e92008-05-08 11:03:10 +0200446 for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
447 is used for loading the names or storing.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200448 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200449 fields = ('items', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200450
451 def as_const(self):
452 return tuple(x.as_const() for x in self.items)
453
454 def can_assign(self):
455 for item in self.items:
456 if not item.can_assign():
457 return False
458 return True
459
460
461class List(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200462 """Any list literal such as ``[1, 2, 3]``"""
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 [x.as_const() for x in self.items]
467
468
469class Dict(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200470 """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
471 :class:`Pair` nodes.
472 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200473 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200474
475 def as_const(self):
476 return dict(x.as_const() for x in self.items)
477
478
479class Pair(Helper):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200480 """A key, value pair for dicts."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200481 fields = ('key', 'value')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200482
483 def as_const(self):
484 return self.key.as_const(), self.value.as_const()
485
486
Armin Ronacher8efc5222008-04-08 14:47:40 +0200487class Keyword(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200488 """A key, value pair for keyword arguments where key is a string."""
Armin Ronacher8efc5222008-04-08 14:47:40 +0200489 fields = ('key', 'value')
490
491
Armin Ronacher07bc6842008-03-31 14:18:49 +0200492class CondExpr(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200493 """A conditional expression (inline if expression). (``{{
494 foo if bar else baz }}``)
495 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200496 fields = ('test', 'expr1', 'expr2')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200497
498 def as_const(self):
499 if self.test.as_const():
500 return self.expr1.as_const()
501 return self.expr2.as_const()
502
503
504class Filter(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200505 """This node applies a filter on an expression. `name` is the name of
506 the filter, the rest of the fields are the same as for :class:`Call`.
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200507
508 If the `node` of a filter is `None` the contents of the last buffer are
509 filtered. Buffers are created by macros and filter blocks.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200510 """
Armin Ronacherd55ab532008-04-09 16:13:39 +0200511 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200512
Armin Ronacher00d5d212008-04-13 01:10:18 +0200513 def as_const(self, obj=None):
514 if self.node is obj is None:
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200515 raise Impossible()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200516 filter = self.environment.filters.get(self.name)
517 if filter is None or getattr(filter, 'contextfilter', False):
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200518 raise Impossible()
Armin Ronacher00d5d212008-04-13 01:10:18 +0200519 if obj is None:
520 obj = self.node.as_const()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200521 args = [x.as_const() for x in self.args]
Armin Ronacher9a027f42008-04-17 11:13:40 +0200522 if getattr(filter, 'environmentfilter', False):
523 args.insert(0, self.environment)
Armin Ronacherd55ab532008-04-09 16:13:39 +0200524 kwargs = dict(x.as_const() for x in self.kwargs)
525 if self.dyn_args is not None:
526 try:
527 args.extend(self.dyn_args.as_const())
528 except:
529 raise Impossible()
530 if self.dyn_kwargs is not None:
531 try:
532 kwargs.update(self.dyn_kwargs.as_const())
533 except:
534 raise Impossible()
535 try:
536 return filter(obj, *args, **kwargs)
537 except:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200538 raise Impossible()
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200539
540
Armin Ronacher07bc6842008-03-31 14:18:49 +0200541class Test(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200542 """Applies a test on an expression. `name` is the name of the test, the
543 rest of the fields are the same as for :class:`Call`.
544 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200545 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200546
547
548class Call(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200549 """Calls an expression. `args` is a list of arguments, `kwargs` a list
550 of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
551 and `dyn_kwargs` has to be either `None` or a node that is used as
552 node for dynamic positional (``*args``) or keyword (``**kwargs``)
553 arguments.
554 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200555 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200556
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200557 def as_const(self):
558 obj = self.node.as_const()
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200559
560 # don't evaluate context functions
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200561 args = [x.as_const() for x in self.args]
Armin Ronacherfd310492008-05-25 00:16:51 +0200562 if getattr(obj, 'contextfunction', False):
563 raise Impossible()
564 elif getattr(obj, 'environmentfunction', False):
565 args.insert(0, self.environment)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200566
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200567 kwargs = dict(x.as_const() for x in self.kwargs)
568 if self.dyn_args is not None:
569 try:
570 args.extend(self.dyn_args.as_const())
571 except:
572 raise Impossible()
573 if self.dyn_kwargs is not None:
574 try:
Armin Ronacherd55ab532008-04-09 16:13:39 +0200575 kwargs.update(self.dyn_kwargs.as_const())
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200576 except:
577 raise Impossible()
578 try:
579 return obj(*args, **kwargs)
580 except:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200581 raise Impossible()
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200582
Armin Ronacher07bc6842008-03-31 14:18:49 +0200583
584class Subscript(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200585 """Subscribe an expression by an argument. This node performs a dict
586 and an attribute lookup on the object whatever succeeds.
587 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200588 fields = ('node', 'arg', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200589
590 def as_const(self):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200591 if self.ctx != 'load':
592 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200593 try:
Benjamin Wieganda3152742008-04-28 18:07:52 +0200594 return self.environment.subscribe(self.node.as_const(),
595 self.arg.as_const())
Armin Ronacher07bc6842008-03-31 14:18:49 +0200596 except:
597 raise Impossible()
598
599 def can_assign(self):
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200600 return False
Armin Ronacher07bc6842008-03-31 14:18:49 +0200601
602
603class Slice(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200604 """Represents a slice object. This must only be used as argument for
605 :class:`Subscript`.
606 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200607 fields = ('start', 'stop', 'step')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200608
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200609 def as_const(self):
610 def const(obj):
611 if obj is None:
612 return obj
613 return obj.as_const()
614 return slice(const(self.start), const(self.stop), const(self.step))
615
Armin Ronacher07bc6842008-03-31 14:18:49 +0200616
617class Concat(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200618 """Concatenates the list of expressions provided after converting them to
619 unicode.
620 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200621 fields = ('nodes',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200622
623 def as_const(self):
624 return ''.join(unicode(x.as_const()) for x in self.nodes)
625
626
627class Compare(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200628 """Compares an expression with some other expressions. `ops` must be a
629 list of :class:`Operand`\s.
630 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200631 fields = ('expr', 'ops')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200632
Armin Ronacher625215e2008-04-13 16:31:08 +0200633 def as_const(self):
634 result = value = self.expr.as_const()
Armin Ronacherb5124e62008-04-25 00:36:14 +0200635 try:
636 for op in self.ops:
637 new_value = op.expr.as_const()
638 result = _cmpop_to_func[op.op](value, new_value)
639 value = new_value
640 except:
641 raise Impossible()
Armin Ronacher625215e2008-04-13 16:31:08 +0200642 return result
643
Armin Ronacher07bc6842008-03-31 14:18:49 +0200644
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200645class Operand(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200646 """Holds an operator and an expression."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200647 fields = ('op', 'expr')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200648
Armin Ronacher023b5e92008-05-08 11:03:10 +0200649if __debug__:
650 Operand.__doc__ += '\nThe following operators are available: ' + \
651 ', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
652 set(_uaop_to_func) | set(_cmpop_to_func)))
653
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200654
Armin Ronacher07bc6842008-03-31 14:18:49 +0200655class Mul(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200656 """Multiplies the left with the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200657 operator = '*'
658
659
660class Div(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200661 """Divides the left by the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200662 operator = '/'
663
664
665class FloorDiv(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200666 """Divides the left by the right node and truncates conver the
667 result into an integer by truncating.
668 """
Armin Ronacher07bc6842008-03-31 14:18:49 +0200669 operator = '//'
670
671
672class Add(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200673 """Add the left to the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200674 operator = '+'
675
676
677class Sub(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200678 """Substract the right from the left node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200679 operator = '-'
680
681
682class Mod(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200683 """Left modulo right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200684 operator = '%'
685
686
687class Pow(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200688 """Left to the power of right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200689 operator = '**'
690
691
692class And(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200693 """Short circuited AND."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200694 operator = 'and'
695
696 def as_const(self):
697 return self.left.as_const() and self.right.as_const()
698
699
700class Or(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200701 """Short circuited OR."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200702 operator = 'or'
703
704 def as_const(self):
705 return self.left.as_const() or self.right.as_const()
706
707
708class Not(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200709 """Negate the expression."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200710 operator = 'not'
711
712
Armin Ronachere791c2a2008-04-07 18:39:54 +0200713class Neg(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200714 """Make the expression negative."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200715 operator = '-'
716
717
Armin Ronachere791c2a2008-04-07 18:39:54 +0200718class Pos(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200719 """Make the expression positive (noop for most expressions)"""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200720 operator = '+'
Armin Ronacher023b5e92008-05-08 11:03:10 +0200721
722
723# Helpers for extensions
724
725
726class EnvironmentAttribute(Expr):
727 """Loads an attribute from the environment object. This is useful for
728 extensions that want to call a callback stored on the environment.
729 """
730 fields = ('name',)
731
732
733class ExtensionAttribute(Expr):
734 """Returns the attribute of an extension bound to the environment.
735 The identifier is the identifier of the :class:`Extension`.
Armin Ronacherb9e78752008-05-10 23:36:28 +0200736
737 This node is usually constructed by calling the
738 :meth:`~jinja2.ext.Extension.attr` method on an extension.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200739 """
Armin Ronacher6df604e2008-05-23 22:18:38 +0200740 fields = ('identifier', 'name')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200741
742
743class ImportedName(Expr):
744 """If created with an import name the import name is returned on node
745 access. For example ``ImportedName('cgi.escape')`` returns the `escape`
746 function from the cgi module on evaluation. Imports are optimized by the
747 compiler so there is no need to assign them to local variables.
748 """
749 fields = ('importname',)
750
751
752class InternalName(Expr):
753 """An internal name in the compiler. You cannot create these nodes
Armin Ronacher762079c2008-05-08 23:57:56 +0200754 yourself but the parser provides a
755 :meth:`~jinja2.parser.Parser.free_identifier` method that creates
Armin Ronacher023b5e92008-05-08 11:03:10 +0200756 a new identifier for you. This identifier is not available from the
757 template and is not threated specially by the compiler.
758 """
759 fields = ('name',)
760
761 def __init__(self):
762 raise TypeError('Can\'t create internal names. Use the '
763 '`free_identifier` method on a parser.')
764
765
766class MarkSafe(Expr):
767 """Mark the wrapped expression as safe (wrap it as `Markup`)."""
768 fields = ('expr',)
769
770 def as_const(self):
771 return Markup(self.expr.as_const())
772
773
Armin Ronacher6df604e2008-05-23 22:18:38 +0200774class ContextReference(Expr):
775 """Returns the current template context."""
776
777
Armin Ronachered1e0d42008-05-18 20:25:28 +0200778class Continue(Stmt):
779 """Continue a loop."""
780
781
782class Break(Stmt):
783 """Break a loop."""
784
785
Armin Ronacher8a1d27f2008-05-19 08:37:19 +0200786# make sure nobody creates custom nodes
787def _failing_new(*args, **kwargs):
788 raise TypeError('can\'t create custom node types')
789NodeType.__new__ = staticmethod(_failing_new); del _failing_new