blob: 81fafb8b8d0a7f9efafc4d582cc3ef0139bd7dbb [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"""
15import operator
Armin Ronacherc87d4cf2013-05-19 13:46:22 +010016
Armin Ronacher82b3f3d2008-03-31 20:01:08 +020017from collections import deque
Armin Ronachere9098672013-05-19 14:16:13 +010018from jinja2.utils import Markup
19from jinja2._compat import next, izip, with_metaclass, text_type, \
20 method_type, function_type
Armin Ronacher5a5ce732010-05-23 22:58:28 +020021
22
23#: the types we support for context functions
Armin Ronachere9098672013-05-19 14:16:13 +010024_context_function_types = (function_type, method_type)
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 Ronacher07bc6842008-03-31 14:18:49 +0200235 def __repr__(self):
236 return '%s(%s)' % (
237 self.__class__.__name__,
238 ', '.join('%s=%r' % (arg, getattr(self, arg, None)) for
Armin Ronachere791c2a2008-04-07 18:39:54 +0200239 arg in self.fields)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200240 )
241
242
243class Stmt(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200244 """Base node for all statements."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200245 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200246
247
248class Helper(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200249 """Nodes that exist in a specific context only."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200250 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200251
252
253class Template(Node):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200254 """Node that represents a template. This must be the outermost node that
255 is passed to the compiler.
256 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200257 fields = ('body',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200258
259
260class Output(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200261 """A node that holds multiple expressions which are then printed out.
262 This is used both for the `print` statement and the regular template data.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200263 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200264 fields = ('nodes',)
265
Armin Ronacher07bc6842008-03-31 14:18:49 +0200266
267class Extends(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200268 """Represents an extends statement."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200269 fields = ('template',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200270
271
272class For(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200273 """The for loop. `target` is the target for the iteration (usually a
274 :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list
275 of nodes that are used as loop-body, and `else_` a list of nodes for the
276 `else` block. If no else node exists it has to be an empty list.
277
278 For filtered nodes an expression can be stored as `test`, otherwise `None`.
279 """
Armin Ronacherfdf95302008-05-11 22:20:51 +0200280 fields = ('target', 'iter', 'body', 'else_', 'test', 'recursive')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200281
282
283class If(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200284 """If `test` is true, `body` is rendered, else `else_`."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200285 fields = ('test', 'body', 'else_')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200286
287
288class Macro(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200289 """A macro definition. `name` is the name of the macro, `args` a list of
290 arguments and `defaults` a list of defaults if there are any. `body` is
291 a list of nodes for the macro body.
292 """
Armin Ronacher8efc5222008-04-08 14:47:40 +0200293 fields = ('name', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200294
295
296class CallBlock(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200297 """Like a macro without a name but a call instead. `call` is called with
298 the unnamed macro as `caller` argument this node holds.
299 """
Armin Ronacherc9705c22008-04-27 21:28:03 +0200300 fields = ('call', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200301
302
Armin Ronacher07bc6842008-03-31 14:18:49 +0200303class FilterBlock(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200304 """Node for filter sections."""
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200305 fields = ('body', 'filter')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200306
307
308class Block(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200309 """A node that represents a block."""
Armin Ronacher74a0cd92009-02-19 15:56:53 +0100310 fields = ('name', 'body', 'scoped')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200311
312
313class Include(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200314 """A node that represents the include tag."""
Armin Ronacher37f58ce2008-12-27 13:10:38 +0100315 fields = ('template', 'with_context', 'ignore_missing')
Armin Ronacher0611e492008-04-25 23:44:14 +0200316
317
318class Import(Stmt):
319 """A node that represents the import tag."""
Armin Ronacherea847c52008-05-02 20:04:32 +0200320 fields = ('template', 'target', 'with_context')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200321
322
Armin Ronacher0611e492008-04-25 23:44:14 +0200323class FromImport(Stmt):
324 """A node that represents the from import tag. It's important to not
325 pass unsafe names to the name attribute. The compiler translates the
326 attribute lookups directly into getattr calls and does *not* use the
Armin Ronacherb9388772008-06-25 20:43:18 +0200327 subscript callback of the interface. As exported variables may not
Armin Ronacher0611e492008-04-25 23:44:14 +0200328 start with double underscores (which the parser asserts) this is not a
329 problem for regular Jinja code, but if this node is used in an extension
330 extra care must be taken.
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200331
332 The list of names may contain tuples if aliases are wanted.
Armin Ronacher0611e492008-04-25 23:44:14 +0200333 """
Armin Ronacherea847c52008-05-02 20:04:32 +0200334 fields = ('template', 'names', 'with_context')
Armin Ronacher0611e492008-04-25 23:44:14 +0200335
336
Armin Ronacher07bc6842008-03-31 14:18:49 +0200337class ExprStmt(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200338 """A statement that evaluates an expression and discards the result."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200339 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200340
341
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200342class Assign(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200343 """Assigns an expression to a target."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200344 fields = ('target', 'node')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200345
346
Armin Ronacher07bc6842008-03-31 14:18:49 +0200347class Expr(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200348 """Baseclass for all expressions."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200349 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200350
Armin Ronacher8346bd72010-03-14 19:43:47 +0100351 def as_const(self, eval_ctx=None):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200352 """Return the value of the expression as constant or raise
Armin Ronacher8346bd72010-03-14 19:43:47 +0100353 :exc:`Impossible` if this was not possible.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200354
Armin Ronacher8346bd72010-03-14 19:43:47 +0100355 An :class:`EvalContext` can be provided, if none is given
356 a default context is created which requires the nodes to have
357 an attached environment.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200358
Armin Ronacher8346bd72010-03-14 19:43:47 +0100359 .. versionchanged:: 2.4
360 the `eval_ctx` parameter was added.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200361 """
362 raise Impossible()
363
364 def can_assign(self):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200365 """Check if it's possible to assign something to this node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200366 return False
367
368
369class BinExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200370 """Baseclass for all binary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200371 fields = ('left', 'right')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200372 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200373 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200374
Armin Ronacher8346bd72010-03-14 19:43:47 +0100375 def as_const(self, eval_ctx=None):
376 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronachera9195382010-11-29 13:21:57 +0100377 # intercepted operators cannot be folded at compile time
378 if self.environment.sandboxed and \
379 self.operator in self.environment.intercepted_binops:
380 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200381 f = _binop_to_func[self.operator]
382 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100383 return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900384 except Exception:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200385 raise Impossible()
386
387
388class UnaryExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200389 """Baseclass for all unary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200390 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200391 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200392 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200393
Armin Ronacher8346bd72010-03-14 19:43:47 +0100394 def as_const(self, eval_ctx=None):
395 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronachera9195382010-11-29 13:21:57 +0100396 # intercepted operators cannot be folded at compile time
397 if self.environment.sandboxed and \
398 self.operator in self.environment.intercepted_unops:
399 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200400 f = _uaop_to_func[self.operator]
401 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100402 return f(self.node.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900403 except Exception:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200404 raise Impossible()
405
406
407class Name(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200408 """Looks up a name or stores a value in a name.
409 The `ctx` of the node can be one of the following values:
410
411 - `store`: store a value in the name
412 - `load`: load that name
413 - `param`: like `store` but if the name was defined as function parameter.
414 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200415 fields = ('name', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200416
417 def can_assign(self):
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200418 return self.name not in ('true', 'false', 'none',
419 'True', 'False', 'None')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200420
421
422class Literal(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200423 """Baseclass for literals."""
Armin Ronacher69e12db2008-05-12 09:00:03 +0200424 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200425
426
427class Const(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200428 """All constant values. The parser will return this node for simple
429 constants such as ``42`` or ``"foo"`` but it can be used to store more
430 complex values such as lists too. Only constants with a safe
431 representation (objects where ``eval(repr(x)) == x`` is true).
432 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200433 fields = ('value',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200434
Armin Ronacher8346bd72010-03-14 19:43:47 +0100435 def as_const(self, eval_ctx=None):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200436 return self.value
437
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200438 @classmethod
Armin Ronacherd55ab532008-04-09 16:13:39 +0200439 def from_untrusted(cls, value, lineno=None, environment=None):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200440 """Return a const object if the value is representable as
441 constant value in the generated code, otherwise it will raise
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200442 an `Impossible` exception.
443 """
Thomas Waldmanne0003552013-05-17 23:52:14 +0200444 from .compiler import has_safe_repr
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200445 if not has_safe_repr(value):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200446 raise Impossible()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200447 return cls(value, lineno=lineno, environment=environment)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200448
Armin Ronacher07bc6842008-03-31 14:18:49 +0200449
Armin Ronacher5411ce72008-05-25 11:36:22 +0200450class TemplateData(Literal):
451 """A constant template string."""
452 fields = ('data',)
453
Armin Ronacher8346bd72010-03-14 19:43:47 +0100454 def as_const(self, eval_ctx=None):
Armin Ronacherffaa2e72010-05-29 20:57:16 +0200455 eval_ctx = get_eval_context(self, eval_ctx)
456 if eval_ctx.volatile:
457 raise Impossible()
458 if eval_ctx.autoescape:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200459 return Markup(self.data)
460 return self.data
461
462
Armin Ronacher07bc6842008-03-31 14:18:49 +0200463class Tuple(Literal):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200464 """For loop unpacking and some other things like multiple arguments
Armin Ronacher023b5e92008-05-08 11:03:10 +0200465 for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
466 is used for loading the names or storing.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200467 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200468 fields = ('items', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200469
Armin Ronacher8346bd72010-03-14 19:43:47 +0100470 def as_const(self, eval_ctx=None):
471 eval_ctx = get_eval_context(self, eval_ctx)
472 return tuple(x.as_const(eval_ctx) for x in self.items)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200473
474 def can_assign(self):
475 for item in self.items:
476 if not item.can_assign():
477 return False
478 return True
479
480
481class List(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200482 """Any list literal such as ``[1, 2, 3]``"""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200483 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200484
Armin Ronacher8346bd72010-03-14 19:43:47 +0100485 def as_const(self, eval_ctx=None):
486 eval_ctx = get_eval_context(self, eval_ctx)
487 return [x.as_const(eval_ctx) for x in self.items]
Armin Ronacher07bc6842008-03-31 14:18:49 +0200488
489
490class Dict(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200491 """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
492 :class:`Pair` nodes.
493 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200494 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200495
Armin Ronacher8346bd72010-03-14 19:43:47 +0100496 def as_const(self, eval_ctx=None):
497 eval_ctx = get_eval_context(self, eval_ctx)
498 return dict(x.as_const(eval_ctx) for x in self.items)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200499
500
501class Pair(Helper):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200502 """A key, value pair for dicts."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200503 fields = ('key', 'value')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200504
Armin Ronacher8346bd72010-03-14 19:43:47 +0100505 def as_const(self, eval_ctx=None):
506 eval_ctx = get_eval_context(self, eval_ctx)
507 return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200508
509
Armin Ronacher8efc5222008-04-08 14:47:40 +0200510class Keyword(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200511 """A key, value pair for keyword arguments where key is a string."""
Armin Ronacher8efc5222008-04-08 14:47:40 +0200512 fields = ('key', 'value')
513
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 self.key, self.value.as_const(eval_ctx)
Armin Ronacher335b87a2008-09-21 17:08:48 +0200517
Armin Ronacher8efc5222008-04-08 14:47:40 +0200518
Armin Ronacher07bc6842008-03-31 14:18:49 +0200519class CondExpr(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200520 """A conditional expression (inline if expression). (``{{
521 foo if bar else baz }}``)
522 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200523 fields = ('test', 'expr1', 'expr2')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200524
Armin Ronacher8346bd72010-03-14 19:43:47 +0100525 def as_const(self, eval_ctx=None):
526 eval_ctx = get_eval_context(self, eval_ctx)
527 if self.test.as_const(eval_ctx):
528 return self.expr1.as_const(eval_ctx)
Armin Ronacher547d0b62008-07-04 16:35:10 +0200529
530 # if we evaluate to an undefined object, we better do that at runtime
531 if self.expr2 is None:
532 raise Impossible()
533
Armin Ronacher8346bd72010-03-14 19:43:47 +0100534 return self.expr2.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200535
536
537class Filter(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200538 """This node applies a filter on an expression. `name` is the name of
539 the filter, the rest of the fields are the same as for :class:`Call`.
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200540
541 If the `node` of a filter is `None` the contents of the last buffer are
542 filtered. Buffers are created by macros and filter blocks.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200543 """
Armin Ronacherd55ab532008-04-09 16:13:39 +0200544 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200545
Armin Ronacher8346bd72010-03-14 19:43:47 +0100546 def as_const(self, eval_ctx=None):
547 eval_ctx = get_eval_context(self, eval_ctx)
548 if eval_ctx.volatile or self.node is None:
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200549 raise Impossible()
Armin Ronacher0d242be2010-02-10 01:35:13 +0100550 # we have to be careful here because we call filter_ below.
551 # if this variable would be called filter, 2to3 would wrap the
552 # call in a list beause it is assuming we are talking about the
553 # builtin filter function here which no longer returns a list in
554 # python 3. because of that, do not rename filter_ to filter!
555 filter_ = self.environment.filters.get(self.name)
556 if filter_ is None or getattr(filter_, 'contextfilter', False):
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200557 raise Impossible()
Armin Ronacher8346bd72010-03-14 19:43:47 +0100558 obj = self.node.as_const(eval_ctx)
559 args = [x.as_const(eval_ctx) for x in self.args]
560 if getattr(filter_, 'evalcontextfilter', False):
561 args.insert(0, eval_ctx)
562 elif getattr(filter_, 'environmentfilter', False):
Armin Ronacher9a027f42008-04-17 11:13:40 +0200563 args.insert(0, self.environment)
Armin Ronacher8346bd72010-03-14 19:43:47 +0100564 kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
Armin Ronacherd55ab532008-04-09 16:13:39 +0200565 if self.dyn_args is not None:
566 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100567 args.extend(self.dyn_args.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900568 except Exception:
Armin Ronacherd55ab532008-04-09 16:13:39 +0200569 raise Impossible()
570 if self.dyn_kwargs is not None:
571 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100572 kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900573 except Exception:
Armin Ronacherd55ab532008-04-09 16:13:39 +0200574 raise Impossible()
575 try:
Armin Ronacher0d242be2010-02-10 01:35:13 +0100576 return filter_(obj, *args, **kwargs)
Ian Lewisab014bd2010-10-31 20:29:28 +0900577 except Exception:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200578 raise Impossible()
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200579
580
Armin Ronacher07bc6842008-03-31 14:18:49 +0200581class Test(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200582 """Applies a test on an expression. `name` is the name of the test, the
583 rest of the fields are the same as for :class:`Call`.
584 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200585 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200586
587
588class Call(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200589 """Calls an expression. `args` is a list of arguments, `kwargs` a list
590 of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
591 and `dyn_kwargs` has to be either `None` or a node that is used as
592 node for dynamic positional (``*args``) or keyword (``**kwargs``)
593 arguments.
594 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200595 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200596
Armin Ronacher8346bd72010-03-14 19:43:47 +0100597 def as_const(self, eval_ctx=None):
598 eval_ctx = get_eval_context(self, eval_ctx)
599 if eval_ctx.volatile:
600 raise Impossible()
601 obj = self.node.as_const(eval_ctx)
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200602
603 # don't evaluate context functions
Armin Ronacher8346bd72010-03-14 19:43:47 +0100604 args = [x.as_const(eval_ctx) for x in self.args]
Armin Ronacher5a5ce732010-05-23 22:58:28 +0200605 if isinstance(obj, _context_function_types):
606 if getattr(obj, 'contextfunction', False):
607 raise Impossible()
608 elif getattr(obj, 'evalcontextfunction', False):
609 args.insert(0, eval_ctx)
610 elif getattr(obj, 'environmentfunction', False):
611 args.insert(0, self.environment)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200612
Armin Ronacher8346bd72010-03-14 19:43:47 +0100613 kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200614 if self.dyn_args is not None:
615 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100616 args.extend(self.dyn_args.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900617 except Exception:
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200618 raise Impossible()
619 if self.dyn_kwargs is not None:
620 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100621 kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900622 except Exception:
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200623 raise Impossible()
624 try:
625 return obj(*args, **kwargs)
Ian Lewisab014bd2010-10-31 20:29:28 +0900626 except Exception:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200627 raise Impossible()
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200628
Armin Ronacher07bc6842008-03-31 14:18:49 +0200629
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200630class Getitem(Expr):
Armin Ronacherb9388772008-06-25 20:43:18 +0200631 """Get an attribute or item from an expression and prefer the item."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200632 fields = ('node', 'arg', 'ctx')
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 Ronacher4dfc9752008-04-09 15:03:29 +0200636 if self.ctx != 'load':
637 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200638 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100639 return self.environment.getitem(self.node.as_const(eval_ctx),
640 self.arg.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900641 except Exception:
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200642 raise Impossible()
643
644 def can_assign(self):
645 return False
646
647
648class Getattr(Expr):
Armin Ronacherb9388772008-06-25 20:43:18 +0200649 """Get an attribute or item from an expression that is a ascii-only
650 bytestring and prefer the attribute.
651 """
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200652 fields = ('node', 'attr', 'ctx')
653
Armin Ronacher8346bd72010-03-14 19:43:47 +0100654 def as_const(self, eval_ctx=None):
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200655 if self.ctx != 'load':
656 raise Impossible()
657 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100658 eval_ctx = get_eval_context(self, eval_ctx)
Georg Brandl93d2df72010-05-23 22:35:53 +0200659 return self.environment.getattr(self.node.as_const(eval_ctx),
660 self.attr)
Ian Lewisab014bd2010-10-31 20:29:28 +0900661 except Exception:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200662 raise Impossible()
663
664 def can_assign(self):
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200665 return False
Armin Ronacher07bc6842008-03-31 14:18:49 +0200666
667
668class Slice(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200669 """Represents a slice object. This must only be used as argument for
670 :class:`Subscript`.
671 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200672 fields = ('start', 'stop', 'step')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200673
Armin Ronacher8346bd72010-03-14 19:43:47 +0100674 def as_const(self, eval_ctx=None):
675 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200676 def const(obj):
677 if obj is None:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100678 return None
679 return obj.as_const(eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200680 return slice(const(self.start), const(self.stop), const(self.step))
681
Armin Ronacher07bc6842008-03-31 14:18:49 +0200682
683class Concat(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200684 """Concatenates the list of expressions provided after converting them to
685 unicode.
686 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200687 fields = ('nodes',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200688
Armin Ronacher8346bd72010-03-14 19:43:47 +0100689 def as_const(self, eval_ctx=None):
690 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronachere9098672013-05-19 14:16:13 +0100691 return ''.join(text_type(x.as_const(eval_ctx)) for x in self.nodes)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200692
693
694class Compare(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200695 """Compares an expression with some other expressions. `ops` must be a
696 list of :class:`Operand`\s.
697 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200698 fields = ('expr', 'ops')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200699
Armin Ronacher8346bd72010-03-14 19:43:47 +0100700 def as_const(self, eval_ctx=None):
701 eval_ctx = get_eval_context(self, eval_ctx)
702 result = value = self.expr.as_const(eval_ctx)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200703 try:
704 for op in self.ops:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100705 new_value = op.expr.as_const(eval_ctx)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200706 result = _cmpop_to_func[op.op](value, new_value)
707 value = new_value
Ian Lewisab014bd2010-10-31 20:29:28 +0900708 except Exception:
Armin Ronacherb5124e62008-04-25 00:36:14 +0200709 raise Impossible()
Armin Ronacher625215e2008-04-13 16:31:08 +0200710 return result
711
Armin Ronacher07bc6842008-03-31 14:18:49 +0200712
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200713class Operand(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200714 """Holds an operator and an expression."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200715 fields = ('op', 'expr')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200716
Armin Ronacher023b5e92008-05-08 11:03:10 +0200717if __debug__:
718 Operand.__doc__ += '\nThe following operators are available: ' + \
719 ', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
720 set(_uaop_to_func) | set(_cmpop_to_func)))
721
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200722
Armin Ronacher07bc6842008-03-31 14:18:49 +0200723class Mul(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200724 """Multiplies the left with the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200725 operator = '*'
726
727
728class Div(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200729 """Divides the left by the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200730 operator = '/'
731
732
733class FloorDiv(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200734 """Divides the left by the right node and truncates conver the
735 result into an integer by truncating.
736 """
Armin Ronacher07bc6842008-03-31 14:18:49 +0200737 operator = '//'
738
739
740class Add(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200741 """Add the left to the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200742 operator = '+'
743
744
745class Sub(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200746 """Substract the right from the left node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200747 operator = '-'
748
749
750class Mod(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200751 """Left modulo right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200752 operator = '%'
753
754
755class Pow(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200756 """Left to the power of right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200757 operator = '**'
758
759
760class And(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200761 """Short circuited AND."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200762 operator = 'and'
763
Armin Ronacher8346bd72010-03-14 19:43:47 +0100764 def as_const(self, eval_ctx=None):
765 eval_ctx = get_eval_context(self, eval_ctx)
766 return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200767
768
769class Or(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200770 """Short circuited OR."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200771 operator = 'or'
772
Armin Ronacher8346bd72010-03-14 19:43:47 +0100773 def as_const(self, eval_ctx=None):
774 eval_ctx = get_eval_context(self, eval_ctx)
775 return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200776
777
778class Not(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200779 """Negate the expression."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200780 operator = 'not'
781
782
Armin Ronachere791c2a2008-04-07 18:39:54 +0200783class Neg(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200784 """Make the expression negative."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200785 operator = '-'
786
787
Armin Ronachere791c2a2008-04-07 18:39:54 +0200788class Pos(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200789 """Make the expression positive (noop for most expressions)"""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200790 operator = '+'
Armin Ronacher023b5e92008-05-08 11:03:10 +0200791
792
793# Helpers for extensions
794
795
796class EnvironmentAttribute(Expr):
797 """Loads an attribute from the environment object. This is useful for
798 extensions that want to call a callback stored on the environment.
799 """
800 fields = ('name',)
801
802
803class ExtensionAttribute(Expr):
804 """Returns the attribute of an extension bound to the environment.
805 The identifier is the identifier of the :class:`Extension`.
Armin Ronacherb9e78752008-05-10 23:36:28 +0200806
807 This node is usually constructed by calling the
808 :meth:`~jinja2.ext.Extension.attr` method on an extension.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200809 """
Armin Ronacher6df604e2008-05-23 22:18:38 +0200810 fields = ('identifier', 'name')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200811
812
813class ImportedName(Expr):
814 """If created with an import name the import name is returned on node
815 access. For example ``ImportedName('cgi.escape')`` returns the `escape`
816 function from the cgi module on evaluation. Imports are optimized by the
817 compiler so there is no need to assign them to local variables.
818 """
819 fields = ('importname',)
820
821
822class InternalName(Expr):
823 """An internal name in the compiler. You cannot create these nodes
Armin Ronacher762079c2008-05-08 23:57:56 +0200824 yourself but the parser provides a
825 :meth:`~jinja2.parser.Parser.free_identifier` method that creates
Armin Ronacher023b5e92008-05-08 11:03:10 +0200826 a new identifier for you. This identifier is not available from the
827 template and is not threated specially by the compiler.
828 """
829 fields = ('name',)
830
831 def __init__(self):
832 raise TypeError('Can\'t create internal names. Use the '
833 '`free_identifier` method on a parser.')
834
835
836class MarkSafe(Expr):
837 """Mark the wrapped expression as safe (wrap it as `Markup`)."""
838 fields = ('expr',)
839
Armin Ronacher8346bd72010-03-14 19:43:47 +0100840 def as_const(self, eval_ctx=None):
841 eval_ctx = get_eval_context(self, eval_ctx)
842 return Markup(self.expr.as_const(eval_ctx))
Armin Ronacher023b5e92008-05-08 11:03:10 +0200843
844
Armin Ronacher4da90342010-05-29 17:35:10 +0200845class MarkSafeIfAutoescape(Expr):
846 """Mark the wrapped expression as safe (wrap it as `Markup`) but
847 only if autoescaping is active.
848
849 .. versionadded:: 2.5
850 """
851 fields = ('expr',)
852
853 def as_const(self, eval_ctx=None):
854 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacherffaa2e72010-05-29 20:57:16 +0200855 if eval_ctx.volatile:
856 raise Impossible()
Armin Ronacher4da90342010-05-29 17:35:10 +0200857 expr = self.expr.as_const(eval_ctx)
858 if eval_ctx.autoescape:
859 return Markup(expr)
860 return expr
861
862
Armin Ronacher6df604e2008-05-23 22:18:38 +0200863class ContextReference(Expr):
Armin Ronachercedb4822010-03-24 10:53:22 +0100864 """Returns the current template context. It can be used like a
865 :class:`Name` node, with a ``'load'`` ctx and will return the
866 current :class:`~jinja2.runtime.Context` object.
867
868 Here an example that assigns the current template name to a
869 variable named `foo`::
870
871 Assign(Name('foo', ctx='store'),
872 Getattr(ContextReference(), 'name'))
873 """
Armin Ronacher6df604e2008-05-23 22:18:38 +0200874
875
Armin Ronachered1e0d42008-05-18 20:25:28 +0200876class Continue(Stmt):
877 """Continue a loop."""
878
879
880class Break(Stmt):
881 """Break a loop."""
882
883
Armin Ronacher271a0eb2009-02-11 22:49:08 +0100884class Scope(Stmt):
885 """An artificial scope."""
886 fields = ('body',)
887
888
Armin Ronacher8346bd72010-03-14 19:43:47 +0100889class EvalContextModifier(Stmt):
Armin Ronacher30fda272010-03-15 03:06:04 +0100890 """Modifies the eval context. For each option that should be modified,
891 a :class:`Keyword` has to be added to the :attr:`options` list.
892
893 Example to change the `autoescape` setting::
894
895 EvalContextModifier(options=[Keyword('autoescape', Const(True))])
896 """
Armin Ronacher8346bd72010-03-14 19:43:47 +0100897 fields = ('options',)
898
899
900class ScopedEvalContextModifier(EvalContextModifier):
Armin Ronacher30fda272010-03-15 03:06:04 +0100901 """Modifies the eval context and reverts it later. Works exactly like
902 :class:`EvalContextModifier` but will only modify the
Armin Ronacher0dbaf392010-03-15 10:06:53 +0100903 :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.
Armin Ronacher30fda272010-03-15 03:06:04 +0100904 """
Armin Ronacher8346bd72010-03-14 19:43:47 +0100905 fields = ('body',)
906
907
Armin Ronacher8a1d27f2008-05-19 08:37:19 +0200908# make sure nobody creates custom nodes
909def _failing_new(*args, **kwargs):
910 raise TypeError('can\'t create custom node types')
911NodeType.__new__ = staticmethod(_failing_new); del _failing_new