blob: 5e0726a365df8b4b4c8a71bc255cdb6206e7d0aa [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 Ronacher028f0582017-01-07 14:57:44 +010020from jinja2._compat import izip, with_metaclass, text_type, PY2
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 Ronacher028f0582017-01-07 14:57:44 +0100473 rv = self.value
474 if PY2 and type(rv) is text_type and \
475 self.environment.policies['compiler.ascii_str']:
476 try:
477 rv = rv.encode('ascii')
478 except UnicodeError:
479 pass
480 return rv
Armin Ronacher07bc6842008-03-31 14:18:49 +0200481
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200482 @classmethod
Armin Ronacherd55ab532008-04-09 16:13:39 +0200483 def from_untrusted(cls, value, lineno=None, environment=None):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200484 """Return a const object if the value is representable as
485 constant value in the generated code, otherwise it will raise
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200486 an `Impossible` exception.
487 """
Thomas Waldmanne0003552013-05-17 23:52:14 +0200488 from .compiler import has_safe_repr
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200489 if not has_safe_repr(value):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200490 raise Impossible()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200491 return cls(value, lineno=lineno, environment=environment)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200492
Armin Ronacher07bc6842008-03-31 14:18:49 +0200493
Armin Ronacher5411ce72008-05-25 11:36:22 +0200494class TemplateData(Literal):
495 """A constant template string."""
496 fields = ('data',)
497
Armin Ronacher8346bd72010-03-14 19:43:47 +0100498 def as_const(self, eval_ctx=None):
Armin Ronacherffaa2e72010-05-29 20:57:16 +0200499 eval_ctx = get_eval_context(self, eval_ctx)
500 if eval_ctx.volatile:
501 raise Impossible()
502 if eval_ctx.autoescape:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200503 return Markup(self.data)
504 return self.data
505
506
Armin Ronacher07bc6842008-03-31 14:18:49 +0200507class Tuple(Literal):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200508 """For loop unpacking and some other things like multiple arguments
Armin Ronacher023b5e92008-05-08 11:03:10 +0200509 for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
510 is used for loading the names or storing.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200511 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200512 fields = ('items', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200513
Armin Ronacher8346bd72010-03-14 19:43:47 +0100514 def as_const(self, eval_ctx=None):
515 eval_ctx = get_eval_context(self, eval_ctx)
516 return tuple(x.as_const(eval_ctx) for x in self.items)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200517
518 def can_assign(self):
519 for item in self.items:
520 if not item.can_assign():
521 return False
522 return True
523
524
525class List(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200526 """Any list literal such as ``[1, 2, 3]``"""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200527 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200528
Armin Ronacher8346bd72010-03-14 19:43:47 +0100529 def as_const(self, eval_ctx=None):
530 eval_ctx = get_eval_context(self, eval_ctx)
531 return [x.as_const(eval_ctx) for x in self.items]
Armin Ronacher07bc6842008-03-31 14:18:49 +0200532
533
534class Dict(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200535 """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
536 :class:`Pair` nodes.
537 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200538 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200539
Armin Ronacher8346bd72010-03-14 19:43:47 +0100540 def as_const(self, eval_ctx=None):
541 eval_ctx = get_eval_context(self, eval_ctx)
542 return dict(x.as_const(eval_ctx) for x in self.items)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200543
544
545class Pair(Helper):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200546 """A key, value pair for dicts."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200547 fields = ('key', 'value')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200548
Armin Ronacher8346bd72010-03-14 19:43:47 +0100549 def as_const(self, eval_ctx=None):
550 eval_ctx = get_eval_context(self, eval_ctx)
551 return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200552
553
Armin Ronacher8efc5222008-04-08 14:47:40 +0200554class Keyword(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200555 """A key, value pair for keyword arguments where key is a string."""
Armin Ronacher8efc5222008-04-08 14:47:40 +0200556 fields = ('key', 'value')
557
Armin Ronacher8346bd72010-03-14 19:43:47 +0100558 def as_const(self, eval_ctx=None):
559 eval_ctx = get_eval_context(self, eval_ctx)
560 return self.key, self.value.as_const(eval_ctx)
Armin Ronacher335b87a2008-09-21 17:08:48 +0200561
Armin Ronacher8efc5222008-04-08 14:47:40 +0200562
Armin Ronacher07bc6842008-03-31 14:18:49 +0200563class CondExpr(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200564 """A conditional expression (inline if expression). (``{{
565 foo if bar else baz }}``)
566 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200567 fields = ('test', 'expr1', 'expr2')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200568
Armin Ronacher8346bd72010-03-14 19:43:47 +0100569 def as_const(self, eval_ctx=None):
570 eval_ctx = get_eval_context(self, eval_ctx)
571 if self.test.as_const(eval_ctx):
572 return self.expr1.as_const(eval_ctx)
Armin Ronacher547d0b62008-07-04 16:35:10 +0200573
574 # if we evaluate to an undefined object, we better do that at runtime
575 if self.expr2 is None:
576 raise Impossible()
577
Armin Ronacher8346bd72010-03-14 19:43:47 +0100578 return self.expr2.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200579
580
581class Filter(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200582 """This node applies a filter on an expression. `name` is the name of
583 the filter, the rest of the fields are the same as for :class:`Call`.
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200584
585 If the `node` of a filter is `None` the contents of the last buffer are
586 filtered. Buffers are created by macros and filter blocks.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200587 """
Armin Ronacherd55ab532008-04-09 16:13:39 +0200588 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200589
Armin Ronacher8346bd72010-03-14 19:43:47 +0100590 def as_const(self, eval_ctx=None):
591 eval_ctx = get_eval_context(self, eval_ctx)
592 if eval_ctx.volatile or self.node is None:
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200593 raise Impossible()
Armin Ronacher0d242be2010-02-10 01:35:13 +0100594 # we have to be careful here because we call filter_ below.
595 # if this variable would be called filter, 2to3 would wrap the
596 # call in a list beause it is assuming we are talking about the
597 # builtin filter function here which no longer returns a list in
598 # python 3. because of that, do not rename filter_ to filter!
599 filter_ = self.environment.filters.get(self.name)
600 if filter_ is None or getattr(filter_, 'contextfilter', False):
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200601 raise Impossible()
Armin Ronacher01d9e7e2017-01-07 02:44:37 +0100602
603 # We cannot constant handle async filters, so we need to make sure
604 # to not go down this path.
605 if eval_ctx.environment.is_async and \
606 getattr(filter_, 'asyncfiltervariant', False):
607 raise Impossible()
608
Armin Ronacher8346bd72010-03-14 19:43:47 +0100609 obj = self.node.as_const(eval_ctx)
Armin Ronacherfa2d9552017-01-06 23:07:57 +0100610 args = [obj] + [x.as_const(eval_ctx) for x in self.args]
Armin Ronacher8346bd72010-03-14 19:43:47 +0100611 if getattr(filter_, 'evalcontextfilter', False):
612 args.insert(0, eval_ctx)
613 elif getattr(filter_, 'environmentfilter', False):
Armin Ronacher9a027f42008-04-17 11:13:40 +0200614 args.insert(0, self.environment)
Armin Ronacher8346bd72010-03-14 19:43:47 +0100615 kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
Armin Ronacherd55ab532008-04-09 16:13:39 +0200616 if self.dyn_args is not None:
617 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100618 args.extend(self.dyn_args.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900619 except Exception:
Armin Ronacherd55ab532008-04-09 16:13:39 +0200620 raise Impossible()
621 if self.dyn_kwargs is not None:
622 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100623 kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900624 except Exception:
Armin Ronacherd55ab532008-04-09 16:13:39 +0200625 raise Impossible()
626 try:
Armin Ronacherfa2d9552017-01-06 23:07:57 +0100627 return filter_(*args, **kwargs)
Ian Lewisab014bd2010-10-31 20:29:28 +0900628 except Exception:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200629 raise Impossible()
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200630
631
Armin Ronacher07bc6842008-03-31 14:18:49 +0200632class Test(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200633 """Applies a test on an expression. `name` is the name of the test, the
634 rest of the fields are the same as for :class:`Call`.
635 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200636 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200637
638
639class Call(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200640 """Calls an expression. `args` is a list of arguments, `kwargs` a list
641 of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
642 and `dyn_kwargs` has to be either `None` or a node that is used as
643 node for dynamic positional (``*args``) or keyword (``**kwargs``)
644 arguments.
645 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200646 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200647
Armin Ronacher07bc6842008-03-31 14:18:49 +0200648
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200649class Getitem(Expr):
Armin Ronacherb9388772008-06-25 20:43:18 +0200650 """Get an attribute or item from an expression and prefer the item."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200651 fields = ('node', 'arg', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200652
Armin Ronacher8346bd72010-03-14 19:43:47 +0100653 def as_const(self, eval_ctx=None):
654 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200655 if self.ctx != 'load':
656 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200657 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100658 return self.environment.getitem(self.node.as_const(eval_ctx),
659 self.arg.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900660 except Exception:
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200661 raise Impossible()
662
663 def can_assign(self):
664 return False
665
666
667class Getattr(Expr):
Armin Ronacherb9388772008-06-25 20:43:18 +0200668 """Get an attribute or item from an expression that is a ascii-only
669 bytestring and prefer the attribute.
670 """
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200671 fields = ('node', 'attr', 'ctx')
672
Armin Ronacher8346bd72010-03-14 19:43:47 +0100673 def as_const(self, eval_ctx=None):
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200674 if self.ctx != 'load':
675 raise Impossible()
676 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100677 eval_ctx = get_eval_context(self, eval_ctx)
Georg Brandl93d2df72010-05-23 22:35:53 +0200678 return self.environment.getattr(self.node.as_const(eval_ctx),
679 self.attr)
Ian Lewisab014bd2010-10-31 20:29:28 +0900680 except Exception:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200681 raise Impossible()
682
683 def can_assign(self):
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200684 return False
Armin Ronacher07bc6842008-03-31 14:18:49 +0200685
686
687class Slice(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200688 """Represents a slice object. This must only be used as argument for
689 :class:`Subscript`.
690 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200691 fields = ('start', 'stop', 'step')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200692
Armin Ronacher8346bd72010-03-14 19:43:47 +0100693 def as_const(self, eval_ctx=None):
694 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200695 def const(obj):
696 if obj is None:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100697 return None
698 return obj.as_const(eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200699 return slice(const(self.start), const(self.stop), const(self.step))
700
Armin Ronacher07bc6842008-03-31 14:18:49 +0200701
702class Concat(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200703 """Concatenates the list of expressions provided after converting them to
704 unicode.
705 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200706 fields = ('nodes',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200707
Armin Ronacher8346bd72010-03-14 19:43:47 +0100708 def as_const(self, eval_ctx=None):
709 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronachere9098672013-05-19 14:16:13 +0100710 return ''.join(text_type(x.as_const(eval_ctx)) for x in self.nodes)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200711
712
713class Compare(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200714 """Compares an expression with some other expressions. `ops` must be a
715 list of :class:`Operand`\s.
716 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200717 fields = ('expr', 'ops')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200718
Armin Ronacher8346bd72010-03-14 19:43:47 +0100719 def as_const(self, eval_ctx=None):
720 eval_ctx = get_eval_context(self, eval_ctx)
721 result = value = self.expr.as_const(eval_ctx)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200722 try:
723 for op in self.ops:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100724 new_value = op.expr.as_const(eval_ctx)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200725 result = _cmpop_to_func[op.op](value, new_value)
726 value = new_value
Ian Lewisab014bd2010-10-31 20:29:28 +0900727 except Exception:
Armin Ronacherb5124e62008-04-25 00:36:14 +0200728 raise Impossible()
Armin Ronacher625215e2008-04-13 16:31:08 +0200729 return result
730
Armin Ronacher07bc6842008-03-31 14:18:49 +0200731
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200732class Operand(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200733 """Holds an operator and an expression."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200734 fields = ('op', 'expr')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200735
Armin Ronacher023b5e92008-05-08 11:03:10 +0200736if __debug__:
737 Operand.__doc__ += '\nThe following operators are available: ' + \
738 ', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
739 set(_uaop_to_func) | set(_cmpop_to_func)))
740
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200741
Armin Ronacher07bc6842008-03-31 14:18:49 +0200742class Mul(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200743 """Multiplies the left with the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200744 operator = '*'
745
746
747class Div(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200748 """Divides the left by the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200749 operator = '/'
750
751
752class FloorDiv(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200753 """Divides the left by the right node and truncates conver the
754 result into an integer by truncating.
755 """
Armin Ronacher07bc6842008-03-31 14:18:49 +0200756 operator = '//'
757
758
759class Add(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200760 """Add the left to the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200761 operator = '+'
762
763
764class Sub(BinExpr):
Jakub Wilk3fc008b2013-05-25 23:37:34 +0200765 """Subtract the right from the left node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200766 operator = '-'
767
768
769class Mod(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200770 """Left modulo right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200771 operator = '%'
772
773
774class Pow(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200775 """Left to the power of right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200776 operator = '**'
777
778
779class And(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200780 """Short circuited AND."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200781 operator = 'and'
782
Armin Ronacher8346bd72010-03-14 19:43:47 +0100783 def as_const(self, eval_ctx=None):
784 eval_ctx = get_eval_context(self, eval_ctx)
785 return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200786
787
788class Or(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200789 """Short circuited OR."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200790 operator = 'or'
791
Armin Ronacher8346bd72010-03-14 19:43:47 +0100792 def as_const(self, eval_ctx=None):
793 eval_ctx = get_eval_context(self, eval_ctx)
794 return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200795
796
797class Not(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200798 """Negate the expression."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200799 operator = 'not'
800
801
Armin Ronachere791c2a2008-04-07 18:39:54 +0200802class Neg(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200803 """Make the expression negative."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200804 operator = '-'
805
806
Armin Ronachere791c2a2008-04-07 18:39:54 +0200807class Pos(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200808 """Make the expression positive (noop for most expressions)"""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200809 operator = '+'
Armin Ronacher023b5e92008-05-08 11:03:10 +0200810
811
812# Helpers for extensions
813
814
815class EnvironmentAttribute(Expr):
816 """Loads an attribute from the environment object. This is useful for
817 extensions that want to call a callback stored on the environment.
818 """
819 fields = ('name',)
820
821
822class ExtensionAttribute(Expr):
823 """Returns the attribute of an extension bound to the environment.
824 The identifier is the identifier of the :class:`Extension`.
Armin Ronacherb9e78752008-05-10 23:36:28 +0200825
826 This node is usually constructed by calling the
827 :meth:`~jinja2.ext.Extension.attr` method on an extension.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200828 """
Armin Ronacher6df604e2008-05-23 22:18:38 +0200829 fields = ('identifier', 'name')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200830
831
832class ImportedName(Expr):
833 """If created with an import name the import name is returned on node
834 access. For example ``ImportedName('cgi.escape')`` returns the `escape`
835 function from the cgi module on evaluation. Imports are optimized by the
836 compiler so there is no need to assign them to local variables.
837 """
838 fields = ('importname',)
839
840
841class InternalName(Expr):
842 """An internal name in the compiler. You cannot create these nodes
Armin Ronacher762079c2008-05-08 23:57:56 +0200843 yourself but the parser provides a
844 :meth:`~jinja2.parser.Parser.free_identifier` method that creates
Armin Ronacher023b5e92008-05-08 11:03:10 +0200845 a new identifier for you. This identifier is not available from the
846 template and is not threated specially by the compiler.
847 """
848 fields = ('name',)
849
850 def __init__(self):
851 raise TypeError('Can\'t create internal names. Use the '
852 '`free_identifier` method on a parser.')
853
854
855class MarkSafe(Expr):
856 """Mark the wrapped expression as safe (wrap it as `Markup`)."""
857 fields = ('expr',)
858
Armin Ronacher8346bd72010-03-14 19:43:47 +0100859 def as_const(self, eval_ctx=None):
860 eval_ctx = get_eval_context(self, eval_ctx)
861 return Markup(self.expr.as_const(eval_ctx))
Armin Ronacher023b5e92008-05-08 11:03:10 +0200862
863
Armin Ronacher4da90342010-05-29 17:35:10 +0200864class MarkSafeIfAutoescape(Expr):
865 """Mark the wrapped expression as safe (wrap it as `Markup`) but
866 only if autoescaping is active.
867
868 .. versionadded:: 2.5
869 """
870 fields = ('expr',)
871
872 def as_const(self, eval_ctx=None):
873 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacherffaa2e72010-05-29 20:57:16 +0200874 if eval_ctx.volatile:
875 raise Impossible()
Armin Ronacher4da90342010-05-29 17:35:10 +0200876 expr = self.expr.as_const(eval_ctx)
877 if eval_ctx.autoescape:
878 return Markup(expr)
879 return expr
880
881
Armin Ronacher6df604e2008-05-23 22:18:38 +0200882class ContextReference(Expr):
Armin Ronachercedb4822010-03-24 10:53:22 +0100883 """Returns the current template context. It can be used like a
884 :class:`Name` node, with a ``'load'`` ctx and will return the
885 current :class:`~jinja2.runtime.Context` object.
886
887 Here an example that assigns the current template name to a
888 variable named `foo`::
889
890 Assign(Name('foo', ctx='store'),
891 Getattr(ContextReference(), 'name'))
892 """
Armin Ronacher6df604e2008-05-23 22:18:38 +0200893
894
Armin Ronachered1e0d42008-05-18 20:25:28 +0200895class Continue(Stmt):
896 """Continue a loop."""
897
898
899class Break(Stmt):
900 """Break a loop."""
901
902
Armin Ronacher271a0eb2009-02-11 22:49:08 +0100903class Scope(Stmt):
904 """An artificial scope."""
905 fields = ('body',)
906
907
Armin Ronacher8346bd72010-03-14 19:43:47 +0100908class EvalContextModifier(Stmt):
Armin Ronacher30fda272010-03-15 03:06:04 +0100909 """Modifies the eval context. For each option that should be modified,
910 a :class:`Keyword` has to be added to the :attr:`options` list.
911
912 Example to change the `autoescape` setting::
913
914 EvalContextModifier(options=[Keyword('autoescape', Const(True))])
915 """
Armin Ronacher8346bd72010-03-14 19:43:47 +0100916 fields = ('options',)
917
918
919class ScopedEvalContextModifier(EvalContextModifier):
Armin Ronacher30fda272010-03-15 03:06:04 +0100920 """Modifies the eval context and reverts it later. Works exactly like
921 :class:`EvalContextModifier` but will only modify the
Armin Ronacher0dbaf392010-03-15 10:06:53 +0100922 :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.
Armin Ronacher30fda272010-03-15 03:06:04 +0100923 """
Armin Ronacher8346bd72010-03-14 19:43:47 +0100924 fields = ('body',)
925
926
Armin Ronacher8a1d27f2008-05-19 08:37:19 +0200927# make sure nobody creates custom nodes
928def _failing_new(*args, **kwargs):
929 raise TypeError('can\'t create custom node types')
930NodeType.__new__ = staticmethod(_failing_new); del _failing_new