blob: 424c1cd8e36837e7b4a6160e101353facbd571cb [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 Ronacher55494e42010-01-22 09:41:48 +010012 :copyright: (c) 2010 by the Jinja Team.
Armin Ronacher07bc6842008-03-31 14:18:49 +020013 :license: BSD, see LICENSE for more details.
14"""
15import operator
16from itertools import chain, izip
Armin Ronacher82b3f3d2008-03-31 20:01:08 +020017from collections import deque
Armin Ronacherd84ec462008-04-29 13:43:16 +020018from jinja2.utils import Markup
Armin Ronacher07bc6842008-03-31 14:18:49 +020019
20
21_binop_to_func = {
22 '*': operator.mul,
23 '/': operator.truediv,
24 '//': operator.floordiv,
25 '**': operator.pow,
26 '%': operator.mod,
27 '+': operator.add,
28 '-': operator.sub
29}
30
31_uaop_to_func = {
32 'not': operator.not_,
33 '+': operator.pos,
34 '-': operator.neg
35}
36
Armin Ronacher625215e2008-04-13 16:31:08 +020037_cmpop_to_func = {
38 'eq': operator.eq,
39 'ne': operator.ne,
40 'gt': operator.gt,
41 'gteq': operator.ge,
42 'lt': operator.lt,
43 'lteq': operator.le,
Armin Ronacherb5124e62008-04-25 00:36:14 +020044 'in': lambda a, b: a in b,
45 'notin': lambda a, b: a not in b
Armin Ronacher625215e2008-04-13 16:31:08 +020046}
47
Armin Ronacher07bc6842008-03-31 14:18:49 +020048
49class Impossible(Exception):
Armin Ronacher8efc5222008-04-08 14:47:40 +020050 """Raised if the node could not perform a requested action."""
Armin Ronacher07bc6842008-03-31 14:18:49 +020051
52
53class NodeType(type):
Armin Ronacher8efc5222008-04-08 14:47:40 +020054 """A metaclass for nodes that handles the field and attribute
55 inheritance. fields and attributes from the parent class are
56 automatically forwarded to the child."""
Armin Ronacher07bc6842008-03-31 14:18:49 +020057
58 def __new__(cls, name, bases, d):
Armin Ronachere791c2a2008-04-07 18:39:54 +020059 for attr in 'fields', 'attributes':
Armin Ronacher07bc6842008-03-31 14:18:49 +020060 storage = []
Armin Ronacher7324eb82008-04-21 07:55:52 +020061 storage.extend(getattr(bases[0], attr, ()))
Armin Ronacher07bc6842008-03-31 14:18:49 +020062 storage.extend(d.get(attr, ()))
Armin Ronacher7324eb82008-04-21 07:55:52 +020063 assert len(bases) == 1, 'multiple inheritance not allowed'
64 assert len(storage) == len(set(storage)), 'layout conflict'
Armin Ronacher07bc6842008-03-31 14:18:49 +020065 d[attr] = tuple(storage)
Armin Ronacher023b5e92008-05-08 11:03:10 +020066 d.setdefault('abstract', False)
Armin Ronacher7324eb82008-04-21 07:55:52 +020067 return type.__new__(cls, name, bases, d)
Armin Ronacher07bc6842008-03-31 14:18:49 +020068
69
70class Node(object):
Armin Ronacher023b5e92008-05-08 11:03:10 +020071 """Baseclass for all Jinja2 nodes. There are a number of nodes available
72 of different types. There are three major types:
73
74 - :class:`Stmt`: statements
75 - :class:`Expr`: expressions
76 - :class:`Helper`: helper nodes
77 - :class:`Template`: the outermost wrapper node
78
79 All nodes have fields and attributes. Fields may be other nodes, lists,
80 or arbitrary values. Fields are passed to the constructor as regular
81 positional arguments, attributes as keyword arguments. Each node has
82 two attributes: `lineno` (the line number of the node) and `environment`.
83 The `environment` attribute is set at the end of the parsing process for
84 all nodes automatically.
85 """
Armin Ronacher07bc6842008-03-31 14:18:49 +020086 __metaclass__ = NodeType
Armin Ronachere791c2a2008-04-07 18:39:54 +020087 fields = ()
Armin Ronacherd55ab532008-04-09 16:13:39 +020088 attributes = ('lineno', 'environment')
Armin Ronacher023b5e92008-05-08 11:03:10 +020089 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +020090
Armin Ronacher023b5e92008-05-08 11:03:10 +020091 def __init__(self, *fields, **attributes):
Armin Ronacher69e12db2008-05-12 09:00:03 +020092 if self.abstract:
93 raise TypeError('abstract nodes are not instanciable')
Armin Ronacher023b5e92008-05-08 11:03:10 +020094 if fields:
95 if len(fields) != len(self.fields):
Armin Ronachere791c2a2008-04-07 18:39:54 +020096 if not self.fields:
Armin Ronacher07bc6842008-03-31 14:18:49 +020097 raise TypeError('%r takes 0 arguments' %
98 self.__class__.__name__)
99 raise TypeError('%r takes 0 or %d argument%s' % (
100 self.__class__.__name__,
Armin Ronachere791c2a2008-04-07 18:39:54 +0200101 len(self.fields),
102 len(self.fields) != 1 and 's' or ''
Armin Ronacher07bc6842008-03-31 14:18:49 +0200103 ))
Armin Ronacher023b5e92008-05-08 11:03:10 +0200104 for name, arg in izip(self.fields, fields):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200105 setattr(self, name, arg)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200106 for attr in self.attributes:
Armin Ronacher023b5e92008-05-08 11:03:10 +0200107 setattr(self, attr, attributes.pop(attr, None))
108 if attributes:
109 raise TypeError('unknown attribute %r' %
110 iter(attributes).next())
Armin Ronacher07bc6842008-03-31 14:18:49 +0200111
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200112 def iter_fields(self, exclude=None, only=None):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200113 """This method iterates over all fields that are defined and yields
Armin Ronacher3da90312008-05-23 16:37:28 +0200114 ``(key, value)`` tuples. Per default all fields are returned, but
115 it's possible to limit that to some fields by providing the `only`
116 parameter or to exclude some using the `exclude` parameter. Both
117 should be sets or tuples of field names.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200118 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200119 for name in self.fields:
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200120 if (exclude is only is None) or \
121 (exclude is not None and name not in exclude) or \
122 (only is not None and name in only):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200123 try:
124 yield name, getattr(self, name)
125 except AttributeError:
126 pass
Armin Ronacher07bc6842008-03-31 14:18:49 +0200127
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200128 def iter_child_nodes(self, exclude=None, only=None):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200129 """Iterates over all direct child nodes of the node. This iterates
130 over all fields and yields the values of they are nodes. If the value
131 of a field is a list all the nodes in that list are returned.
132 """
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200133 for field, item in self.iter_fields(exclude, only):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200134 if isinstance(item, list):
135 for n in item:
136 if isinstance(n, Node):
137 yield n
138 elif isinstance(item, Node):
139 yield item
140
Armin Ronachere791c2a2008-04-07 18:39:54 +0200141 def find(self, node_type):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200142 """Find the first node of a given type. If no such node exists the
143 return value is `None`.
144 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200145 for result in self.find_all(node_type):
146 return result
147
148 def find_all(self, node_type):
Armin Ronacher63cf9b82009-07-26 10:33:36 +0200149 """Find all the nodes of a given type. If the type is a tuple,
150 the check is performed for any of the tuple items.
151 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200152 for child in self.iter_child_nodes():
153 if isinstance(child, node_type):
154 yield child
155 for result in child.find_all(node_type):
156 yield result
157
158 def set_ctx(self, ctx):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200159 """Reset the context of a node and all child nodes. Per default the
160 parser will all generate nodes that have a 'load' context as it's the
161 most common one. This method is used in the parser to set assignment
162 targets and other nodes to a store context.
Armin Ronachere791c2a2008-04-07 18:39:54 +0200163 """
164 todo = deque([self])
165 while todo:
166 node = todo.popleft()
167 if 'ctx' in node.fields:
168 node.ctx = ctx
169 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200170 return self
Armin Ronachere791c2a2008-04-07 18:39:54 +0200171
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200172 def set_lineno(self, lineno, override=False):
173 """Set the line numbers of the node and children."""
174 todo = deque([self])
175 while todo:
176 node = todo.popleft()
177 if 'lineno' in node.attributes:
178 if node.lineno is None or override:
179 node.lineno = lineno
180 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200181 return self
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200182
Armin Ronacherd55ab532008-04-09 16:13:39 +0200183 def set_environment(self, environment):
184 """Set the environment for all nodes."""
185 todo = deque([self])
186 while todo:
187 node = todo.popleft()
188 node.environment = environment
189 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200190 return self
Armin Ronacherd55ab532008-04-09 16:13:39 +0200191
Armin Ronacher69e12db2008-05-12 09:00:03 +0200192 def __eq__(self, other):
Armin Ronacherb3a1fcf2008-05-15 11:04:14 +0200193 return type(self) is type(other) and \
194 tuple(self.iter_fields()) == tuple(other.iter_fields())
Armin Ronacher69e12db2008-05-12 09:00:03 +0200195
196 def __ne__(self, other):
197 return not self.__eq__(other)
198
Armin Ronacher07bc6842008-03-31 14:18:49 +0200199 def __repr__(self):
200 return '%s(%s)' % (
201 self.__class__.__name__,
202 ', '.join('%s=%r' % (arg, getattr(self, arg, None)) for
Armin Ronachere791c2a2008-04-07 18:39:54 +0200203 arg in self.fields)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200204 )
205
206
207class Stmt(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200208 """Base node for all statements."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200209 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200210
211
212class Helper(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200213 """Nodes that exist in a specific context only."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200214 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200215
216
217class Template(Node):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200218 """Node that represents a template. This must be the outermost node that
219 is passed to the compiler.
220 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200221 fields = ('body',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200222
223
224class Output(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200225 """A node that holds multiple expressions which are then printed out.
226 This is used both for the `print` statement and the regular template data.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200227 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200228 fields = ('nodes',)
229
Armin Ronacher07bc6842008-03-31 14:18:49 +0200230
231class Extends(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200232 """Represents an extends statement."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200233 fields = ('template',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200234
235
236class For(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200237 """The for loop. `target` is the target for the iteration (usually a
238 :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list
239 of nodes that are used as loop-body, and `else_` a list of nodes for the
240 `else` block. If no else node exists it has to be an empty list.
241
242 For filtered nodes an expression can be stored as `test`, otherwise `None`.
243 """
Armin Ronacherfdf95302008-05-11 22:20:51 +0200244 fields = ('target', 'iter', 'body', 'else_', 'test', 'recursive')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200245
246
247class If(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200248 """If `test` is true, `body` is rendered, else `else_`."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200249 fields = ('test', 'body', 'else_')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200250
251
252class Macro(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200253 """A macro definition. `name` is the name of the macro, `args` a list of
254 arguments and `defaults` a list of defaults if there are any. `body` is
255 a list of nodes for the macro body.
256 """
Armin Ronacher8efc5222008-04-08 14:47:40 +0200257 fields = ('name', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200258
259
260class CallBlock(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200261 """Like a macro without a name but a call instead. `call` is called with
262 the unnamed macro as `caller` argument this node holds.
263 """
Armin Ronacherc9705c22008-04-27 21:28:03 +0200264 fields = ('call', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200265
266
Armin Ronacher07bc6842008-03-31 14:18:49 +0200267class FilterBlock(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200268 """Node for filter sections."""
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200269 fields = ('body', 'filter')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200270
271
272class Block(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200273 """A node that represents a block."""
Armin Ronacher74a0cd92009-02-19 15:56:53 +0100274 fields = ('name', 'body', 'scoped')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200275
276
277class Include(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200278 """A node that represents the include tag."""
Armin Ronacher37f58ce2008-12-27 13:10:38 +0100279 fields = ('template', 'with_context', 'ignore_missing')
Armin Ronacher0611e492008-04-25 23:44:14 +0200280
281
282class Import(Stmt):
283 """A node that represents the import tag."""
Armin Ronacherea847c52008-05-02 20:04:32 +0200284 fields = ('template', 'target', 'with_context')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200285
286
Armin Ronacher0611e492008-04-25 23:44:14 +0200287class FromImport(Stmt):
288 """A node that represents the from import tag. It's important to not
289 pass unsafe names to the name attribute. The compiler translates the
290 attribute lookups directly into getattr calls and does *not* use the
Armin Ronacherb9388772008-06-25 20:43:18 +0200291 subscript callback of the interface. As exported variables may not
Armin Ronacher0611e492008-04-25 23:44:14 +0200292 start with double underscores (which the parser asserts) this is not a
293 problem for regular Jinja code, but if this node is used in an extension
294 extra care must be taken.
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200295
296 The list of names may contain tuples if aliases are wanted.
Armin Ronacher0611e492008-04-25 23:44:14 +0200297 """
Armin Ronacherea847c52008-05-02 20:04:32 +0200298 fields = ('template', 'names', 'with_context')
Armin Ronacher0611e492008-04-25 23:44:14 +0200299
300
Armin Ronacher07bc6842008-03-31 14:18:49 +0200301class ExprStmt(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200302 """A statement that evaluates an expression and discards the result."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200303 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200304
305
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200306class Assign(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200307 """Assigns an expression to a target."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200308 fields = ('target', 'node')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200309
310
Armin Ronacher07bc6842008-03-31 14:18:49 +0200311class Expr(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200312 """Baseclass for all expressions."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200313 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200314
315 def as_const(self):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200316 """Return the value of the expression as constant or raise
Armin Ronacher023b5e92008-05-08 11:03:10 +0200317 :exc:`Impossible` if this was not possible:
318
319 >>> Add(Const(23), Const(42)).as_const()
320 65
321 >>> Add(Const(23), Name('var', 'load')).as_const()
322 Traceback (most recent call last):
323 ...
324 Impossible
325
326 This requires the `environment` attribute of all nodes to be
327 set to the environment that created the nodes.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200328 """
329 raise Impossible()
330
331 def can_assign(self):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200332 """Check if it's possible to assign something to this node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200333 return False
334
335
336class BinExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200337 """Baseclass for all binary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200338 fields = ('left', 'right')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200339 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200340 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200341
342 def as_const(self):
343 f = _binop_to_func[self.operator]
344 try:
345 return f(self.left.as_const(), self.right.as_const())
346 except:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200347 raise Impossible()
348
349
350class UnaryExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200351 """Baseclass for all unary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200352 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200353 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200354 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200355
356 def as_const(self):
357 f = _uaop_to_func[self.operator]
358 try:
359 return f(self.node.as_const())
360 except:
361 raise Impossible()
362
363
364class Name(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200365 """Looks up a name or stores a value in a name.
366 The `ctx` of the node can be one of the following values:
367
368 - `store`: store a value in the name
369 - `load`: load that name
370 - `param`: like `store` but if the name was defined as function parameter.
371 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200372 fields = ('name', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200373
374 def can_assign(self):
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200375 return self.name not in ('true', 'false', 'none',
376 'True', 'False', 'None')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200377
378
379class Literal(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200380 """Baseclass for literals."""
Armin Ronacher69e12db2008-05-12 09:00:03 +0200381 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200382
383
384class Const(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200385 """All constant values. The parser will return this node for simple
386 constants such as ``42`` or ``"foo"`` but it can be used to store more
387 complex values such as lists too. Only constants with a safe
388 representation (objects where ``eval(repr(x)) == x`` is true).
389 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200390 fields = ('value',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200391
392 def as_const(self):
393 return self.value
394
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200395 @classmethod
Armin Ronacherd55ab532008-04-09 16:13:39 +0200396 def from_untrusted(cls, value, lineno=None, environment=None):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200397 """Return a const object if the value is representable as
398 constant value in the generated code, otherwise it will raise
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200399 an `Impossible` exception.
400 """
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200401 from compiler import has_safe_repr
402 if not has_safe_repr(value):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200403 raise Impossible()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200404 return cls(value, lineno=lineno, environment=environment)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200405
Armin Ronacher07bc6842008-03-31 14:18:49 +0200406
Armin Ronacher5411ce72008-05-25 11:36:22 +0200407class TemplateData(Literal):
408 """A constant template string."""
409 fields = ('data',)
410
411 def as_const(self):
412 if self.environment.autoescape:
413 return Markup(self.data)
414 return self.data
415
416
Armin Ronacher07bc6842008-03-31 14:18:49 +0200417class Tuple(Literal):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200418 """For loop unpacking and some other things like multiple arguments
Armin Ronacher023b5e92008-05-08 11:03:10 +0200419 for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
420 is used for loading the names or storing.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200421 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200422 fields = ('items', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200423
424 def as_const(self):
425 return tuple(x.as_const() for x in self.items)
426
427 def can_assign(self):
428 for item in self.items:
429 if not item.can_assign():
430 return False
431 return True
432
433
434class List(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200435 """Any list literal such as ``[1, 2, 3]``"""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200436 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200437
438 def as_const(self):
439 return [x.as_const() for x in self.items]
440
441
442class Dict(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200443 """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
444 :class:`Pair` nodes.
445 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200446 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200447
448 def as_const(self):
449 return dict(x.as_const() for x in self.items)
450
451
452class Pair(Helper):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200453 """A key, value pair for dicts."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200454 fields = ('key', 'value')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200455
456 def as_const(self):
457 return self.key.as_const(), self.value.as_const()
458
459
Armin Ronacher8efc5222008-04-08 14:47:40 +0200460class Keyword(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200461 """A key, value pair for keyword arguments where key is a string."""
Armin Ronacher8efc5222008-04-08 14:47:40 +0200462 fields = ('key', 'value')
463
Armin Ronacher335b87a2008-09-21 17:08:48 +0200464 def as_const(self):
465 return self.key, self.value.as_const()
466
Armin Ronacher8efc5222008-04-08 14:47:40 +0200467
Armin Ronacher07bc6842008-03-31 14:18:49 +0200468class CondExpr(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200469 """A conditional expression (inline if expression). (``{{
470 foo if bar else baz }}``)
471 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200472 fields = ('test', 'expr1', 'expr2')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200473
474 def as_const(self):
475 if self.test.as_const():
476 return self.expr1.as_const()
Armin Ronacher547d0b62008-07-04 16:35:10 +0200477
478 # if we evaluate to an undefined object, we better do that at runtime
479 if self.expr2 is None:
480 raise Impossible()
481
Armin Ronacher07bc6842008-03-31 14:18:49 +0200482 return self.expr2.as_const()
483
484
485class Filter(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200486 """This node applies a filter on an expression. `name` is the name of
487 the filter, the rest of the fields are the same as for :class:`Call`.
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200488
489 If the `node` of a filter is `None` the contents of the last buffer are
490 filtered. Buffers are created by macros and filter blocks.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200491 """
Armin Ronacherd55ab532008-04-09 16:13:39 +0200492 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200493
Armin Ronacher00d5d212008-04-13 01:10:18 +0200494 def as_const(self, obj=None):
495 if self.node is obj is None:
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200496 raise Impossible()
Armin Ronacher0d242be2010-02-10 01:35:13 +0100497 # we have to be careful here because we call filter_ below.
498 # if this variable would be called filter, 2to3 would wrap the
499 # call in a list beause it is assuming we are talking about the
500 # builtin filter function here which no longer returns a list in
501 # python 3. because of that, do not rename filter_ to filter!
502 filter_ = self.environment.filters.get(self.name)
503 if filter_ is None or getattr(filter_, 'contextfilter', False):
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200504 raise Impossible()
Armin Ronacher00d5d212008-04-13 01:10:18 +0200505 if obj is None:
506 obj = self.node.as_const()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200507 args = [x.as_const() for x in self.args]
Armin Ronacher0d242be2010-02-10 01:35:13 +0100508 if getattr(filter_, 'environmentfilter', False):
Armin Ronacher9a027f42008-04-17 11:13:40 +0200509 args.insert(0, self.environment)
Armin Ronacherd55ab532008-04-09 16:13:39 +0200510 kwargs = dict(x.as_const() for x in self.kwargs)
511 if self.dyn_args is not None:
512 try:
513 args.extend(self.dyn_args.as_const())
514 except:
515 raise Impossible()
516 if self.dyn_kwargs is not None:
517 try:
518 kwargs.update(self.dyn_kwargs.as_const())
519 except:
520 raise Impossible()
521 try:
Armin Ronacher0d242be2010-02-10 01:35:13 +0100522 return filter_(obj, *args, **kwargs)
Armin Ronacherd55ab532008-04-09 16:13:39 +0200523 except:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200524 raise Impossible()
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200525
526
Armin Ronacher07bc6842008-03-31 14:18:49 +0200527class Test(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200528 """Applies a test on an expression. `name` is the name of the test, the
529 rest of the fields are the same as for :class:`Call`.
530 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200531 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200532
533
534class Call(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200535 """Calls an expression. `args` is a list of arguments, `kwargs` a list
536 of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
537 and `dyn_kwargs` has to be either `None` or a node that is used as
538 node for dynamic positional (``*args``) or keyword (``**kwargs``)
539 arguments.
540 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200541 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200542
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200543 def as_const(self):
544 obj = self.node.as_const()
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200545
546 # don't evaluate context functions
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200547 args = [x.as_const() for x in self.args]
Armin Ronacherfd310492008-05-25 00:16:51 +0200548 if getattr(obj, 'contextfunction', False):
549 raise Impossible()
550 elif getattr(obj, 'environmentfunction', False):
551 args.insert(0, self.environment)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200552
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200553 kwargs = dict(x.as_const() for x in self.kwargs)
554 if self.dyn_args is not None:
555 try:
556 args.extend(self.dyn_args.as_const())
557 except:
558 raise Impossible()
559 if self.dyn_kwargs is not None:
560 try:
Armin Ronacherd55ab532008-04-09 16:13:39 +0200561 kwargs.update(self.dyn_kwargs.as_const())
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200562 except:
563 raise Impossible()
564 try:
565 return obj(*args, **kwargs)
566 except:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200567 raise Impossible()
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200568
Armin Ronacher07bc6842008-03-31 14:18:49 +0200569
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200570class Getitem(Expr):
Armin Ronacherb9388772008-06-25 20:43:18 +0200571 """Get an attribute or item from an expression and prefer the item."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200572 fields = ('node', 'arg', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200573
574 def as_const(self):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200575 if self.ctx != 'load':
576 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200577 try:
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200578 return self.environment.getitem(self.node.as_const(),
579 self.arg.as_const())
580 except:
581 raise Impossible()
582
583 def can_assign(self):
584 return False
585
586
587class Getattr(Expr):
Armin Ronacherb9388772008-06-25 20:43:18 +0200588 """Get an attribute or item from an expression that is a ascii-only
589 bytestring and prefer the attribute.
590 """
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200591 fields = ('node', 'attr', 'ctx')
592
593 def as_const(self):
594 if self.ctx != 'load':
595 raise Impossible()
596 try:
597 return self.environment.getattr(self.node.as_const(), arg)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200598 except:
599 raise Impossible()
600
601 def can_assign(self):
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200602 return False
Armin Ronacher07bc6842008-03-31 14:18:49 +0200603
604
605class Slice(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200606 """Represents a slice object. This must only be used as argument for
607 :class:`Subscript`.
608 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200609 fields = ('start', 'stop', 'step')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200610
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200611 def as_const(self):
612 def const(obj):
613 if obj is None:
614 return obj
615 return obj.as_const()
616 return slice(const(self.start), const(self.stop), const(self.step))
617
Armin Ronacher07bc6842008-03-31 14:18:49 +0200618
619class Concat(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200620 """Concatenates the list of expressions provided after converting them to
621 unicode.
622 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200623 fields = ('nodes',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200624
625 def as_const(self):
626 return ''.join(unicode(x.as_const()) for x in self.nodes)
627
628
629class Compare(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200630 """Compares an expression with some other expressions. `ops` must be a
631 list of :class:`Operand`\s.
632 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200633 fields = ('expr', 'ops')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200634
Armin Ronacher625215e2008-04-13 16:31:08 +0200635 def as_const(self):
636 result = value = self.expr.as_const()
Armin Ronacherb5124e62008-04-25 00:36:14 +0200637 try:
638 for op in self.ops:
639 new_value = op.expr.as_const()
640 result = _cmpop_to_func[op.op](value, new_value)
641 value = new_value
642 except:
643 raise Impossible()
Armin Ronacher625215e2008-04-13 16:31:08 +0200644 return result
645
Armin Ronacher07bc6842008-03-31 14:18:49 +0200646
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200647class Operand(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200648 """Holds an operator and an expression."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200649 fields = ('op', 'expr')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200650
Armin Ronacher023b5e92008-05-08 11:03:10 +0200651if __debug__:
652 Operand.__doc__ += '\nThe following operators are available: ' + \
653 ', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
654 set(_uaop_to_func) | set(_cmpop_to_func)))
655
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200656
Armin Ronacher07bc6842008-03-31 14:18:49 +0200657class Mul(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200658 """Multiplies the left with the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200659 operator = '*'
660
661
662class Div(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200663 """Divides the left by the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200664 operator = '/'
665
666
667class FloorDiv(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200668 """Divides the left by the right node and truncates conver the
669 result into an integer by truncating.
670 """
Armin Ronacher07bc6842008-03-31 14:18:49 +0200671 operator = '//'
672
673
674class Add(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200675 """Add the left to the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200676 operator = '+'
677
678
679class Sub(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200680 """Substract the right from the left node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200681 operator = '-'
682
683
684class Mod(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200685 """Left modulo right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200686 operator = '%'
687
688
689class Pow(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200690 """Left to the power of right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200691 operator = '**'
692
693
694class And(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200695 """Short circuited AND."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200696 operator = 'and'
697
698 def as_const(self):
699 return self.left.as_const() and self.right.as_const()
700
701
702class Or(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200703 """Short circuited OR."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200704 operator = 'or'
705
706 def as_const(self):
707 return self.left.as_const() or self.right.as_const()
708
709
710class Not(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200711 """Negate the expression."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200712 operator = 'not'
713
714
Armin Ronachere791c2a2008-04-07 18:39:54 +0200715class Neg(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200716 """Make the expression negative."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200717 operator = '-'
718
719
Armin Ronachere791c2a2008-04-07 18:39:54 +0200720class Pos(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200721 """Make the expression positive (noop for most expressions)"""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200722 operator = '+'
Armin Ronacher023b5e92008-05-08 11:03:10 +0200723
724
725# Helpers for extensions
726
727
728class EnvironmentAttribute(Expr):
729 """Loads an attribute from the environment object. This is useful for
730 extensions that want to call a callback stored on the environment.
731 """
732 fields = ('name',)
733
734
735class ExtensionAttribute(Expr):
736 """Returns the attribute of an extension bound to the environment.
737 The identifier is the identifier of the :class:`Extension`.
Armin Ronacherb9e78752008-05-10 23:36:28 +0200738
739 This node is usually constructed by calling the
740 :meth:`~jinja2.ext.Extension.attr` method on an extension.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200741 """
Armin Ronacher6df604e2008-05-23 22:18:38 +0200742 fields = ('identifier', 'name')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200743
744
745class ImportedName(Expr):
746 """If created with an import name the import name is returned on node
747 access. For example ``ImportedName('cgi.escape')`` returns the `escape`
748 function from the cgi module on evaluation. Imports are optimized by the
749 compiler so there is no need to assign them to local variables.
750 """
751 fields = ('importname',)
752
753
754class InternalName(Expr):
755 """An internal name in the compiler. You cannot create these nodes
Armin Ronacher762079c2008-05-08 23:57:56 +0200756 yourself but the parser provides a
757 :meth:`~jinja2.parser.Parser.free_identifier` method that creates
Armin Ronacher023b5e92008-05-08 11:03:10 +0200758 a new identifier for you. This identifier is not available from the
759 template and is not threated specially by the compiler.
760 """
761 fields = ('name',)
762
763 def __init__(self):
764 raise TypeError('Can\'t create internal names. Use the '
765 '`free_identifier` method on a parser.')
766
767
768class MarkSafe(Expr):
769 """Mark the wrapped expression as safe (wrap it as `Markup`)."""
770 fields = ('expr',)
771
772 def as_const(self):
773 return Markup(self.expr.as_const())
774
775
Armin Ronacher6df604e2008-05-23 22:18:38 +0200776class ContextReference(Expr):
777 """Returns the current template context."""
778
779
Armin Ronachered1e0d42008-05-18 20:25:28 +0200780class Continue(Stmt):
781 """Continue a loop."""
782
783
784class Break(Stmt):
785 """Break a loop."""
786
787
Armin Ronacher271a0eb2009-02-11 22:49:08 +0100788class Scope(Stmt):
789 """An artificial scope."""
790 fields = ('body',)
791
792
Armin Ronacher8a1d27f2008-05-19 08:37:19 +0200793# make sure nobody creates custom nodes
794def _failing_new(*args, **kwargs):
795 raise TypeError('can\'t create custom node types')
796NodeType.__new__ = staticmethod(_failing_new); del _failing_new