blob: 960a5408005b814f4ef5f94fddc1d56082f9d59b [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
Armin Ronacher023b5e92008-05-08 11:03:10 +020051# if this is `True` no new Node classes can be created.
52_node_setup_finished = False
53
54
Armin Ronacher07bc6842008-03-31 14:18:49 +020055class Impossible(Exception):
Armin Ronacher8efc5222008-04-08 14:47:40 +020056 """Raised if the node could not perform a requested action."""
Armin Ronacher07bc6842008-03-31 14:18:49 +020057
58
59class NodeType(type):
Armin Ronacher8efc5222008-04-08 14:47:40 +020060 """A metaclass for nodes that handles the field and attribute
61 inheritance. fields and attributes from the parent class are
62 automatically forwarded to the child."""
Armin Ronacher07bc6842008-03-31 14:18:49 +020063
64 def __new__(cls, name, bases, d):
Armin Ronacher023b5e92008-05-08 11:03:10 +020065 if __debug__ and _node_setup_finished:
66 raise TypeError('Can\'t create custom node types.')
Armin Ronachere791c2a2008-04-07 18:39:54 +020067 for attr in 'fields', 'attributes':
Armin Ronacher07bc6842008-03-31 14:18:49 +020068 storage = []
Armin Ronacher7324eb82008-04-21 07:55:52 +020069 storage.extend(getattr(bases[0], attr, ()))
Armin Ronacher07bc6842008-03-31 14:18:49 +020070 storage.extend(d.get(attr, ()))
Armin Ronacher7324eb82008-04-21 07:55:52 +020071 assert len(bases) == 1, 'multiple inheritance not allowed'
72 assert len(storage) == len(set(storage)), 'layout conflict'
Armin Ronacher07bc6842008-03-31 14:18:49 +020073 d[attr] = tuple(storage)
Armin Ronacher023b5e92008-05-08 11:03:10 +020074 d.setdefault('abstract', False)
Armin Ronacher7324eb82008-04-21 07:55:52 +020075 return type.__new__(cls, name, bases, d)
Armin Ronacher07bc6842008-03-31 14:18:49 +020076
77
78class Node(object):
Armin Ronacher023b5e92008-05-08 11:03:10 +020079 """Baseclass for all Jinja2 nodes. There are a number of nodes available
80 of different types. There are three major types:
81
82 - :class:`Stmt`: statements
83 - :class:`Expr`: expressions
84 - :class:`Helper`: helper nodes
85 - :class:`Template`: the outermost wrapper node
86
87 All nodes have fields and attributes. Fields may be other nodes, lists,
88 or arbitrary values. Fields are passed to the constructor as regular
89 positional arguments, attributes as keyword arguments. Each node has
90 two attributes: `lineno` (the line number of the node) and `environment`.
91 The `environment` attribute is set at the end of the parsing process for
92 all nodes automatically.
Armin Ronacher69e12db2008-05-12 09:00:03 +020093
94 Nodes can be frozen which makes them hashable. The compiler freezes the
95 nodes automatically. Modifications on frozen nodes are possible but not
96 allowed.
Armin Ronacher023b5e92008-05-08 11:03:10 +020097 """
Armin Ronacher07bc6842008-03-31 14:18:49 +020098 __metaclass__ = NodeType
Armin Ronachere791c2a2008-04-07 18:39:54 +020099 fields = ()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200100 attributes = ('lineno', 'environment')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200101 abstract = True
Armin Ronacher69e12db2008-05-12 09:00:03 +0200102 frozen = False
Armin Ronacher07bc6842008-03-31 14:18:49 +0200103
Armin Ronacher023b5e92008-05-08 11:03:10 +0200104 def __init__(self, *fields, **attributes):
Armin Ronacher69e12db2008-05-12 09:00:03 +0200105 if self.abstract:
106 raise TypeError('abstract nodes are not instanciable')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200107 if fields:
108 if len(fields) != len(self.fields):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200109 if not self.fields:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200110 raise TypeError('%r takes 0 arguments' %
111 self.__class__.__name__)
112 raise TypeError('%r takes 0 or %d argument%s' % (
113 self.__class__.__name__,
Armin Ronachere791c2a2008-04-07 18:39:54 +0200114 len(self.fields),
115 len(self.fields) != 1 and 's' or ''
Armin Ronacher07bc6842008-03-31 14:18:49 +0200116 ))
Armin Ronacher023b5e92008-05-08 11:03:10 +0200117 for name, arg in izip(self.fields, fields):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200118 setattr(self, name, arg)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200119 for attr in self.attributes:
Armin Ronacher023b5e92008-05-08 11:03:10 +0200120 setattr(self, attr, attributes.pop(attr, None))
121 if attributes:
122 raise TypeError('unknown attribute %r' %
123 iter(attributes).next())
Armin Ronacher07bc6842008-03-31 14:18:49 +0200124
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200125 def iter_fields(self, exclude=()):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200126 """This method iterates over all fields that are defined and yields
127 ``(key, value)`` tuples. Optionally a parameter of ignored fields
128 can be provided.
129 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200130 for name in self.fields:
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200131 if name not in exclude:
132 try:
133 yield name, getattr(self, name)
134 except AttributeError:
135 pass
Armin Ronacher07bc6842008-03-31 14:18:49 +0200136
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200137 def iter_child_nodes(self, exclude=()):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200138 """Iterates over all direct child nodes of the node. This iterates
139 over all fields and yields the values of they are nodes. If the value
140 of a field is a list all the nodes in that list are returned.
141 """
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200142 for field, item in self.iter_fields(exclude):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200143 if isinstance(item, list):
144 for n in item:
145 if isinstance(n, Node):
146 yield n
147 elif isinstance(item, Node):
148 yield item
149
Armin Ronachere791c2a2008-04-07 18:39:54 +0200150 def find(self, node_type):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200151 """Find the first node of a given type. If no such node exists the
152 return value is `None`.
153 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200154 for result in self.find_all(node_type):
155 return result
156
157 def find_all(self, node_type):
158 """Find all the nodes of a given type."""
159 for child in self.iter_child_nodes():
160 if isinstance(child, node_type):
161 yield child
162 for result in child.find_all(node_type):
163 yield result
164
Armin Ronacher0ecb8592008-04-09 16:29:47 +0200165 def copy(self):
166 """Return a deep copy of the node."""
167 result = object.__new__(self.__class__)
168 for field, value in self.iter_fields():
169 if isinstance(value, Node):
170 new_value = value.copy()
171 elif isinstance(value, list):
172 new_value = []
Armin Ronacherd436e982008-04-09 16:31:20 +0200173 for item in value:
Armin Ronacher0ecb8592008-04-09 16:29:47 +0200174 if isinstance(item, Node):
175 item = item.copy()
176 else:
177 item = copy(item)
178 new_value.append(item)
179 else:
Armin Ronacherd436e982008-04-09 16:31:20 +0200180 new_value = copy(value)
Armin Ronacher0ecb8592008-04-09 16:29:47 +0200181 setattr(result, field, new_value)
182 for attr in self.attributes:
183 try:
184 setattr(result, attr, getattr(self, attr))
185 except AttributeError:
186 pass
187 return result
188
Armin Ronachere791c2a2008-04-07 18:39:54 +0200189 def set_ctx(self, ctx):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200190 """Reset the context of a node and all child nodes. Per default the
191 parser will all generate nodes that have a 'load' context as it's the
192 most common one. This method is used in the parser to set assignment
193 targets and other nodes to a store context.
Armin Ronachere791c2a2008-04-07 18:39:54 +0200194 """
195 todo = deque([self])
196 while todo:
197 node = todo.popleft()
198 if 'ctx' in node.fields:
199 node.ctx = ctx
200 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200201 return self
Armin Ronachere791c2a2008-04-07 18:39:54 +0200202
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200203 def set_lineno(self, lineno, override=False):
204 """Set the line numbers of the node and children."""
205 todo = deque([self])
206 while todo:
207 node = todo.popleft()
208 if 'lineno' in node.attributes:
209 if node.lineno is None or override:
210 node.lineno = lineno
211 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200212 return self
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200213
Armin Ronacherd55ab532008-04-09 16:13:39 +0200214 def set_environment(self, environment):
215 """Set the environment for all nodes."""
216 todo = deque([self])
217 while todo:
218 node = todo.popleft()
219 node.environment = environment
220 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200221 return self
Armin Ronacherd55ab532008-04-09 16:13:39 +0200222
Armin Ronacher69e12db2008-05-12 09:00:03 +0200223 def freeze(self):
224 """Freeze the complete node tree which makes them hashable.
225 This happens automatically on compilation. Frozen nodes must not be
226 modified any further. Extensions may not freeze nodes that appear
227 in the final node tree (ie: nodes that are returned from the extension
228 parse method).
229 """
230 todo = deque([self])
231 while todo:
232 node = todo.popleft()
233 node.frozen = True
234 todo.extend(node.iter_child_nodes())
235
236 def __eq__(self, other):
Armin Ronacherb3a1fcf2008-05-15 11:04:14 +0200237 return type(self) is type(other) and \
238 tuple(self.iter_fields()) == tuple(other.iter_fields())
Armin Ronacher69e12db2008-05-12 09:00:03 +0200239
240 def __ne__(self, other):
241 return not self.__eq__(other)
242
243 def __hash__(self):
244 if not self.frozen:
245 raise TypeError('unfrozen nodes are unhashable')
Armin Ronacherb3a1fcf2008-05-15 11:04:14 +0200246 return hash(tuple(self.iter_fields()))
Armin Ronacher69e12db2008-05-12 09:00:03 +0200247
Armin Ronacher07bc6842008-03-31 14:18:49 +0200248 def __repr__(self):
249 return '%s(%s)' % (
250 self.__class__.__name__,
251 ', '.join('%s=%r' % (arg, getattr(self, arg, None)) for
Armin Ronachere791c2a2008-04-07 18:39:54 +0200252 arg in self.fields)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200253 )
254
255
256class Stmt(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200257 """Base node for all statements."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200258 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200259
260
261class Helper(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200262 """Nodes that exist in a specific context only."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200263 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200264
265
266class Template(Node):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200267 """Node that represents a template. This must be the outermost node that
268 is passed to the compiler.
269 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200270 fields = ('body',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200271
272
273class Output(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200274 """A node that holds multiple expressions which are then printed out.
275 This is used both for the `print` statement and the regular template data.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200276 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200277 fields = ('nodes',)
278
279 def optimized_nodes(self):
280 """Try to optimize the nodes."""
281 buffer = []
282 for node in self.nodes:
283 try:
284 const = unicode(node.as_const())
285 except:
286 buffer.append(node)
287 else:
288 if buffer and isinstance(buffer[-1], unicode):
289 buffer[-1] += const
290 else:
291 buffer.append(const)
292 return buffer
Armin Ronacher07bc6842008-03-31 14:18:49 +0200293
294
295class Extends(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200296 """Represents an extends statement."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200297 fields = ('template',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200298
299
300class For(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200301 """The for loop. `target` is the target for the iteration (usually a
302 :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list
303 of nodes that are used as loop-body, and `else_` a list of nodes for the
304 `else` block. If no else node exists it has to be an empty list.
305
306 For filtered nodes an expression can be stored as `test`, otherwise `None`.
307 """
Armin Ronacherfdf95302008-05-11 22:20:51 +0200308 fields = ('target', 'iter', 'body', 'else_', 'test', 'recursive')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200309
310
311class If(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200312 """If `test` is true, `body` is rendered, else `else_`."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200313 fields = ('test', 'body', 'else_')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200314
315
316class Macro(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200317 """A macro definition. `name` is the name of the macro, `args` a list of
318 arguments and `defaults` a list of defaults if there are any. `body` is
319 a list of nodes for the macro body.
320 """
Armin Ronacher8efc5222008-04-08 14:47:40 +0200321 fields = ('name', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200322
323
324class CallBlock(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200325 """Like a macro without a name but a call instead. `call` is called with
326 the unnamed macro as `caller` argument this node holds.
327 """
Armin Ronacherc9705c22008-04-27 21:28:03 +0200328 fields = ('call', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200329
330
331class Set(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200332 """Allows defining own variables."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200333 fields = ('name', 'expr')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200334
335
336class FilterBlock(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200337 """Node for filter sections."""
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200338 fields = ('body', 'filter')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200339
340
341class Block(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200342 """A node that represents a block."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200343 fields = ('name', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200344
345
346class Include(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200347 """A node that represents the include tag."""
Armin Ronacherea847c52008-05-02 20:04:32 +0200348 fields = ('template', 'with_context')
Armin Ronacher0611e492008-04-25 23:44:14 +0200349
350
351class Import(Stmt):
352 """A node that represents the import tag."""
Armin Ronacherea847c52008-05-02 20:04:32 +0200353 fields = ('template', 'target', 'with_context')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200354
355
Armin Ronacher0611e492008-04-25 23:44:14 +0200356class FromImport(Stmt):
357 """A node that represents the from import tag. It's important to not
358 pass unsafe names to the name attribute. The compiler translates the
359 attribute lookups directly into getattr calls and does *not* use the
360 subscribe callback of the interface. As exported variables may not
361 start with double underscores (which the parser asserts) this is not a
362 problem for regular Jinja code, but if this node is used in an extension
363 extra care must be taken.
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200364
365 The list of names may contain tuples if aliases are wanted.
Armin Ronacher0611e492008-04-25 23:44:14 +0200366 """
Armin Ronacherea847c52008-05-02 20:04:32 +0200367 fields = ('template', 'names', 'with_context')
Armin Ronacher0611e492008-04-25 23:44:14 +0200368
369
Armin Ronacher07bc6842008-03-31 14:18:49 +0200370class ExprStmt(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200371 """A statement that evaluates an expression and discards the result."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200372 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200373
374
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200375class Assign(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200376 """Assigns an expression to a target."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200377 fields = ('target', 'node')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200378
379
Armin Ronacher07bc6842008-03-31 14:18:49 +0200380class Expr(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200381 """Baseclass for all expressions."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200382 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200383
384 def as_const(self):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200385 """Return the value of the expression as constant or raise
Armin Ronacher023b5e92008-05-08 11:03:10 +0200386 :exc:`Impossible` if this was not possible:
387
388 >>> Add(Const(23), Const(42)).as_const()
389 65
390 >>> Add(Const(23), Name('var', 'load')).as_const()
391 Traceback (most recent call last):
392 ...
393 Impossible
394
395 This requires the `environment` attribute of all nodes to be
396 set to the environment that created the nodes.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200397 """
398 raise Impossible()
399
400 def can_assign(self):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200401 """Check if it's possible to assign something to this node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200402 return False
403
404
405class BinExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200406 """Baseclass for all binary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200407 fields = ('left', 'right')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200408 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200409 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200410
411 def as_const(self):
412 f = _binop_to_func[self.operator]
413 try:
414 return f(self.left.as_const(), self.right.as_const())
415 except:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200416 raise Impossible()
417
418
419class UnaryExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200420 """Baseclass for all unary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200421 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200422 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200423 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200424
425 def as_const(self):
426 f = _uaop_to_func[self.operator]
427 try:
428 return f(self.node.as_const())
429 except:
430 raise Impossible()
431
432
433class Name(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200434 """Looks up a name or stores a value in a name.
435 The `ctx` of the node can be one of the following values:
436
437 - `store`: store a value in the name
438 - `load`: load that name
439 - `param`: like `store` but if the name was defined as function parameter.
440 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200441 fields = ('name', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200442
443 def can_assign(self):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200444 return self.name not in ('true', 'false', 'none')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200445
446
447class Literal(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200448 """Baseclass for literals."""
Armin Ronacher69e12db2008-05-12 09:00:03 +0200449 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200450
451
452class Const(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200453 """All constant values. The parser will return this node for simple
454 constants such as ``42`` or ``"foo"`` but it can be used to store more
455 complex values such as lists too. Only constants with a safe
456 representation (objects where ``eval(repr(x)) == x`` is true).
457 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200458 fields = ('value',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200459
460 def as_const(self):
461 return self.value
462
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200463 @classmethod
Armin Ronacherd55ab532008-04-09 16:13:39 +0200464 def from_untrusted(cls, value, lineno=None, environment=None):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200465 """Return a const object if the value is representable as
466 constant value in the generated code, otherwise it will raise
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200467 an `Impossible` exception.
468 """
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200469 from compiler import has_safe_repr
470 if not has_safe_repr(value):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200471 raise Impossible()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200472 return cls(value, lineno=lineno, environment=environment)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200473
Armin Ronacher07bc6842008-03-31 14:18:49 +0200474
475class Tuple(Literal):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200476 """For loop unpacking and some other things like multiple arguments
Armin Ronacher023b5e92008-05-08 11:03:10 +0200477 for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
478 is used for loading the names or storing.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200479 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200480 fields = ('items', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200481
482 def as_const(self):
483 return tuple(x.as_const() for x in self.items)
484
485 def can_assign(self):
486 for item in self.items:
487 if not item.can_assign():
488 return False
489 return True
490
491
492class List(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200493 """Any list literal such as ``[1, 2, 3]``"""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200494 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200495
496 def as_const(self):
497 return [x.as_const() for x in self.items]
498
499
500class Dict(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200501 """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
502 :class:`Pair` nodes.
503 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200504 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200505
506 def as_const(self):
507 return dict(x.as_const() for x in self.items)
508
509
510class Pair(Helper):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200511 """A key, value pair for dicts."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200512 fields = ('key', 'value')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200513
514 def as_const(self):
515 return self.key.as_const(), self.value.as_const()
516
517
Armin Ronacher8efc5222008-04-08 14:47:40 +0200518class Keyword(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200519 """A key, value pair for keyword arguments where key is a string."""
Armin Ronacher8efc5222008-04-08 14:47:40 +0200520 fields = ('key', 'value')
521
522
Armin Ronacher07bc6842008-03-31 14:18:49 +0200523class CondExpr(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200524 """A conditional expression (inline if expression). (``{{
525 foo if bar else baz }}``)
526 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200527 fields = ('test', 'expr1', 'expr2')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200528
529 def as_const(self):
530 if self.test.as_const():
531 return self.expr1.as_const()
532 return self.expr2.as_const()
533
534
535class Filter(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200536 """This node applies a filter on an expression. `name` is the name of
537 the filter, the rest of the fields are the same as for :class:`Call`.
538 """
Armin Ronacherd55ab532008-04-09 16:13:39 +0200539 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200540
Armin Ronacher00d5d212008-04-13 01:10:18 +0200541 def as_const(self, obj=None):
542 if self.node is obj is None:
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200543 raise Impossible()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200544 filter = self.environment.filters.get(self.name)
545 if filter is None or getattr(filter, 'contextfilter', False):
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200546 raise Impossible()
Armin Ronacher00d5d212008-04-13 01:10:18 +0200547 if obj is None:
548 obj = self.node.as_const()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200549 args = [x.as_const() for x in self.args]
Armin Ronacher9a027f42008-04-17 11:13:40 +0200550 if getattr(filter, 'environmentfilter', False):
551 args.insert(0, self.environment)
Armin Ronacherd55ab532008-04-09 16:13:39 +0200552 kwargs = dict(x.as_const() for x in self.kwargs)
553 if self.dyn_args is not None:
554 try:
555 args.extend(self.dyn_args.as_const())
556 except:
557 raise Impossible()
558 if self.dyn_kwargs is not None:
559 try:
560 kwargs.update(self.dyn_kwargs.as_const())
561 except:
562 raise Impossible()
563 try:
564 return filter(obj, *args, **kwargs)
565 except:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200566 raise Impossible()
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200567
568
Armin Ronacher07bc6842008-03-31 14:18:49 +0200569class Test(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200570 """Applies a test on an expression. `name` is the name of the test, the
571 rest of the fields are the same as for :class:`Call`.
572 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200573 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200574
575
576class Call(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200577 """Calls an expression. `args` is a list of arguments, `kwargs` a list
578 of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
579 and `dyn_kwargs` has to be either `None` or a node that is used as
580 node for dynamic positional (``*args``) or keyword (``**kwargs``)
581 arguments.
582 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200583 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200584
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200585 def as_const(self):
586 obj = self.node.as_const()
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200587
588 # don't evaluate context functions
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200589 args = [x.as_const() for x in self.args]
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200590 if type(obj) is FunctionType:
591 if getattr(obj, 'contextfunction', False):
592 raise Impossible()
593 elif obj.environmentfunction:
594 args.insert(0, self.environment)
595
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200596 kwargs = dict(x.as_const() for x in self.kwargs)
597 if self.dyn_args is not None:
598 try:
599 args.extend(self.dyn_args.as_const())
600 except:
601 raise Impossible()
602 if self.dyn_kwargs is not None:
603 try:
Armin Ronacherd55ab532008-04-09 16:13:39 +0200604 kwargs.update(self.dyn_kwargs.as_const())
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200605 except:
606 raise Impossible()
607 try:
608 return obj(*args, **kwargs)
609 except:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200610 raise Impossible()
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200611
Armin Ronacher07bc6842008-03-31 14:18:49 +0200612
613class Subscript(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200614 """Subscribe an expression by an argument. This node performs a dict
615 and an attribute lookup on the object whatever succeeds.
616 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200617 fields = ('node', 'arg', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200618
619 def as_const(self):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200620 if self.ctx != 'load':
621 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200622 try:
Benjamin Wieganda3152742008-04-28 18:07:52 +0200623 return self.environment.subscribe(self.node.as_const(),
624 self.arg.as_const())
Armin Ronacher07bc6842008-03-31 14:18:49 +0200625 except:
626 raise Impossible()
627
628 def can_assign(self):
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200629 return False
Armin Ronacher07bc6842008-03-31 14:18:49 +0200630
631
632class Slice(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200633 """Represents a slice object. This must only be used as argument for
634 :class:`Subscript`.
635 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200636 fields = ('start', 'stop', 'step')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200637
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200638 def as_const(self):
639 def const(obj):
640 if obj is None:
641 return obj
642 return obj.as_const()
643 return slice(const(self.start), const(self.stop), const(self.step))
644
Armin Ronacher07bc6842008-03-31 14:18:49 +0200645
646class Concat(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200647 """Concatenates the list of expressions provided after converting them to
648 unicode.
649 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200650 fields = ('nodes',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200651
652 def as_const(self):
653 return ''.join(unicode(x.as_const()) for x in self.nodes)
654
655
656class Compare(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200657 """Compares an expression with some other expressions. `ops` must be a
658 list of :class:`Operand`\s.
659 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200660 fields = ('expr', 'ops')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200661
Armin Ronacher625215e2008-04-13 16:31:08 +0200662 def as_const(self):
663 result = value = self.expr.as_const()
Armin Ronacherb5124e62008-04-25 00:36:14 +0200664 try:
665 for op in self.ops:
666 new_value = op.expr.as_const()
667 result = _cmpop_to_func[op.op](value, new_value)
668 value = new_value
669 except:
670 raise Impossible()
Armin Ronacher625215e2008-04-13 16:31:08 +0200671 return result
672
Armin Ronacher07bc6842008-03-31 14:18:49 +0200673
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200674class Operand(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200675 """Holds an operator and an expression."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200676 fields = ('op', 'expr')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200677
Armin Ronacher023b5e92008-05-08 11:03:10 +0200678if __debug__:
679 Operand.__doc__ += '\nThe following operators are available: ' + \
680 ', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
681 set(_uaop_to_func) | set(_cmpop_to_func)))
682
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200683
Armin Ronacher07bc6842008-03-31 14:18:49 +0200684class Mul(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200685 """Multiplies the left with the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200686 operator = '*'
687
688
689class Div(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200690 """Divides the left by the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200691 operator = '/'
692
693
694class FloorDiv(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200695 """Divides the left by the right node and truncates conver the
696 result into an integer by truncating.
697 """
Armin Ronacher07bc6842008-03-31 14:18:49 +0200698 operator = '//'
699
700
701class Add(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200702 """Add the left to the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200703 operator = '+'
704
705
706class Sub(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200707 """Substract the right from the left node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200708 operator = '-'
709
710
711class Mod(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200712 """Left modulo right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200713 operator = '%'
714
715
716class Pow(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200717 """Left to the power of right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200718 operator = '**'
719
720
721class And(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200722 """Short circuited AND."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200723 operator = 'and'
724
725 def as_const(self):
726 return self.left.as_const() and self.right.as_const()
727
728
729class Or(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200730 """Short circuited OR."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200731 operator = 'or'
732
733 def as_const(self):
734 return self.left.as_const() or self.right.as_const()
735
736
737class Not(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200738 """Negate the expression."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200739 operator = 'not'
740
741
Armin Ronachere791c2a2008-04-07 18:39:54 +0200742class Neg(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200743 """Make the expression negative."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200744 operator = '-'
745
746
Armin Ronachere791c2a2008-04-07 18:39:54 +0200747class Pos(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200748 """Make the expression positive (noop for most expressions)"""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200749 operator = '+'
Armin Ronacher023b5e92008-05-08 11:03:10 +0200750
751
752# Helpers for extensions
753
754
755class EnvironmentAttribute(Expr):
756 """Loads an attribute from the environment object. This is useful for
757 extensions that want to call a callback stored on the environment.
758 """
759 fields = ('name',)
760
761
762class ExtensionAttribute(Expr):
763 """Returns the attribute of an extension bound to the environment.
764 The identifier is the identifier of the :class:`Extension`.
Armin Ronacherb9e78752008-05-10 23:36:28 +0200765
766 This node is usually constructed by calling the
767 :meth:`~jinja2.ext.Extension.attr` method on an extension.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200768 """
769 fields = ('identifier', 'attr')
770
771
772class ImportedName(Expr):
773 """If created with an import name the import name is returned on node
774 access. For example ``ImportedName('cgi.escape')`` returns the `escape`
775 function from the cgi module on evaluation. Imports are optimized by the
776 compiler so there is no need to assign them to local variables.
777 """
778 fields = ('importname',)
779
780
781class InternalName(Expr):
782 """An internal name in the compiler. You cannot create these nodes
Armin Ronacher762079c2008-05-08 23:57:56 +0200783 yourself but the parser provides a
784 :meth:`~jinja2.parser.Parser.free_identifier` method that creates
Armin Ronacher023b5e92008-05-08 11:03:10 +0200785 a new identifier for you. This identifier is not available from the
786 template and is not threated specially by the compiler.
787 """
788 fields = ('name',)
789
790 def __init__(self):
791 raise TypeError('Can\'t create internal names. Use the '
792 '`free_identifier` method on a parser.')
793
794
795class MarkSafe(Expr):
796 """Mark the wrapped expression as safe (wrap it as `Markup`)."""
797 fields = ('expr',)
798
799 def as_const(self):
800 return Markup(self.expr.as_const())
801
802
Armin Ronachered1e0d42008-05-18 20:25:28 +0200803class Continue(Stmt):
804 """Continue a loop."""
805
806
807class Break(Stmt):
808 """Break a loop."""
809
810
Armin Ronacher023b5e92008-05-08 11:03:10 +0200811# and close down
812_node_setup_finished = True