blob: e276f7ef1ff6cc9af3e70809c1acfd4a86de41cf [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 Ronacherc87d4cf2013-05-19 13:46:22 +010015import six
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 Ronacher5a5ce732010-05-23 22:58:28 +020019from jinja2.utils import Markup, MethodType, FunctionType
Armin Ronacherc87d4cf2013-05-19 13:46:22 +010020from jinja2._compat import next
Thomas Waldmann7d295622013-05-18 00:06:22 +020021from six.moves import zip
Armin Ronacher5a5ce732010-05-23 22:58:28 +020022
23
24#: the types we support for context functions
25_context_function_types = (FunctionType, MethodType)
Armin Ronacher07bc6842008-03-31 14:18:49 +020026
27
28_binop_to_func = {
29 '*': operator.mul,
30 '/': operator.truediv,
31 '//': operator.floordiv,
32 '**': operator.pow,
33 '%': operator.mod,
34 '+': operator.add,
35 '-': operator.sub
36}
37
38_uaop_to_func = {
39 'not': operator.not_,
40 '+': operator.pos,
41 '-': operator.neg
42}
43
Armin Ronacher625215e2008-04-13 16:31:08 +020044_cmpop_to_func = {
45 'eq': operator.eq,
46 'ne': operator.ne,
47 'gt': operator.gt,
48 'gteq': operator.ge,
49 'lt': operator.lt,
50 'lteq': operator.le,
Armin Ronacherb5124e62008-04-25 00:36:14 +020051 'in': lambda a, b: a in b,
52 'notin': lambda a, b: a not in b
Armin Ronacher625215e2008-04-13 16:31:08 +020053}
54
Armin Ronacher07bc6842008-03-31 14:18:49 +020055
56class Impossible(Exception):
Armin Ronacher8efc5222008-04-08 14:47:40 +020057 """Raised if the node could not perform a requested action."""
Armin Ronacher07bc6842008-03-31 14:18:49 +020058
59
60class NodeType(type):
Armin Ronacher8efc5222008-04-08 14:47:40 +020061 """A metaclass for nodes that handles the field and attribute
62 inheritance. fields and attributes from the parent class are
63 automatically forwarded to the child."""
Armin Ronacher07bc6842008-03-31 14:18:49 +020064
65 def __new__(cls, name, bases, d):
Armin Ronachere791c2a2008-04-07 18:39:54 +020066 for attr in 'fields', 'attributes':
Armin Ronacher07bc6842008-03-31 14:18:49 +020067 storage = []
Armin Ronacher7324eb82008-04-21 07:55:52 +020068 storage.extend(getattr(bases[0], attr, ()))
Armin Ronacher07bc6842008-03-31 14:18:49 +020069 storage.extend(d.get(attr, ()))
Armin Ronacher7324eb82008-04-21 07:55:52 +020070 assert len(bases) == 1, 'multiple inheritance not allowed'
71 assert len(storage) == len(set(storage)), 'layout conflict'
Armin Ronacher07bc6842008-03-31 14:18:49 +020072 d[attr] = tuple(storage)
Armin Ronacher023b5e92008-05-08 11:03:10 +020073 d.setdefault('abstract', False)
Armin Ronacher7324eb82008-04-21 07:55:52 +020074 return type.__new__(cls, name, bases, d)
Armin Ronacher07bc6842008-03-31 14:18:49 +020075
76
Armin Ronacher8346bd72010-03-14 19:43:47 +010077class EvalContext(object):
Armin Ronacher30fda272010-03-15 03:06:04 +010078 """Holds evaluation time information. Custom attributes can be attached
79 to it in extensions.
80 """
Armin Ronacher8346bd72010-03-14 19:43:47 +010081
Armin Ronacher1da23d12010-04-05 18:11:18 +020082 def __init__(self, environment, template_name=None):
Armin Ronacher3383e1c2011-01-24 01:13:51 +010083 self.environment = environment
Armin Ronacher1da23d12010-04-05 18:11:18 +020084 if callable(environment.autoescape):
85 self.autoescape = environment.autoescape(template_name)
86 else:
87 self.autoescape = environment.autoescape
Armin Ronacher8346bd72010-03-14 19:43:47 +010088 self.volatile = False
89
90 def save(self):
91 return self.__dict__.copy()
92
93 def revert(self, old):
94 self.__dict__.clear()
95 self.__dict__.update(old)
96
97
98def get_eval_context(node, ctx):
99 if ctx is None:
100 if node.environment is None:
101 raise RuntimeError('if no eval context is passed, the '
102 'node must have an attached '
103 'environment.')
104 return EvalContext(node.environment)
105 return ctx
106
107
Thomas Waldmann7d295622013-05-18 00:06:22 +0200108class Node(six.with_metaclass(NodeType, object)):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200109 """Baseclass for all Jinja2 nodes. There are a number of nodes available
kracekumar9c198cd2011-11-25 08:26:55 +0530110 of different types. There are four major types:
Armin Ronacher023b5e92008-05-08 11:03:10 +0200111
112 - :class:`Stmt`: statements
113 - :class:`Expr`: expressions
114 - :class:`Helper`: helper nodes
115 - :class:`Template`: the outermost wrapper node
116
117 All nodes have fields and attributes. Fields may be other nodes, lists,
118 or arbitrary values. Fields are passed to the constructor as regular
119 positional arguments, attributes as keyword arguments. Each node has
120 two attributes: `lineno` (the line number of the node) and `environment`.
121 The `environment` attribute is set at the end of the parsing process for
122 all nodes automatically.
123 """
Armin Ronacher07bc6842008-03-31 14:18:49 +0200124 __metaclass__ = NodeType
Armin Ronachere791c2a2008-04-07 18:39:54 +0200125 fields = ()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200126 attributes = ('lineno', 'environment')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200127 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200128
Armin Ronacher023b5e92008-05-08 11:03:10 +0200129 def __init__(self, *fields, **attributes):
Armin Ronacher69e12db2008-05-12 09:00:03 +0200130 if self.abstract:
131 raise TypeError('abstract nodes are not instanciable')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200132 if fields:
133 if len(fields) != len(self.fields):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200134 if not self.fields:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200135 raise TypeError('%r takes 0 arguments' %
136 self.__class__.__name__)
137 raise TypeError('%r takes 0 or %d argument%s' % (
138 self.__class__.__name__,
Armin Ronachere791c2a2008-04-07 18:39:54 +0200139 len(self.fields),
140 len(self.fields) != 1 and 's' or ''
Armin Ronacher07bc6842008-03-31 14:18:49 +0200141 ))
Thomas Waldmann7d295622013-05-18 00:06:22 +0200142 for name, arg in zip(self.fields, fields):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200143 setattr(self, name, arg)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200144 for attr in self.attributes:
Armin Ronacher023b5e92008-05-08 11:03:10 +0200145 setattr(self, attr, attributes.pop(attr, None))
146 if attributes:
147 raise TypeError('unknown attribute %r' %
Armin Ronacherc87d4cf2013-05-19 13:46:22 +0100148 next(iter(attributes)))
Armin Ronacher07bc6842008-03-31 14:18:49 +0200149
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200150 def iter_fields(self, exclude=None, only=None):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200151 """This method iterates over all fields that are defined and yields
Armin Ronacher3da90312008-05-23 16:37:28 +0200152 ``(key, value)`` tuples. Per default all fields are returned, but
153 it's possible to limit that to some fields by providing the `only`
154 parameter or to exclude some using the `exclude` parameter. Both
155 should be sets or tuples of field names.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200156 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200157 for name in self.fields:
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200158 if (exclude is only is None) or \
159 (exclude is not None and name not in exclude) or \
160 (only is not None and name in only):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200161 try:
162 yield name, getattr(self, name)
163 except AttributeError:
164 pass
Armin Ronacher07bc6842008-03-31 14:18:49 +0200165
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200166 def iter_child_nodes(self, exclude=None, only=None):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200167 """Iterates over all direct child nodes of the node. This iterates
168 over all fields and yields the values of they are nodes. If the value
169 of a field is a list all the nodes in that list are returned.
170 """
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200171 for field, item in self.iter_fields(exclude, only):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200172 if isinstance(item, list):
173 for n in item:
174 if isinstance(n, Node):
175 yield n
176 elif isinstance(item, Node):
177 yield item
178
Armin Ronachere791c2a2008-04-07 18:39:54 +0200179 def find(self, node_type):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200180 """Find the first node of a given type. If no such node exists the
181 return value is `None`.
182 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200183 for result in self.find_all(node_type):
184 return result
185
186 def find_all(self, node_type):
Armin Ronacher63cf9b82009-07-26 10:33:36 +0200187 """Find all the nodes of a given type. If the type is a tuple,
188 the check is performed for any of the tuple items.
189 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200190 for child in self.iter_child_nodes():
191 if isinstance(child, node_type):
192 yield child
193 for result in child.find_all(node_type):
194 yield result
195
196 def set_ctx(self, ctx):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200197 """Reset the context of a node and all child nodes. Per default the
198 parser will all generate nodes that have a 'load' context as it's the
199 most common one. This method is used in the parser to set assignment
200 targets and other nodes to a store context.
Armin Ronachere791c2a2008-04-07 18:39:54 +0200201 """
202 todo = deque([self])
203 while todo:
204 node = todo.popleft()
205 if 'ctx' in node.fields:
206 node.ctx = ctx
207 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200208 return self
Armin Ronachere791c2a2008-04-07 18:39:54 +0200209
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200210 def set_lineno(self, lineno, override=False):
211 """Set the line numbers of the node and children."""
212 todo = deque([self])
213 while todo:
214 node = todo.popleft()
215 if 'lineno' in node.attributes:
216 if node.lineno is None or override:
217 node.lineno = lineno
218 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200219 return self
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200220
Armin Ronacherd55ab532008-04-09 16:13:39 +0200221 def set_environment(self, environment):
222 """Set the environment for all nodes."""
223 todo = deque([self])
224 while todo:
225 node = todo.popleft()
226 node.environment = environment
227 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200228 return self
Armin Ronacherd55ab532008-04-09 16:13:39 +0200229
Armin Ronacher69e12db2008-05-12 09:00:03 +0200230 def __eq__(self, other):
Armin Ronacherb3a1fcf2008-05-15 11:04:14 +0200231 return type(self) is type(other) and \
232 tuple(self.iter_fields()) == tuple(other.iter_fields())
Armin Ronacher69e12db2008-05-12 09:00:03 +0200233
234 def __ne__(self, other):
235 return not self.__eq__(other)
236
Armin Ronacher07bc6842008-03-31 14:18:49 +0200237 def __repr__(self):
238 return '%s(%s)' % (
239 self.__class__.__name__,
240 ', '.join('%s=%r' % (arg, getattr(self, arg, None)) for
Armin Ronachere791c2a2008-04-07 18:39:54 +0200241 arg in self.fields)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200242 )
243
244
245class Stmt(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200246 """Base node for all statements."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200247 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200248
249
250class Helper(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200251 """Nodes that exist in a specific context only."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200252 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200253
254
255class Template(Node):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200256 """Node that represents a template. This must be the outermost node that
257 is passed to the compiler.
258 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200259 fields = ('body',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200260
261
262class Output(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200263 """A node that holds multiple expressions which are then printed out.
264 This is used both for the `print` statement and the regular template data.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200265 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200266 fields = ('nodes',)
267
Armin Ronacher07bc6842008-03-31 14:18:49 +0200268
269class Extends(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200270 """Represents an extends statement."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200271 fields = ('template',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200272
273
274class For(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200275 """The for loop. `target` is the target for the iteration (usually a
276 :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list
277 of nodes that are used as loop-body, and `else_` a list of nodes for the
278 `else` block. If no else node exists it has to be an empty list.
279
280 For filtered nodes an expression can be stored as `test`, otherwise `None`.
281 """
Armin Ronacherfdf95302008-05-11 22:20:51 +0200282 fields = ('target', 'iter', 'body', 'else_', 'test', 'recursive')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200283
284
285class If(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200286 """If `test` is true, `body` is rendered, else `else_`."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200287 fields = ('test', 'body', 'else_')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200288
289
290class Macro(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200291 """A macro definition. `name` is the name of the macro, `args` a list of
292 arguments and `defaults` a list of defaults if there are any. `body` is
293 a list of nodes for the macro body.
294 """
Armin Ronacher8efc5222008-04-08 14:47:40 +0200295 fields = ('name', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200296
297
298class CallBlock(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200299 """Like a macro without a name but a call instead. `call` is called with
300 the unnamed macro as `caller` argument this node holds.
301 """
Armin Ronacherc9705c22008-04-27 21:28:03 +0200302 fields = ('call', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200303
304
Armin Ronacher07bc6842008-03-31 14:18:49 +0200305class FilterBlock(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200306 """Node for filter sections."""
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200307 fields = ('body', 'filter')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200308
309
310class Block(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200311 """A node that represents a block."""
Armin Ronacher74a0cd92009-02-19 15:56:53 +0100312 fields = ('name', 'body', 'scoped')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200313
314
315class Include(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200316 """A node that represents the include tag."""
Armin Ronacher37f58ce2008-12-27 13:10:38 +0100317 fields = ('template', 'with_context', 'ignore_missing')
Armin Ronacher0611e492008-04-25 23:44:14 +0200318
319
320class Import(Stmt):
321 """A node that represents the import tag."""
Armin Ronacherea847c52008-05-02 20:04:32 +0200322 fields = ('template', 'target', 'with_context')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200323
324
Armin Ronacher0611e492008-04-25 23:44:14 +0200325class FromImport(Stmt):
326 """A node that represents the from import tag. It's important to not
327 pass unsafe names to the name attribute. The compiler translates the
328 attribute lookups directly into getattr calls and does *not* use the
Armin Ronacherb9388772008-06-25 20:43:18 +0200329 subscript callback of the interface. As exported variables may not
Armin Ronacher0611e492008-04-25 23:44:14 +0200330 start with double underscores (which the parser asserts) this is not a
331 problem for regular Jinja code, but if this node is used in an extension
332 extra care must be taken.
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200333
334 The list of names may contain tuples if aliases are wanted.
Armin Ronacher0611e492008-04-25 23:44:14 +0200335 """
Armin Ronacherea847c52008-05-02 20:04:32 +0200336 fields = ('template', 'names', 'with_context')
Armin Ronacher0611e492008-04-25 23:44:14 +0200337
338
Armin Ronacher07bc6842008-03-31 14:18:49 +0200339class ExprStmt(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200340 """A statement that evaluates an expression and discards the result."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200341 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200342
343
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200344class Assign(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200345 """Assigns an expression to a target."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200346 fields = ('target', 'node')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200347
348
Armin Ronacher07bc6842008-03-31 14:18:49 +0200349class Expr(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200350 """Baseclass for all expressions."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200351 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200352
Armin Ronacher8346bd72010-03-14 19:43:47 +0100353 def as_const(self, eval_ctx=None):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200354 """Return the value of the expression as constant or raise
Armin Ronacher8346bd72010-03-14 19:43:47 +0100355 :exc:`Impossible` if this was not possible.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200356
Armin Ronacher8346bd72010-03-14 19:43:47 +0100357 An :class:`EvalContext` can be provided, if none is given
358 a default context is created which requires the nodes to have
359 an attached environment.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200360
Armin Ronacher8346bd72010-03-14 19:43:47 +0100361 .. versionchanged:: 2.4
362 the `eval_ctx` parameter was added.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200363 """
364 raise Impossible()
365
366 def can_assign(self):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200367 """Check if it's possible to assign something to this node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200368 return False
369
370
371class BinExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200372 """Baseclass for all binary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200373 fields = ('left', 'right')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200374 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200375 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200376
Armin Ronacher8346bd72010-03-14 19:43:47 +0100377 def as_const(self, eval_ctx=None):
378 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronachera9195382010-11-29 13:21:57 +0100379 # intercepted operators cannot be folded at compile time
380 if self.environment.sandboxed and \
381 self.operator in self.environment.intercepted_binops:
382 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200383 f = _binop_to_func[self.operator]
384 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100385 return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900386 except Exception:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200387 raise Impossible()
388
389
390class UnaryExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200391 """Baseclass for all unary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200392 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200393 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200394 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200395
Armin Ronacher8346bd72010-03-14 19:43:47 +0100396 def as_const(self, eval_ctx=None):
397 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronachera9195382010-11-29 13:21:57 +0100398 # intercepted operators cannot be folded at compile time
399 if self.environment.sandboxed and \
400 self.operator in self.environment.intercepted_unops:
401 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200402 f = _uaop_to_func[self.operator]
403 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100404 return f(self.node.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900405 except Exception:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200406 raise Impossible()
407
408
409class Name(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200410 """Looks up a name or stores a value in a name.
411 The `ctx` of the node can be one of the following values:
412
413 - `store`: store a value in the name
414 - `load`: load that name
415 - `param`: like `store` but if the name was defined as function parameter.
416 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200417 fields = ('name', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200418
419 def can_assign(self):
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200420 return self.name not in ('true', 'false', 'none',
421 'True', 'False', 'None')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200422
423
424class Literal(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200425 """Baseclass for literals."""
Armin Ronacher69e12db2008-05-12 09:00:03 +0200426 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200427
428
429class Const(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200430 """All constant values. The parser will return this node for simple
431 constants such as ``42`` or ``"foo"`` but it can be used to store more
432 complex values such as lists too. Only constants with a safe
433 representation (objects where ``eval(repr(x)) == x`` is true).
434 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200435 fields = ('value',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200436
Armin Ronacher8346bd72010-03-14 19:43:47 +0100437 def as_const(self, eval_ctx=None):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200438 return self.value
439
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200440 @classmethod
Armin Ronacherd55ab532008-04-09 16:13:39 +0200441 def from_untrusted(cls, value, lineno=None, environment=None):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200442 """Return a const object if the value is representable as
443 constant value in the generated code, otherwise it will raise
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200444 an `Impossible` exception.
445 """
Thomas Waldmanne0003552013-05-17 23:52:14 +0200446 from .compiler import has_safe_repr
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200447 if not has_safe_repr(value):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200448 raise Impossible()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200449 return cls(value, lineno=lineno, environment=environment)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200450
Armin Ronacher07bc6842008-03-31 14:18:49 +0200451
Armin Ronacher5411ce72008-05-25 11:36:22 +0200452class TemplateData(Literal):
453 """A constant template string."""
454 fields = ('data',)
455
Armin Ronacher8346bd72010-03-14 19:43:47 +0100456 def as_const(self, eval_ctx=None):
Armin Ronacherffaa2e72010-05-29 20:57:16 +0200457 eval_ctx = get_eval_context(self, eval_ctx)
458 if eval_ctx.volatile:
459 raise Impossible()
460 if eval_ctx.autoescape:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200461 return Markup(self.data)
462 return self.data
463
464
Armin Ronacher07bc6842008-03-31 14:18:49 +0200465class Tuple(Literal):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200466 """For loop unpacking and some other things like multiple arguments
Armin Ronacher023b5e92008-05-08 11:03:10 +0200467 for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
468 is used for loading the names or storing.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200469 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200470 fields = ('items', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200471
Armin Ronacher8346bd72010-03-14 19:43:47 +0100472 def as_const(self, eval_ctx=None):
473 eval_ctx = get_eval_context(self, eval_ctx)
474 return tuple(x.as_const(eval_ctx) for x in self.items)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200475
476 def can_assign(self):
477 for item in self.items:
478 if not item.can_assign():
479 return False
480 return True
481
482
483class List(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200484 """Any list literal such as ``[1, 2, 3]``"""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200485 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200486
Armin Ronacher8346bd72010-03-14 19:43:47 +0100487 def as_const(self, eval_ctx=None):
488 eval_ctx = get_eval_context(self, eval_ctx)
489 return [x.as_const(eval_ctx) for x in self.items]
Armin Ronacher07bc6842008-03-31 14:18:49 +0200490
491
492class Dict(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200493 """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
494 :class:`Pair` nodes.
495 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200496 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200497
Armin Ronacher8346bd72010-03-14 19:43:47 +0100498 def as_const(self, eval_ctx=None):
499 eval_ctx = get_eval_context(self, eval_ctx)
500 return dict(x.as_const(eval_ctx) for x in self.items)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200501
502
503class Pair(Helper):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200504 """A key, value pair for dicts."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200505 fields = ('key', 'value')
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 self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200510
511
Armin Ronacher8efc5222008-04-08 14:47:40 +0200512class Keyword(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200513 """A key, value pair for keyword arguments where key is a string."""
Armin Ronacher8efc5222008-04-08 14:47:40 +0200514 fields = ('key', 'value')
515
Armin Ronacher8346bd72010-03-14 19:43:47 +0100516 def as_const(self, eval_ctx=None):
517 eval_ctx = get_eval_context(self, eval_ctx)
518 return self.key, self.value.as_const(eval_ctx)
Armin Ronacher335b87a2008-09-21 17:08:48 +0200519
Armin Ronacher8efc5222008-04-08 14:47:40 +0200520
Armin Ronacher07bc6842008-03-31 14:18:49 +0200521class CondExpr(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200522 """A conditional expression (inline if expression). (``{{
523 foo if bar else baz }}``)
524 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200525 fields = ('test', 'expr1', 'expr2')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200526
Armin Ronacher8346bd72010-03-14 19:43:47 +0100527 def as_const(self, eval_ctx=None):
528 eval_ctx = get_eval_context(self, eval_ctx)
529 if self.test.as_const(eval_ctx):
530 return self.expr1.as_const(eval_ctx)
Armin Ronacher547d0b62008-07-04 16:35:10 +0200531
532 # if we evaluate to an undefined object, we better do that at runtime
533 if self.expr2 is None:
534 raise Impossible()
535
Armin Ronacher8346bd72010-03-14 19:43:47 +0100536 return self.expr2.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200537
538
539class Filter(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200540 """This node applies a filter on an expression. `name` is the name of
541 the filter, the rest of the fields are the same as for :class:`Call`.
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200542
543 If the `node` of a filter is `None` the contents of the last buffer are
544 filtered. Buffers are created by macros and filter blocks.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200545 """
Armin Ronacherd55ab532008-04-09 16:13:39 +0200546 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200547
Armin Ronacher8346bd72010-03-14 19:43:47 +0100548 def as_const(self, eval_ctx=None):
549 eval_ctx = get_eval_context(self, eval_ctx)
550 if eval_ctx.volatile or self.node is None:
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200551 raise Impossible()
Armin Ronacher0d242be2010-02-10 01:35:13 +0100552 # we have to be careful here because we call filter_ below.
553 # if this variable would be called filter, 2to3 would wrap the
554 # call in a list beause it is assuming we are talking about the
555 # builtin filter function here which no longer returns a list in
556 # python 3. because of that, do not rename filter_ to filter!
557 filter_ = self.environment.filters.get(self.name)
558 if filter_ is None or getattr(filter_, 'contextfilter', False):
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200559 raise Impossible()
Armin Ronacher8346bd72010-03-14 19:43:47 +0100560 obj = self.node.as_const(eval_ctx)
561 args = [x.as_const(eval_ctx) for x in self.args]
562 if getattr(filter_, 'evalcontextfilter', False):
563 args.insert(0, eval_ctx)
564 elif getattr(filter_, 'environmentfilter', False):
Armin Ronacher9a027f42008-04-17 11:13:40 +0200565 args.insert(0, self.environment)
Armin Ronacher8346bd72010-03-14 19:43:47 +0100566 kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
Armin Ronacherd55ab532008-04-09 16:13:39 +0200567 if self.dyn_args is not None:
568 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100569 args.extend(self.dyn_args.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900570 except Exception:
Armin Ronacherd55ab532008-04-09 16:13:39 +0200571 raise Impossible()
572 if self.dyn_kwargs is not None:
573 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100574 kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900575 except Exception:
Armin Ronacherd55ab532008-04-09 16:13:39 +0200576 raise Impossible()
577 try:
Armin Ronacher0d242be2010-02-10 01:35:13 +0100578 return filter_(obj, *args, **kwargs)
Ian Lewisab014bd2010-10-31 20:29:28 +0900579 except Exception:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200580 raise Impossible()
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200581
582
Armin Ronacher07bc6842008-03-31 14:18:49 +0200583class Test(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200584 """Applies a test on an expression. `name` is the name of the test, the
585 rest of the fields are the same as for :class:`Call`.
586 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200587 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200588
589
590class Call(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200591 """Calls an expression. `args` is a list of arguments, `kwargs` a list
592 of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
593 and `dyn_kwargs` has to be either `None` or a node that is used as
594 node for dynamic positional (``*args``) or keyword (``**kwargs``)
595 arguments.
596 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200597 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200598
Armin Ronacher8346bd72010-03-14 19:43:47 +0100599 def as_const(self, eval_ctx=None):
600 eval_ctx = get_eval_context(self, eval_ctx)
601 if eval_ctx.volatile:
602 raise Impossible()
603 obj = self.node.as_const(eval_ctx)
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200604
605 # don't evaluate context functions
Armin Ronacher8346bd72010-03-14 19:43:47 +0100606 args = [x.as_const(eval_ctx) for x in self.args]
Armin Ronacher5a5ce732010-05-23 22:58:28 +0200607 if isinstance(obj, _context_function_types):
608 if getattr(obj, 'contextfunction', False):
609 raise Impossible()
610 elif getattr(obj, 'evalcontextfunction', False):
611 args.insert(0, eval_ctx)
612 elif getattr(obj, 'environmentfunction', False):
613 args.insert(0, self.environment)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200614
Armin Ronacher8346bd72010-03-14 19:43:47 +0100615 kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
Armin Ronacher4dfc9752008-04-09 15:03:29 +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 Ronacher4dfc9752008-04-09 15:03:29 +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 Ronacher4dfc9752008-04-09 15:03:29 +0200625 raise Impossible()
626 try:
627 return obj(*args, **kwargs)
Ian Lewisab014bd2010-10-31 20:29:28 +0900628 except Exception:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200629 raise Impossible()
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200630
Armin Ronacher07bc6842008-03-31 14:18:49 +0200631
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200632class Getitem(Expr):
Armin Ronacherb9388772008-06-25 20:43:18 +0200633 """Get an attribute or item from an expression and prefer the item."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200634 fields = ('node', 'arg', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200635
Armin Ronacher8346bd72010-03-14 19:43:47 +0100636 def as_const(self, eval_ctx=None):
637 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200638 if self.ctx != 'load':
639 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200640 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100641 return self.environment.getitem(self.node.as_const(eval_ctx),
642 self.arg.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900643 except Exception:
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200644 raise Impossible()
645
646 def can_assign(self):
647 return False
648
649
650class Getattr(Expr):
Armin Ronacherb9388772008-06-25 20:43:18 +0200651 """Get an attribute or item from an expression that is a ascii-only
652 bytestring and prefer the attribute.
653 """
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200654 fields = ('node', 'attr', 'ctx')
655
Armin Ronacher8346bd72010-03-14 19:43:47 +0100656 def as_const(self, eval_ctx=None):
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200657 if self.ctx != 'load':
658 raise Impossible()
659 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100660 eval_ctx = get_eval_context(self, eval_ctx)
Georg Brandl93d2df72010-05-23 22:35:53 +0200661 return self.environment.getattr(self.node.as_const(eval_ctx),
662 self.attr)
Ian Lewisab014bd2010-10-31 20:29:28 +0900663 except Exception:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200664 raise Impossible()
665
666 def can_assign(self):
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200667 return False
Armin Ronacher07bc6842008-03-31 14:18:49 +0200668
669
670class Slice(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200671 """Represents a slice object. This must only be used as argument for
672 :class:`Subscript`.
673 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200674 fields = ('start', 'stop', 'step')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200675
Armin Ronacher8346bd72010-03-14 19:43:47 +0100676 def as_const(self, eval_ctx=None):
677 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200678 def const(obj):
679 if obj is None:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100680 return None
681 return obj.as_const(eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200682 return slice(const(self.start), const(self.stop), const(self.step))
683
Armin Ronacher07bc6842008-03-31 14:18:49 +0200684
685class Concat(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200686 """Concatenates the list of expressions provided after converting them to
687 unicode.
688 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200689 fields = ('nodes',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200690
Armin Ronacher8346bd72010-03-14 19:43:47 +0100691 def as_const(self, eval_ctx=None):
692 eval_ctx = get_eval_context(self, eval_ctx)
Thomas Waldmanne0003552013-05-17 23:52:14 +0200693 return ''.join(six.text_type(x.as_const(eval_ctx)) for x in self.nodes)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200694
695
696class Compare(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200697 """Compares an expression with some other expressions. `ops` must be a
698 list of :class:`Operand`\s.
699 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200700 fields = ('expr', 'ops')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200701
Armin Ronacher8346bd72010-03-14 19:43:47 +0100702 def as_const(self, eval_ctx=None):
703 eval_ctx = get_eval_context(self, eval_ctx)
704 result = value = self.expr.as_const(eval_ctx)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200705 try:
706 for op in self.ops:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100707 new_value = op.expr.as_const(eval_ctx)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200708 result = _cmpop_to_func[op.op](value, new_value)
709 value = new_value
Ian Lewisab014bd2010-10-31 20:29:28 +0900710 except Exception:
Armin Ronacherb5124e62008-04-25 00:36:14 +0200711 raise Impossible()
Armin Ronacher625215e2008-04-13 16:31:08 +0200712 return result
713
Armin Ronacher07bc6842008-03-31 14:18:49 +0200714
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200715class Operand(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200716 """Holds an operator and an expression."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200717 fields = ('op', 'expr')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200718
Armin Ronacher023b5e92008-05-08 11:03:10 +0200719if __debug__:
720 Operand.__doc__ += '\nThe following operators are available: ' + \
721 ', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
722 set(_uaop_to_func) | set(_cmpop_to_func)))
723
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200724
Armin Ronacher07bc6842008-03-31 14:18:49 +0200725class Mul(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200726 """Multiplies the left with the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200727 operator = '*'
728
729
730class Div(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200731 """Divides the left by the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200732 operator = '/'
733
734
735class FloorDiv(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200736 """Divides the left by the right node and truncates conver the
737 result into an integer by truncating.
738 """
Armin Ronacher07bc6842008-03-31 14:18:49 +0200739 operator = '//'
740
741
742class Add(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200743 """Add the left to the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200744 operator = '+'
745
746
747class Sub(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200748 """Substract the right from the left node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200749 operator = '-'
750
751
752class Mod(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200753 """Left modulo right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200754 operator = '%'
755
756
757class Pow(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200758 """Left to the power of right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200759 operator = '**'
760
761
762class And(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200763 """Short circuited AND."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200764 operator = 'and'
765
Armin Ronacher8346bd72010-03-14 19:43:47 +0100766 def as_const(self, eval_ctx=None):
767 eval_ctx = get_eval_context(self, eval_ctx)
768 return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200769
770
771class Or(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200772 """Short circuited OR."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200773 operator = 'or'
774
Armin Ronacher8346bd72010-03-14 19:43:47 +0100775 def as_const(self, eval_ctx=None):
776 eval_ctx = get_eval_context(self, eval_ctx)
777 return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200778
779
780class Not(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200781 """Negate the expression."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200782 operator = 'not'
783
784
Armin Ronachere791c2a2008-04-07 18:39:54 +0200785class Neg(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200786 """Make the expression negative."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200787 operator = '-'
788
789
Armin Ronachere791c2a2008-04-07 18:39:54 +0200790class Pos(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200791 """Make the expression positive (noop for most expressions)"""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200792 operator = '+'
Armin Ronacher023b5e92008-05-08 11:03:10 +0200793
794
795# Helpers for extensions
796
797
798class EnvironmentAttribute(Expr):
799 """Loads an attribute from the environment object. This is useful for
800 extensions that want to call a callback stored on the environment.
801 """
802 fields = ('name',)
803
804
805class ExtensionAttribute(Expr):
806 """Returns the attribute of an extension bound to the environment.
807 The identifier is the identifier of the :class:`Extension`.
Armin Ronacherb9e78752008-05-10 23:36:28 +0200808
809 This node is usually constructed by calling the
810 :meth:`~jinja2.ext.Extension.attr` method on an extension.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200811 """
Armin Ronacher6df604e2008-05-23 22:18:38 +0200812 fields = ('identifier', 'name')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200813
814
815class ImportedName(Expr):
816 """If created with an import name the import name is returned on node
817 access. For example ``ImportedName('cgi.escape')`` returns the `escape`
818 function from the cgi module on evaluation. Imports are optimized by the
819 compiler so there is no need to assign them to local variables.
820 """
821 fields = ('importname',)
822
823
824class InternalName(Expr):
825 """An internal name in the compiler. You cannot create these nodes
Armin Ronacher762079c2008-05-08 23:57:56 +0200826 yourself but the parser provides a
827 :meth:`~jinja2.parser.Parser.free_identifier` method that creates
Armin Ronacher023b5e92008-05-08 11:03:10 +0200828 a new identifier for you. This identifier is not available from the
829 template and is not threated specially by the compiler.
830 """
831 fields = ('name',)
832
833 def __init__(self):
834 raise TypeError('Can\'t create internal names. Use the '
835 '`free_identifier` method on a parser.')
836
837
838class MarkSafe(Expr):
839 """Mark the wrapped expression as safe (wrap it as `Markup`)."""
840 fields = ('expr',)
841
Armin Ronacher8346bd72010-03-14 19:43:47 +0100842 def as_const(self, eval_ctx=None):
843 eval_ctx = get_eval_context(self, eval_ctx)
844 return Markup(self.expr.as_const(eval_ctx))
Armin Ronacher023b5e92008-05-08 11:03:10 +0200845
846
Armin Ronacher4da90342010-05-29 17:35:10 +0200847class MarkSafeIfAutoescape(Expr):
848 """Mark the wrapped expression as safe (wrap it as `Markup`) but
849 only if autoescaping is active.
850
851 .. versionadded:: 2.5
852 """
853 fields = ('expr',)
854
855 def as_const(self, eval_ctx=None):
856 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacherffaa2e72010-05-29 20:57:16 +0200857 if eval_ctx.volatile:
858 raise Impossible()
Armin Ronacher4da90342010-05-29 17:35:10 +0200859 expr = self.expr.as_const(eval_ctx)
860 if eval_ctx.autoescape:
861 return Markup(expr)
862 return expr
863
864
Armin Ronacher6df604e2008-05-23 22:18:38 +0200865class ContextReference(Expr):
Armin Ronachercedb4822010-03-24 10:53:22 +0100866 """Returns the current template context. It can be used like a
867 :class:`Name` node, with a ``'load'`` ctx and will return the
868 current :class:`~jinja2.runtime.Context` object.
869
870 Here an example that assigns the current template name to a
871 variable named `foo`::
872
873 Assign(Name('foo', ctx='store'),
874 Getattr(ContextReference(), 'name'))
875 """
Armin Ronacher6df604e2008-05-23 22:18:38 +0200876
877
Armin Ronachered1e0d42008-05-18 20:25:28 +0200878class Continue(Stmt):
879 """Continue a loop."""
880
881
882class Break(Stmt):
883 """Break a loop."""
884
885
Armin Ronacher271a0eb2009-02-11 22:49:08 +0100886class Scope(Stmt):
887 """An artificial scope."""
888 fields = ('body',)
889
890
Armin Ronacher8346bd72010-03-14 19:43:47 +0100891class EvalContextModifier(Stmt):
Armin Ronacher30fda272010-03-15 03:06:04 +0100892 """Modifies the eval context. For each option that should be modified,
893 a :class:`Keyword` has to be added to the :attr:`options` list.
894
895 Example to change the `autoescape` setting::
896
897 EvalContextModifier(options=[Keyword('autoescape', Const(True))])
898 """
Armin Ronacher8346bd72010-03-14 19:43:47 +0100899 fields = ('options',)
900
901
902class ScopedEvalContextModifier(EvalContextModifier):
Armin Ronacher30fda272010-03-15 03:06:04 +0100903 """Modifies the eval context and reverts it later. Works exactly like
904 :class:`EvalContextModifier` but will only modify the
Armin Ronacher0dbaf392010-03-15 10:06:53 +0100905 :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.
Armin Ronacher30fda272010-03-15 03:06:04 +0100906 """
Armin Ronacher8346bd72010-03-14 19:43:47 +0100907 fields = ('body',)
908
909
Armin Ronacher8a1d27f2008-05-19 08:37:19 +0200910# make sure nobody creates custom nodes
911def _failing_new(*args, **kwargs):
912 raise TypeError('can\'t create custom node types')
913NodeType.__new__ = staticmethod(_failing_new); del _failing_new