blob: 969d785910db723e9b127d16903a3ff0c88c7173 [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 Ronacher2feed1d2008-04-26 16:26:52 +0200119 def iter_fields(self, exclude=()):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200120 """This method iterates over all fields that are defined and yields
121 ``(key, value)`` tuples. Optionally a parameter of ignored fields
122 can be provided.
123 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200124 for name in self.fields:
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200125 if name not in exclude:
126 try:
127 yield name, getattr(self, name)
128 except AttributeError:
129 pass
Armin Ronacher07bc6842008-03-31 14:18:49 +0200130
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200131 def iter_child_nodes(self, exclude=()):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200132 """Iterates over all direct child nodes of the node. This iterates
133 over all fields and yields the values of they are nodes. If the value
134 of a field is a list all the nodes in that list are returned.
135 """
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200136 for field, item in self.iter_fields(exclude):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200137 if isinstance(item, list):
138 for n in item:
139 if isinstance(n, Node):
140 yield n
141 elif isinstance(item, Node):
142 yield item
143
Armin Ronachere791c2a2008-04-07 18:39:54 +0200144 def find(self, node_type):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200145 """Find the first node of a given type. If no such node exists the
146 return value is `None`.
147 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200148 for result in self.find_all(node_type):
149 return result
150
151 def find_all(self, node_type):
152 """Find all the nodes of a given type."""
153 for child in self.iter_child_nodes():
154 if isinstance(child, node_type):
155 yield child
156 for result in child.find_all(node_type):
157 yield result
158
Armin Ronacher0ecb8592008-04-09 16:29:47 +0200159 def copy(self):
160 """Return a deep copy of the node."""
161 result = object.__new__(self.__class__)
162 for field, value in self.iter_fields():
163 if isinstance(value, Node):
164 new_value = value.copy()
165 elif isinstance(value, list):
166 new_value = []
Armin Ronacherd436e982008-04-09 16:31:20 +0200167 for item in value:
Armin Ronacher0ecb8592008-04-09 16:29:47 +0200168 if isinstance(item, Node):
169 item = item.copy()
170 else:
171 item = copy(item)
172 new_value.append(item)
173 else:
Armin Ronacherd436e982008-04-09 16:31:20 +0200174 new_value = copy(value)
Armin Ronacher0ecb8592008-04-09 16:29:47 +0200175 setattr(result, field, new_value)
176 for attr in self.attributes:
177 try:
178 setattr(result, attr, getattr(self, attr))
179 except AttributeError:
180 pass
181 return result
182
Armin Ronachere791c2a2008-04-07 18:39:54 +0200183 def set_ctx(self, ctx):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200184 """Reset the context of a node and all child nodes. Per default the
185 parser will all generate nodes that have a 'load' context as it's the
186 most common one. This method is used in the parser to set assignment
187 targets and other nodes to a store context.
Armin Ronachere791c2a2008-04-07 18:39:54 +0200188 """
189 todo = deque([self])
190 while todo:
191 node = todo.popleft()
192 if 'ctx' in node.fields:
193 node.ctx = ctx
194 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200195 return self
Armin Ronachere791c2a2008-04-07 18:39:54 +0200196
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200197 def set_lineno(self, lineno, override=False):
198 """Set the line numbers of the node and children."""
199 todo = deque([self])
200 while todo:
201 node = todo.popleft()
202 if 'lineno' in node.attributes:
203 if node.lineno is None or override:
204 node.lineno = lineno
205 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200206 return self
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200207
Armin Ronacherd55ab532008-04-09 16:13:39 +0200208 def set_environment(self, environment):
209 """Set the environment for all nodes."""
210 todo = deque([self])
211 while todo:
212 node = todo.popleft()
213 node.environment = environment
214 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200215 return self
Armin Ronacherd55ab532008-04-09 16:13:39 +0200216
Armin Ronacher69e12db2008-05-12 09:00:03 +0200217 def freeze(self):
218 """Freeze the complete node tree which makes them hashable.
219 This happens automatically on compilation. Frozen nodes must not be
220 modified any further. Extensions may not freeze nodes that appear
221 in the final node tree (ie: nodes that are returned from the extension
222 parse method).
223 """
224 todo = deque([self])
225 while todo:
226 node = todo.popleft()
227 node.frozen = True
228 todo.extend(node.iter_child_nodes())
229
230 def __eq__(self, other):
Armin Ronacherb3a1fcf2008-05-15 11:04:14 +0200231 return type(self) is type(other) and \
232 tuple(self.iter_fields()) == tuple(other.iter_fields())
Armin Ronacher69e12db2008-05-12 09:00:03 +0200233
234 def __ne__(self, other):
235 return not self.__eq__(other)
236
237 def __hash__(self):
238 if not self.frozen:
239 raise TypeError('unfrozen nodes are unhashable')
Armin Ronacherb3a1fcf2008-05-15 11:04:14 +0200240 return hash(tuple(self.iter_fields()))
Armin Ronacher69e12db2008-05-12 09:00:03 +0200241
Armin Ronacher07bc6842008-03-31 14:18:49 +0200242 def __repr__(self):
243 return '%s(%s)' % (
244 self.__class__.__name__,
245 ', '.join('%s=%r' % (arg, getattr(self, arg, None)) for
Armin Ronachere791c2a2008-04-07 18:39:54 +0200246 arg in self.fields)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200247 )
248
249
250class Stmt(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200251 """Base node for all statements."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200252 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200253
254
255class Helper(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200256 """Nodes that exist in a specific context only."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200257 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200258
259
260class Template(Node):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200261 """Node that represents a template. This must be the outermost node that
262 is passed to the compiler.
263 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200264 fields = ('body',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200265
266
267class Output(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200268 """A node that holds multiple expressions which are then printed out.
269 This is used both for the `print` statement and the regular template data.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200270 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200271 fields = ('nodes',)
272
273 def optimized_nodes(self):
274 """Try to optimize the nodes."""
275 buffer = []
276 for node in self.nodes:
277 try:
278 const = unicode(node.as_const())
279 except:
280 buffer.append(node)
281 else:
282 if buffer and isinstance(buffer[-1], unicode):
283 buffer[-1] += const
284 else:
285 buffer.append(const)
286 return buffer
Armin Ronacher07bc6842008-03-31 14:18:49 +0200287
288
289class Extends(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200290 """Represents an extends statement."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200291 fields = ('template',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200292
293
294class For(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200295 """The for loop. `target` is the target for the iteration (usually a
296 :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list
297 of nodes that are used as loop-body, and `else_` a list of nodes for the
298 `else` block. If no else node exists it has to be an empty list.
299
300 For filtered nodes an expression can be stored as `test`, otherwise `None`.
301 """
Armin Ronacherfdf95302008-05-11 22:20:51 +0200302 fields = ('target', 'iter', 'body', 'else_', 'test', 'recursive')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200303
304
305class If(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200306 """If `test` is true, `body` is rendered, else `else_`."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200307 fields = ('test', 'body', 'else_')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200308
309
310class Macro(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200311 """A macro definition. `name` is the name of the macro, `args` a list of
312 arguments and `defaults` a list of defaults if there are any. `body` is
313 a list of nodes for the macro body.
314 """
Armin Ronacher8efc5222008-04-08 14:47:40 +0200315 fields = ('name', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200316
317
318class CallBlock(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200319 """Like a macro without a name but a call instead. `call` is called with
320 the unnamed macro as `caller` argument this node holds.
321 """
Armin Ronacherc9705c22008-04-27 21:28:03 +0200322 fields = ('call', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200323
324
325class Set(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200326 """Allows defining own variables."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200327 fields = ('name', 'expr')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200328
329
330class FilterBlock(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200331 """Node for filter sections."""
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200332 fields = ('body', 'filter')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200333
334
335class Block(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200336 """A node that represents a block."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200337 fields = ('name', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200338
339
340class Include(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200341 """A node that represents the include tag."""
Armin Ronacherea847c52008-05-02 20:04:32 +0200342 fields = ('template', 'with_context')
Armin Ronacher0611e492008-04-25 23:44:14 +0200343
344
345class Import(Stmt):
346 """A node that represents the import tag."""
Armin Ronacherea847c52008-05-02 20:04:32 +0200347 fields = ('template', 'target', 'with_context')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200348
349
Armin Ronacher0611e492008-04-25 23:44:14 +0200350class FromImport(Stmt):
351 """A node that represents the from import tag. It's important to not
352 pass unsafe names to the name attribute. The compiler translates the
353 attribute lookups directly into getattr calls and does *not* use the
354 subscribe callback of the interface. As exported variables may not
355 start with double underscores (which the parser asserts) this is not a
356 problem for regular Jinja code, but if this node is used in an extension
357 extra care must be taken.
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200358
359 The list of names may contain tuples if aliases are wanted.
Armin Ronacher0611e492008-04-25 23:44:14 +0200360 """
Armin Ronacherea847c52008-05-02 20:04:32 +0200361 fields = ('template', 'names', 'with_context')
Armin Ronacher0611e492008-04-25 23:44:14 +0200362
363
Armin Ronacher07bc6842008-03-31 14:18:49 +0200364class ExprStmt(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200365 """A statement that evaluates an expression and discards the result."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200366 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200367
368
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200369class Assign(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200370 """Assigns an expression to a target."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200371 fields = ('target', 'node')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200372
373
Armin Ronacher07bc6842008-03-31 14:18:49 +0200374class Expr(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200375 """Baseclass for all expressions."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200376 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200377
378 def as_const(self):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200379 """Return the value of the expression as constant or raise
Armin Ronacher023b5e92008-05-08 11:03:10 +0200380 :exc:`Impossible` if this was not possible:
381
382 >>> Add(Const(23), Const(42)).as_const()
383 65
384 >>> Add(Const(23), Name('var', 'load')).as_const()
385 Traceback (most recent call last):
386 ...
387 Impossible
388
389 This requires the `environment` attribute of all nodes to be
390 set to the environment that created the nodes.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200391 """
392 raise Impossible()
393
394 def can_assign(self):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200395 """Check if it's possible to assign something to this node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200396 return False
397
398
399class BinExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200400 """Baseclass for all binary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200401 fields = ('left', 'right')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200402 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200403 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200404
405 def as_const(self):
406 f = _binop_to_func[self.operator]
407 try:
408 return f(self.left.as_const(), self.right.as_const())
409 except:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200410 raise Impossible()
411
412
413class UnaryExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200414 """Baseclass for all unary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200415 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200416 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200417 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200418
419 def as_const(self):
420 f = _uaop_to_func[self.operator]
421 try:
422 return f(self.node.as_const())
423 except:
424 raise Impossible()
425
426
427class Name(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200428 """Looks up a name or stores a value in a name.
429 The `ctx` of the node can be one of the following values:
430
431 - `store`: store a value in the name
432 - `load`: load that name
433 - `param`: like `store` but if the name was defined as function parameter.
434 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200435 fields = ('name', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200436
437 def can_assign(self):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200438 return self.name not in ('true', 'false', 'none')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200439
440
441class Literal(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200442 """Baseclass for literals."""
Armin Ronacher69e12db2008-05-12 09:00:03 +0200443 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200444
445
446class Const(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200447 """All constant values. The parser will return this node for simple
448 constants such as ``42`` or ``"foo"`` but it can be used to store more
449 complex values such as lists too. Only constants with a safe
450 representation (objects where ``eval(repr(x)) == x`` is true).
451 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200452 fields = ('value',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200453
454 def as_const(self):
455 return self.value
456
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200457 @classmethod
Armin Ronacherd55ab532008-04-09 16:13:39 +0200458 def from_untrusted(cls, value, lineno=None, environment=None):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200459 """Return a const object if the value is representable as
460 constant value in the generated code, otherwise it will raise
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200461 an `Impossible` exception.
462 """
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200463 from compiler import has_safe_repr
464 if not has_safe_repr(value):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200465 raise Impossible()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200466 return cls(value, lineno=lineno, environment=environment)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200467
Armin Ronacher07bc6842008-03-31 14:18:49 +0200468
469class Tuple(Literal):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200470 """For loop unpacking and some other things like multiple arguments
Armin Ronacher023b5e92008-05-08 11:03:10 +0200471 for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
472 is used for loading the names or storing.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200473 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200474 fields = ('items', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200475
476 def as_const(self):
477 return tuple(x.as_const() for x in self.items)
478
479 def can_assign(self):
480 for item in self.items:
481 if not item.can_assign():
482 return False
483 return True
484
485
486class List(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200487 """Any list literal such as ``[1, 2, 3]``"""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200488 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200489
490 def as_const(self):
491 return [x.as_const() for x in self.items]
492
493
494class Dict(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200495 """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
496 :class:`Pair` nodes.
497 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200498 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200499
500 def as_const(self):
501 return dict(x.as_const() for x in self.items)
502
503
504class Pair(Helper):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200505 """A key, value pair for dicts."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200506 fields = ('key', 'value')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200507
508 def as_const(self):
509 return self.key.as_const(), self.value.as_const()
510
511
Armin Ronacher8efc5222008-04-08 14:47:40 +0200512class Keyword(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200513 """A key, value pair for keyword arguments where key is a string."""
Armin Ronacher8efc5222008-04-08 14:47:40 +0200514 fields = ('key', 'value')
515
516
Armin Ronacher07bc6842008-03-31 14:18:49 +0200517class CondExpr(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200518 """A conditional expression (inline if expression). (``{{
519 foo if bar else baz }}``)
520 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200521 fields = ('test', 'expr1', 'expr2')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200522
523 def as_const(self):
524 if self.test.as_const():
525 return self.expr1.as_const()
526 return self.expr2.as_const()
527
528
529class Filter(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200530 """This node applies a filter on an expression. `name` is the name of
531 the filter, the rest of the fields are the same as for :class:`Call`.
532 """
Armin Ronacherd55ab532008-04-09 16:13:39 +0200533 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200534
Armin Ronacher00d5d212008-04-13 01:10:18 +0200535 def as_const(self, obj=None):
536 if self.node is obj is None:
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200537 raise Impossible()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200538 filter = self.environment.filters.get(self.name)
539 if filter is None or getattr(filter, 'contextfilter', False):
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200540 raise Impossible()
Armin Ronacher00d5d212008-04-13 01:10:18 +0200541 if obj is None:
542 obj = self.node.as_const()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200543 args = [x.as_const() for x in self.args]
Armin Ronacher9a027f42008-04-17 11:13:40 +0200544 if getattr(filter, 'environmentfilter', False):
545 args.insert(0, self.environment)
Armin Ronacherd55ab532008-04-09 16:13:39 +0200546 kwargs = dict(x.as_const() for x in self.kwargs)
547 if self.dyn_args is not None:
548 try:
549 args.extend(self.dyn_args.as_const())
550 except:
551 raise Impossible()
552 if self.dyn_kwargs is not None:
553 try:
554 kwargs.update(self.dyn_kwargs.as_const())
555 except:
556 raise Impossible()
557 try:
558 return filter(obj, *args, **kwargs)
559 except:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200560 raise Impossible()
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200561
562
Armin Ronacher07bc6842008-03-31 14:18:49 +0200563class Test(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200564 """Applies a test on an expression. `name` is the name of the test, the
565 rest of the fields are the same as for :class:`Call`.
566 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200567 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200568
569
570class Call(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200571 """Calls an expression. `args` is a list of arguments, `kwargs` a list
572 of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
573 and `dyn_kwargs` has to be either `None` or a node that is used as
574 node for dynamic positional (``*args``) or keyword (``**kwargs``)
575 arguments.
576 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200577 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200578
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200579 def as_const(self):
580 obj = self.node.as_const()
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200581
582 # don't evaluate context functions
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200583 args = [x.as_const() for x in self.args]
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200584 if type(obj) is FunctionType:
585 if getattr(obj, 'contextfunction', False):
586 raise Impossible()
587 elif obj.environmentfunction:
588 args.insert(0, self.environment)
589
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200590 kwargs = dict(x.as_const() for x in self.kwargs)
591 if self.dyn_args is not None:
592 try:
593 args.extend(self.dyn_args.as_const())
594 except:
595 raise Impossible()
596 if self.dyn_kwargs is not None:
597 try:
Armin Ronacherd55ab532008-04-09 16:13:39 +0200598 kwargs.update(self.dyn_kwargs.as_const())
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200599 except:
600 raise Impossible()
601 try:
602 return obj(*args, **kwargs)
603 except:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200604 raise Impossible()
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200605
Armin Ronacher07bc6842008-03-31 14:18:49 +0200606
607class Subscript(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200608 """Subscribe an expression by an argument. This node performs a dict
609 and an attribute lookup on the object whatever succeeds.
610 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200611 fields = ('node', 'arg', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200612
613 def as_const(self):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200614 if self.ctx != 'load':
615 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200616 try:
Benjamin Wieganda3152742008-04-28 18:07:52 +0200617 return self.environment.subscribe(self.node.as_const(),
618 self.arg.as_const())
Armin Ronacher07bc6842008-03-31 14:18:49 +0200619 except:
620 raise Impossible()
621
622 def can_assign(self):
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200623 return False
Armin Ronacher07bc6842008-03-31 14:18:49 +0200624
625
626class Slice(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200627 """Represents a slice object. This must only be used as argument for
628 :class:`Subscript`.
629 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200630 fields = ('start', 'stop', 'step')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200631
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200632 def as_const(self):
633 def const(obj):
634 if obj is None:
635 return obj
636 return obj.as_const()
637 return slice(const(self.start), const(self.stop), const(self.step))
638
Armin Ronacher07bc6842008-03-31 14:18:49 +0200639
640class Concat(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200641 """Concatenates the list of expressions provided after converting them to
642 unicode.
643 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200644 fields = ('nodes',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200645
646 def as_const(self):
647 return ''.join(unicode(x.as_const()) for x in self.nodes)
648
649
650class Compare(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200651 """Compares an expression with some other expressions. `ops` must be a
652 list of :class:`Operand`\s.
653 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200654 fields = ('expr', 'ops')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200655
Armin Ronacher625215e2008-04-13 16:31:08 +0200656 def as_const(self):
657 result = value = self.expr.as_const()
Armin Ronacherb5124e62008-04-25 00:36:14 +0200658 try:
659 for op in self.ops:
660 new_value = op.expr.as_const()
661 result = _cmpop_to_func[op.op](value, new_value)
662 value = new_value
663 except:
664 raise Impossible()
Armin Ronacher625215e2008-04-13 16:31:08 +0200665 return result
666
Armin Ronacher07bc6842008-03-31 14:18:49 +0200667
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200668class Operand(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200669 """Holds an operator and an expression."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200670 fields = ('op', 'expr')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200671
Armin Ronacher023b5e92008-05-08 11:03:10 +0200672if __debug__:
673 Operand.__doc__ += '\nThe following operators are available: ' + \
674 ', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
675 set(_uaop_to_func) | set(_cmpop_to_func)))
676
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200677
Armin Ronacher07bc6842008-03-31 14:18:49 +0200678class Mul(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200679 """Multiplies the left with the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200680 operator = '*'
681
682
683class Div(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200684 """Divides the left by the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200685 operator = '/'
686
687
688class FloorDiv(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200689 """Divides the left by the right node and truncates conver the
690 result into an integer by truncating.
691 """
Armin Ronacher07bc6842008-03-31 14:18:49 +0200692 operator = '//'
693
694
695class Add(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200696 """Add the left to the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200697 operator = '+'
698
699
700class Sub(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200701 """Substract the right from the left node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200702 operator = '-'
703
704
705class Mod(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200706 """Left modulo right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200707 operator = '%'
708
709
710class Pow(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200711 """Left to the power of right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200712 operator = '**'
713
714
715class And(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200716 """Short circuited AND."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200717 operator = 'and'
718
719 def as_const(self):
720 return self.left.as_const() and self.right.as_const()
721
722
723class Or(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200724 """Short circuited OR."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200725 operator = 'or'
726
727 def as_const(self):
728 return self.left.as_const() or self.right.as_const()
729
730
731class Not(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200732 """Negate the expression."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200733 operator = 'not'
734
735
Armin Ronachere791c2a2008-04-07 18:39:54 +0200736class Neg(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200737 """Make the expression negative."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200738 operator = '-'
739
740
Armin Ronachere791c2a2008-04-07 18:39:54 +0200741class Pos(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200742 """Make the expression positive (noop for most expressions)"""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200743 operator = '+'
Armin Ronacher023b5e92008-05-08 11:03:10 +0200744
745
746# Helpers for extensions
747
748
749class EnvironmentAttribute(Expr):
750 """Loads an attribute from the environment object. This is useful for
751 extensions that want to call a callback stored on the environment.
752 """
753 fields = ('name',)
754
755
756class ExtensionAttribute(Expr):
757 """Returns the attribute of an extension bound to the environment.
758 The identifier is the identifier of the :class:`Extension`.
Armin Ronacherb9e78752008-05-10 23:36:28 +0200759
760 This node is usually constructed by calling the
761 :meth:`~jinja2.ext.Extension.attr` method on an extension.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200762 """
763 fields = ('identifier', 'attr')
764
765
766class ImportedName(Expr):
767 """If created with an import name the import name is returned on node
768 access. For example ``ImportedName('cgi.escape')`` returns the `escape`
769 function from the cgi module on evaluation. Imports are optimized by the
770 compiler so there is no need to assign them to local variables.
771 """
772 fields = ('importname',)
773
774
775class InternalName(Expr):
776 """An internal name in the compiler. You cannot create these nodes
Armin Ronacher762079c2008-05-08 23:57:56 +0200777 yourself but the parser provides a
778 :meth:`~jinja2.parser.Parser.free_identifier` method that creates
Armin Ronacher023b5e92008-05-08 11:03:10 +0200779 a new identifier for you. This identifier is not available from the
780 template and is not threated specially by the compiler.
781 """
782 fields = ('name',)
783
784 def __init__(self):
785 raise TypeError('Can\'t create internal names. Use the '
786 '`free_identifier` method on a parser.')
787
788
789class MarkSafe(Expr):
790 """Mark the wrapped expression as safe (wrap it as `Markup`)."""
791 fields = ('expr',)
792
793 def as_const(self):
794 return Markup(self.expr.as_const())
795
796
Armin Ronachered1e0d42008-05-18 20:25:28 +0200797class Continue(Stmt):
798 """Continue a loop."""
799
800
801class Break(Stmt):
802 """Break a loop."""
803
804
Armin Ronacher8a1d27f2008-05-19 08:37:19 +0200805# make sure nobody creates custom nodes
806def _failing_new(*args, **kwargs):
807 raise TypeError('can\'t create custom node types')
808NodeType.__new__ = staticmethod(_failing_new); del _failing_new