blob: c18d299c83817c6911c024addbcd8a3aa29fc284 [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 Ronachera9195382010-11-29 13:21:57 +0100375 # intercepted operators cannot be folded at compile time
376 if self.environment.sandboxed and \
377 self.operator in self.environment.intercepted_binops:
378 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200379 f = _binop_to_func[self.operator]
380 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100381 return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900382 except Exception:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200383 raise Impossible()
384
385
386class UnaryExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200387 """Baseclass for all unary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200388 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200389 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200390 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200391
Armin Ronacher8346bd72010-03-14 19:43:47 +0100392 def as_const(self, eval_ctx=None):
393 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronachera9195382010-11-29 13:21:57 +0100394 # intercepted operators cannot be folded at compile time
395 if self.environment.sandboxed and \
396 self.operator in self.environment.intercepted_unops:
397 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200398 f = _uaop_to_func[self.operator]
399 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100400 return f(self.node.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900401 except Exception:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200402 raise Impossible()
403
404
405class Name(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200406 """Looks up a name or stores a value in a name.
407 The `ctx` of the node can be one of the following values:
408
409 - `store`: store a value in the name
410 - `load`: load that name
411 - `param`: like `store` but if the name was defined as function parameter.
412 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200413 fields = ('name', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200414
415 def can_assign(self):
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200416 return self.name not in ('true', 'false', 'none',
417 'True', 'False', 'None')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200418
419
420class Literal(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200421 """Baseclass for literals."""
Armin Ronacher69e12db2008-05-12 09:00:03 +0200422 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200423
424
425class Const(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200426 """All constant values. The parser will return this node for simple
427 constants such as ``42`` or ``"foo"`` but it can be used to store more
428 complex values such as lists too. Only constants with a safe
429 representation (objects where ``eval(repr(x)) == x`` is true).
430 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200431 fields = ('value',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200432
Armin Ronacher8346bd72010-03-14 19:43:47 +0100433 def as_const(self, eval_ctx=None):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200434 return self.value
435
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200436 @classmethod
Armin Ronacherd55ab532008-04-09 16:13:39 +0200437 def from_untrusted(cls, value, lineno=None, environment=None):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200438 """Return a const object if the value is representable as
439 constant value in the generated code, otherwise it will raise
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200440 an `Impossible` exception.
441 """
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200442 from compiler import has_safe_repr
443 if not has_safe_repr(value):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200444 raise Impossible()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200445 return cls(value, lineno=lineno, environment=environment)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200446
Armin Ronacher07bc6842008-03-31 14:18:49 +0200447
Armin Ronacher5411ce72008-05-25 11:36:22 +0200448class TemplateData(Literal):
449 """A constant template string."""
450 fields = ('data',)
451
Armin Ronacher8346bd72010-03-14 19:43:47 +0100452 def as_const(self, eval_ctx=None):
Armin Ronacherffaa2e72010-05-29 20:57:16 +0200453 eval_ctx = get_eval_context(self, eval_ctx)
454 if eval_ctx.volatile:
455 raise Impossible()
456 if eval_ctx.autoescape:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200457 return Markup(self.data)
458 return self.data
459
460
Armin Ronacher07bc6842008-03-31 14:18:49 +0200461class Tuple(Literal):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200462 """For loop unpacking and some other things like multiple arguments
Armin Ronacher023b5e92008-05-08 11:03:10 +0200463 for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
464 is used for loading the names or storing.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200465 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200466 fields = ('items', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200467
Armin Ronacher8346bd72010-03-14 19:43:47 +0100468 def as_const(self, eval_ctx=None):
469 eval_ctx = get_eval_context(self, eval_ctx)
470 return tuple(x.as_const(eval_ctx) for x in self.items)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200471
472 def can_assign(self):
473 for item in self.items:
474 if not item.can_assign():
475 return False
476 return True
477
478
479class List(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200480 """Any list literal such as ``[1, 2, 3]``"""
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 [x.as_const(eval_ctx) for x in self.items]
Armin Ronacher07bc6842008-03-31 14:18:49 +0200486
487
488class Dict(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200489 """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
490 :class:`Pair` nodes.
491 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200492 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200493
Armin Ronacher8346bd72010-03-14 19:43:47 +0100494 def as_const(self, eval_ctx=None):
495 eval_ctx = get_eval_context(self, eval_ctx)
496 return dict(x.as_const(eval_ctx) for x in self.items)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200497
498
499class Pair(Helper):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200500 """A key, value pair for dicts."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200501 fields = ('key', 'value')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200502
Armin Ronacher8346bd72010-03-14 19:43:47 +0100503 def as_const(self, eval_ctx=None):
504 eval_ctx = get_eval_context(self, eval_ctx)
505 return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200506
507
Armin Ronacher8efc5222008-04-08 14:47:40 +0200508class Keyword(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200509 """A key, value pair for keyword arguments where key is a string."""
Armin Ronacher8efc5222008-04-08 14:47:40 +0200510 fields = ('key', 'value')
511
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 return self.key, self.value.as_const(eval_ctx)
Armin Ronacher335b87a2008-09-21 17:08:48 +0200515
Armin Ronacher8efc5222008-04-08 14:47:40 +0200516
Armin Ronacher07bc6842008-03-31 14:18:49 +0200517class CondExpr(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200518 """A conditional expression (inline if expression). (``{{
519 foo if bar else baz }}``)
520 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200521 fields = ('test', 'expr1', 'expr2')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200522
Armin Ronacher8346bd72010-03-14 19:43:47 +0100523 def as_const(self, eval_ctx=None):
524 eval_ctx = get_eval_context(self, eval_ctx)
525 if self.test.as_const(eval_ctx):
526 return self.expr1.as_const(eval_ctx)
Armin Ronacher547d0b62008-07-04 16:35:10 +0200527
528 # if we evaluate to an undefined object, we better do that at runtime
529 if self.expr2 is None:
530 raise Impossible()
531
Armin Ronacher8346bd72010-03-14 19:43:47 +0100532 return self.expr2.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200533
534
535class Filter(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200536 """This node applies a filter on an expression. `name` is the name of
537 the filter, the rest of the fields are the same as for :class:`Call`.
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200538
539 If the `node` of a filter is `None` the contents of the last buffer are
540 filtered. Buffers are created by macros and filter blocks.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200541 """
Armin Ronacherd55ab532008-04-09 16:13:39 +0200542 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200543
Armin Ronacher8346bd72010-03-14 19:43:47 +0100544 def as_const(self, eval_ctx=None):
545 eval_ctx = get_eval_context(self, eval_ctx)
546 if eval_ctx.volatile or self.node is None:
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200547 raise Impossible()
Armin Ronacher0d242be2010-02-10 01:35:13 +0100548 # we have to be careful here because we call filter_ below.
549 # if this variable would be called filter, 2to3 would wrap the
550 # call in a list beause it is assuming we are talking about the
551 # builtin filter function here which no longer returns a list in
552 # python 3. because of that, do not rename filter_ to filter!
553 filter_ = self.environment.filters.get(self.name)
554 if filter_ is None or getattr(filter_, 'contextfilter', False):
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200555 raise Impossible()
Armin Ronacher8346bd72010-03-14 19:43:47 +0100556 obj = self.node.as_const(eval_ctx)
557 args = [x.as_const(eval_ctx) for x in self.args]
558 if getattr(filter_, 'evalcontextfilter', False):
559 args.insert(0, eval_ctx)
560 elif getattr(filter_, 'environmentfilter', False):
Armin Ronacher9a027f42008-04-17 11:13:40 +0200561 args.insert(0, self.environment)
Armin Ronacher8346bd72010-03-14 19:43:47 +0100562 kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
Armin Ronacherd55ab532008-04-09 16:13:39 +0200563 if self.dyn_args is not None:
564 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100565 args.extend(self.dyn_args.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900566 except Exception:
Armin Ronacherd55ab532008-04-09 16:13:39 +0200567 raise Impossible()
568 if self.dyn_kwargs is not None:
569 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100570 kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900571 except Exception:
Armin Ronacherd55ab532008-04-09 16:13:39 +0200572 raise Impossible()
573 try:
Armin Ronacher0d242be2010-02-10 01:35:13 +0100574 return filter_(obj, *args, **kwargs)
Ian Lewisab014bd2010-10-31 20:29:28 +0900575 except Exception:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200576 raise Impossible()
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200577
578
Armin Ronacher07bc6842008-03-31 14:18:49 +0200579class Test(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200580 """Applies a test on an expression. `name` is the name of the test, the
581 rest of the fields are the same as for :class:`Call`.
582 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200583 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200584
585
586class Call(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200587 """Calls an expression. `args` is a list of arguments, `kwargs` a list
588 of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
589 and `dyn_kwargs` has to be either `None` or a node that is used as
590 node for dynamic positional (``*args``) or keyword (``**kwargs``)
591 arguments.
592 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200593 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200594
Armin Ronacher8346bd72010-03-14 19:43:47 +0100595 def as_const(self, eval_ctx=None):
596 eval_ctx = get_eval_context(self, eval_ctx)
597 if eval_ctx.volatile:
598 raise Impossible()
599 obj = self.node.as_const(eval_ctx)
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200600
601 # don't evaluate context functions
Armin Ronacher8346bd72010-03-14 19:43:47 +0100602 args = [x.as_const(eval_ctx) for x in self.args]
Armin Ronacher5a5ce732010-05-23 22:58:28 +0200603 if isinstance(obj, _context_function_types):
604 if getattr(obj, 'contextfunction', False):
605 raise Impossible()
606 elif getattr(obj, 'evalcontextfunction', False):
607 args.insert(0, eval_ctx)
608 elif getattr(obj, 'environmentfunction', False):
609 args.insert(0, self.environment)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200610
Armin Ronacher8346bd72010-03-14 19:43:47 +0100611 kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200612 if self.dyn_args is not None:
613 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100614 args.extend(self.dyn_args.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900615 except Exception:
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200616 raise Impossible()
617 if self.dyn_kwargs is not None:
618 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100619 kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900620 except Exception:
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200621 raise Impossible()
622 try:
623 return obj(*args, **kwargs)
Ian Lewisab014bd2010-10-31 20:29:28 +0900624 except Exception:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200625 raise Impossible()
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200626
Armin Ronacher07bc6842008-03-31 14:18:49 +0200627
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200628class Getitem(Expr):
Armin Ronacherb9388772008-06-25 20:43:18 +0200629 """Get an attribute or item from an expression and prefer the item."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200630 fields = ('node', 'arg', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200631
Armin Ronacher8346bd72010-03-14 19:43:47 +0100632 def as_const(self, eval_ctx=None):
633 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200634 if self.ctx != 'load':
635 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200636 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100637 return self.environment.getitem(self.node.as_const(eval_ctx),
638 self.arg.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900639 except Exception:
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200640 raise Impossible()
641
642 def can_assign(self):
643 return False
644
645
646class Getattr(Expr):
Armin Ronacherb9388772008-06-25 20:43:18 +0200647 """Get an attribute or item from an expression that is a ascii-only
648 bytestring and prefer the attribute.
649 """
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200650 fields = ('node', 'attr', 'ctx')
651
Armin Ronacher8346bd72010-03-14 19:43:47 +0100652 def as_const(self, eval_ctx=None):
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200653 if self.ctx != 'load':
654 raise Impossible()
655 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100656 eval_ctx = get_eval_context(self, eval_ctx)
Georg Brandl93d2df72010-05-23 22:35:53 +0200657 return self.environment.getattr(self.node.as_const(eval_ctx),
658 self.attr)
Ian Lewisab014bd2010-10-31 20:29:28 +0900659 except Exception:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200660 raise Impossible()
661
662 def can_assign(self):
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200663 return False
Armin Ronacher07bc6842008-03-31 14:18:49 +0200664
665
666class Slice(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200667 """Represents a slice object. This must only be used as argument for
668 :class:`Subscript`.
669 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200670 fields = ('start', 'stop', 'step')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200671
Armin Ronacher8346bd72010-03-14 19:43:47 +0100672 def as_const(self, eval_ctx=None):
673 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200674 def const(obj):
675 if obj is None:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100676 return None
677 return obj.as_const(eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200678 return slice(const(self.start), const(self.stop), const(self.step))
679
Armin Ronacher07bc6842008-03-31 14:18:49 +0200680
681class Concat(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200682 """Concatenates the list of expressions provided after converting them to
683 unicode.
684 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200685 fields = ('nodes',)
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 return ''.join(unicode(x.as_const(eval_ctx)) for x in self.nodes)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200690
691
692class Compare(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200693 """Compares an expression with some other expressions. `ops` must be a
694 list of :class:`Operand`\s.
695 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200696 fields = ('expr', 'ops')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200697
Armin Ronacher8346bd72010-03-14 19:43:47 +0100698 def as_const(self, eval_ctx=None):
699 eval_ctx = get_eval_context(self, eval_ctx)
700 result = value = self.expr.as_const(eval_ctx)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200701 try:
702 for op in self.ops:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100703 new_value = op.expr.as_const(eval_ctx)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200704 result = _cmpop_to_func[op.op](value, new_value)
705 value = new_value
Ian Lewisab014bd2010-10-31 20:29:28 +0900706 except Exception:
Armin Ronacherb5124e62008-04-25 00:36:14 +0200707 raise Impossible()
Armin Ronacher625215e2008-04-13 16:31:08 +0200708 return result
709
Armin Ronacher07bc6842008-03-31 14:18:49 +0200710
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200711class Operand(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200712 """Holds an operator and an expression."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200713 fields = ('op', 'expr')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200714
Armin Ronacher023b5e92008-05-08 11:03:10 +0200715if __debug__:
716 Operand.__doc__ += '\nThe following operators are available: ' + \
717 ', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
718 set(_uaop_to_func) | set(_cmpop_to_func)))
719
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200720
Armin Ronacher07bc6842008-03-31 14:18:49 +0200721class Mul(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200722 """Multiplies the left with the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200723 operator = '*'
724
725
726class Div(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200727 """Divides the left by the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200728 operator = '/'
729
730
731class FloorDiv(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200732 """Divides the left by the right node and truncates conver the
733 result into an integer by truncating.
734 """
Armin Ronacher07bc6842008-03-31 14:18:49 +0200735 operator = '//'
736
737
738class Add(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200739 """Add the left to the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200740 operator = '+'
741
742
743class Sub(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200744 """Substract the right from the left node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200745 operator = '-'
746
747
748class Mod(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200749 """Left modulo right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200750 operator = '%'
751
752
753class Pow(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200754 """Left to the power of right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200755 operator = '**'
756
757
758class And(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200759 """Short circuited AND."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200760 operator = 'and'
761
Armin Ronacher8346bd72010-03-14 19:43:47 +0100762 def as_const(self, eval_ctx=None):
763 eval_ctx = get_eval_context(self, eval_ctx)
764 return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200765
766
767class Or(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200768 """Short circuited OR."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200769 operator = 'or'
770
Armin Ronacher8346bd72010-03-14 19:43:47 +0100771 def as_const(self, eval_ctx=None):
772 eval_ctx = get_eval_context(self, eval_ctx)
773 return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200774
775
776class Not(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200777 """Negate the expression."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200778 operator = 'not'
779
780
Armin Ronachere791c2a2008-04-07 18:39:54 +0200781class Neg(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200782 """Make the expression negative."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200783 operator = '-'
784
785
Armin Ronachere791c2a2008-04-07 18:39:54 +0200786class Pos(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200787 """Make the expression positive (noop for most expressions)"""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200788 operator = '+'
Armin Ronacher023b5e92008-05-08 11:03:10 +0200789
790
791# Helpers for extensions
792
793
794class EnvironmentAttribute(Expr):
795 """Loads an attribute from the environment object. This is useful for
796 extensions that want to call a callback stored on the environment.
797 """
798 fields = ('name',)
799
800
801class ExtensionAttribute(Expr):
802 """Returns the attribute of an extension bound to the environment.
803 The identifier is the identifier of the :class:`Extension`.
Armin Ronacherb9e78752008-05-10 23:36:28 +0200804
805 This node is usually constructed by calling the
806 :meth:`~jinja2.ext.Extension.attr` method on an extension.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200807 """
Armin Ronacher6df604e2008-05-23 22:18:38 +0200808 fields = ('identifier', 'name')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200809
810
811class ImportedName(Expr):
812 """If created with an import name the import name is returned on node
813 access. For example ``ImportedName('cgi.escape')`` returns the `escape`
814 function from the cgi module on evaluation. Imports are optimized by the
815 compiler so there is no need to assign them to local variables.
816 """
817 fields = ('importname',)
818
819
820class InternalName(Expr):
821 """An internal name in the compiler. You cannot create these nodes
Armin Ronacher762079c2008-05-08 23:57:56 +0200822 yourself but the parser provides a
823 :meth:`~jinja2.parser.Parser.free_identifier` method that creates
Armin Ronacher023b5e92008-05-08 11:03:10 +0200824 a new identifier for you. This identifier is not available from the
825 template and is not threated specially by the compiler.
826 """
827 fields = ('name',)
828
829 def __init__(self):
830 raise TypeError('Can\'t create internal names. Use the '
831 '`free_identifier` method on a parser.')
832
833
834class MarkSafe(Expr):
835 """Mark the wrapped expression as safe (wrap it as `Markup`)."""
836 fields = ('expr',)
837
Armin Ronacher8346bd72010-03-14 19:43:47 +0100838 def as_const(self, eval_ctx=None):
839 eval_ctx = get_eval_context(self, eval_ctx)
840 return Markup(self.expr.as_const(eval_ctx))
Armin Ronacher023b5e92008-05-08 11:03:10 +0200841
842
Armin Ronacher4da90342010-05-29 17:35:10 +0200843class MarkSafeIfAutoescape(Expr):
844 """Mark the wrapped expression as safe (wrap it as `Markup`) but
845 only if autoescaping is active.
846
847 .. versionadded:: 2.5
848 """
849 fields = ('expr',)
850
851 def as_const(self, eval_ctx=None):
852 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacherffaa2e72010-05-29 20:57:16 +0200853 if eval_ctx.volatile:
854 raise Impossible()
Armin Ronacher4da90342010-05-29 17:35:10 +0200855 expr = self.expr.as_const(eval_ctx)
856 if eval_ctx.autoescape:
857 return Markup(expr)
858 return expr
859
860
Armin Ronacher6df604e2008-05-23 22:18:38 +0200861class ContextReference(Expr):
Armin Ronachercedb4822010-03-24 10:53:22 +0100862 """Returns the current template context. It can be used like a
863 :class:`Name` node, with a ``'load'`` ctx and will return the
864 current :class:`~jinja2.runtime.Context` object.
865
866 Here an example that assigns the current template name to a
867 variable named `foo`::
868
869 Assign(Name('foo', ctx='store'),
870 Getattr(ContextReference(), 'name'))
871 """
Armin Ronacher6df604e2008-05-23 22:18:38 +0200872
873
Armin Ronachered1e0d42008-05-18 20:25:28 +0200874class Continue(Stmt):
875 """Continue a loop."""
876
877
878class Break(Stmt):
879 """Break a loop."""
880
881
Armin Ronacher271a0eb2009-02-11 22:49:08 +0100882class Scope(Stmt):
883 """An artificial scope."""
884 fields = ('body',)
885
886
Armin Ronacher8346bd72010-03-14 19:43:47 +0100887class EvalContextModifier(Stmt):
Armin Ronacher30fda272010-03-15 03:06:04 +0100888 """Modifies the eval context. For each option that should be modified,
889 a :class:`Keyword` has to be added to the :attr:`options` list.
890
891 Example to change the `autoescape` setting::
892
893 EvalContextModifier(options=[Keyword('autoescape', Const(True))])
894 """
Armin Ronacher8346bd72010-03-14 19:43:47 +0100895 fields = ('options',)
896
897
898class ScopedEvalContextModifier(EvalContextModifier):
Armin Ronacher30fda272010-03-15 03:06:04 +0100899 """Modifies the eval context and reverts it later. Works exactly like
900 :class:`EvalContextModifier` but will only modify the
Armin Ronacher0dbaf392010-03-15 10:06:53 +0100901 :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.
Armin Ronacher30fda272010-03-15 03:06:04 +0100902 """
Armin Ronacher8346bd72010-03-14 19:43:47 +0100903 fields = ('body',)
904
905
Armin Ronacher8a1d27f2008-05-19 08:37:19 +0200906# make sure nobody creates custom nodes
907def _failing_new(*args, **kwargs):
908 raise TypeError('can\'t create custom node types')
909NodeType.__new__ = staticmethod(_failing_new); del _failing_new