blob: 27c9ddbcd2e6a6862bc9fe3812b58a75d1be18a6 [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
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 Ronacher105f0dc2008-05-23 16:12:47 +0200125 if (exclude is only is None) or \
126 (exclude is not None and name not in exclude) or \
127 (only is not None and name in only):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200128 try:
129 yield name, getattr(self, name)
130 except AttributeError:
131 pass
Armin Ronacher07bc6842008-03-31 14:18:49 +0200132
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200133 def iter_child_nodes(self, exclude=None, only=None):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200134 """Iterates over all direct child nodes of the node. This iterates
135 over all fields and yields the values of they are nodes. If the value
136 of a field is a list all the nodes in that list are returned.
137 """
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200138 for field, item in self.iter_fields(exclude, only):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200139 if isinstance(item, list):
140 for n in item:
141 if isinstance(n, Node):
142 yield n
143 elif isinstance(item, Node):
144 yield item
145
Armin Ronachere791c2a2008-04-07 18:39:54 +0200146 def find(self, node_type):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200147 """Find the first node of a given type. If no such node exists the
148 return value is `None`.
149 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200150 for result in self.find_all(node_type):
151 return result
152
153 def find_all(self, node_type):
154 """Find all the nodes of a given type."""
155 for child in self.iter_child_nodes():
156 if isinstance(child, node_type):
157 yield child
158 for result in child.find_all(node_type):
159 yield result
160
Armin Ronacher0ecb8592008-04-09 16:29:47 +0200161 def copy(self):
162 """Return a deep copy of the node."""
163 result = object.__new__(self.__class__)
164 for field, value in self.iter_fields():
165 if isinstance(value, Node):
166 new_value = value.copy()
167 elif isinstance(value, list):
168 new_value = []
Armin Ronacherd436e982008-04-09 16:31:20 +0200169 for item in value:
Armin Ronacher0ecb8592008-04-09 16:29:47 +0200170 if isinstance(item, Node):
171 item = item.copy()
172 else:
173 item = copy(item)
174 new_value.append(item)
175 else:
Armin Ronacherd436e982008-04-09 16:31:20 +0200176 new_value = copy(value)
Armin Ronacher0ecb8592008-04-09 16:29:47 +0200177 setattr(result, field, new_value)
178 for attr in self.attributes:
179 try:
180 setattr(result, attr, getattr(self, attr))
181 except AttributeError:
182 pass
183 return result
184
Armin Ronachere791c2a2008-04-07 18:39:54 +0200185 def set_ctx(self, ctx):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200186 """Reset the context of a node and all child nodes. Per default the
187 parser will all generate nodes that have a 'load' context as it's the
188 most common one. This method is used in the parser to set assignment
189 targets and other nodes to a store context.
Armin Ronachere791c2a2008-04-07 18:39:54 +0200190 """
191 todo = deque([self])
192 while todo:
193 node = todo.popleft()
194 if 'ctx' in node.fields:
195 node.ctx = ctx
196 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200197 return self
Armin Ronachere791c2a2008-04-07 18:39:54 +0200198
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200199 def set_lineno(self, lineno, override=False):
200 """Set the line numbers of the node and children."""
201 todo = deque([self])
202 while todo:
203 node = todo.popleft()
204 if 'lineno' in node.attributes:
205 if node.lineno is None or override:
206 node.lineno = lineno
207 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200208 return self
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200209
Armin Ronacherd55ab532008-04-09 16:13:39 +0200210 def set_environment(self, environment):
211 """Set the environment for all nodes."""
212 todo = deque([self])
213 while todo:
214 node = todo.popleft()
215 node.environment = environment
216 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200217 return self
Armin Ronacherd55ab532008-04-09 16:13:39 +0200218
Armin Ronacher69e12db2008-05-12 09:00:03 +0200219 def freeze(self):
220 """Freeze the complete node tree which makes them hashable.
221 This happens automatically on compilation. Frozen nodes must not be
222 modified any further. Extensions may not freeze nodes that appear
223 in the final node tree (ie: nodes that are returned from the extension
224 parse method).
225 """
226 todo = deque([self])
227 while todo:
228 node = todo.popleft()
229 node.frozen = True
230 todo.extend(node.iter_child_nodes())
231
232 def __eq__(self, other):
Armin Ronacherb3a1fcf2008-05-15 11:04:14 +0200233 return type(self) is type(other) and \
234 tuple(self.iter_fields()) == tuple(other.iter_fields())
Armin Ronacher69e12db2008-05-12 09:00:03 +0200235
236 def __ne__(self, other):
237 return not self.__eq__(other)
238
239 def __hash__(self):
240 if not self.frozen:
241 raise TypeError('unfrozen nodes are unhashable')
Armin Ronacherb3a1fcf2008-05-15 11:04:14 +0200242 return hash(tuple(self.iter_fields()))
Armin Ronacher69e12db2008-05-12 09:00:03 +0200243
Armin Ronacher07bc6842008-03-31 14:18:49 +0200244 def __repr__(self):
245 return '%s(%s)' % (
246 self.__class__.__name__,
247 ', '.join('%s=%r' % (arg, getattr(self, arg, None)) for
Armin Ronachere791c2a2008-04-07 18:39:54 +0200248 arg in self.fields)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200249 )
250
251
252class Stmt(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200253 """Base node for all statements."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200254 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200255
256
257class Helper(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200258 """Nodes that exist in a specific context only."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200259 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200260
261
262class Template(Node):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200263 """Node that represents a template. This must be the outermost node that
264 is passed to the compiler.
265 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200266 fields = ('body',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200267
268
269class Output(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200270 """A node that holds multiple expressions which are then printed out.
271 This is used both for the `print` statement and the regular template data.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200272 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200273 fields = ('nodes',)
274
275 def optimized_nodes(self):
276 """Try to optimize the nodes."""
277 buffer = []
278 for node in self.nodes:
279 try:
280 const = unicode(node.as_const())
281 except:
282 buffer.append(node)
283 else:
284 if buffer and isinstance(buffer[-1], unicode):
285 buffer[-1] += const
286 else:
287 buffer.append(const)
288 return buffer
Armin Ronacher07bc6842008-03-31 14:18:49 +0200289
290
291class Extends(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200292 """Represents an extends statement."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200293 fields = ('template',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200294
295
296class For(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200297 """The for loop. `target` is the target for the iteration (usually a
298 :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list
299 of nodes that are used as loop-body, and `else_` a list of nodes for the
300 `else` block. If no else node exists it has to be an empty list.
301
302 For filtered nodes an expression can be stored as `test`, otherwise `None`.
303 """
Armin Ronacherfdf95302008-05-11 22:20:51 +0200304 fields = ('target', 'iter', 'body', 'else_', 'test', 'recursive')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200305
306
307class If(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200308 """If `test` is true, `body` is rendered, else `else_`."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200309 fields = ('test', 'body', 'else_')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200310
311
312class Macro(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200313 """A macro definition. `name` is the name of the macro, `args` a list of
314 arguments and `defaults` a list of defaults if there are any. `body` is
315 a list of nodes for the macro body.
316 """
Armin Ronacher8efc5222008-04-08 14:47:40 +0200317 fields = ('name', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200318
319
320class CallBlock(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200321 """Like a macro without a name but a call instead. `call` is called with
322 the unnamed macro as `caller` argument this node holds.
323 """
Armin Ronacherc9705c22008-04-27 21:28:03 +0200324 fields = ('call', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200325
326
327class Set(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200328 """Allows defining own variables."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200329 fields = ('name', 'expr')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200330
331
332class FilterBlock(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200333 """Node for filter sections."""
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200334 fields = ('body', 'filter')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200335
336
337class Block(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200338 """A node that represents a block."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200339 fields = ('name', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200340
341
342class Include(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200343 """A node that represents the include tag."""
Armin Ronacherea847c52008-05-02 20:04:32 +0200344 fields = ('template', 'with_context')
Armin Ronacher0611e492008-04-25 23:44:14 +0200345
346
347class Import(Stmt):
348 """A node that represents the import tag."""
Armin Ronacherea847c52008-05-02 20:04:32 +0200349 fields = ('template', 'target', 'with_context')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200350
351
Armin Ronacher0611e492008-04-25 23:44:14 +0200352class FromImport(Stmt):
353 """A node that represents the from import tag. It's important to not
354 pass unsafe names to the name attribute. The compiler translates the
355 attribute lookups directly into getattr calls and does *not* use the
356 subscribe callback of the interface. As exported variables may not
357 start with double underscores (which the parser asserts) this is not a
358 problem for regular Jinja code, but if this node is used in an extension
359 extra care must be taken.
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200360
361 The list of names may contain tuples if aliases are wanted.
Armin Ronacher0611e492008-04-25 23:44:14 +0200362 """
Armin Ronacherea847c52008-05-02 20:04:32 +0200363 fields = ('template', 'names', 'with_context')
Armin Ronacher0611e492008-04-25 23:44:14 +0200364
365
Armin Ronacher07bc6842008-03-31 14:18:49 +0200366class ExprStmt(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200367 """A statement that evaluates an expression and discards the result."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200368 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200369
370
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200371class Assign(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200372 """Assigns an expression to a target."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200373 fields = ('target', 'node')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200374
375
Armin Ronacher07bc6842008-03-31 14:18:49 +0200376class Expr(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200377 """Baseclass for all expressions."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200378 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200379
380 def as_const(self):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200381 """Return the value of the expression as constant or raise
Armin Ronacher023b5e92008-05-08 11:03:10 +0200382 :exc:`Impossible` if this was not possible:
383
384 >>> Add(Const(23), Const(42)).as_const()
385 65
386 >>> Add(Const(23), Name('var', 'load')).as_const()
387 Traceback (most recent call last):
388 ...
389 Impossible
390
391 This requires the `environment` attribute of all nodes to be
392 set to the environment that created the nodes.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200393 """
394 raise Impossible()
395
396 def can_assign(self):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200397 """Check if it's possible to assign something to this node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200398 return False
399
400
401class BinExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200402 """Baseclass for all binary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200403 fields = ('left', 'right')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200404 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200405 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200406
407 def as_const(self):
408 f = _binop_to_func[self.operator]
409 try:
410 return f(self.left.as_const(), self.right.as_const())
411 except:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200412 raise Impossible()
413
414
415class UnaryExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200416 """Baseclass for all unary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200417 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200418 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200419 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200420
421 def as_const(self):
422 f = _uaop_to_func[self.operator]
423 try:
424 return f(self.node.as_const())
425 except:
426 raise Impossible()
427
428
429class Name(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200430 """Looks up a name or stores a value in a name.
431 The `ctx` of the node can be one of the following values:
432
433 - `store`: store a value in the name
434 - `load`: load that name
435 - `param`: like `store` but if the name was defined as function parameter.
436 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200437 fields = ('name', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200438
439 def can_assign(self):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200440 return self.name not in ('true', 'false', 'none')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200441
442
443class Literal(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200444 """Baseclass for literals."""
Armin Ronacher69e12db2008-05-12 09:00:03 +0200445 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200446
447
448class Const(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200449 """All constant values. The parser will return this node for simple
450 constants such as ``42`` or ``"foo"`` but it can be used to store more
451 complex values such as lists too. Only constants with a safe
452 representation (objects where ``eval(repr(x)) == x`` is true).
453 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200454 fields = ('value',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200455
456 def as_const(self):
457 return self.value
458
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200459 @classmethod
Armin Ronacherd55ab532008-04-09 16:13:39 +0200460 def from_untrusted(cls, value, lineno=None, environment=None):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200461 """Return a const object if the value is representable as
462 constant value in the generated code, otherwise it will raise
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200463 an `Impossible` exception.
464 """
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200465 from compiler import has_safe_repr
466 if not has_safe_repr(value):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200467 raise Impossible()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200468 return cls(value, lineno=lineno, environment=environment)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200469
Armin Ronacher07bc6842008-03-31 14:18:49 +0200470
471class Tuple(Literal):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200472 """For loop unpacking and some other things like multiple arguments
Armin Ronacher023b5e92008-05-08 11:03:10 +0200473 for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
474 is used for loading the names or storing.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200475 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200476 fields = ('items', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200477
478 def as_const(self):
479 return tuple(x.as_const() for x in self.items)
480
481 def can_assign(self):
482 for item in self.items:
483 if not item.can_assign():
484 return False
485 return True
486
487
488class List(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200489 """Any list literal such as ``[1, 2, 3]``"""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200490 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200491
492 def as_const(self):
493 return [x.as_const() for x in self.items]
494
495
496class Dict(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200497 """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
498 :class:`Pair` nodes.
499 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200500 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200501
502 def as_const(self):
503 return dict(x.as_const() for x in self.items)
504
505
506class Pair(Helper):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200507 """A key, value pair for dicts."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200508 fields = ('key', 'value')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200509
510 def as_const(self):
511 return self.key.as_const(), self.value.as_const()
512
513
Armin Ronacher8efc5222008-04-08 14:47:40 +0200514class Keyword(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200515 """A key, value pair for keyword arguments where key is a string."""
Armin Ronacher8efc5222008-04-08 14:47:40 +0200516 fields = ('key', 'value')
517
518
Armin Ronacher07bc6842008-03-31 14:18:49 +0200519class CondExpr(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200520 """A conditional expression (inline if expression). (``{{
521 foo if bar else baz }}``)
522 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200523 fields = ('test', 'expr1', 'expr2')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200524
525 def as_const(self):
526 if self.test.as_const():
527 return self.expr1.as_const()
528 return self.expr2.as_const()
529
530
531class Filter(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200532 """This node applies a filter on an expression. `name` is the name of
533 the filter, the rest of the fields are the same as for :class:`Call`.
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200534
535 If the `node` of a filter is `None` the contents of the last buffer are
536 filtered. Buffers are created by macros and filter blocks.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200537 """
Armin Ronacherd55ab532008-04-09 16:13:39 +0200538 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200539
Armin Ronacher00d5d212008-04-13 01:10:18 +0200540 def as_const(self, obj=None):
541 if self.node is obj is None:
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200542 raise Impossible()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200543 filter = self.environment.filters.get(self.name)
544 if filter is None or getattr(filter, 'contextfilter', False):
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200545 raise Impossible()
Armin Ronacher00d5d212008-04-13 01:10:18 +0200546 if obj is None:
547 obj = self.node.as_const()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200548 args = [x.as_const() for x in self.args]
Armin Ronacher9a027f42008-04-17 11:13:40 +0200549 if getattr(filter, 'environmentfilter', False):
550 args.insert(0, self.environment)
Armin Ronacherd55ab532008-04-09 16:13:39 +0200551 kwargs = dict(x.as_const() for x in self.kwargs)
552 if self.dyn_args is not None:
553 try:
554 args.extend(self.dyn_args.as_const())
555 except:
556 raise Impossible()
557 if self.dyn_kwargs is not None:
558 try:
559 kwargs.update(self.dyn_kwargs.as_const())
560 except:
561 raise Impossible()
562 try:
563 return filter(obj, *args, **kwargs)
564 except:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200565 raise Impossible()
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200566
567
Armin Ronacher07bc6842008-03-31 14:18:49 +0200568class Test(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200569 """Applies a test on an expression. `name` is the name of the test, the
570 rest of the fields are the same as for :class:`Call`.
571 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200572 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200573
574
575class Call(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200576 """Calls an expression. `args` is a list of arguments, `kwargs` a list
577 of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
578 and `dyn_kwargs` has to be either `None` or a node that is used as
579 node for dynamic positional (``*args``) or keyword (``**kwargs``)
580 arguments.
581 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200582 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200583
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200584 def as_const(self):
585 obj = self.node.as_const()
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200586
587 # don't evaluate context functions
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200588 args = [x.as_const() for x in self.args]
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200589 if type(obj) is FunctionType:
590 if getattr(obj, 'contextfunction', False):
591 raise Impossible()
592 elif obj.environmentfunction:
593 args.insert(0, self.environment)
594
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200595 kwargs = dict(x.as_const() for x in self.kwargs)
596 if self.dyn_args is not None:
597 try:
598 args.extend(self.dyn_args.as_const())
599 except:
600 raise Impossible()
601 if self.dyn_kwargs is not None:
602 try:
Armin Ronacherd55ab532008-04-09 16:13:39 +0200603 kwargs.update(self.dyn_kwargs.as_const())
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200604 except:
605 raise Impossible()
606 try:
607 return obj(*args, **kwargs)
608 except:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200609 raise Impossible()
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200610
Armin Ronacher07bc6842008-03-31 14:18:49 +0200611
612class Subscript(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200613 """Subscribe an expression by an argument. This node performs a dict
614 and an attribute lookup on the object whatever succeeds.
615 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200616 fields = ('node', 'arg', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200617
618 def as_const(self):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200619 if self.ctx != 'load':
620 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200621 try:
Benjamin Wieganda3152742008-04-28 18:07:52 +0200622 return self.environment.subscribe(self.node.as_const(),
623 self.arg.as_const())
Armin Ronacher07bc6842008-03-31 14:18:49 +0200624 except:
625 raise Impossible()
626
627 def can_assign(self):
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200628 return False
Armin Ronacher07bc6842008-03-31 14:18:49 +0200629
630
631class Slice(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200632 """Represents a slice object. This must only be used as argument for
633 :class:`Subscript`.
634 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200635 fields = ('start', 'stop', 'step')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200636
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200637 def as_const(self):
638 def const(obj):
639 if obj is None:
640 return obj
641 return obj.as_const()
642 return slice(const(self.start), const(self.stop), const(self.step))
643
Armin Ronacher07bc6842008-03-31 14:18:49 +0200644
645class Concat(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200646 """Concatenates the list of expressions provided after converting them to
647 unicode.
648 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200649 fields = ('nodes',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200650
651 def as_const(self):
652 return ''.join(unicode(x.as_const()) for x in self.nodes)
653
654
655class Compare(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200656 """Compares an expression with some other expressions. `ops` must be a
657 list of :class:`Operand`\s.
658 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200659 fields = ('expr', 'ops')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200660
Armin Ronacher625215e2008-04-13 16:31:08 +0200661 def as_const(self):
662 result = value = self.expr.as_const()
Armin Ronacherb5124e62008-04-25 00:36:14 +0200663 try:
664 for op in self.ops:
665 new_value = op.expr.as_const()
666 result = _cmpop_to_func[op.op](value, new_value)
667 value = new_value
668 except:
669 raise Impossible()
Armin Ronacher625215e2008-04-13 16:31:08 +0200670 return result
671
Armin Ronacher07bc6842008-03-31 14:18:49 +0200672
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200673class Operand(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200674 """Holds an operator and an expression."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200675 fields = ('op', 'expr')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200676
Armin Ronacher023b5e92008-05-08 11:03:10 +0200677if __debug__:
678 Operand.__doc__ += '\nThe following operators are available: ' + \
679 ', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
680 set(_uaop_to_func) | set(_cmpop_to_func)))
681
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200682
Armin Ronacher07bc6842008-03-31 14:18:49 +0200683class Mul(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200684 """Multiplies the left with the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200685 operator = '*'
686
687
688class Div(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200689 """Divides the left by the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200690 operator = '/'
691
692
693class FloorDiv(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200694 """Divides the left by the right node and truncates conver the
695 result into an integer by truncating.
696 """
Armin Ronacher07bc6842008-03-31 14:18:49 +0200697 operator = '//'
698
699
700class Add(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200701 """Add the left to the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200702 operator = '+'
703
704
705class Sub(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200706 """Substract the right from the left node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200707 operator = '-'
708
709
710class Mod(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200711 """Left modulo right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200712 operator = '%'
713
714
715class Pow(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200716 """Left to the power of right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200717 operator = '**'
718
719
720class And(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200721 """Short circuited AND."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200722 operator = 'and'
723
724 def as_const(self):
725 return self.left.as_const() and self.right.as_const()
726
727
728class Or(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200729 """Short circuited OR."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200730 operator = 'or'
731
732 def as_const(self):
733 return self.left.as_const() or self.right.as_const()
734
735
736class Not(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200737 """Negate the expression."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200738 operator = 'not'
739
740
Armin Ronachere791c2a2008-04-07 18:39:54 +0200741class Neg(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200742 """Make the expression negative."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200743 operator = '-'
744
745
Armin Ronachere791c2a2008-04-07 18:39:54 +0200746class Pos(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200747 """Make the expression positive (noop for most expressions)"""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200748 operator = '+'
Armin Ronacher023b5e92008-05-08 11:03:10 +0200749
750
751# Helpers for extensions
752
753
754class EnvironmentAttribute(Expr):
755 """Loads an attribute from the environment object. This is useful for
756 extensions that want to call a callback stored on the environment.
757 """
758 fields = ('name',)
759
760
761class ExtensionAttribute(Expr):
762 """Returns the attribute of an extension bound to the environment.
763 The identifier is the identifier of the :class:`Extension`.
Armin Ronacherb9e78752008-05-10 23:36:28 +0200764
765 This node is usually constructed by calling the
766 :meth:`~jinja2.ext.Extension.attr` method on an extension.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200767 """
768 fields = ('identifier', 'attr')
769
770
771class ImportedName(Expr):
772 """If created with an import name the import name is returned on node
773 access. For example ``ImportedName('cgi.escape')`` returns the `escape`
774 function from the cgi module on evaluation. Imports are optimized by the
775 compiler so there is no need to assign them to local variables.
776 """
777 fields = ('importname',)
778
779
780class InternalName(Expr):
781 """An internal name in the compiler. You cannot create these nodes
Armin Ronacher762079c2008-05-08 23:57:56 +0200782 yourself but the parser provides a
783 :meth:`~jinja2.parser.Parser.free_identifier` method that creates
Armin Ronacher023b5e92008-05-08 11:03:10 +0200784 a new identifier for you. This identifier is not available from the
785 template and is not threated specially by the compiler.
786 """
787 fields = ('name',)
788
789 def __init__(self):
790 raise TypeError('Can\'t create internal names. Use the '
791 '`free_identifier` method on a parser.')
792
793
794class MarkSafe(Expr):
795 """Mark the wrapped expression as safe (wrap it as `Markup`)."""
796 fields = ('expr',)
797
798 def as_const(self):
799 return Markup(self.expr.as_const())
800
801
Armin Ronachered1e0d42008-05-18 20:25:28 +0200802class Continue(Stmt):
803 """Continue a loop."""
804
805
806class Break(Stmt):
807 """Break a loop."""
808
809
Armin Ronacher8a1d27f2008-05-19 08:37:19 +0200810# make sure nobody creates custom nodes
811def _failing_new(*args, **kwargs):
812 raise TypeError('can\'t create custom node types')
813NodeType.__new__ = staticmethod(_failing_new); del _failing_new