blob: 7c6b358a550546d2fb56edd70fbe87aca26f4a57 [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))
Ian Lewisab014bd2010-10-31 20:29:28 +0900378 except Exception:
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))
Ian Lewisab014bd2010-10-31 20:29:28 +0900393 except Exception:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200394 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):
Armin Ronacherffaa2e72010-05-29 20:57:16 +0200445 eval_ctx = get_eval_context(self, eval_ctx)
446 if eval_ctx.volatile:
447 raise Impossible()
448 if eval_ctx.autoescape:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200449 return Markup(self.data)
450 return self.data
451
452
Armin Ronacher07bc6842008-03-31 14:18:49 +0200453class Tuple(Literal):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200454 """For loop unpacking and some other things like multiple arguments
Armin Ronacher023b5e92008-05-08 11:03:10 +0200455 for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
456 is used for loading the names or storing.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200457 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200458 fields = ('items', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200459
Armin Ronacher8346bd72010-03-14 19:43:47 +0100460 def as_const(self, eval_ctx=None):
461 eval_ctx = get_eval_context(self, eval_ctx)
462 return tuple(x.as_const(eval_ctx) for x in self.items)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200463
464 def can_assign(self):
465 for item in self.items:
466 if not item.can_assign():
467 return False
468 return True
469
470
471class List(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200472 """Any list literal such as ``[1, 2, 3]``"""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200473 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200474
Armin Ronacher8346bd72010-03-14 19:43:47 +0100475 def as_const(self, eval_ctx=None):
476 eval_ctx = get_eval_context(self, eval_ctx)
477 return [x.as_const(eval_ctx) for x in self.items]
Armin Ronacher07bc6842008-03-31 14:18:49 +0200478
479
480class Dict(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200481 """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
482 :class:`Pair` nodes.
483 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200484 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200485
Armin Ronacher8346bd72010-03-14 19:43:47 +0100486 def as_const(self, eval_ctx=None):
487 eval_ctx = get_eval_context(self, eval_ctx)
488 return dict(x.as_const(eval_ctx) for x in self.items)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200489
490
491class Pair(Helper):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200492 """A key, value pair for dicts."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200493 fields = ('key', 'value')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200494
Armin Ronacher8346bd72010-03-14 19:43:47 +0100495 def as_const(self, eval_ctx=None):
496 eval_ctx = get_eval_context(self, eval_ctx)
497 return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200498
499
Armin Ronacher8efc5222008-04-08 14:47:40 +0200500class Keyword(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200501 """A key, value pair for keyword arguments where key is a string."""
Armin Ronacher8efc5222008-04-08 14:47:40 +0200502 fields = ('key', 'value')
503
Armin Ronacher8346bd72010-03-14 19:43:47 +0100504 def as_const(self, eval_ctx=None):
505 eval_ctx = get_eval_context(self, eval_ctx)
506 return self.key, self.value.as_const(eval_ctx)
Armin Ronacher335b87a2008-09-21 17:08:48 +0200507
Armin Ronacher8efc5222008-04-08 14:47:40 +0200508
Armin Ronacher07bc6842008-03-31 14:18:49 +0200509class CondExpr(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200510 """A conditional expression (inline if expression). (``{{
511 foo if bar else baz }}``)
512 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200513 fields = ('test', 'expr1', 'expr2')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200514
Armin Ronacher8346bd72010-03-14 19:43:47 +0100515 def as_const(self, eval_ctx=None):
516 eval_ctx = get_eval_context(self, eval_ctx)
517 if self.test.as_const(eval_ctx):
518 return self.expr1.as_const(eval_ctx)
Armin Ronacher547d0b62008-07-04 16:35:10 +0200519
520 # if we evaluate to an undefined object, we better do that at runtime
521 if self.expr2 is None:
522 raise Impossible()
523
Armin Ronacher8346bd72010-03-14 19:43:47 +0100524 return self.expr2.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200525
526
527class Filter(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200528 """This node applies a filter on an expression. `name` is the name of
529 the filter, the rest of the fields are the same as for :class:`Call`.
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200530
531 If the `node` of a filter is `None` the contents of the last buffer are
532 filtered. Buffers are created by macros and filter blocks.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200533 """
Armin Ronacherd55ab532008-04-09 16:13:39 +0200534 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200535
Armin Ronacher8346bd72010-03-14 19:43:47 +0100536 def as_const(self, eval_ctx=None):
537 eval_ctx = get_eval_context(self, eval_ctx)
538 if eval_ctx.volatile or self.node is None:
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200539 raise Impossible()
Armin Ronacher0d242be2010-02-10 01:35:13 +0100540 # we have to be careful here because we call filter_ below.
541 # if this variable would be called filter, 2to3 would wrap the
542 # call in a list beause it is assuming we are talking about the
543 # builtin filter function here which no longer returns a list in
544 # python 3. because of that, do not rename filter_ to filter!
545 filter_ = self.environment.filters.get(self.name)
546 if filter_ is None or getattr(filter_, 'contextfilter', False):
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200547 raise Impossible()
Armin Ronacher8346bd72010-03-14 19:43:47 +0100548 obj = self.node.as_const(eval_ctx)
549 args = [x.as_const(eval_ctx) for x in self.args]
550 if getattr(filter_, 'evalcontextfilter', False):
551 args.insert(0, eval_ctx)
552 elif getattr(filter_, 'environmentfilter', False):
Armin Ronacher9a027f42008-04-17 11:13:40 +0200553 args.insert(0, self.environment)
Armin Ronacher8346bd72010-03-14 19:43:47 +0100554 kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
Armin Ronacherd55ab532008-04-09 16:13:39 +0200555 if self.dyn_args is not None:
556 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100557 args.extend(self.dyn_args.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900558 except Exception:
Armin Ronacherd55ab532008-04-09 16:13:39 +0200559 raise Impossible()
560 if self.dyn_kwargs is not None:
561 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100562 kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900563 except Exception:
Armin Ronacherd55ab532008-04-09 16:13:39 +0200564 raise Impossible()
565 try:
Armin Ronacher0d242be2010-02-10 01:35:13 +0100566 return filter_(obj, *args, **kwargs)
Ian Lewisab014bd2010-10-31 20:29:28 +0900567 except Exception:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200568 raise Impossible()
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200569
570
Armin Ronacher07bc6842008-03-31 14:18:49 +0200571class Test(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200572 """Applies a test on an expression. `name` is the name of the test, the
573 rest of the fields are the same as for :class:`Call`.
574 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200575 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200576
577
578class Call(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200579 """Calls an expression. `args` is a list of arguments, `kwargs` a list
580 of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
581 and `dyn_kwargs` has to be either `None` or a node that is used as
582 node for dynamic positional (``*args``) or keyword (``**kwargs``)
583 arguments.
584 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200585 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200586
Armin Ronacher8346bd72010-03-14 19:43:47 +0100587 def as_const(self, eval_ctx=None):
588 eval_ctx = get_eval_context(self, eval_ctx)
589 if eval_ctx.volatile:
590 raise Impossible()
591 obj = self.node.as_const(eval_ctx)
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200592
593 # don't evaluate context functions
Armin Ronacher8346bd72010-03-14 19:43:47 +0100594 args = [x.as_const(eval_ctx) for x in self.args]
Armin Ronacher5a5ce732010-05-23 22:58:28 +0200595 if isinstance(obj, _context_function_types):
596 if getattr(obj, 'contextfunction', False):
597 raise Impossible()
598 elif getattr(obj, 'evalcontextfunction', False):
599 args.insert(0, eval_ctx)
600 elif getattr(obj, 'environmentfunction', False):
601 args.insert(0, self.environment)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200602
Armin Ronacher8346bd72010-03-14 19:43:47 +0100603 kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200604 if self.dyn_args is not None:
605 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100606 args.extend(self.dyn_args.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900607 except Exception:
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200608 raise Impossible()
609 if self.dyn_kwargs is not None:
610 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100611 kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900612 except Exception:
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200613 raise Impossible()
614 try:
615 return obj(*args, **kwargs)
Ian Lewisab014bd2010-10-31 20:29:28 +0900616 except Exception:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200617 raise Impossible()
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200618
Armin Ronacher07bc6842008-03-31 14:18:49 +0200619
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200620class Getitem(Expr):
Armin Ronacherb9388772008-06-25 20:43:18 +0200621 """Get an attribute or item from an expression and prefer the item."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200622 fields = ('node', 'arg', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200623
Armin Ronacher8346bd72010-03-14 19:43:47 +0100624 def as_const(self, eval_ctx=None):
625 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200626 if self.ctx != 'load':
627 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200628 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100629 return self.environment.getitem(self.node.as_const(eval_ctx),
630 self.arg.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900631 except Exception:
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200632 raise Impossible()
633
634 def can_assign(self):
635 return False
636
637
638class Getattr(Expr):
Armin Ronacherb9388772008-06-25 20:43:18 +0200639 """Get an attribute or item from an expression that is a ascii-only
640 bytestring and prefer the attribute.
641 """
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200642 fields = ('node', 'attr', 'ctx')
643
Armin Ronacher8346bd72010-03-14 19:43:47 +0100644 def as_const(self, eval_ctx=None):
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200645 if self.ctx != 'load':
646 raise Impossible()
647 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100648 eval_ctx = get_eval_context(self, eval_ctx)
Georg Brandl93d2df72010-05-23 22:35:53 +0200649 return self.environment.getattr(self.node.as_const(eval_ctx),
650 self.attr)
Ian Lewisab014bd2010-10-31 20:29:28 +0900651 except Exception:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200652 raise Impossible()
653
654 def can_assign(self):
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200655 return False
Armin Ronacher07bc6842008-03-31 14:18:49 +0200656
657
658class Slice(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200659 """Represents a slice object. This must only be used as argument for
660 :class:`Subscript`.
661 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200662 fields = ('start', 'stop', 'step')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200663
Armin Ronacher8346bd72010-03-14 19:43:47 +0100664 def as_const(self, eval_ctx=None):
665 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200666 def const(obj):
667 if obj is None:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100668 return None
669 return obj.as_const(eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200670 return slice(const(self.start), const(self.stop), const(self.step))
671
Armin Ronacher07bc6842008-03-31 14:18:49 +0200672
673class Concat(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200674 """Concatenates the list of expressions provided after converting them to
675 unicode.
676 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200677 fields = ('nodes',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200678
Armin Ronacher8346bd72010-03-14 19:43:47 +0100679 def as_const(self, eval_ctx=None):
680 eval_ctx = get_eval_context(self, eval_ctx)
681 return ''.join(unicode(x.as_const(eval_ctx)) for x in self.nodes)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200682
683
684class Compare(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200685 """Compares an expression with some other expressions. `ops` must be a
686 list of :class:`Operand`\s.
687 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200688 fields = ('expr', 'ops')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200689
Armin Ronacher8346bd72010-03-14 19:43:47 +0100690 def as_const(self, eval_ctx=None):
691 eval_ctx = get_eval_context(self, eval_ctx)
692 result = value = self.expr.as_const(eval_ctx)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200693 try:
694 for op in self.ops:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100695 new_value = op.expr.as_const(eval_ctx)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200696 result = _cmpop_to_func[op.op](value, new_value)
697 value = new_value
Ian Lewisab014bd2010-10-31 20:29:28 +0900698 except Exception:
Armin Ronacherb5124e62008-04-25 00:36:14 +0200699 raise Impossible()
Armin Ronacher625215e2008-04-13 16:31:08 +0200700 return result
701
Armin Ronacher07bc6842008-03-31 14:18:49 +0200702
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200703class Operand(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200704 """Holds an operator and an expression."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200705 fields = ('op', 'expr')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200706
Armin Ronacher023b5e92008-05-08 11:03:10 +0200707if __debug__:
708 Operand.__doc__ += '\nThe following operators are available: ' + \
709 ', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
710 set(_uaop_to_func) | set(_cmpop_to_func)))
711
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200712
Armin Ronacher07bc6842008-03-31 14:18:49 +0200713class Mul(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200714 """Multiplies the left with the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200715 operator = '*'
716
717
718class Div(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200719 """Divides the left by the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200720 operator = '/'
721
722
723class FloorDiv(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200724 """Divides the left by the right node and truncates conver the
725 result into an integer by truncating.
726 """
Armin Ronacher07bc6842008-03-31 14:18:49 +0200727 operator = '//'
728
729
730class Add(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200731 """Add the left to the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200732 operator = '+'
733
734
735class Sub(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200736 """Substract the right from the left node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200737 operator = '-'
738
739
740class Mod(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200741 """Left modulo right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200742 operator = '%'
743
744
745class Pow(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200746 """Left to the power of right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200747 operator = '**'
748
749
750class And(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200751 """Short circuited AND."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200752 operator = 'and'
753
Armin Ronacher8346bd72010-03-14 19:43:47 +0100754 def as_const(self, eval_ctx=None):
755 eval_ctx = get_eval_context(self, eval_ctx)
756 return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200757
758
759class Or(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200760 """Short circuited OR."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200761 operator = 'or'
762
Armin Ronacher8346bd72010-03-14 19:43:47 +0100763 def as_const(self, eval_ctx=None):
764 eval_ctx = get_eval_context(self, eval_ctx)
765 return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200766
767
768class Not(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200769 """Negate the expression."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200770 operator = 'not'
771
772
Armin Ronachere791c2a2008-04-07 18:39:54 +0200773class Neg(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200774 """Make the expression negative."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200775 operator = '-'
776
777
Armin Ronachere791c2a2008-04-07 18:39:54 +0200778class Pos(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200779 """Make the expression positive (noop for most expressions)"""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200780 operator = '+'
Armin Ronacher023b5e92008-05-08 11:03:10 +0200781
782
783# Helpers for extensions
784
785
786class EnvironmentAttribute(Expr):
787 """Loads an attribute from the environment object. This is useful for
788 extensions that want to call a callback stored on the environment.
789 """
790 fields = ('name',)
791
792
793class ExtensionAttribute(Expr):
794 """Returns the attribute of an extension bound to the environment.
795 The identifier is the identifier of the :class:`Extension`.
Armin Ronacherb9e78752008-05-10 23:36:28 +0200796
797 This node is usually constructed by calling the
798 :meth:`~jinja2.ext.Extension.attr` method on an extension.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200799 """
Armin Ronacher6df604e2008-05-23 22:18:38 +0200800 fields = ('identifier', 'name')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200801
802
803class ImportedName(Expr):
804 """If created with an import name the import name is returned on node
805 access. For example ``ImportedName('cgi.escape')`` returns the `escape`
806 function from the cgi module on evaluation. Imports are optimized by the
807 compiler so there is no need to assign them to local variables.
808 """
809 fields = ('importname',)
810
811
812class InternalName(Expr):
813 """An internal name in the compiler. You cannot create these nodes
Armin Ronacher762079c2008-05-08 23:57:56 +0200814 yourself but the parser provides a
815 :meth:`~jinja2.parser.Parser.free_identifier` method that creates
Armin Ronacher023b5e92008-05-08 11:03:10 +0200816 a new identifier for you. This identifier is not available from the
817 template and is not threated specially by the compiler.
818 """
819 fields = ('name',)
820
821 def __init__(self):
822 raise TypeError('Can\'t create internal names. Use the '
823 '`free_identifier` method on a parser.')
824
825
826class MarkSafe(Expr):
827 """Mark the wrapped expression as safe (wrap it as `Markup`)."""
828 fields = ('expr',)
829
Armin Ronacher8346bd72010-03-14 19:43:47 +0100830 def as_const(self, eval_ctx=None):
831 eval_ctx = get_eval_context(self, eval_ctx)
832 return Markup(self.expr.as_const(eval_ctx))
Armin Ronacher023b5e92008-05-08 11:03:10 +0200833
834
Armin Ronacher4da90342010-05-29 17:35:10 +0200835class MarkSafeIfAutoescape(Expr):
836 """Mark the wrapped expression as safe (wrap it as `Markup`) but
837 only if autoescaping is active.
838
839 .. versionadded:: 2.5
840 """
841 fields = ('expr',)
842
843 def as_const(self, eval_ctx=None):
844 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacherffaa2e72010-05-29 20:57:16 +0200845 if eval_ctx.volatile:
846 raise Impossible()
Armin Ronacher4da90342010-05-29 17:35:10 +0200847 expr = self.expr.as_const(eval_ctx)
848 if eval_ctx.autoescape:
849 return Markup(expr)
850 return expr
851
852
Armin Ronacher6df604e2008-05-23 22:18:38 +0200853class ContextReference(Expr):
Armin Ronachercedb4822010-03-24 10:53:22 +0100854 """Returns the current template context. It can be used like a
855 :class:`Name` node, with a ``'load'`` ctx and will return the
856 current :class:`~jinja2.runtime.Context` object.
857
858 Here an example that assigns the current template name to a
859 variable named `foo`::
860
861 Assign(Name('foo', ctx='store'),
862 Getattr(ContextReference(), 'name'))
863 """
Armin Ronacher6df604e2008-05-23 22:18:38 +0200864
865
Armin Ronachered1e0d42008-05-18 20:25:28 +0200866class Continue(Stmt):
867 """Continue a loop."""
868
869
870class Break(Stmt):
871 """Break a loop."""
872
873
Armin Ronacher271a0eb2009-02-11 22:49:08 +0100874class Scope(Stmt):
875 """An artificial scope."""
876 fields = ('body',)
877
878
Armin Ronacher8346bd72010-03-14 19:43:47 +0100879class EvalContextModifier(Stmt):
Armin Ronacher30fda272010-03-15 03:06:04 +0100880 """Modifies the eval context. For each option that should be modified,
881 a :class:`Keyword` has to be added to the :attr:`options` list.
882
883 Example to change the `autoescape` setting::
884
885 EvalContextModifier(options=[Keyword('autoescape', Const(True))])
886 """
Armin Ronacher8346bd72010-03-14 19:43:47 +0100887 fields = ('options',)
888
889
890class ScopedEvalContextModifier(EvalContextModifier):
Armin Ronacher30fda272010-03-15 03:06:04 +0100891 """Modifies the eval context and reverts it later. Works exactly like
892 :class:`EvalContextModifier` but will only modify the
Armin Ronacher0dbaf392010-03-15 10:06:53 +0100893 :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.
Armin Ronacher30fda272010-03-15 03:06:04 +0100894 """
Armin Ronacher8346bd72010-03-14 19:43:47 +0100895 fields = ('body',)
896
897
Armin Ronacher8a1d27f2008-05-19 08:37:19 +0200898# make sure nobody creates custom nodes
899def _failing_new(*args, **kwargs):
900 raise TypeError('can\'t create custom node types')
901NodeType.__new__ = staticmethod(_failing_new); del _failing_new