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