blob: d867aca9a67713fca5958c5fff1d80482452016c [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 Ronacher55494e42010-01-22 09:41:48 +010012 :copyright: (c) 2010 by the Jinja Team.
Armin Ronacher07bc6842008-03-31 14:18:49 +020013 :license: BSD, see LICENSE for more details.
14"""
Armin Ronacher1c5315a2013-05-20 17:03:46 +010015import types
Armin Ronacher07bc6842008-03-31 14:18:49 +020016import operator
Armin Ronacherc87d4cf2013-05-19 13:46:22 +010017
Armin Ronacher82b3f3d2008-03-31 20:01:08 +020018from collections import deque
Armin Ronachere9098672013-05-19 14:16:13 +010019from jinja2.utils import Markup
Armin Ronacher1c5315a2013-05-20 17:03:46 +010020from jinja2._compat import izip, with_metaclass, text_type
Armin Ronacher5a5ce732010-05-23 22:58:28 +020021
22
23#: the types we support for context functions
Armin Ronacher1c5315a2013-05-20 17:03:46 +010024_context_function_types = (types.FunctionType, types.MethodType)
Armin Ronacher07bc6842008-03-31 14:18:49 +020025
26
27_binop_to_func = {
28 '*': operator.mul,
29 '/': operator.truediv,
30 '//': operator.floordiv,
31 '**': operator.pow,
32 '%': operator.mod,
33 '+': operator.add,
34 '-': operator.sub
35}
36
37_uaop_to_func = {
38 'not': operator.not_,
39 '+': operator.pos,
40 '-': operator.neg
41}
42
Armin Ronacher625215e2008-04-13 16:31:08 +020043_cmpop_to_func = {
44 'eq': operator.eq,
45 'ne': operator.ne,
46 'gt': operator.gt,
47 'gteq': operator.ge,
48 'lt': operator.lt,
49 'lteq': operator.le,
Armin Ronacherb5124e62008-04-25 00:36:14 +020050 'in': lambda a, b: a in b,
51 'notin': lambda a, b: a not in b
Armin Ronacher625215e2008-04-13 16:31:08 +020052}
53
Armin Ronacher07bc6842008-03-31 14:18:49 +020054
55class 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 Ronachere791c2a2008-04-07 18:39:54 +020065 for attr in 'fields', 'attributes':
Armin Ronacher07bc6842008-03-31 14:18:49 +020066 storage = []
Armin Ronacher7324eb82008-04-21 07:55:52 +020067 storage.extend(getattr(bases[0], attr, ()))
Armin Ronacher07bc6842008-03-31 14:18:49 +020068 storage.extend(d.get(attr, ()))
Armin Ronacher7324eb82008-04-21 07:55:52 +020069 assert len(bases) == 1, 'multiple inheritance not allowed'
70 assert len(storage) == len(set(storage)), 'layout conflict'
Armin Ronacher07bc6842008-03-31 14:18:49 +020071 d[attr] = tuple(storage)
Armin Ronacher023b5e92008-05-08 11:03:10 +020072 d.setdefault('abstract', False)
Armin Ronacher7324eb82008-04-21 07:55:52 +020073 return type.__new__(cls, name, bases, d)
Armin Ronacher07bc6842008-03-31 14:18:49 +020074
75
Armin Ronacher8346bd72010-03-14 19:43:47 +010076class EvalContext(object):
Armin Ronacher30fda272010-03-15 03:06:04 +010077 """Holds evaluation time information. Custom attributes can be attached
78 to it in extensions.
79 """
Armin Ronacher8346bd72010-03-14 19:43:47 +010080
Armin Ronacher1da23d12010-04-05 18:11:18 +020081 def __init__(self, environment, template_name=None):
Armin Ronacher3383e1c2011-01-24 01:13:51 +010082 self.environment = environment
Armin Ronacher1da23d12010-04-05 18:11:18 +020083 if callable(environment.autoescape):
84 self.autoescape = environment.autoescape(template_name)
85 else:
86 self.autoescape = environment.autoescape
Armin Ronacher8346bd72010-03-14 19:43:47 +010087 self.volatile = False
88
89 def save(self):
90 return self.__dict__.copy()
91
92 def revert(self, old):
93 self.__dict__.clear()
94 self.__dict__.update(old)
95
96
97def get_eval_context(node, ctx):
98 if ctx is None:
99 if node.environment is None:
100 raise RuntimeError('if no eval context is passed, the '
101 'node must have an attached '
102 'environment.')
103 return EvalContext(node.environment)
104 return ctx
105
106
Armin Ronachere9098672013-05-19 14:16:13 +0100107class Node(with_metaclass(NodeType, object)):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200108 """Baseclass for all Jinja2 nodes. There are a number of nodes available
kracekumar9c198cd2011-11-25 08:26:55 +0530109 of different types. There are four major types:
Armin Ronacher023b5e92008-05-08 11:03:10 +0200110
111 - :class:`Stmt`: statements
112 - :class:`Expr`: expressions
113 - :class:`Helper`: helper nodes
114 - :class:`Template`: the outermost wrapper node
115
116 All nodes have fields and attributes. Fields may be other nodes, lists,
117 or arbitrary values. Fields are passed to the constructor as regular
118 positional arguments, attributes as keyword arguments. Each node has
119 two attributes: `lineno` (the line number of the node) and `environment`.
120 The `environment` attribute is set at the end of the parsing process for
121 all nodes automatically.
122 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200123 fields = ()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200124 attributes = ('lineno', 'environment')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200125 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200126
Armin Ronacher023b5e92008-05-08 11:03:10 +0200127 def __init__(self, *fields, **attributes):
Armin Ronacher69e12db2008-05-12 09:00:03 +0200128 if self.abstract:
129 raise TypeError('abstract nodes are not instanciable')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200130 if fields:
131 if len(fields) != len(self.fields):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200132 if not self.fields:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200133 raise TypeError('%r takes 0 arguments' %
134 self.__class__.__name__)
135 raise TypeError('%r takes 0 or %d argument%s' % (
136 self.__class__.__name__,
Armin Ronachere791c2a2008-04-07 18:39:54 +0200137 len(self.fields),
138 len(self.fields) != 1 and 's' or ''
Armin Ronacher07bc6842008-03-31 14:18:49 +0200139 ))
Armin Ronachere9098672013-05-19 14:16:13 +0100140 for name, arg in izip(self.fields, fields):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200141 setattr(self, name, arg)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200142 for attr in self.attributes:
Armin Ronacher023b5e92008-05-08 11:03:10 +0200143 setattr(self, attr, attributes.pop(attr, None))
144 if attributes:
145 raise TypeError('unknown attribute %r' %
Armin Ronacherc87d4cf2013-05-19 13:46:22 +0100146 next(iter(attributes)))
Armin Ronacher07bc6842008-03-31 14:18:49 +0200147
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200148 def iter_fields(self, exclude=None, only=None):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200149 """This method iterates over all fields that are defined and yields
Armin Ronacher3da90312008-05-23 16:37:28 +0200150 ``(key, value)`` tuples. Per default all fields are returned, but
151 it's possible to limit that to some fields by providing the `only`
152 parameter or to exclude some using the `exclude` parameter. Both
153 should be sets or tuples of field names.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200154 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200155 for name in self.fields:
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200156 if (exclude is only is None) or \
157 (exclude is not None and name not in exclude) or \
158 (only is not None and name in only):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200159 try:
160 yield name, getattr(self, name)
161 except AttributeError:
162 pass
Armin Ronacher07bc6842008-03-31 14:18:49 +0200163
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200164 def iter_child_nodes(self, exclude=None, only=None):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200165 """Iterates over all direct child nodes of the node. This iterates
166 over all fields and yields the values of they are nodes. If the value
167 of a field is a list all the nodes in that list are returned.
168 """
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200169 for field, item in self.iter_fields(exclude, only):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200170 if isinstance(item, list):
171 for n in item:
172 if isinstance(n, Node):
173 yield n
174 elif isinstance(item, Node):
175 yield item
176
Armin Ronachere791c2a2008-04-07 18:39:54 +0200177 def find(self, node_type):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200178 """Find the first node of a given type. If no such node exists the
179 return value is `None`.
180 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200181 for result in self.find_all(node_type):
182 return result
183
184 def find_all(self, node_type):
Armin Ronacher63cf9b82009-07-26 10:33:36 +0200185 """Find all the nodes of a given type. If the type is a tuple,
186 the check is performed for any of the tuple items.
187 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200188 for child in self.iter_child_nodes():
189 if isinstance(child, node_type):
190 yield child
191 for result in child.find_all(node_type):
192 yield result
193
194 def set_ctx(self, ctx):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200195 """Reset the context of a node and all child nodes. Per default the
196 parser will all generate nodes that have a 'load' context as it's the
197 most common one. This method is used in the parser to set assignment
198 targets and other nodes to a store context.
Armin Ronachere791c2a2008-04-07 18:39:54 +0200199 """
200 todo = deque([self])
201 while todo:
202 node = todo.popleft()
203 if 'ctx' in node.fields:
204 node.ctx = ctx
205 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200206 return self
Armin Ronachere791c2a2008-04-07 18:39:54 +0200207
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200208 def set_lineno(self, lineno, override=False):
209 """Set the line numbers of the node and children."""
210 todo = deque([self])
211 while todo:
212 node = todo.popleft()
213 if 'lineno' in node.attributes:
214 if node.lineno is None or override:
215 node.lineno = lineno
216 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200217 return self
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200218
Armin Ronacherd55ab532008-04-09 16:13:39 +0200219 def set_environment(self, environment):
220 """Set the environment for all nodes."""
221 todo = deque([self])
222 while todo:
223 node = todo.popleft()
224 node.environment = environment
225 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200226 return self
Armin Ronacherd55ab532008-04-09 16:13:39 +0200227
Armin Ronacher69e12db2008-05-12 09:00:03 +0200228 def __eq__(self, other):
Armin Ronacherb3a1fcf2008-05-15 11:04:14 +0200229 return type(self) is type(other) and \
230 tuple(self.iter_fields()) == tuple(other.iter_fields())
Armin Ronacher69e12db2008-05-12 09:00:03 +0200231
232 def __ne__(self, other):
233 return not self.__eq__(other)
234
Armin Ronacher563fd2e2013-08-07 12:48:37 +0100235 # Restore Python 2 hashing behavior on Python 3
236 __hash__ = object.__hash__
237
Armin Ronacher07bc6842008-03-31 14:18:49 +0200238 def __repr__(self):
239 return '%s(%s)' % (
240 self.__class__.__name__,
241 ', '.join('%s=%r' % (arg, getattr(self, arg, None)) for
Armin Ronachere791c2a2008-04-07 18:39:54 +0200242 arg in self.fields)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200243 )
244
Armin Ronacher1205e642017-01-02 12:09:52 +0100245 def dump(self):
246 def _dump(node):
247 if not isinstance(node, Node):
248 buf.append(repr(node))
249 return
250
251 buf.append('nodes.%s(' % node.__class__.__name__)
252 if not node.fields:
253 buf.append(')')
254 return
255 for idx, field in enumerate(node.fields):
256 if idx:
257 buf.append(', ')
258 value = getattr(node, field)
259 if isinstance(value, list):
260 buf.append('[')
261 for idx, item in enumerate(value):
262 if idx:
263 buf.append(', ')
264 _dump(item)
265 buf.append(']')
266 else:
267 _dump(value)
268 buf.append(')')
269 buf = []
270 _dump(self)
271 return ''.join(buf)
272
273
Armin Ronacher07bc6842008-03-31 14:18:49 +0200274
275class Stmt(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200276 """Base node for all statements."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200277 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200278
279
280class Helper(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200281 """Nodes that exist in a specific context only."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200282 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200283
284
285class Template(Node):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200286 """Node that represents a template. This must be the outermost node that
287 is passed to the compiler.
288 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200289 fields = ('body',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200290
291
292class Output(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200293 """A node that holds multiple expressions which are then printed out.
294 This is used both for the `print` statement and the regular template data.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200295 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200296 fields = ('nodes',)
297
Armin Ronacher07bc6842008-03-31 14:18:49 +0200298
299class Extends(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200300 """Represents an extends statement."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200301 fields = ('template',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200302
303
304class For(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200305 """The for loop. `target` is the target for the iteration (usually a
306 :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list
307 of nodes that are used as loop-body, and `else_` a list of nodes for the
308 `else` block. If no else node exists it has to be an empty list.
309
310 For filtered nodes an expression can be stored as `test`, otherwise `None`.
311 """
Armin Ronacherfdf95302008-05-11 22:20:51 +0200312 fields = ('target', 'iter', 'body', 'else_', 'test', 'recursive')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200313
314
315class If(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200316 """If `test` is true, `body` is rendered, else `else_`."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200317 fields = ('test', 'body', 'else_')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200318
319
320class Macro(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200321 """A macro definition. `name` is the name of the macro, `args` a list of
322 arguments and `defaults` a list of defaults if there are any. `body` is
323 a list of nodes for the macro body.
324 """
Armin Ronacher8efc5222008-04-08 14:47:40 +0200325 fields = ('name', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200326
327
328class CallBlock(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200329 """Like a macro without a name but a call instead. `call` is called with
330 the unnamed macro as `caller` argument this node holds.
331 """
Armin Ronacherc9705c22008-04-27 21:28:03 +0200332 fields = ('call', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200333
334
Armin Ronacher07bc6842008-03-31 14:18:49 +0200335class FilterBlock(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200336 """Node for filter sections."""
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200337 fields = ('body', 'filter')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200338
339
340class Block(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200341 """A node that represents a block."""
Armin Ronacher74a0cd92009-02-19 15:56:53 +0100342 fields = ('name', 'body', 'scoped')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200343
344
345class Include(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200346 """A node that represents the include tag."""
Armin Ronacher37f58ce2008-12-27 13:10:38 +0100347 fields = ('template', 'with_context', 'ignore_missing')
Armin Ronacher0611e492008-04-25 23:44:14 +0200348
349
350class Import(Stmt):
351 """A node that represents the import tag."""
Armin Ronacherea847c52008-05-02 20:04:32 +0200352 fields = ('template', 'target', 'with_context')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200353
354
Armin Ronacher0611e492008-04-25 23:44:14 +0200355class FromImport(Stmt):
356 """A node that represents the from import tag. It's important to not
357 pass unsafe names to the name attribute. The compiler translates the
358 attribute lookups directly into getattr calls and does *not* use the
Armin Ronacherb9388772008-06-25 20:43:18 +0200359 subscript callback of the interface. As exported variables may not
Armin Ronacher0611e492008-04-25 23:44:14 +0200360 start with double underscores (which the parser asserts) this is not a
361 problem for regular Jinja code, but if this node is used in an extension
362 extra care must be taken.
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200363
364 The list of names may contain tuples if aliases are wanted.
Armin Ronacher0611e492008-04-25 23:44:14 +0200365 """
Armin Ronacherea847c52008-05-02 20:04:32 +0200366 fields = ('template', 'names', 'with_context')
Armin Ronacher0611e492008-04-25 23:44:14 +0200367
368
Armin Ronacher07bc6842008-03-31 14:18:49 +0200369class ExprStmt(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200370 """A statement that evaluates an expression and discards the result."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200371 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200372
373
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200374class Assign(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200375 """Assigns an expression to a target."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200376 fields = ('target', 'node')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200377
378
Armin Ronacher9bf94b52014-06-07 00:56:05 +0600379class AssignBlock(Stmt):
380 """Assigns a block to a target."""
381 fields = ('target', 'body')
382
383
Armin Ronacher07bc6842008-03-31 14:18:49 +0200384class Expr(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200385 """Baseclass for all expressions."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200386 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200387
Armin Ronacher8346bd72010-03-14 19:43:47 +0100388 def as_const(self, eval_ctx=None):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200389 """Return the value of the expression as constant or raise
Armin Ronacher8346bd72010-03-14 19:43:47 +0100390 :exc:`Impossible` if this was not possible.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200391
Armin Ronacher8346bd72010-03-14 19:43:47 +0100392 An :class:`EvalContext` can be provided, if none is given
393 a default context is created which requires the nodes to have
394 an attached environment.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200395
Armin Ronacher8346bd72010-03-14 19:43:47 +0100396 .. versionchanged:: 2.4
397 the `eval_ctx` parameter was added.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200398 """
399 raise Impossible()
400
401 def can_assign(self):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200402 """Check if it's possible to assign something to this node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200403 return False
404
405
406class BinExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200407 """Baseclass for all binary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200408 fields = ('left', 'right')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200409 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200410 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200411
Armin Ronacher8346bd72010-03-14 19:43:47 +0100412 def as_const(self, eval_ctx=None):
413 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronachera9195382010-11-29 13:21:57 +0100414 # intercepted operators cannot be folded at compile time
415 if self.environment.sandboxed and \
416 self.operator in self.environment.intercepted_binops:
417 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200418 f = _binop_to_func[self.operator]
419 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100420 return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900421 except Exception:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200422 raise Impossible()
423
424
425class UnaryExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200426 """Baseclass for all unary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200427 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200428 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200429 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200430
Armin Ronacher8346bd72010-03-14 19:43:47 +0100431 def as_const(self, eval_ctx=None):
432 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronachera9195382010-11-29 13:21:57 +0100433 # intercepted operators cannot be folded at compile time
434 if self.environment.sandboxed and \
435 self.operator in self.environment.intercepted_unops:
436 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200437 f = _uaop_to_func[self.operator]
438 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100439 return f(self.node.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900440 except Exception:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200441 raise Impossible()
442
443
444class Name(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200445 """Looks up a name or stores a value in a name.
446 The `ctx` of the node can be one of the following values:
447
448 - `store`: store a value in the name
449 - `load`: load that name
450 - `param`: like `store` but if the name was defined as function parameter.
451 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200452 fields = ('name', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200453
454 def can_assign(self):
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200455 return self.name not in ('true', 'false', 'none',
456 'True', 'False', 'None')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200457
458
459class Literal(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200460 """Baseclass for literals."""
Armin Ronacher69e12db2008-05-12 09:00:03 +0200461 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200462
463
464class Const(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200465 """All constant values. The parser will return this node for simple
466 constants such as ``42`` or ``"foo"`` but it can be used to store more
467 complex values such as lists too. Only constants with a safe
468 representation (objects where ``eval(repr(x)) == x`` is true).
469 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200470 fields = ('value',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200471
Armin Ronacher8346bd72010-03-14 19:43:47 +0100472 def as_const(self, eval_ctx=None):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200473 return self.value
474
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200475 @classmethod
Armin Ronacherd55ab532008-04-09 16:13:39 +0200476 def from_untrusted(cls, value, lineno=None, environment=None):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200477 """Return a const object if the value is representable as
478 constant value in the generated code, otherwise it will raise
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200479 an `Impossible` exception.
480 """
Thomas Waldmanne0003552013-05-17 23:52:14 +0200481 from .compiler import has_safe_repr
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200482 if not has_safe_repr(value):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200483 raise Impossible()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200484 return cls(value, lineno=lineno, environment=environment)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200485
Armin Ronacher07bc6842008-03-31 14:18:49 +0200486
Armin Ronacher5411ce72008-05-25 11:36:22 +0200487class TemplateData(Literal):
488 """A constant template string."""
489 fields = ('data',)
490
Armin Ronacher8346bd72010-03-14 19:43:47 +0100491 def as_const(self, eval_ctx=None):
Armin Ronacherffaa2e72010-05-29 20:57:16 +0200492 eval_ctx = get_eval_context(self, eval_ctx)
493 if eval_ctx.volatile:
494 raise Impossible()
495 if eval_ctx.autoescape:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200496 return Markup(self.data)
497 return self.data
498
499
Armin Ronacher07bc6842008-03-31 14:18:49 +0200500class Tuple(Literal):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200501 """For loop unpacking and some other things like multiple arguments
Armin Ronacher023b5e92008-05-08 11:03:10 +0200502 for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
503 is used for loading the names or storing.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200504 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200505 fields = ('items', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200506
Armin Ronacher8346bd72010-03-14 19:43:47 +0100507 def as_const(self, eval_ctx=None):
508 eval_ctx = get_eval_context(self, eval_ctx)
509 return tuple(x.as_const(eval_ctx) for x in self.items)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200510
511 def can_assign(self):
512 for item in self.items:
513 if not item.can_assign():
514 return False
515 return True
516
517
518class List(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200519 """Any list literal such as ``[1, 2, 3]``"""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200520 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200521
Armin Ronacher8346bd72010-03-14 19:43:47 +0100522 def as_const(self, eval_ctx=None):
523 eval_ctx = get_eval_context(self, eval_ctx)
524 return [x.as_const(eval_ctx) for x in self.items]
Armin Ronacher07bc6842008-03-31 14:18:49 +0200525
526
527class Dict(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200528 """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
529 :class:`Pair` nodes.
530 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200531 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200532
Armin Ronacher8346bd72010-03-14 19:43:47 +0100533 def as_const(self, eval_ctx=None):
534 eval_ctx = get_eval_context(self, eval_ctx)
535 return dict(x.as_const(eval_ctx) for x in self.items)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200536
537
538class Pair(Helper):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200539 """A key, value pair for dicts."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200540 fields = ('key', 'value')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200541
Armin Ronacher8346bd72010-03-14 19:43:47 +0100542 def as_const(self, eval_ctx=None):
543 eval_ctx = get_eval_context(self, eval_ctx)
544 return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200545
546
Armin Ronacher8efc5222008-04-08 14:47:40 +0200547class Keyword(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200548 """A key, value pair for keyword arguments where key is a string."""
Armin Ronacher8efc5222008-04-08 14:47:40 +0200549 fields = ('key', 'value')
550
Armin Ronacher8346bd72010-03-14 19:43:47 +0100551 def as_const(self, eval_ctx=None):
552 eval_ctx = get_eval_context(self, eval_ctx)
553 return self.key, self.value.as_const(eval_ctx)
Armin Ronacher335b87a2008-09-21 17:08:48 +0200554
Armin Ronacher8efc5222008-04-08 14:47:40 +0200555
Armin Ronacher07bc6842008-03-31 14:18:49 +0200556class CondExpr(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200557 """A conditional expression (inline if expression). (``{{
558 foo if bar else baz }}``)
559 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200560 fields = ('test', 'expr1', 'expr2')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200561
Armin Ronacher8346bd72010-03-14 19:43:47 +0100562 def as_const(self, eval_ctx=None):
563 eval_ctx = get_eval_context(self, eval_ctx)
564 if self.test.as_const(eval_ctx):
565 return self.expr1.as_const(eval_ctx)
Armin Ronacher547d0b62008-07-04 16:35:10 +0200566
567 # if we evaluate to an undefined object, we better do that at runtime
568 if self.expr2 is None:
569 raise Impossible()
570
Armin Ronacher8346bd72010-03-14 19:43:47 +0100571 return self.expr2.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200572
573
574class Filter(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200575 """This node applies a filter on an expression. `name` is the name of
576 the filter, the rest of the fields are the same as for :class:`Call`.
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200577
578 If the `node` of a filter is `None` the contents of the last buffer are
579 filtered. Buffers are created by macros and filter blocks.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200580 """
Armin Ronacherd55ab532008-04-09 16:13:39 +0200581 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200582
Armin Ronacher8346bd72010-03-14 19:43:47 +0100583 def as_const(self, eval_ctx=None):
584 eval_ctx = get_eval_context(self, eval_ctx)
585 if eval_ctx.volatile or self.node is None:
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200586 raise Impossible()
Armin Ronacher0d242be2010-02-10 01:35:13 +0100587 # we have to be careful here because we call filter_ below.
588 # if this variable would be called filter, 2to3 would wrap the
589 # call in a list beause it is assuming we are talking about the
590 # builtin filter function here which no longer returns a list in
591 # python 3. because of that, do not rename filter_ to filter!
592 filter_ = self.environment.filters.get(self.name)
593 if filter_ is None or getattr(filter_, 'contextfilter', False):
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200594 raise Impossible()
Armin Ronacher8346bd72010-03-14 19:43:47 +0100595 obj = self.node.as_const(eval_ctx)
Armin Ronacherfa2d9552017-01-06 23:07:57 +0100596 args = [obj] + [x.as_const(eval_ctx) for x in self.args]
Armin Ronacher8346bd72010-03-14 19:43:47 +0100597 if getattr(filter_, 'evalcontextfilter', False):
598 args.insert(0, eval_ctx)
599 elif getattr(filter_, 'environmentfilter', False):
Armin Ronacher9a027f42008-04-17 11:13:40 +0200600 args.insert(0, self.environment)
Armin Ronacher8346bd72010-03-14 19:43:47 +0100601 kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
Armin Ronacherd55ab532008-04-09 16:13:39 +0200602 if self.dyn_args is not None:
603 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100604 args.extend(self.dyn_args.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900605 except Exception:
Armin Ronacherd55ab532008-04-09 16:13:39 +0200606 raise Impossible()
607 if self.dyn_kwargs is not None:
608 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100609 kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900610 except Exception:
Armin Ronacherd55ab532008-04-09 16:13:39 +0200611 raise Impossible()
612 try:
Armin Ronacherfa2d9552017-01-06 23:07:57 +0100613 return filter_(*args, **kwargs)
Ian Lewisab014bd2010-10-31 20:29:28 +0900614 except Exception:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200615 raise Impossible()
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200616
617
Armin Ronacher07bc6842008-03-31 14:18:49 +0200618class Test(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200619 """Applies a test on an expression. `name` is the name of the test, the
620 rest of the fields are the same as for :class:`Call`.
621 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200622 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200623
624
625class Call(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200626 """Calls an expression. `args` is a list of arguments, `kwargs` a list
627 of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
628 and `dyn_kwargs` has to be either `None` or a node that is used as
629 node for dynamic positional (``*args``) or keyword (``**kwargs``)
630 arguments.
631 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200632 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200633
Armin Ronacher8346bd72010-03-14 19:43:47 +0100634 def as_const(self, eval_ctx=None):
635 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher9b530452016-12-29 14:13:38 +0100636 if eval_ctx.volatile or eval_ctx.environment.sandboxed:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100637 raise Impossible()
638 obj = self.node.as_const(eval_ctx)
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200639
640 # don't evaluate context functions
Armin Ronacher8346bd72010-03-14 19:43:47 +0100641 args = [x.as_const(eval_ctx) for x in self.args]
Armin Ronacher5a5ce732010-05-23 22:58:28 +0200642 if isinstance(obj, _context_function_types):
643 if getattr(obj, 'contextfunction', False):
644 raise Impossible()
645 elif getattr(obj, 'evalcontextfunction', False):
646 args.insert(0, eval_ctx)
647 elif getattr(obj, 'environmentfunction', False):
648 args.insert(0, self.environment)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200649
Armin Ronacher8346bd72010-03-14 19:43:47 +0100650 kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200651 if self.dyn_args is not None:
652 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100653 args.extend(self.dyn_args.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900654 except Exception:
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200655 raise Impossible()
656 if self.dyn_kwargs is not None:
657 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100658 kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900659 except Exception:
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200660 raise Impossible()
661 try:
662 return obj(*args, **kwargs)
Ian Lewisab014bd2010-10-31 20:29:28 +0900663 except Exception:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200664 raise Impossible()
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200665
Armin Ronacher07bc6842008-03-31 14:18:49 +0200666
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200667class Getitem(Expr):
Armin Ronacherb9388772008-06-25 20:43:18 +0200668 """Get an attribute or item from an expression and prefer the item."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200669 fields = ('node', 'arg', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200670
Armin Ronacher8346bd72010-03-14 19:43:47 +0100671 def as_const(self, eval_ctx=None):
672 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200673 if self.ctx != 'load':
674 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200675 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100676 return self.environment.getitem(self.node.as_const(eval_ctx),
677 self.arg.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900678 except Exception:
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200679 raise Impossible()
680
681 def can_assign(self):
682 return False
683
684
685class Getattr(Expr):
Armin Ronacherb9388772008-06-25 20:43:18 +0200686 """Get an attribute or item from an expression that is a ascii-only
687 bytestring and prefer the attribute.
688 """
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200689 fields = ('node', 'attr', 'ctx')
690
Armin Ronacher8346bd72010-03-14 19:43:47 +0100691 def as_const(self, eval_ctx=None):
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200692 if self.ctx != 'load':
693 raise Impossible()
694 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100695 eval_ctx = get_eval_context(self, eval_ctx)
Georg Brandl93d2df72010-05-23 22:35:53 +0200696 return self.environment.getattr(self.node.as_const(eval_ctx),
697 self.attr)
Ian Lewisab014bd2010-10-31 20:29:28 +0900698 except Exception:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200699 raise Impossible()
700
701 def can_assign(self):
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200702 return False
Armin Ronacher07bc6842008-03-31 14:18:49 +0200703
704
705class Slice(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200706 """Represents a slice object. This must only be used as argument for
707 :class:`Subscript`.
708 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200709 fields = ('start', 'stop', 'step')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200710
Armin Ronacher8346bd72010-03-14 19:43:47 +0100711 def as_const(self, eval_ctx=None):
712 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200713 def const(obj):
714 if obj is None:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100715 return None
716 return obj.as_const(eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200717 return slice(const(self.start), const(self.stop), const(self.step))
718
Armin Ronacher07bc6842008-03-31 14:18:49 +0200719
720class Concat(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200721 """Concatenates the list of expressions provided after converting them to
722 unicode.
723 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200724 fields = ('nodes',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200725
Armin Ronacher8346bd72010-03-14 19:43:47 +0100726 def as_const(self, eval_ctx=None):
727 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronachere9098672013-05-19 14:16:13 +0100728 return ''.join(text_type(x.as_const(eval_ctx)) for x in self.nodes)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200729
730
731class Compare(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200732 """Compares an expression with some other expressions. `ops` must be a
733 list of :class:`Operand`\s.
734 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200735 fields = ('expr', 'ops')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200736
Armin Ronacher8346bd72010-03-14 19:43:47 +0100737 def as_const(self, eval_ctx=None):
738 eval_ctx = get_eval_context(self, eval_ctx)
739 result = value = self.expr.as_const(eval_ctx)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200740 try:
741 for op in self.ops:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100742 new_value = op.expr.as_const(eval_ctx)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200743 result = _cmpop_to_func[op.op](value, new_value)
744 value = new_value
Ian Lewisab014bd2010-10-31 20:29:28 +0900745 except Exception:
Armin Ronacherb5124e62008-04-25 00:36:14 +0200746 raise Impossible()
Armin Ronacher625215e2008-04-13 16:31:08 +0200747 return result
748
Armin Ronacher07bc6842008-03-31 14:18:49 +0200749
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200750class Operand(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200751 """Holds an operator and an expression."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200752 fields = ('op', 'expr')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200753
Armin Ronacher023b5e92008-05-08 11:03:10 +0200754if __debug__:
755 Operand.__doc__ += '\nThe following operators are available: ' + \
756 ', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
757 set(_uaop_to_func) | set(_cmpop_to_func)))
758
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200759
Armin Ronacher07bc6842008-03-31 14:18:49 +0200760class Mul(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200761 """Multiplies the left with the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200762 operator = '*'
763
764
765class Div(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200766 """Divides the left by the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200767 operator = '/'
768
769
770class FloorDiv(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200771 """Divides the left by the right node and truncates conver the
772 result into an integer by truncating.
773 """
Armin Ronacher07bc6842008-03-31 14:18:49 +0200774 operator = '//'
775
776
777class Add(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200778 """Add the left to the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200779 operator = '+'
780
781
782class Sub(BinExpr):
Jakub Wilk3fc008b2013-05-25 23:37:34 +0200783 """Subtract the right from the left node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200784 operator = '-'
785
786
787class Mod(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200788 """Left modulo right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200789 operator = '%'
790
791
792class Pow(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200793 """Left to the power of right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200794 operator = '**'
795
796
797class And(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200798 """Short circuited AND."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200799 operator = 'and'
800
Armin Ronacher8346bd72010-03-14 19:43:47 +0100801 def as_const(self, eval_ctx=None):
802 eval_ctx = get_eval_context(self, eval_ctx)
803 return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200804
805
806class Or(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200807 """Short circuited OR."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200808 operator = 'or'
809
Armin Ronacher8346bd72010-03-14 19:43:47 +0100810 def as_const(self, eval_ctx=None):
811 eval_ctx = get_eval_context(self, eval_ctx)
812 return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200813
814
815class Not(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200816 """Negate the expression."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200817 operator = 'not'
818
819
Armin Ronachere791c2a2008-04-07 18:39:54 +0200820class Neg(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200821 """Make the expression negative."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200822 operator = '-'
823
824
Armin Ronachere791c2a2008-04-07 18:39:54 +0200825class Pos(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200826 """Make the expression positive (noop for most expressions)"""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200827 operator = '+'
Armin Ronacher023b5e92008-05-08 11:03:10 +0200828
829
830# Helpers for extensions
831
832
833class EnvironmentAttribute(Expr):
834 """Loads an attribute from the environment object. This is useful for
835 extensions that want to call a callback stored on the environment.
836 """
837 fields = ('name',)
838
839
840class ExtensionAttribute(Expr):
841 """Returns the attribute of an extension bound to the environment.
842 The identifier is the identifier of the :class:`Extension`.
Armin Ronacherb9e78752008-05-10 23:36:28 +0200843
844 This node is usually constructed by calling the
845 :meth:`~jinja2.ext.Extension.attr` method on an extension.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200846 """
Armin Ronacher6df604e2008-05-23 22:18:38 +0200847 fields = ('identifier', 'name')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200848
849
850class ImportedName(Expr):
851 """If created with an import name the import name is returned on node
852 access. For example ``ImportedName('cgi.escape')`` returns the `escape`
853 function from the cgi module on evaluation. Imports are optimized by the
854 compiler so there is no need to assign them to local variables.
855 """
856 fields = ('importname',)
857
858
859class InternalName(Expr):
860 """An internal name in the compiler. You cannot create these nodes
Armin Ronacher762079c2008-05-08 23:57:56 +0200861 yourself but the parser provides a
862 :meth:`~jinja2.parser.Parser.free_identifier` method that creates
Armin Ronacher023b5e92008-05-08 11:03:10 +0200863 a new identifier for you. This identifier is not available from the
864 template and is not threated specially by the compiler.
865 """
866 fields = ('name',)
867
868 def __init__(self):
869 raise TypeError('Can\'t create internal names. Use the '
870 '`free_identifier` method on a parser.')
871
872
873class MarkSafe(Expr):
874 """Mark the wrapped expression as safe (wrap it as `Markup`)."""
875 fields = ('expr',)
876
Armin Ronacher8346bd72010-03-14 19:43:47 +0100877 def as_const(self, eval_ctx=None):
878 eval_ctx = get_eval_context(self, eval_ctx)
879 return Markup(self.expr.as_const(eval_ctx))
Armin Ronacher023b5e92008-05-08 11:03:10 +0200880
881
Armin Ronacher4da90342010-05-29 17:35:10 +0200882class MarkSafeIfAutoescape(Expr):
883 """Mark the wrapped expression as safe (wrap it as `Markup`) but
884 only if autoescaping is active.
885
886 .. versionadded:: 2.5
887 """
888 fields = ('expr',)
889
890 def as_const(self, eval_ctx=None):
891 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacherffaa2e72010-05-29 20:57:16 +0200892 if eval_ctx.volatile:
893 raise Impossible()
Armin Ronacher4da90342010-05-29 17:35:10 +0200894 expr = self.expr.as_const(eval_ctx)
895 if eval_ctx.autoescape:
896 return Markup(expr)
897 return expr
898
899
Armin Ronacher6df604e2008-05-23 22:18:38 +0200900class ContextReference(Expr):
Armin Ronachercedb4822010-03-24 10:53:22 +0100901 """Returns the current template context. It can be used like a
902 :class:`Name` node, with a ``'load'`` ctx and will return the
903 current :class:`~jinja2.runtime.Context` object.
904
905 Here an example that assigns the current template name to a
906 variable named `foo`::
907
908 Assign(Name('foo', ctx='store'),
909 Getattr(ContextReference(), 'name'))
910 """
Armin Ronacher6df604e2008-05-23 22:18:38 +0200911
912
Armin Ronachered1e0d42008-05-18 20:25:28 +0200913class Continue(Stmt):
914 """Continue a loop."""
915
916
917class Break(Stmt):
918 """Break a loop."""
919
920
Armin Ronacher271a0eb2009-02-11 22:49:08 +0100921class Scope(Stmt):
922 """An artificial scope."""
923 fields = ('body',)
924
925
Armin Ronacher8346bd72010-03-14 19:43:47 +0100926class EvalContextModifier(Stmt):
Armin Ronacher30fda272010-03-15 03:06:04 +0100927 """Modifies the eval context. For each option that should be modified,
928 a :class:`Keyword` has to be added to the :attr:`options` list.
929
930 Example to change the `autoescape` setting::
931
932 EvalContextModifier(options=[Keyword('autoescape', Const(True))])
933 """
Armin Ronacher8346bd72010-03-14 19:43:47 +0100934 fields = ('options',)
935
936
937class ScopedEvalContextModifier(EvalContextModifier):
Armin Ronacher30fda272010-03-15 03:06:04 +0100938 """Modifies the eval context and reverts it later. Works exactly like
939 :class:`EvalContextModifier` but will only modify the
Armin Ronacher0dbaf392010-03-15 10:06:53 +0100940 :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.
Armin Ronacher30fda272010-03-15 03:06:04 +0100941 """
Armin Ronacher8346bd72010-03-14 19:43:47 +0100942 fields = ('body',)
943
944
Armin Ronacher8a1d27f2008-05-19 08:37:19 +0200945# make sure nobody creates custom nodes
946def _failing_new(*args, **kwargs):
947 raise TypeError('can\'t create custom node types')
948NodeType.__new__ = staticmethod(_failing_new); del _failing_new