blob: ad39903acec5b21da17c59ad6033b08084725bad [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 Ronacher4f7d2d52008-04-22 10:40:26 +020017from types import FunctionType
Armin Ronacher07bc6842008-03-31 14:18:49 +020018from itertools import chain, izip
Armin Ronacher82b3f3d2008-03-31 20:01:08 +020019from collections import deque
Armin Ronacherd84ec462008-04-29 13:43:16 +020020from jinja2.utils import Markup
Armin Ronacher07bc6842008-03-31 14:18:49 +020021
22
23_binop_to_func = {
24 '*': operator.mul,
25 '/': operator.truediv,
26 '//': operator.floordiv,
27 '**': operator.pow,
28 '%': operator.mod,
29 '+': operator.add,
30 '-': operator.sub
31}
32
33_uaop_to_func = {
34 'not': operator.not_,
35 '+': operator.pos,
36 '-': operator.neg
37}
38
Armin Ronacher625215e2008-04-13 16:31:08 +020039_cmpop_to_func = {
40 'eq': operator.eq,
41 'ne': operator.ne,
42 'gt': operator.gt,
43 'gteq': operator.ge,
44 'lt': operator.lt,
45 'lteq': operator.le,
Armin Ronacherb5124e62008-04-25 00:36:14 +020046 'in': lambda a, b: a in b,
47 'notin': lambda a, b: a not in b
Armin Ronacher625215e2008-04-13 16:31:08 +020048}
49
Armin Ronacher07bc6842008-03-31 14:18:49 +020050
51class Impossible(Exception):
Armin Ronacher8efc5222008-04-08 14:47:40 +020052 """Raised if the node could not perform a requested action."""
Armin Ronacher07bc6842008-03-31 14:18:49 +020053
54
55class NodeType(type):
Armin Ronacher8efc5222008-04-08 14:47:40 +020056 """A metaclass for nodes that handles the field and attribute
57 inheritance. fields and attributes from the parent class are
58 automatically forwarded to the child."""
Armin Ronacher07bc6842008-03-31 14:18:49 +020059
60 def __new__(cls, name, bases, d):
Armin Ronachere791c2a2008-04-07 18:39:54 +020061 for attr in 'fields', 'attributes':
Armin Ronacher07bc6842008-03-31 14:18:49 +020062 storage = []
Armin Ronacher7324eb82008-04-21 07:55:52 +020063 storage.extend(getattr(bases[0], attr, ()))
Armin Ronacher07bc6842008-03-31 14:18:49 +020064 storage.extend(d.get(attr, ()))
Armin Ronacher7324eb82008-04-21 07:55:52 +020065 assert len(bases) == 1, 'multiple inheritance not allowed'
66 assert len(storage) == len(set(storage)), 'layout conflict'
Armin Ronacher07bc6842008-03-31 14:18:49 +020067 d[attr] = tuple(storage)
Armin Ronacher023b5e92008-05-08 11:03:10 +020068 d.setdefault('abstract', False)
Armin Ronacher7324eb82008-04-21 07:55:52 +020069 return type.__new__(cls, name, bases, d)
Armin Ronacher07bc6842008-03-31 14:18:49 +020070
71
72class Node(object):
Armin Ronacher023b5e92008-05-08 11:03:10 +020073 """Baseclass for all Jinja2 nodes. There are a number of nodes available
74 of different types. There are three major types:
75
76 - :class:`Stmt`: statements
77 - :class:`Expr`: expressions
78 - :class:`Helper`: helper nodes
79 - :class:`Template`: the outermost wrapper node
80
81 All nodes have fields and attributes. Fields may be other nodes, lists,
82 or arbitrary values. Fields are passed to the constructor as regular
83 positional arguments, attributes as keyword arguments. Each node has
84 two attributes: `lineno` (the line number of the node) and `environment`.
85 The `environment` attribute is set at the end of the parsing process for
86 all nodes automatically.
Armin Ronacher69e12db2008-05-12 09:00:03 +020087
88 Nodes can be frozen which makes them hashable. The compiler freezes the
89 nodes automatically. Modifications on frozen nodes are possible but not
90 allowed.
Armin Ronacher023b5e92008-05-08 11:03:10 +020091 """
Armin Ronacher07bc6842008-03-31 14:18:49 +020092 __metaclass__ = NodeType
Armin Ronachere791c2a2008-04-07 18:39:54 +020093 fields = ()
Armin Ronacherd55ab532008-04-09 16:13:39 +020094 attributes = ('lineno', 'environment')
Armin Ronacher023b5e92008-05-08 11:03:10 +020095 abstract = True
Armin Ronacher69e12db2008-05-12 09:00:03 +020096 frozen = False
Armin Ronacher07bc6842008-03-31 14:18:49 +020097
Armin Ronacher023b5e92008-05-08 11:03:10 +020098 def __init__(self, *fields, **attributes):
Armin Ronacher69e12db2008-05-12 09:00:03 +020099 if self.abstract:
100 raise TypeError('abstract nodes are not instanciable')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200101 if fields:
102 if len(fields) != len(self.fields):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200103 if not self.fields:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200104 raise TypeError('%r takes 0 arguments' %
105 self.__class__.__name__)
106 raise TypeError('%r takes 0 or %d argument%s' % (
107 self.__class__.__name__,
Armin Ronachere791c2a2008-04-07 18:39:54 +0200108 len(self.fields),
109 len(self.fields) != 1 and 's' or ''
Armin Ronacher07bc6842008-03-31 14:18:49 +0200110 ))
Armin Ronacher023b5e92008-05-08 11:03:10 +0200111 for name, arg in izip(self.fields, fields):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200112 setattr(self, name, arg)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200113 for attr in self.attributes:
Armin Ronacher023b5e92008-05-08 11:03:10 +0200114 setattr(self, attr, attributes.pop(attr, None))
115 if attributes:
116 raise TypeError('unknown attribute %r' %
117 iter(attributes).next())
Armin Ronacher07bc6842008-03-31 14:18:49 +0200118
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200119 def iter_fields(self, exclude=None, only=None):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200120 """This method iterates over all fields that are defined and yields
Armin Ronacher3da90312008-05-23 16:37:28 +0200121 ``(key, value)`` tuples. Per default all fields are returned, but
122 it's possible to limit that to some fields by providing the `only`
123 parameter or to exclude some using the `exclude` parameter. Both
124 should be sets or tuples of field names.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200125 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200126 for name in self.fields:
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200127 if (exclude is only is None) or \
128 (exclude is not None and name not in exclude) or \
129 (only is not None and name in only):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200130 try:
131 yield name, getattr(self, name)
132 except AttributeError:
133 pass
Armin Ronacher07bc6842008-03-31 14:18:49 +0200134
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200135 def iter_child_nodes(self, exclude=None, only=None):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200136 """Iterates over all direct child nodes of the node. This iterates
137 over all fields and yields the values of they are nodes. If the value
138 of a field is a list all the nodes in that list are returned.
139 """
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200140 for field, item in self.iter_fields(exclude, only):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200141 if isinstance(item, list):
142 for n in item:
143 if isinstance(n, Node):
144 yield n
145 elif isinstance(item, Node):
146 yield item
147
Armin Ronachere791c2a2008-04-07 18:39:54 +0200148 def find(self, node_type):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200149 """Find the first node of a given type. If no such node exists the
150 return value is `None`.
151 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200152 for result in self.find_all(node_type):
153 return result
154
155 def find_all(self, node_type):
156 """Find all the nodes of a given type."""
157 for child in self.iter_child_nodes():
158 if isinstance(child, node_type):
159 yield child
160 for result in child.find_all(node_type):
161 yield result
162
Armin Ronacher0ecb8592008-04-09 16:29:47 +0200163 def copy(self):
164 """Return a deep copy of the node."""
165 result = object.__new__(self.__class__)
166 for field, value in self.iter_fields():
167 if isinstance(value, Node):
168 new_value = value.copy()
169 elif isinstance(value, list):
170 new_value = []
Armin Ronacherd436e982008-04-09 16:31:20 +0200171 for item in value:
Armin Ronacher0ecb8592008-04-09 16:29:47 +0200172 if isinstance(item, Node):
173 item = item.copy()
174 else:
175 item = copy(item)
176 new_value.append(item)
177 else:
Armin Ronacherd436e982008-04-09 16:31:20 +0200178 new_value = copy(value)
Armin Ronacher0ecb8592008-04-09 16:29:47 +0200179 setattr(result, field, new_value)
180 for attr in self.attributes:
181 try:
182 setattr(result, attr, getattr(self, attr))
183 except AttributeError:
184 pass
185 return result
186
Armin Ronachere791c2a2008-04-07 18:39:54 +0200187 def set_ctx(self, ctx):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200188 """Reset the context of a node and all child nodes. Per default the
189 parser will all generate nodes that have a 'load' context as it's the
190 most common one. This method is used in the parser to set assignment
191 targets and other nodes to a store context.
Armin Ronachere791c2a2008-04-07 18:39:54 +0200192 """
193 todo = deque([self])
194 while todo:
195 node = todo.popleft()
196 if 'ctx' in node.fields:
197 node.ctx = ctx
198 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200199 return self
Armin Ronachere791c2a2008-04-07 18:39:54 +0200200
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200201 def set_lineno(self, lineno, override=False):
202 """Set the line numbers of the node and children."""
203 todo = deque([self])
204 while todo:
205 node = todo.popleft()
206 if 'lineno' in node.attributes:
207 if node.lineno is None or override:
208 node.lineno = lineno
209 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200210 return self
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200211
Armin Ronacherd55ab532008-04-09 16:13:39 +0200212 def set_environment(self, environment):
213 """Set the environment for all nodes."""
214 todo = deque([self])
215 while todo:
216 node = todo.popleft()
217 node.environment = environment
218 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200219 return self
Armin Ronacherd55ab532008-04-09 16:13:39 +0200220
Armin Ronacher69e12db2008-05-12 09:00:03 +0200221 def freeze(self):
222 """Freeze the complete node tree which makes them hashable.
223 This happens automatically on compilation. Frozen nodes must not be
224 modified any further. Extensions may not freeze nodes that appear
225 in the final node tree (ie: nodes that are returned from the extension
226 parse method).
227 """
228 todo = deque([self])
229 while todo:
230 node = todo.popleft()
231 node.frozen = True
232 todo.extend(node.iter_child_nodes())
233
234 def __eq__(self, other):
Armin Ronacherb3a1fcf2008-05-15 11:04:14 +0200235 return type(self) is type(other) and \
236 tuple(self.iter_fields()) == tuple(other.iter_fields())
Armin Ronacher69e12db2008-05-12 09:00:03 +0200237
238 def __ne__(self, other):
239 return not self.__eq__(other)
240
241 def __hash__(self):
242 if not self.frozen:
243 raise TypeError('unfrozen nodes are unhashable')
Armin Ronacherb3a1fcf2008-05-15 11:04:14 +0200244 return hash(tuple(self.iter_fields()))
Armin Ronacher69e12db2008-05-12 09:00:03 +0200245
Armin Ronacher07bc6842008-03-31 14:18:49 +0200246 def __repr__(self):
247 return '%s(%s)' % (
248 self.__class__.__name__,
249 ', '.join('%s=%r' % (arg, getattr(self, arg, None)) for
Armin Ronachere791c2a2008-04-07 18:39:54 +0200250 arg in self.fields)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200251 )
252
253
254class Stmt(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200255 """Base node for all statements."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200256 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200257
258
259class Helper(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200260 """Nodes that exist in a specific context only."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200261 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200262
263
264class Template(Node):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200265 """Node that represents a template. This must be the outermost node that
266 is passed to the compiler.
267 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200268 fields = ('body',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200269
270
271class Output(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200272 """A node that holds multiple expressions which are then printed out.
273 This is used both for the `print` statement and the regular template data.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200274 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200275 fields = ('nodes',)
276
277 def optimized_nodes(self):
278 """Try to optimize the nodes."""
279 buffer = []
280 for node in self.nodes:
281 try:
282 const = unicode(node.as_const())
283 except:
284 buffer.append(node)
285 else:
286 if buffer and isinstance(buffer[-1], unicode):
287 buffer[-1] += const
288 else:
289 buffer.append(const)
290 return buffer
Armin Ronacher07bc6842008-03-31 14:18:49 +0200291
292
293class Extends(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200294 """Represents an extends statement."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200295 fields = ('template',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200296
297
298class For(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200299 """The for loop. `target` is the target for the iteration (usually a
300 :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list
301 of nodes that are used as loop-body, and `else_` a list of nodes for the
302 `else` block. If no else node exists it has to be an empty list.
303
304 For filtered nodes an expression can be stored as `test`, otherwise `None`.
305 """
Armin Ronacherfdf95302008-05-11 22:20:51 +0200306 fields = ('target', 'iter', 'body', 'else_', 'test', 'recursive')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200307
308
309class If(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200310 """If `test` is true, `body` is rendered, else `else_`."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200311 fields = ('test', 'body', 'else_')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200312
313
314class Macro(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200315 """A macro definition. `name` is the name of the macro, `args` a list of
316 arguments and `defaults` a list of defaults if there are any. `body` is
317 a list of nodes for the macro body.
318 """
Armin Ronacher8efc5222008-04-08 14:47:40 +0200319 fields = ('name', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200320
321
322class CallBlock(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200323 """Like a macro without a name but a call instead. `call` is called with
324 the unnamed macro as `caller` argument this node holds.
325 """
Armin Ronacherc9705c22008-04-27 21:28:03 +0200326 fields = ('call', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200327
328
329class Set(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200330 """Allows defining own variables."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200331 fields = ('name', 'expr')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200332
333
334class FilterBlock(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200335 """Node for filter sections."""
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200336 fields = ('body', 'filter')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200337
338
339class Block(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200340 """A node that represents a block."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200341 fields = ('name', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200342
343
344class Include(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200345 """A node that represents the include tag."""
Armin Ronacherea847c52008-05-02 20:04:32 +0200346 fields = ('template', 'with_context')
Armin Ronacher0611e492008-04-25 23:44:14 +0200347
348
349class Import(Stmt):
350 """A node that represents the import tag."""
Armin Ronacherea847c52008-05-02 20:04:32 +0200351 fields = ('template', 'target', 'with_context')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200352
353
Armin Ronacher0611e492008-04-25 23:44:14 +0200354class FromImport(Stmt):
355 """A node that represents the from import tag. It's important to not
356 pass unsafe names to the name attribute. The compiler translates the
357 attribute lookups directly into getattr calls and does *not* use the
358 subscribe callback of the interface. As exported variables may not
359 start with double underscores (which the parser asserts) this is not a
360 problem for regular Jinja code, but if this node is used in an extension
361 extra care must be taken.
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200362
363 The list of names may contain tuples if aliases are wanted.
Armin Ronacher0611e492008-04-25 23:44:14 +0200364 """
Armin Ronacherea847c52008-05-02 20:04:32 +0200365 fields = ('template', 'names', 'with_context')
Armin Ronacher0611e492008-04-25 23:44:14 +0200366
367
Armin Ronacher07bc6842008-03-31 14:18:49 +0200368class ExprStmt(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200369 """A statement that evaluates an expression and discards the result."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200370 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200371
372
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200373class Assign(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200374 """Assigns an expression to a target."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200375 fields = ('target', 'node')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200376
377
Armin Ronacher07bc6842008-03-31 14:18:49 +0200378class Expr(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200379 """Baseclass for all expressions."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200380 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200381
382 def as_const(self):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200383 """Return the value of the expression as constant or raise
Armin Ronacher023b5e92008-05-08 11:03:10 +0200384 :exc:`Impossible` if this was not possible:
385
386 >>> Add(Const(23), Const(42)).as_const()
387 65
388 >>> Add(Const(23), Name('var', 'load')).as_const()
389 Traceback (most recent call last):
390 ...
391 Impossible
392
393 This requires the `environment` attribute of all nodes to be
394 set to the environment that created the nodes.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200395 """
396 raise Impossible()
397
398 def can_assign(self):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200399 """Check if it's possible to assign something to this node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200400 return False
401
402
403class BinExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200404 """Baseclass for all binary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200405 fields = ('left', 'right')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200406 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200407 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200408
409 def as_const(self):
410 f = _binop_to_func[self.operator]
411 try:
412 return f(self.left.as_const(), self.right.as_const())
413 except:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200414 raise Impossible()
415
416
417class UnaryExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200418 """Baseclass for all unary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200419 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200420 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200421 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200422
423 def as_const(self):
424 f = _uaop_to_func[self.operator]
425 try:
426 return f(self.node.as_const())
427 except:
428 raise Impossible()
429
430
431class Name(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200432 """Looks up a name or stores a value in a name.
433 The `ctx` of the node can be one of the following values:
434
435 - `store`: store a value in the name
436 - `load`: load that name
437 - `param`: like `store` but if the name was defined as function parameter.
438 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200439 fields = ('name', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200440
441 def can_assign(self):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200442 return self.name not in ('true', 'false', 'none')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200443
444
445class Literal(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200446 """Baseclass for literals."""
Armin Ronacher69e12db2008-05-12 09:00:03 +0200447 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200448
449
450class Const(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200451 """All constant values. The parser will return this node for simple
452 constants such as ``42`` or ``"foo"`` but it can be used to store more
453 complex values such as lists too. Only constants with a safe
454 representation (objects where ``eval(repr(x)) == x`` is true).
455 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200456 fields = ('value',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200457
458 def as_const(self):
459 return self.value
460
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200461 @classmethod
Armin Ronacherd55ab532008-04-09 16:13:39 +0200462 def from_untrusted(cls, value, lineno=None, environment=None):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200463 """Return a const object if the value is representable as
464 constant value in the generated code, otherwise it will raise
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200465 an `Impossible` exception.
466 """
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200467 from compiler import has_safe_repr
468 if not has_safe_repr(value):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200469 raise Impossible()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200470 return cls(value, lineno=lineno, environment=environment)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200471
Armin Ronacher07bc6842008-03-31 14:18:49 +0200472
473class Tuple(Literal):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200474 """For loop unpacking and some other things like multiple arguments
Armin Ronacher023b5e92008-05-08 11:03:10 +0200475 for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
476 is used for loading the names or storing.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200477 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200478 fields = ('items', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200479
480 def as_const(self):
481 return tuple(x.as_const() for x in self.items)
482
483 def can_assign(self):
484 for item in self.items:
485 if not item.can_assign():
486 return False
487 return True
488
489
490class List(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200491 """Any list literal such as ``[1, 2, 3]``"""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200492 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200493
494 def as_const(self):
495 return [x.as_const() for x in self.items]
496
497
498class Dict(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200499 """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
500 :class:`Pair` nodes.
501 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200502 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200503
504 def as_const(self):
505 return dict(x.as_const() for x in self.items)
506
507
508class Pair(Helper):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200509 """A key, value pair for dicts."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200510 fields = ('key', 'value')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200511
512 def as_const(self):
513 return self.key.as_const(), self.value.as_const()
514
515
Armin Ronacher8efc5222008-04-08 14:47:40 +0200516class Keyword(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200517 """A key, value pair for keyword arguments where key is a string."""
Armin Ronacher8efc5222008-04-08 14:47:40 +0200518 fields = ('key', 'value')
519
520
Armin Ronacher07bc6842008-03-31 14:18:49 +0200521class CondExpr(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200522 """A conditional expression (inline if expression). (``{{
523 foo if bar else baz }}``)
524 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200525 fields = ('test', 'expr1', 'expr2')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200526
527 def as_const(self):
528 if self.test.as_const():
529 return self.expr1.as_const()
530 return self.expr2.as_const()
531
532
533class Filter(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200534 """This node applies a filter on an expression. `name` is the name of
535 the filter, the rest of the fields are the same as for :class:`Call`.
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200536
537 If the `node` of a filter is `None` the contents of the last buffer are
538 filtered. Buffers are created by macros and filter blocks.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200539 """
Armin Ronacherd55ab532008-04-09 16:13:39 +0200540 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200541
Armin Ronacher00d5d212008-04-13 01:10:18 +0200542 def as_const(self, obj=None):
543 if self.node is obj is None:
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200544 raise Impossible()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200545 filter = self.environment.filters.get(self.name)
546 if filter is None or getattr(filter, 'contextfilter', False):
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200547 raise Impossible()
Armin Ronacher00d5d212008-04-13 01:10:18 +0200548 if obj is None:
549 obj = self.node.as_const()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200550 args = [x.as_const() for x in self.args]
Armin Ronacher9a027f42008-04-17 11:13:40 +0200551 if getattr(filter, 'environmentfilter', False):
552 args.insert(0, self.environment)
Armin Ronacherd55ab532008-04-09 16:13:39 +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:
561 kwargs.update(self.dyn_kwargs.as_const())
562 except:
563 raise Impossible()
564 try:
565 return filter(obj, *args, **kwargs)
566 except:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200567 raise Impossible()
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200568
569
Armin Ronacher07bc6842008-03-31 14:18:49 +0200570class Test(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200571 """Applies a test on an expression. `name` is the name of the test, the
572 rest of the fields are the same as for :class:`Call`.
573 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200574 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200575
576
577class Call(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200578 """Calls an expression. `args` is a list of arguments, `kwargs` a list
579 of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
580 and `dyn_kwargs` has to be either `None` or a node that is used as
581 node for dynamic positional (``*args``) or keyword (``**kwargs``)
582 arguments.
583 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200584 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200585
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200586 def as_const(self):
587 obj = self.node.as_const()
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200588
589 # don't evaluate context functions
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200590 args = [x.as_const() for x in self.args]
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200591 if type(obj) is FunctionType:
592 if getattr(obj, 'contextfunction', False):
593 raise Impossible()
594 elif obj.environmentfunction:
595 args.insert(0, self.environment)
596
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200597 kwargs = dict(x.as_const() for x in self.kwargs)
598 if self.dyn_args is not None:
599 try:
600 args.extend(self.dyn_args.as_const())
601 except:
602 raise Impossible()
603 if self.dyn_kwargs is not None:
604 try:
Armin Ronacherd55ab532008-04-09 16:13:39 +0200605 kwargs.update(self.dyn_kwargs.as_const())
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200606 except:
607 raise Impossible()
608 try:
609 return obj(*args, **kwargs)
610 except:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200611 raise Impossible()
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200612
Armin Ronacher07bc6842008-03-31 14:18:49 +0200613
614class Subscript(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200615 """Subscribe an expression by an argument. This node performs a dict
616 and an attribute lookup on the object whatever succeeds.
617 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200618 fields = ('node', 'arg', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200619
620 def as_const(self):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200621 if self.ctx != 'load':
622 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200623 try:
Benjamin Wieganda3152742008-04-28 18:07:52 +0200624 return self.environment.subscribe(self.node.as_const(),
625 self.arg.as_const())
Armin Ronacher07bc6842008-03-31 14:18:49 +0200626 except:
627 raise Impossible()
628
629 def can_assign(self):
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200630 return False
Armin Ronacher07bc6842008-03-31 14:18:49 +0200631
632
633class Slice(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200634 """Represents a slice object. This must only be used as argument for
635 :class:`Subscript`.
636 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200637 fields = ('start', 'stop', 'step')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200638
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200639 def as_const(self):
640 def const(obj):
641 if obj is None:
642 return obj
643 return obj.as_const()
644 return slice(const(self.start), const(self.stop), const(self.step))
645
Armin Ronacher07bc6842008-03-31 14:18:49 +0200646
647class Concat(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200648 """Concatenates the list of expressions provided after converting them to
649 unicode.
650 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200651 fields = ('nodes',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200652
653 def as_const(self):
654 return ''.join(unicode(x.as_const()) for x in self.nodes)
655
656
657class Compare(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200658 """Compares an expression with some other expressions. `ops` must be a
659 list of :class:`Operand`\s.
660 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200661 fields = ('expr', 'ops')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200662
Armin Ronacher625215e2008-04-13 16:31:08 +0200663 def as_const(self):
664 result = value = self.expr.as_const()
Armin Ronacherb5124e62008-04-25 00:36:14 +0200665 try:
666 for op in self.ops:
667 new_value = op.expr.as_const()
668 result = _cmpop_to_func[op.op](value, new_value)
669 value = new_value
670 except:
671 raise Impossible()
Armin Ronacher625215e2008-04-13 16:31:08 +0200672 return result
673
Armin Ronacher07bc6842008-03-31 14:18:49 +0200674
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200675class Operand(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200676 """Holds an operator and an expression."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200677 fields = ('op', 'expr')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200678
Armin Ronacher023b5e92008-05-08 11:03:10 +0200679if __debug__:
680 Operand.__doc__ += '\nThe following operators are available: ' + \
681 ', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
682 set(_uaop_to_func) | set(_cmpop_to_func)))
683
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200684
Armin Ronacher07bc6842008-03-31 14:18:49 +0200685class Mul(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200686 """Multiplies the left with the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200687 operator = '*'
688
689
690class Div(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200691 """Divides the left by the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200692 operator = '/'
693
694
695class FloorDiv(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200696 """Divides the left by the right node and truncates conver the
697 result into an integer by truncating.
698 """
Armin Ronacher07bc6842008-03-31 14:18:49 +0200699 operator = '//'
700
701
702class Add(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200703 """Add the left to the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200704 operator = '+'
705
706
707class Sub(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200708 """Substract the right from the left node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200709 operator = '-'
710
711
712class Mod(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200713 """Left modulo right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200714 operator = '%'
715
716
717class Pow(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200718 """Left to the power of right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200719 operator = '**'
720
721
722class And(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200723 """Short circuited AND."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200724 operator = 'and'
725
726 def as_const(self):
727 return self.left.as_const() and self.right.as_const()
728
729
730class Or(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200731 """Short circuited OR."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200732 operator = 'or'
733
734 def as_const(self):
735 return self.left.as_const() or self.right.as_const()
736
737
738class Not(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200739 """Negate the expression."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200740 operator = 'not'
741
742
Armin Ronachere791c2a2008-04-07 18:39:54 +0200743class Neg(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200744 """Make the expression negative."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200745 operator = '-'
746
747
Armin Ronachere791c2a2008-04-07 18:39:54 +0200748class Pos(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200749 """Make the expression positive (noop for most expressions)"""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200750 operator = '+'
Armin Ronacher023b5e92008-05-08 11:03:10 +0200751
752
753# Helpers for extensions
754
755
756class EnvironmentAttribute(Expr):
757 """Loads an attribute from the environment object. This is useful for
758 extensions that want to call a callback stored on the environment.
759 """
760 fields = ('name',)
761
762
763class ExtensionAttribute(Expr):
764 """Returns the attribute of an extension bound to the environment.
765 The identifier is the identifier of the :class:`Extension`.
Armin Ronacherb9e78752008-05-10 23:36:28 +0200766
767 This node is usually constructed by calling the
768 :meth:`~jinja2.ext.Extension.attr` method on an extension.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200769 """
770 fields = ('identifier', 'attr')
771
772
773class ImportedName(Expr):
774 """If created with an import name the import name is returned on node
775 access. For example ``ImportedName('cgi.escape')`` returns the `escape`
776 function from the cgi module on evaluation. Imports are optimized by the
777 compiler so there is no need to assign them to local variables.
778 """
779 fields = ('importname',)
780
781
782class InternalName(Expr):
783 """An internal name in the compiler. You cannot create these nodes
Armin Ronacher762079c2008-05-08 23:57:56 +0200784 yourself but the parser provides a
785 :meth:`~jinja2.parser.Parser.free_identifier` method that creates
Armin Ronacher023b5e92008-05-08 11:03:10 +0200786 a new identifier for you. This identifier is not available from the
787 template and is not threated specially by the compiler.
788 """
789 fields = ('name',)
790
791 def __init__(self):
792 raise TypeError('Can\'t create internal names. Use the '
793 '`free_identifier` method on a parser.')
794
795
796class MarkSafe(Expr):
797 """Mark the wrapped expression as safe (wrap it as `Markup`)."""
798 fields = ('expr',)
799
800 def as_const(self):
801 return Markup(self.expr.as_const())
802
803
Armin Ronachered1e0d42008-05-18 20:25:28 +0200804class Continue(Stmt):
805 """Continue a loop."""
806
807
808class Break(Stmt):
809 """Break a loop."""
810
811
Armin Ronacher8a1d27f2008-05-19 08:37:19 +0200812# make sure nobody creates custom nodes
813def _failing_new(*args, **kwargs):
814 raise TypeError('can\'t create custom node types')
815NodeType.__new__ = staticmethod(_failing_new); del _failing_new