blob: 8b5f89a4730fc643581c944f045d223c86534e53 [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
16from itertools import chain, izip
Armin Ronacher82b3f3d2008-03-31 20:01:08 +020017from collections import deque
Armin Ronacher5a5ce732010-05-23 22:58:28 +020018from jinja2.utils import Markup, MethodType, FunctionType
19
20
21#: the types we support for context functions
22_context_function_types = (FunctionType, MethodType)
Armin Ronacher07bc6842008-03-31 14:18:49 +020023
24
25_binop_to_func = {
26 '*': operator.mul,
27 '/': operator.truediv,
28 '//': operator.floordiv,
29 '**': operator.pow,
30 '%': operator.mod,
31 '+': operator.add,
32 '-': operator.sub
33}
34
35_uaop_to_func = {
36 'not': operator.not_,
37 '+': operator.pos,
38 '-': operator.neg
39}
40
Armin Ronacher625215e2008-04-13 16:31:08 +020041_cmpop_to_func = {
42 'eq': operator.eq,
43 'ne': operator.ne,
44 'gt': operator.gt,
45 'gteq': operator.ge,
46 'lt': operator.lt,
47 'lteq': operator.le,
Armin Ronacherb5124e62008-04-25 00:36:14 +020048 'in': lambda a, b: a in b,
49 'notin': lambda a, b: a not in b
Armin Ronacher625215e2008-04-13 16:31:08 +020050}
51
Armin Ronacher07bc6842008-03-31 14:18:49 +020052
53class Impossible(Exception):
Armin Ronacher8efc5222008-04-08 14:47:40 +020054 """Raised if the node could not perform a requested action."""
Armin Ronacher07bc6842008-03-31 14:18:49 +020055
56
57class NodeType(type):
Armin Ronacher8efc5222008-04-08 14:47:40 +020058 """A metaclass for nodes that handles the field and attribute
59 inheritance. fields and attributes from the parent class are
60 automatically forwarded to the child."""
Armin Ronacher07bc6842008-03-31 14:18:49 +020061
62 def __new__(cls, name, bases, d):
Armin Ronachere791c2a2008-04-07 18:39:54 +020063 for attr in 'fields', 'attributes':
Armin Ronacher07bc6842008-03-31 14:18:49 +020064 storage = []
Armin Ronacher7324eb82008-04-21 07:55:52 +020065 storage.extend(getattr(bases[0], attr, ()))
Armin Ronacher07bc6842008-03-31 14:18:49 +020066 storage.extend(d.get(attr, ()))
Armin Ronacher7324eb82008-04-21 07:55:52 +020067 assert len(bases) == 1, 'multiple inheritance not allowed'
68 assert len(storage) == len(set(storage)), 'layout conflict'
Armin Ronacher07bc6842008-03-31 14:18:49 +020069 d[attr] = tuple(storage)
Armin Ronacher023b5e92008-05-08 11:03:10 +020070 d.setdefault('abstract', False)
Armin Ronacher7324eb82008-04-21 07:55:52 +020071 return type.__new__(cls, name, bases, d)
Armin Ronacher07bc6842008-03-31 14:18:49 +020072
73
Armin Ronacher8346bd72010-03-14 19:43:47 +010074class EvalContext(object):
Armin Ronacher30fda272010-03-15 03:06:04 +010075 """Holds evaluation time information. Custom attributes can be attached
76 to it in extensions.
77 """
Armin Ronacher8346bd72010-03-14 19:43:47 +010078
Armin Ronacher1da23d12010-04-05 18:11:18 +020079 def __init__(self, environment, template_name=None):
80 if callable(environment.autoescape):
81 self.autoescape = environment.autoescape(template_name)
82 else:
83 self.autoescape = environment.autoescape
Armin Ronacher8346bd72010-03-14 19:43:47 +010084 self.volatile = False
85
86 def save(self):
87 return self.__dict__.copy()
88
89 def revert(self, old):
90 self.__dict__.clear()
91 self.__dict__.update(old)
92
93
94def get_eval_context(node, ctx):
95 if ctx is None:
96 if node.environment is None:
97 raise RuntimeError('if no eval context is passed, the '
98 'node must have an attached '
99 'environment.')
100 return EvalContext(node.environment)
101 return ctx
102
103
Armin Ronacher07bc6842008-03-31 14:18:49 +0200104class Node(object):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200105 """Baseclass for all Jinja2 nodes. There are a number of nodes available
106 of different types. There are three major types:
107
108 - :class:`Stmt`: statements
109 - :class:`Expr`: expressions
110 - :class:`Helper`: helper nodes
111 - :class:`Template`: the outermost wrapper node
112
113 All nodes have fields and attributes. Fields may be other nodes, lists,
114 or arbitrary values. Fields are passed to the constructor as regular
115 positional arguments, attributes as keyword arguments. Each node has
116 two attributes: `lineno` (the line number of the node) and `environment`.
117 The `environment` attribute is set at the end of the parsing process for
118 all nodes automatically.
119 """
Armin Ronacher07bc6842008-03-31 14:18:49 +0200120 __metaclass__ = NodeType
Armin Ronachere791c2a2008-04-07 18:39:54 +0200121 fields = ()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200122 attributes = ('lineno', 'environment')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200123 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200124
Armin Ronacher023b5e92008-05-08 11:03:10 +0200125 def __init__(self, *fields, **attributes):
Armin Ronacher69e12db2008-05-12 09:00:03 +0200126 if self.abstract:
127 raise TypeError('abstract nodes are not instanciable')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200128 if fields:
129 if len(fields) != len(self.fields):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200130 if not self.fields:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200131 raise TypeError('%r takes 0 arguments' %
132 self.__class__.__name__)
133 raise TypeError('%r takes 0 or %d argument%s' % (
134 self.__class__.__name__,
Armin Ronachere791c2a2008-04-07 18:39:54 +0200135 len(self.fields),
136 len(self.fields) != 1 and 's' or ''
Armin Ronacher07bc6842008-03-31 14:18:49 +0200137 ))
Armin Ronacher023b5e92008-05-08 11:03:10 +0200138 for name, arg in izip(self.fields, fields):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200139 setattr(self, name, arg)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200140 for attr in self.attributes:
Armin Ronacher023b5e92008-05-08 11:03:10 +0200141 setattr(self, attr, attributes.pop(attr, None))
142 if attributes:
143 raise TypeError('unknown attribute %r' %
144 iter(attributes).next())
Armin Ronacher07bc6842008-03-31 14:18:49 +0200145
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200146 def iter_fields(self, exclude=None, only=None):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200147 """This method iterates over all fields that are defined and yields
Armin Ronacher3da90312008-05-23 16:37:28 +0200148 ``(key, value)`` tuples. Per default all fields are returned, but
149 it's possible to limit that to some fields by providing the `only`
150 parameter or to exclude some using the `exclude` parameter. Both
151 should be sets or tuples of field names.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200152 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200153 for name in self.fields:
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200154 if (exclude is only is None) or \
155 (exclude is not None and name not in exclude) or \
156 (only is not None and name in only):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200157 try:
158 yield name, getattr(self, name)
159 except AttributeError:
160 pass
Armin Ronacher07bc6842008-03-31 14:18:49 +0200161
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200162 def iter_child_nodes(self, exclude=None, only=None):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200163 """Iterates over all direct child nodes of the node. This iterates
164 over all fields and yields the values of they are nodes. If the value
165 of a field is a list all the nodes in that list are returned.
166 """
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200167 for field, item in self.iter_fields(exclude, only):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200168 if isinstance(item, list):
169 for n in item:
170 if isinstance(n, Node):
171 yield n
172 elif isinstance(item, Node):
173 yield item
174
Armin Ronachere791c2a2008-04-07 18:39:54 +0200175 def find(self, node_type):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200176 """Find the first node of a given type. If no such node exists the
177 return value is `None`.
178 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200179 for result in self.find_all(node_type):
180 return result
181
182 def find_all(self, node_type):
Armin Ronacher63cf9b82009-07-26 10:33:36 +0200183 """Find all the nodes of a given type. If the type is a tuple,
184 the check is performed for any of the tuple items.
185 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200186 for child in self.iter_child_nodes():
187 if isinstance(child, node_type):
188 yield child
189 for result in child.find_all(node_type):
190 yield result
191
192 def set_ctx(self, ctx):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200193 """Reset the context of a node and all child nodes. Per default the
194 parser will all generate nodes that have a 'load' context as it's the
195 most common one. This method is used in the parser to set assignment
196 targets and other nodes to a store context.
Armin Ronachere791c2a2008-04-07 18:39:54 +0200197 """
198 todo = deque([self])
199 while todo:
200 node = todo.popleft()
201 if 'ctx' in node.fields:
202 node.ctx = ctx
203 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200204 return self
Armin Ronachere791c2a2008-04-07 18:39:54 +0200205
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200206 def set_lineno(self, lineno, override=False):
207 """Set the line numbers of the node and children."""
208 todo = deque([self])
209 while todo:
210 node = todo.popleft()
211 if 'lineno' in node.attributes:
212 if node.lineno is None or override:
213 node.lineno = lineno
214 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200215 return self
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200216
Armin Ronacherd55ab532008-04-09 16:13:39 +0200217 def set_environment(self, environment):
218 """Set the environment for all nodes."""
219 todo = deque([self])
220 while todo:
221 node = todo.popleft()
222 node.environment = environment
223 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200224 return self
Armin Ronacherd55ab532008-04-09 16:13:39 +0200225
Armin Ronacher69e12db2008-05-12 09:00:03 +0200226 def __eq__(self, other):
Armin Ronacherb3a1fcf2008-05-15 11:04:14 +0200227 return type(self) is type(other) and \
228 tuple(self.iter_fields()) == tuple(other.iter_fields())
Armin Ronacher69e12db2008-05-12 09:00:03 +0200229
230 def __ne__(self, other):
231 return not self.__eq__(other)
232
Armin Ronacher07bc6842008-03-31 14:18:49 +0200233 def __repr__(self):
234 return '%s(%s)' % (
235 self.__class__.__name__,
236 ', '.join('%s=%r' % (arg, getattr(self, arg, None)) for
Armin Ronachere791c2a2008-04-07 18:39:54 +0200237 arg in self.fields)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200238 )
239
240
241class Stmt(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200242 """Base node for all statements."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200243 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200244
245
246class Helper(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200247 """Nodes that exist in a specific context only."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200248 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200249
250
251class Template(Node):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200252 """Node that represents a template. This must be the outermost node that
253 is passed to the compiler.
254 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200255 fields = ('body',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200256
257
258class Output(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200259 """A node that holds multiple expressions which are then printed out.
260 This is used both for the `print` statement and the regular template data.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200261 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200262 fields = ('nodes',)
263
Armin Ronacher07bc6842008-03-31 14:18:49 +0200264
265class Extends(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200266 """Represents an extends statement."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200267 fields = ('template',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200268
269
270class For(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200271 """The for loop. `target` is the target for the iteration (usually a
272 :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list
273 of nodes that are used as loop-body, and `else_` a list of nodes for the
274 `else` block. If no else node exists it has to be an empty list.
275
276 For filtered nodes an expression can be stored as `test`, otherwise `None`.
277 """
Armin Ronacherfdf95302008-05-11 22:20:51 +0200278 fields = ('target', 'iter', 'body', 'else_', 'test', 'recursive')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200279
280
281class If(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200282 """If `test` is true, `body` is rendered, else `else_`."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200283 fields = ('test', 'body', 'else_')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200284
285
286class Macro(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200287 """A macro definition. `name` is the name of the macro, `args` a list of
288 arguments and `defaults` a list of defaults if there are any. `body` is
289 a list of nodes for the macro body.
290 """
Armin Ronacher8efc5222008-04-08 14:47:40 +0200291 fields = ('name', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200292
293
294class CallBlock(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200295 """Like a macro without a name but a call instead. `call` is called with
296 the unnamed macro as `caller` argument this node holds.
297 """
Armin Ronacherc9705c22008-04-27 21:28:03 +0200298 fields = ('call', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200299
300
Armin Ronacher07bc6842008-03-31 14:18:49 +0200301class FilterBlock(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200302 """Node for filter sections."""
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200303 fields = ('body', 'filter')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200304
305
306class Block(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200307 """A node that represents a block."""
Armin Ronacher74a0cd92009-02-19 15:56:53 +0100308 fields = ('name', 'body', 'scoped')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200309
310
311class Include(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200312 """A node that represents the include tag."""
Armin Ronacher37f58ce2008-12-27 13:10:38 +0100313 fields = ('template', 'with_context', 'ignore_missing')
Armin Ronacher0611e492008-04-25 23:44:14 +0200314
315
316class Import(Stmt):
317 """A node that represents the import tag."""
Armin Ronacherea847c52008-05-02 20:04:32 +0200318 fields = ('template', 'target', 'with_context')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200319
320
Armin Ronacher0611e492008-04-25 23:44:14 +0200321class FromImport(Stmt):
322 """A node that represents the from import tag. It's important to not
323 pass unsafe names to the name attribute. The compiler translates the
324 attribute lookups directly into getattr calls and does *not* use the
Armin Ronacherb9388772008-06-25 20:43:18 +0200325 subscript callback of the interface. As exported variables may not
Armin Ronacher0611e492008-04-25 23:44:14 +0200326 start with double underscores (which the parser asserts) this is not a
327 problem for regular Jinja code, but if this node is used in an extension
328 extra care must be taken.
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200329
330 The list of names may contain tuples if aliases are wanted.
Armin Ronacher0611e492008-04-25 23:44:14 +0200331 """
Armin Ronacherea847c52008-05-02 20:04:32 +0200332 fields = ('template', 'names', 'with_context')
Armin Ronacher0611e492008-04-25 23:44:14 +0200333
334
Armin Ronacher07bc6842008-03-31 14:18:49 +0200335class ExprStmt(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200336 """A statement that evaluates an expression and discards the result."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200337 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200338
339
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200340class Assign(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200341 """Assigns an expression to a target."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200342 fields = ('target', 'node')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200343
344
Armin Ronacher07bc6842008-03-31 14:18:49 +0200345class Expr(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200346 """Baseclass for all expressions."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200347 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200348
Armin Ronacher8346bd72010-03-14 19:43:47 +0100349 def as_const(self, eval_ctx=None):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200350 """Return the value of the expression as constant or raise
Armin Ronacher8346bd72010-03-14 19:43:47 +0100351 :exc:`Impossible` if this was not possible.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200352
Armin Ronacher8346bd72010-03-14 19:43:47 +0100353 An :class:`EvalContext` can be provided, if none is given
354 a default context is created which requires the nodes to have
355 an attached environment.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200356
Armin Ronacher8346bd72010-03-14 19:43:47 +0100357 .. versionchanged:: 2.4
358 the `eval_ctx` parameter was added.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200359 """
360 raise Impossible()
361
362 def can_assign(self):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200363 """Check if it's possible to assign something to this node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200364 return False
365
366
367class BinExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200368 """Baseclass for all binary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200369 fields = ('left', 'right')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200370 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200371 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200372
Armin Ronacher8346bd72010-03-14 19:43:47 +0100373 def as_const(self, eval_ctx=None):
374 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200375 f = _binop_to_func[self.operator]
376 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100377 return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))
Armin Ronacher07bc6842008-03-31 14:18:49 +0200378 except:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200379 raise Impossible()
380
381
382class UnaryExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200383 """Baseclass for all unary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200384 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200385 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +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):
389 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200390 f = _uaop_to_func[self.operator]
391 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100392 return f(self.node.as_const(eval_ctx))
Armin Ronacher07bc6842008-03-31 14:18:49 +0200393 except:
394 raise Impossible()
395
396
397class Name(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200398 """Looks up a name or stores a value in a name.
399 The `ctx` of the node can be one of the following values:
400
401 - `store`: store a value in the name
402 - `load`: load that name
403 - `param`: like `store` but if the name was defined as function parameter.
404 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200405 fields = ('name', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200406
407 def can_assign(self):
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200408 return self.name not in ('true', 'false', 'none',
409 'True', 'False', 'None')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200410
411
412class Literal(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200413 """Baseclass for literals."""
Armin Ronacher69e12db2008-05-12 09:00:03 +0200414 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200415
416
417class Const(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200418 """All constant values. The parser will return this node for simple
419 constants such as ``42`` or ``"foo"`` but it can be used to store more
420 complex values such as lists too. Only constants with a safe
421 representation (objects where ``eval(repr(x)) == x`` is true).
422 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200423 fields = ('value',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200424
Armin Ronacher8346bd72010-03-14 19:43:47 +0100425 def as_const(self, eval_ctx=None):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200426 return self.value
427
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200428 @classmethod
Armin Ronacherd55ab532008-04-09 16:13:39 +0200429 def from_untrusted(cls, value, lineno=None, environment=None):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200430 """Return a const object if the value is representable as
431 constant value in the generated code, otherwise it will raise
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200432 an `Impossible` exception.
433 """
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200434 from compiler import has_safe_repr
435 if not has_safe_repr(value):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200436 raise Impossible()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200437 return cls(value, lineno=lineno, environment=environment)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200438
Armin Ronacher07bc6842008-03-31 14:18:49 +0200439
Armin Ronacher5411ce72008-05-25 11:36:22 +0200440class TemplateData(Literal):
441 """A constant template string."""
442 fields = ('data',)
443
Armin Ronacher8346bd72010-03-14 19:43:47 +0100444 def as_const(self, eval_ctx=None):
445 if get_eval_context(self, eval_ctx).autoescape:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200446 return Markup(self.data)
447 return self.data
448
449
Armin Ronacher07bc6842008-03-31 14:18:49 +0200450class Tuple(Literal):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200451 """For loop unpacking and some other things like multiple arguments
Armin Ronacher023b5e92008-05-08 11:03:10 +0200452 for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
453 is used for loading the names or storing.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200454 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200455 fields = ('items', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200456
Armin Ronacher8346bd72010-03-14 19:43:47 +0100457 def as_const(self, eval_ctx=None):
458 eval_ctx = get_eval_context(self, eval_ctx)
459 return tuple(x.as_const(eval_ctx) for x in self.items)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200460
461 def can_assign(self):
462 for item in self.items:
463 if not item.can_assign():
464 return False
465 return True
466
467
468class List(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200469 """Any list literal such as ``[1, 2, 3]``"""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200470 fields = ('items',)
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 [x.as_const(eval_ctx) for x in self.items]
Armin Ronacher07bc6842008-03-31 14:18:49 +0200475
476
477class Dict(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200478 """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
479 :class:`Pair` nodes.
480 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200481 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200482
Armin Ronacher8346bd72010-03-14 19:43:47 +0100483 def as_const(self, eval_ctx=None):
484 eval_ctx = get_eval_context(self, eval_ctx)
485 return dict(x.as_const(eval_ctx) for x in self.items)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200486
487
488class Pair(Helper):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200489 """A key, value pair for dicts."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200490 fields = ('key', 'value')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200491
Armin Ronacher8346bd72010-03-14 19:43:47 +0100492 def as_const(self, eval_ctx=None):
493 eval_ctx = get_eval_context(self, eval_ctx)
494 return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200495
496
Armin Ronacher8efc5222008-04-08 14:47:40 +0200497class Keyword(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200498 """A key, value pair for keyword arguments where key is a string."""
Armin Ronacher8efc5222008-04-08 14:47:40 +0200499 fields = ('key', 'value')
500
Armin Ronacher8346bd72010-03-14 19:43:47 +0100501 def as_const(self, eval_ctx=None):
502 eval_ctx = get_eval_context(self, eval_ctx)
503 return self.key, self.value.as_const(eval_ctx)
Armin Ronacher335b87a2008-09-21 17:08:48 +0200504
Armin Ronacher8efc5222008-04-08 14:47:40 +0200505
Armin Ronacher07bc6842008-03-31 14:18:49 +0200506class CondExpr(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200507 """A conditional expression (inline if expression). (``{{
508 foo if bar else baz }}``)
509 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200510 fields = ('test', 'expr1', 'expr2')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200511
Armin Ronacher8346bd72010-03-14 19:43:47 +0100512 def as_const(self, eval_ctx=None):
513 eval_ctx = get_eval_context(self, eval_ctx)
514 if self.test.as_const(eval_ctx):
515 return self.expr1.as_const(eval_ctx)
Armin Ronacher547d0b62008-07-04 16:35:10 +0200516
517 # if we evaluate to an undefined object, we better do that at runtime
518 if self.expr2 is None:
519 raise Impossible()
520
Armin Ronacher8346bd72010-03-14 19:43:47 +0100521 return self.expr2.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200522
523
524class Filter(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200525 """This node applies a filter on an expression. `name` is the name of
526 the filter, the rest of the fields are the same as for :class:`Call`.
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200527
528 If the `node` of a filter is `None` the contents of the last buffer are
529 filtered. Buffers are created by macros and filter blocks.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200530 """
Armin Ronacherd55ab532008-04-09 16:13:39 +0200531 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200532
Armin Ronacher8346bd72010-03-14 19:43:47 +0100533 def as_const(self, eval_ctx=None):
534 eval_ctx = get_eval_context(self, eval_ctx)
535 if eval_ctx.volatile or self.node is None:
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200536 raise Impossible()
Armin Ronacher0d242be2010-02-10 01:35:13 +0100537 # we have to be careful here because we call filter_ below.
538 # if this variable would be called filter, 2to3 would wrap the
539 # call in a list beause it is assuming we are talking about the
540 # builtin filter function here which no longer returns a list in
541 # python 3. because of that, do not rename filter_ to filter!
542 filter_ = self.environment.filters.get(self.name)
543 if filter_ is None or getattr(filter_, 'contextfilter', False):
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200544 raise Impossible()
Armin Ronacher8346bd72010-03-14 19:43:47 +0100545 obj = self.node.as_const(eval_ctx)
546 args = [x.as_const(eval_ctx) for x in self.args]
547 if getattr(filter_, 'evalcontextfilter', False):
548 args.insert(0, eval_ctx)
549 elif getattr(filter_, 'environmentfilter', False):
Armin Ronacher9a027f42008-04-17 11:13:40 +0200550 args.insert(0, self.environment)
Armin Ronacher8346bd72010-03-14 19:43:47 +0100551 kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
Armin Ronacherd55ab532008-04-09 16:13:39 +0200552 if self.dyn_args is not None:
553 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100554 args.extend(self.dyn_args.as_const(eval_ctx))
Armin Ronacherd55ab532008-04-09 16:13:39 +0200555 except:
556 raise Impossible()
557 if self.dyn_kwargs is not None:
558 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100559 kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
Armin Ronacherd55ab532008-04-09 16:13:39 +0200560 except:
561 raise Impossible()
562 try:
Armin Ronacher0d242be2010-02-10 01:35:13 +0100563 return filter_(obj, *args, **kwargs)
Armin Ronacherd55ab532008-04-09 16:13:39 +0200564 except:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200565 raise Impossible()
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200566
567
Armin Ronacher07bc6842008-03-31 14:18:49 +0200568class Test(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200569 """Applies a test on an expression. `name` is the name of the test, the
570 rest of the fields are the same as for :class:`Call`.
571 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200572 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200573
574
575class Call(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200576 """Calls an expression. `args` is a list of arguments, `kwargs` a list
577 of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
578 and `dyn_kwargs` has to be either `None` or a node that is used as
579 node for dynamic positional (``*args``) or keyword (``**kwargs``)
580 arguments.
581 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200582 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200583
Armin Ronacher8346bd72010-03-14 19:43:47 +0100584 def as_const(self, eval_ctx=None):
585 eval_ctx = get_eval_context(self, eval_ctx)
586 if eval_ctx.volatile:
587 raise Impossible()
588 obj = self.node.as_const(eval_ctx)
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200589
590 # don't evaluate context functions
Armin Ronacher8346bd72010-03-14 19:43:47 +0100591 args = [x.as_const(eval_ctx) for x in self.args]
Armin Ronacher5a5ce732010-05-23 22:58:28 +0200592 if isinstance(obj, _context_function_types):
593 if getattr(obj, 'contextfunction', False):
594 raise Impossible()
595 elif getattr(obj, 'evalcontextfunction', False):
596 args.insert(0, eval_ctx)
597 elif getattr(obj, 'environmentfunction', False):
598 args.insert(0, self.environment)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200599
Armin Ronacher8346bd72010-03-14 19:43:47 +0100600 kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200601 if self.dyn_args is not None:
602 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100603 args.extend(self.dyn_args.as_const(eval_ctx))
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200604 except:
605 raise Impossible()
606 if self.dyn_kwargs is not None:
607 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100608 kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200609 except:
610 raise Impossible()
611 try:
612 return obj(*args, **kwargs)
613 except:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200614 raise Impossible()
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200615
Armin Ronacher07bc6842008-03-31 14:18:49 +0200616
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200617class Getitem(Expr):
Armin Ronacherb9388772008-06-25 20:43:18 +0200618 """Get an attribute or item from an expression and prefer the item."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200619 fields = ('node', 'arg', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200620
Armin Ronacher8346bd72010-03-14 19:43:47 +0100621 def as_const(self, eval_ctx=None):
622 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200623 if self.ctx != 'load':
624 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200625 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100626 return self.environment.getitem(self.node.as_const(eval_ctx),
627 self.arg.as_const(eval_ctx))
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200628 except:
629 raise Impossible()
630
631 def can_assign(self):
632 return False
633
634
635class Getattr(Expr):
Armin Ronacherb9388772008-06-25 20:43:18 +0200636 """Get an attribute or item from an expression that is a ascii-only
637 bytestring and prefer the attribute.
638 """
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200639 fields = ('node', 'attr', 'ctx')
640
Armin Ronacher8346bd72010-03-14 19:43:47 +0100641 def as_const(self, eval_ctx=None):
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200642 if self.ctx != 'load':
643 raise Impossible()
644 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100645 eval_ctx = get_eval_context(self, eval_ctx)
Georg Brandl93d2df72010-05-23 22:35:53 +0200646 return self.environment.getattr(self.node.as_const(eval_ctx),
647 self.attr)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200648 except:
649 raise Impossible()
650
651 def can_assign(self):
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200652 return False
Armin Ronacher07bc6842008-03-31 14:18:49 +0200653
654
655class Slice(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200656 """Represents a slice object. This must only be used as argument for
657 :class:`Subscript`.
658 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200659 fields = ('start', 'stop', 'step')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200660
Armin Ronacher8346bd72010-03-14 19:43:47 +0100661 def as_const(self, eval_ctx=None):
662 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200663 def const(obj):
664 if obj is None:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100665 return None
666 return obj.as_const(eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200667 return slice(const(self.start), const(self.stop), const(self.step))
668
Armin Ronacher07bc6842008-03-31 14:18:49 +0200669
670class Concat(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200671 """Concatenates the list of expressions provided after converting them to
672 unicode.
673 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200674 fields = ('nodes',)
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)
678 return ''.join(unicode(x.as_const(eval_ctx)) for x in self.nodes)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200679
680
681class Compare(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200682 """Compares an expression with some other expressions. `ops` must be a
683 list of :class:`Operand`\s.
684 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200685 fields = ('expr', 'ops')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200686
Armin Ronacher8346bd72010-03-14 19:43:47 +0100687 def as_const(self, eval_ctx=None):
688 eval_ctx = get_eval_context(self, eval_ctx)
689 result = value = self.expr.as_const(eval_ctx)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200690 try:
691 for op in self.ops:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100692 new_value = op.expr.as_const(eval_ctx)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200693 result = _cmpop_to_func[op.op](value, new_value)
694 value = new_value
695 except:
696 raise Impossible()
Armin Ronacher625215e2008-04-13 16:31:08 +0200697 return result
698
Armin Ronacher07bc6842008-03-31 14:18:49 +0200699
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200700class Operand(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200701 """Holds an operator and an expression."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200702 fields = ('op', 'expr')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200703
Armin Ronacher023b5e92008-05-08 11:03:10 +0200704if __debug__:
705 Operand.__doc__ += '\nThe following operators are available: ' + \
706 ', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
707 set(_uaop_to_func) | set(_cmpop_to_func)))
708
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200709
Armin Ronacher07bc6842008-03-31 14:18:49 +0200710class Mul(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200711 """Multiplies the left with the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200712 operator = '*'
713
714
715class Div(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200716 """Divides the left by the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200717 operator = '/'
718
719
720class FloorDiv(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200721 """Divides the left by the right node and truncates conver the
722 result into an integer by truncating.
723 """
Armin Ronacher07bc6842008-03-31 14:18:49 +0200724 operator = '//'
725
726
727class Add(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200728 """Add the left to the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200729 operator = '+'
730
731
732class Sub(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200733 """Substract the right from the left node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200734 operator = '-'
735
736
737class Mod(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200738 """Left modulo right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200739 operator = '%'
740
741
742class Pow(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200743 """Left to the power of right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200744 operator = '**'
745
746
747class And(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200748 """Short circuited AND."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200749 operator = 'and'
750
Armin Ronacher8346bd72010-03-14 19:43:47 +0100751 def as_const(self, eval_ctx=None):
752 eval_ctx = get_eval_context(self, eval_ctx)
753 return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200754
755
756class Or(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200757 """Short circuited OR."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200758 operator = 'or'
759
Armin Ronacher8346bd72010-03-14 19:43:47 +0100760 def as_const(self, eval_ctx=None):
761 eval_ctx = get_eval_context(self, eval_ctx)
762 return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200763
764
765class Not(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200766 """Negate the expression."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200767 operator = 'not'
768
769
Armin Ronachere791c2a2008-04-07 18:39:54 +0200770class Neg(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200771 """Make the expression negative."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200772 operator = '-'
773
774
Armin Ronachere791c2a2008-04-07 18:39:54 +0200775class Pos(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200776 """Make the expression positive (noop for most expressions)"""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200777 operator = '+'
Armin Ronacher023b5e92008-05-08 11:03:10 +0200778
779
780# Helpers for extensions
781
782
783class EnvironmentAttribute(Expr):
784 """Loads an attribute from the environment object. This is useful for
785 extensions that want to call a callback stored on the environment.
786 """
787 fields = ('name',)
788
789
790class ExtensionAttribute(Expr):
791 """Returns the attribute of an extension bound to the environment.
792 The identifier is the identifier of the :class:`Extension`.
Armin Ronacherb9e78752008-05-10 23:36:28 +0200793
794 This node is usually constructed by calling the
795 :meth:`~jinja2.ext.Extension.attr` method on an extension.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200796 """
Armin Ronacher6df604e2008-05-23 22:18:38 +0200797 fields = ('identifier', 'name')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200798
799
800class ImportedName(Expr):
801 """If created with an import name the import name is returned on node
802 access. For example ``ImportedName('cgi.escape')`` returns the `escape`
803 function from the cgi module on evaluation. Imports are optimized by the
804 compiler so there is no need to assign them to local variables.
805 """
806 fields = ('importname',)
807
808
809class InternalName(Expr):
810 """An internal name in the compiler. You cannot create these nodes
Armin Ronacher762079c2008-05-08 23:57:56 +0200811 yourself but the parser provides a
812 :meth:`~jinja2.parser.Parser.free_identifier` method that creates
Armin Ronacher023b5e92008-05-08 11:03:10 +0200813 a new identifier for you. This identifier is not available from the
814 template and is not threated specially by the compiler.
815 """
816 fields = ('name',)
817
818 def __init__(self):
819 raise TypeError('Can\'t create internal names. Use the '
820 '`free_identifier` method on a parser.')
821
822
823class MarkSafe(Expr):
824 """Mark the wrapped expression as safe (wrap it as `Markup`)."""
825 fields = ('expr',)
826
Armin Ronacher8346bd72010-03-14 19:43:47 +0100827 def as_const(self, eval_ctx=None):
828 eval_ctx = get_eval_context(self, eval_ctx)
829 return Markup(self.expr.as_const(eval_ctx))
Armin Ronacher023b5e92008-05-08 11:03:10 +0200830
831
Armin Ronacher4da90342010-05-29 17:35:10 +0200832class MarkSafeIfAutoescape(Expr):
833 """Mark the wrapped expression as safe (wrap it as `Markup`) but
834 only if autoescaping is active.
835
836 .. versionadded:: 2.5
837 """
838 fields = ('expr',)
839
840 def as_const(self, eval_ctx=None):
841 eval_ctx = get_eval_context(self, eval_ctx)
842 expr = self.expr.as_const(eval_ctx)
843 if eval_ctx.autoescape:
844 return Markup(expr)
845 return expr
846
847
Armin Ronacher6df604e2008-05-23 22:18:38 +0200848class ContextReference(Expr):
Armin Ronachercedb4822010-03-24 10:53:22 +0100849 """Returns the current template context. It can be used like a
850 :class:`Name` node, with a ``'load'`` ctx and will return the
851 current :class:`~jinja2.runtime.Context` object.
852
853 Here an example that assigns the current template name to a
854 variable named `foo`::
855
856 Assign(Name('foo', ctx='store'),
857 Getattr(ContextReference(), 'name'))
858 """
Armin Ronacher6df604e2008-05-23 22:18:38 +0200859
860
Armin Ronachered1e0d42008-05-18 20:25:28 +0200861class Continue(Stmt):
862 """Continue a loop."""
863
864
865class Break(Stmt):
866 """Break a loop."""
867
868
Armin Ronacher271a0eb2009-02-11 22:49:08 +0100869class Scope(Stmt):
870 """An artificial scope."""
871 fields = ('body',)
872
873
Armin Ronacher8346bd72010-03-14 19:43:47 +0100874class EvalContextModifier(Stmt):
Armin Ronacher30fda272010-03-15 03:06:04 +0100875 """Modifies the eval context. For each option that should be modified,
876 a :class:`Keyword` has to be added to the :attr:`options` list.
877
878 Example to change the `autoescape` setting::
879
880 EvalContextModifier(options=[Keyword('autoescape', Const(True))])
881 """
Armin Ronacher8346bd72010-03-14 19:43:47 +0100882 fields = ('options',)
883
884
885class ScopedEvalContextModifier(EvalContextModifier):
Armin Ronacher30fda272010-03-15 03:06:04 +0100886 """Modifies the eval context and reverts it later. Works exactly like
887 :class:`EvalContextModifier` but will only modify the
Armin Ronacher0dbaf392010-03-15 10:06:53 +0100888 :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.
Armin Ronacher30fda272010-03-15 03:06:04 +0100889 """
Armin Ronacher8346bd72010-03-14 19:43:47 +0100890 fields = ('body',)
891
892
Armin Ronacher8a1d27f2008-05-19 08:37:19 +0200893# make sure nobody creates custom nodes
894def _failing_new(*args, **kwargs):
895 raise TypeError('can\'t create custom node types')
896NodeType.__new__ = staticmethod(_failing_new); del _failing_new