blob: c827e2b3001ba1b4428cf0681de1608abf881be3 [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):
Armin Ronacher3383e1c2011-01-24 01:13:51 +010080 self.environment = environment
Armin Ronacher1da23d12010-04-05 18:11:18 +020081 if callable(environment.autoescape):
82 self.autoescape = environment.autoescape(template_name)
83 else:
84 self.autoescape = environment.autoescape
Armin Ronacher8346bd72010-03-14 19:43:47 +010085 self.volatile = False
86
87 def save(self):
88 return self.__dict__.copy()
89
90 def revert(self, old):
91 self.__dict__.clear()
92 self.__dict__.update(old)
93
94
95def get_eval_context(node, ctx):
96 if ctx is None:
97 if node.environment is None:
98 raise RuntimeError('if no eval context is passed, the '
99 'node must have an attached '
100 'environment.')
101 return EvalContext(node.environment)
102 return ctx
103
104
Armin Ronacher07bc6842008-03-31 14:18:49 +0200105class Node(object):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200106 """Baseclass for all Jinja2 nodes. There are a number of nodes available
kracekumar9c198cd2011-11-25 08:26:55 +0530107 of different types. There are four major types:
Armin Ronacher023b5e92008-05-08 11:03:10 +0200108
109 - :class:`Stmt`: statements
110 - :class:`Expr`: expressions
111 - :class:`Helper`: helper nodes
112 - :class:`Template`: the outermost wrapper node
113
114 All nodes have fields and attributes. Fields may be other nodes, lists,
115 or arbitrary values. Fields are passed to the constructor as regular
116 positional arguments, attributes as keyword arguments. Each node has
117 two attributes: `lineno` (the line number of the node) and `environment`.
118 The `environment` attribute is set at the end of the parsing process for
119 all nodes automatically.
120 """
Armin Ronacher07bc6842008-03-31 14:18:49 +0200121 __metaclass__ = NodeType
Armin Ronachere791c2a2008-04-07 18:39:54 +0200122 fields = ()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200123 attributes = ('lineno', 'environment')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200124 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200125
Armin Ronacher023b5e92008-05-08 11:03:10 +0200126 def __init__(self, *fields, **attributes):
Armin Ronacher69e12db2008-05-12 09:00:03 +0200127 if self.abstract:
128 raise TypeError('abstract nodes are not instanciable')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200129 if fields:
130 if len(fields) != len(self.fields):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200131 if not self.fields:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200132 raise TypeError('%r takes 0 arguments' %
133 self.__class__.__name__)
134 raise TypeError('%r takes 0 or %d argument%s' % (
135 self.__class__.__name__,
Armin Ronachere791c2a2008-04-07 18:39:54 +0200136 len(self.fields),
137 len(self.fields) != 1 and 's' or ''
Armin Ronacher07bc6842008-03-31 14:18:49 +0200138 ))
Armin Ronacher023b5e92008-05-08 11:03:10 +0200139 for name, arg in izip(self.fields, fields):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200140 setattr(self, name, arg)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200141 for attr in self.attributes:
Armin Ronacher023b5e92008-05-08 11:03:10 +0200142 setattr(self, attr, attributes.pop(attr, None))
143 if attributes:
144 raise TypeError('unknown attribute %r' %
145 iter(attributes).next())
Armin Ronacher07bc6842008-03-31 14:18:49 +0200146
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200147 def iter_fields(self, exclude=None, only=None):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200148 """This method iterates over all fields that are defined and yields
Armin Ronacher3da90312008-05-23 16:37:28 +0200149 ``(key, value)`` tuples. Per default all fields are returned, but
150 it's possible to limit that to some fields by providing the `only`
151 parameter or to exclude some using the `exclude` parameter. Both
152 should be sets or tuples of field names.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200153 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200154 for name in self.fields:
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200155 if (exclude is only is None) or \
156 (exclude is not None and name not in exclude) or \
157 (only is not None and name in only):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200158 try:
159 yield name, getattr(self, name)
160 except AttributeError:
161 pass
Armin Ronacher07bc6842008-03-31 14:18:49 +0200162
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200163 def iter_child_nodes(self, exclude=None, only=None):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200164 """Iterates over all direct child nodes of the node. This iterates
165 over all fields and yields the values of they are nodes. If the value
166 of a field is a list all the nodes in that list are returned.
167 """
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200168 for field, item in self.iter_fields(exclude, only):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200169 if isinstance(item, list):
170 for n in item:
171 if isinstance(n, Node):
172 yield n
173 elif isinstance(item, Node):
174 yield item
175
Armin Ronachere791c2a2008-04-07 18:39:54 +0200176 def find(self, node_type):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200177 """Find the first node of a given type. If no such node exists the
178 return value is `None`.
179 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200180 for result in self.find_all(node_type):
181 return result
182
183 def find_all(self, node_type):
Armin Ronacher63cf9b82009-07-26 10:33:36 +0200184 """Find all the nodes of a given type. If the type is a tuple,
185 the check is performed for any of the tuple items.
186 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200187 for child in self.iter_child_nodes():
188 if isinstance(child, node_type):
189 yield child
190 for result in child.find_all(node_type):
191 yield result
192
193 def set_ctx(self, ctx):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200194 """Reset the context of a node and all child nodes. Per default the
195 parser will all generate nodes that have a 'load' context as it's the
196 most common one. This method is used in the parser to set assignment
197 targets and other nodes to a store context.
Armin Ronachere791c2a2008-04-07 18:39:54 +0200198 """
199 todo = deque([self])
200 while todo:
201 node = todo.popleft()
202 if 'ctx' in node.fields:
203 node.ctx = ctx
204 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200205 return self
Armin Ronachere791c2a2008-04-07 18:39:54 +0200206
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200207 def set_lineno(self, lineno, override=False):
208 """Set the line numbers of the node and children."""
209 todo = deque([self])
210 while todo:
211 node = todo.popleft()
212 if 'lineno' in node.attributes:
213 if node.lineno is None or override:
214 node.lineno = lineno
215 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200216 return self
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200217
Armin Ronacherd55ab532008-04-09 16:13:39 +0200218 def set_environment(self, environment):
219 """Set the environment for all nodes."""
220 todo = deque([self])
221 while todo:
222 node = todo.popleft()
223 node.environment = environment
224 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200225 return self
Armin Ronacherd55ab532008-04-09 16:13:39 +0200226
Armin Ronacher69e12db2008-05-12 09:00:03 +0200227 def __eq__(self, other):
Armin Ronacherb3a1fcf2008-05-15 11:04:14 +0200228 return type(self) is type(other) and \
229 tuple(self.iter_fields()) == tuple(other.iter_fields())
Armin Ronacher69e12db2008-05-12 09:00:03 +0200230
231 def __ne__(self, other):
232 return not self.__eq__(other)
233
Armin Ronacher07bc6842008-03-31 14:18:49 +0200234 def __repr__(self):
235 return '%s(%s)' % (
236 self.__class__.__name__,
237 ', '.join('%s=%r' % (arg, getattr(self, arg, None)) for
Armin Ronachere791c2a2008-04-07 18:39:54 +0200238 arg in self.fields)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200239 )
240
241
242class Stmt(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200243 """Base node for all statements."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200244 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200245
246
247class Helper(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200248 """Nodes that exist in a specific context only."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200249 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200250
251
252class Template(Node):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200253 """Node that represents a template. This must be the outermost node that
254 is passed to the compiler.
255 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200256 fields = ('body',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200257
258
259class Output(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200260 """A node that holds multiple expressions which are then printed out.
261 This is used both for the `print` statement and the regular template data.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200262 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200263 fields = ('nodes',)
264
Armin Ronacher07bc6842008-03-31 14:18:49 +0200265
266class Extends(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200267 """Represents an extends statement."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200268 fields = ('template',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200269
270
271class For(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200272 """The for loop. `target` is the target for the iteration (usually a
273 :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list
274 of nodes that are used as loop-body, and `else_` a list of nodes for the
275 `else` block. If no else node exists it has to be an empty list.
276
277 For filtered nodes an expression can be stored as `test`, otherwise `None`.
278 """
Armin Ronacherfdf95302008-05-11 22:20:51 +0200279 fields = ('target', 'iter', 'body', 'else_', 'test', 'recursive')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200280
281
282class If(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200283 """If `test` is true, `body` is rendered, else `else_`."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200284 fields = ('test', 'body', 'else_')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200285
286
287class Macro(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200288 """A macro definition. `name` is the name of the macro, `args` a list of
289 arguments and `defaults` a list of defaults if there are any. `body` is
290 a list of nodes for the macro body.
291 """
Armin Ronacher8efc5222008-04-08 14:47:40 +0200292 fields = ('name', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200293
294
295class CallBlock(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200296 """Like a macro without a name but a call instead. `call` is called with
297 the unnamed macro as `caller` argument this node holds.
298 """
Armin Ronacherc9705c22008-04-27 21:28:03 +0200299 fields = ('call', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200300
301
Armin Ronacher07bc6842008-03-31 14:18:49 +0200302class FilterBlock(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200303 """Node for filter sections."""
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200304 fields = ('body', 'filter')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200305
306
307class Block(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200308 """A node that represents a block."""
Armin Ronacher74a0cd92009-02-19 15:56:53 +0100309 fields = ('name', 'body', 'scoped')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200310
311
312class Include(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200313 """A node that represents the include tag."""
Armin Ronacher37f58ce2008-12-27 13:10:38 +0100314 fields = ('template', 'with_context', 'ignore_missing')
Armin Ronacher0611e492008-04-25 23:44:14 +0200315
316
317class Import(Stmt):
318 """A node that represents the import tag."""
Armin Ronacherea847c52008-05-02 20:04:32 +0200319 fields = ('template', 'target', 'with_context')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200320
321
Armin Ronacher0611e492008-04-25 23:44:14 +0200322class FromImport(Stmt):
323 """A node that represents the from import tag. It's important to not
324 pass unsafe names to the name attribute. The compiler translates the
325 attribute lookups directly into getattr calls and does *not* use the
Armin Ronacherb9388772008-06-25 20:43:18 +0200326 subscript callback of the interface. As exported variables may not
Armin Ronacher0611e492008-04-25 23:44:14 +0200327 start with double underscores (which the parser asserts) this is not a
328 problem for regular Jinja code, but if this node is used in an extension
329 extra care must be taken.
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200330
331 The list of names may contain tuples if aliases are wanted.
Armin Ronacher0611e492008-04-25 23:44:14 +0200332 """
Armin Ronacherea847c52008-05-02 20:04:32 +0200333 fields = ('template', 'names', 'with_context')
Armin Ronacher0611e492008-04-25 23:44:14 +0200334
335
Armin Ronacher07bc6842008-03-31 14:18:49 +0200336class ExprStmt(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200337 """A statement that evaluates an expression and discards the result."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200338 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200339
340
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200341class Assign(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200342 """Assigns an expression to a target."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200343 fields = ('target', 'node')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200344
345
Armin Ronacher07bc6842008-03-31 14:18:49 +0200346class Expr(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200347 """Baseclass for all expressions."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200348 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200349
Armin Ronacher8346bd72010-03-14 19:43:47 +0100350 def as_const(self, eval_ctx=None):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200351 """Return the value of the expression as constant or raise
Armin Ronacher8346bd72010-03-14 19:43:47 +0100352 :exc:`Impossible` if this was not possible.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200353
Armin Ronacher8346bd72010-03-14 19:43:47 +0100354 An :class:`EvalContext` can be provided, if none is given
355 a default context is created which requires the nodes to have
356 an attached environment.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200357
Armin Ronacher8346bd72010-03-14 19:43:47 +0100358 .. versionchanged:: 2.4
359 the `eval_ctx` parameter was added.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200360 """
361 raise Impossible()
362
363 def can_assign(self):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200364 """Check if it's possible to assign something to this node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200365 return False
366
367
368class BinExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200369 """Baseclass for all binary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200370 fields = ('left', 'right')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200371 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200372 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200373
Armin Ronacher8346bd72010-03-14 19:43:47 +0100374 def as_const(self, eval_ctx=None):
375 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronachera9195382010-11-29 13:21:57 +0100376 # intercepted operators cannot be folded at compile time
377 if self.environment.sandboxed and \
378 self.operator in self.environment.intercepted_binops:
379 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200380 f = _binop_to_func[self.operator]
381 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100382 return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900383 except Exception:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200384 raise Impossible()
385
386
387class UnaryExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200388 """Baseclass for all unary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200389 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200390 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200391 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200392
Armin Ronacher8346bd72010-03-14 19:43:47 +0100393 def as_const(self, eval_ctx=None):
394 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronachera9195382010-11-29 13:21:57 +0100395 # intercepted operators cannot be folded at compile time
396 if self.environment.sandboxed and \
397 self.operator in self.environment.intercepted_unops:
398 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200399 f = _uaop_to_func[self.operator]
400 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100401 return f(self.node.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900402 except Exception:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200403 raise Impossible()
404
405
406class Name(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200407 """Looks up a name or stores a value in a name.
408 The `ctx` of the node can be one of the following values:
409
410 - `store`: store a value in the name
411 - `load`: load that name
412 - `param`: like `store` but if the name was defined as function parameter.
413 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200414 fields = ('name', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200415
416 def can_assign(self):
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200417 return self.name not in ('true', 'false', 'none',
418 'True', 'False', 'None')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200419
420
421class Literal(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200422 """Baseclass for literals."""
Armin Ronacher69e12db2008-05-12 09:00:03 +0200423 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200424
425
426class Const(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200427 """All constant values. The parser will return this node for simple
428 constants such as ``42`` or ``"foo"`` but it can be used to store more
429 complex values such as lists too. Only constants with a safe
430 representation (objects where ``eval(repr(x)) == x`` is true).
431 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200432 fields = ('value',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200433
Armin Ronacher8346bd72010-03-14 19:43:47 +0100434 def as_const(self, eval_ctx=None):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200435 return self.value
436
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200437 @classmethod
Armin Ronacherd55ab532008-04-09 16:13:39 +0200438 def from_untrusted(cls, value, lineno=None, environment=None):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200439 """Return a const object if the value is representable as
440 constant value in the generated code, otherwise it will raise
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200441 an `Impossible` exception.
442 """
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200443 from compiler import has_safe_repr
444 if not has_safe_repr(value):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200445 raise Impossible()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200446 return cls(value, lineno=lineno, environment=environment)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200447
Armin Ronacher07bc6842008-03-31 14:18:49 +0200448
Armin Ronacher5411ce72008-05-25 11:36:22 +0200449class TemplateData(Literal):
450 """A constant template string."""
451 fields = ('data',)
452
Armin Ronacher8346bd72010-03-14 19:43:47 +0100453 def as_const(self, eval_ctx=None):
Armin Ronacherffaa2e72010-05-29 20:57:16 +0200454 eval_ctx = get_eval_context(self, eval_ctx)
455 if eval_ctx.volatile:
456 raise Impossible()
457 if eval_ctx.autoescape:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200458 return Markup(self.data)
459 return self.data
460
461
Armin Ronacher07bc6842008-03-31 14:18:49 +0200462class Tuple(Literal):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200463 """For loop unpacking and some other things like multiple arguments
Armin Ronacher023b5e92008-05-08 11:03:10 +0200464 for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
465 is used for loading the names or storing.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200466 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200467 fields = ('items', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200468
Armin Ronacher8346bd72010-03-14 19:43:47 +0100469 def as_const(self, eval_ctx=None):
470 eval_ctx = get_eval_context(self, eval_ctx)
471 return tuple(x.as_const(eval_ctx) for x in self.items)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200472
473 def can_assign(self):
474 for item in self.items:
475 if not item.can_assign():
476 return False
477 return True
478
479
480class List(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200481 """Any list literal such as ``[1, 2, 3]``"""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200482 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200483
Armin Ronacher8346bd72010-03-14 19:43:47 +0100484 def as_const(self, eval_ctx=None):
485 eval_ctx = get_eval_context(self, eval_ctx)
486 return [x.as_const(eval_ctx) for x in self.items]
Armin Ronacher07bc6842008-03-31 14:18:49 +0200487
488
489class Dict(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200490 """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
491 :class:`Pair` nodes.
492 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200493 fields = ('items',)
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 dict(x.as_const(eval_ctx) for x in self.items)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200498
499
500class Pair(Helper):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200501 """A key, value pair for dicts."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200502 fields = ('key', 'value')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200503
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.as_const(eval_ctx), self.value.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200507
508
Armin Ronacher8efc5222008-04-08 14:47:40 +0200509class Keyword(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200510 """A key, value pair for keyword arguments where key is a string."""
Armin Ronacher8efc5222008-04-08 14:47:40 +0200511 fields = ('key', 'value')
512
Armin Ronacher8346bd72010-03-14 19:43:47 +0100513 def as_const(self, eval_ctx=None):
514 eval_ctx = get_eval_context(self, eval_ctx)
515 return self.key, self.value.as_const(eval_ctx)
Armin Ronacher335b87a2008-09-21 17:08:48 +0200516
Armin Ronacher8efc5222008-04-08 14:47:40 +0200517
Armin Ronacher07bc6842008-03-31 14:18:49 +0200518class CondExpr(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200519 """A conditional expression (inline if expression). (``{{
520 foo if bar else baz }}``)
521 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200522 fields = ('test', 'expr1', 'expr2')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200523
Armin Ronacher8346bd72010-03-14 19:43:47 +0100524 def as_const(self, eval_ctx=None):
525 eval_ctx = get_eval_context(self, eval_ctx)
526 if self.test.as_const(eval_ctx):
527 return self.expr1.as_const(eval_ctx)
Armin Ronacher547d0b62008-07-04 16:35:10 +0200528
529 # if we evaluate to an undefined object, we better do that at runtime
530 if self.expr2 is None:
531 raise Impossible()
532
Armin Ronacher8346bd72010-03-14 19:43:47 +0100533 return self.expr2.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200534
535
536class Filter(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200537 """This node applies a filter on an expression. `name` is the name of
538 the filter, the rest of the fields are the same as for :class:`Call`.
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200539
540 If the `node` of a filter is `None` the contents of the last buffer are
541 filtered. Buffers are created by macros and filter blocks.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200542 """
Armin Ronacherd55ab532008-04-09 16:13:39 +0200543 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200544
Armin Ronacher8346bd72010-03-14 19:43:47 +0100545 def as_const(self, eval_ctx=None):
546 eval_ctx = get_eval_context(self, eval_ctx)
547 if eval_ctx.volatile or self.node is None:
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200548 raise Impossible()
Armin Ronacher0d242be2010-02-10 01:35:13 +0100549 # we have to be careful here because we call filter_ below.
550 # if this variable would be called filter, 2to3 would wrap the
551 # call in a list beause it is assuming we are talking about the
552 # builtin filter function here which no longer returns a list in
553 # python 3. because of that, do not rename filter_ to filter!
554 filter_ = self.environment.filters.get(self.name)
555 if filter_ is None or getattr(filter_, 'contextfilter', False):
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200556 raise Impossible()
Armin Ronacher8346bd72010-03-14 19:43:47 +0100557 obj = self.node.as_const(eval_ctx)
558 args = [x.as_const(eval_ctx) for x in self.args]
559 if getattr(filter_, 'evalcontextfilter', False):
560 args.insert(0, eval_ctx)
561 elif getattr(filter_, 'environmentfilter', False):
Armin Ronacher9a027f42008-04-17 11:13:40 +0200562 args.insert(0, self.environment)
Armin Ronacher8346bd72010-03-14 19:43:47 +0100563 kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
Armin Ronacherd55ab532008-04-09 16:13:39 +0200564 if self.dyn_args is not None:
565 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100566 args.extend(self.dyn_args.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900567 except Exception:
Armin Ronacherd55ab532008-04-09 16:13:39 +0200568 raise Impossible()
569 if self.dyn_kwargs is not None:
570 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100571 kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900572 except Exception:
Armin Ronacherd55ab532008-04-09 16:13:39 +0200573 raise Impossible()
574 try:
Armin Ronacher0d242be2010-02-10 01:35:13 +0100575 return filter_(obj, *args, **kwargs)
Ian Lewisab014bd2010-10-31 20:29:28 +0900576 except Exception:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200577 raise Impossible()
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200578
579
Armin Ronacher07bc6842008-03-31 14:18:49 +0200580class Test(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200581 """Applies a test on an expression. `name` is the name of the test, the
582 rest of the fields are the same as for :class:`Call`.
583 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200584 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200585
586
587class Call(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200588 """Calls an expression. `args` is a list of arguments, `kwargs` a list
589 of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
590 and `dyn_kwargs` has to be either `None` or a node that is used as
591 node for dynamic positional (``*args``) or keyword (``**kwargs``)
592 arguments.
593 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200594 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200595
Armin Ronacher8346bd72010-03-14 19:43:47 +0100596 def as_const(self, eval_ctx=None):
597 eval_ctx = get_eval_context(self, eval_ctx)
598 if eval_ctx.volatile:
599 raise Impossible()
600 obj = self.node.as_const(eval_ctx)
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200601
602 # don't evaluate context functions
Armin Ronacher8346bd72010-03-14 19:43:47 +0100603 args = [x.as_const(eval_ctx) for x in self.args]
Armin Ronacher5a5ce732010-05-23 22:58:28 +0200604 if isinstance(obj, _context_function_types):
605 if getattr(obj, 'contextfunction', False):
606 raise Impossible()
607 elif getattr(obj, 'evalcontextfunction', False):
608 args.insert(0, eval_ctx)
609 elif getattr(obj, 'environmentfunction', False):
610 args.insert(0, self.environment)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200611
Armin Ronacher8346bd72010-03-14 19:43:47 +0100612 kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200613 if self.dyn_args is not None:
614 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100615 args.extend(self.dyn_args.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900616 except Exception:
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200617 raise Impossible()
618 if self.dyn_kwargs is not None:
619 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100620 kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900621 except Exception:
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200622 raise Impossible()
623 try:
624 return obj(*args, **kwargs)
Ian Lewisab014bd2010-10-31 20:29:28 +0900625 except Exception:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200626 raise Impossible()
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200627
Armin Ronacher07bc6842008-03-31 14:18:49 +0200628
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200629class Getitem(Expr):
Armin Ronacherb9388772008-06-25 20:43:18 +0200630 """Get an attribute or item from an expression and prefer the item."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200631 fields = ('node', 'arg', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200632
Armin Ronacher8346bd72010-03-14 19:43:47 +0100633 def as_const(self, eval_ctx=None):
634 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200635 if self.ctx != 'load':
636 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200637 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100638 return self.environment.getitem(self.node.as_const(eval_ctx),
639 self.arg.as_const(eval_ctx))
Ian Lewisab014bd2010-10-31 20:29:28 +0900640 except Exception:
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200641 raise Impossible()
642
643 def can_assign(self):
644 return False
645
646
647class Getattr(Expr):
Armin Ronacherb9388772008-06-25 20:43:18 +0200648 """Get an attribute or item from an expression that is a ascii-only
649 bytestring and prefer the attribute.
650 """
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200651 fields = ('node', 'attr', 'ctx')
652
Armin Ronacher8346bd72010-03-14 19:43:47 +0100653 def as_const(self, eval_ctx=None):
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200654 if self.ctx != 'load':
655 raise Impossible()
656 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100657 eval_ctx = get_eval_context(self, eval_ctx)
Georg Brandl93d2df72010-05-23 22:35:53 +0200658 return self.environment.getattr(self.node.as_const(eval_ctx),
659 self.attr)
Ian Lewisab014bd2010-10-31 20:29:28 +0900660 except Exception:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200661 raise Impossible()
662
663 def can_assign(self):
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200664 return False
Armin Ronacher07bc6842008-03-31 14:18:49 +0200665
666
667class Slice(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200668 """Represents a slice object. This must only be used as argument for
669 :class:`Subscript`.
670 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200671 fields = ('start', 'stop', 'step')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200672
Armin Ronacher8346bd72010-03-14 19:43:47 +0100673 def as_const(self, eval_ctx=None):
674 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200675 def const(obj):
676 if obj is None:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100677 return None
678 return obj.as_const(eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200679 return slice(const(self.start), const(self.stop), const(self.step))
680
Armin Ronacher07bc6842008-03-31 14:18:49 +0200681
682class Concat(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200683 """Concatenates the list of expressions provided after converting them to
684 unicode.
685 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200686 fields = ('nodes',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200687
Armin Ronacher8346bd72010-03-14 19:43:47 +0100688 def as_const(self, eval_ctx=None):
689 eval_ctx = get_eval_context(self, eval_ctx)
690 return ''.join(unicode(x.as_const(eval_ctx)) for x in self.nodes)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200691
692
693class Compare(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200694 """Compares an expression with some other expressions. `ops` must be a
695 list of :class:`Operand`\s.
696 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200697 fields = ('expr', 'ops')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200698
Armin Ronacher8346bd72010-03-14 19:43:47 +0100699 def as_const(self, eval_ctx=None):
700 eval_ctx = get_eval_context(self, eval_ctx)
701 result = value = self.expr.as_const(eval_ctx)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200702 try:
703 for op in self.ops:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100704 new_value = op.expr.as_const(eval_ctx)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200705 result = _cmpop_to_func[op.op](value, new_value)
706 value = new_value
Ian Lewisab014bd2010-10-31 20:29:28 +0900707 except Exception:
Armin Ronacherb5124e62008-04-25 00:36:14 +0200708 raise Impossible()
Armin Ronacher625215e2008-04-13 16:31:08 +0200709 return result
710
Armin Ronacher07bc6842008-03-31 14:18:49 +0200711
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200712class Operand(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200713 """Holds an operator and an expression."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200714 fields = ('op', 'expr')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200715
Armin Ronacher023b5e92008-05-08 11:03:10 +0200716if __debug__:
717 Operand.__doc__ += '\nThe following operators are available: ' + \
718 ', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
719 set(_uaop_to_func) | set(_cmpop_to_func)))
720
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200721
Armin Ronacher07bc6842008-03-31 14:18:49 +0200722class Mul(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200723 """Multiplies the left with the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200724 operator = '*'
725
726
727class Div(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200728 """Divides the left by the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200729 operator = '/'
730
731
732class FloorDiv(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200733 """Divides the left by the right node and truncates conver the
734 result into an integer by truncating.
735 """
Armin Ronacher07bc6842008-03-31 14:18:49 +0200736 operator = '//'
737
738
739class Add(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200740 """Add the left to the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200741 operator = '+'
742
743
744class Sub(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200745 """Substract the right from the left node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200746 operator = '-'
747
748
749class Mod(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200750 """Left modulo right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200751 operator = '%'
752
753
754class Pow(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200755 """Left to the power of right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200756 operator = '**'
757
758
759class And(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200760 """Short circuited AND."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200761 operator = 'and'
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) and self.right.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200766
767
768class Or(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200769 """Short circuited OR."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200770 operator = 'or'
771
Armin Ronacher8346bd72010-03-14 19:43:47 +0100772 def as_const(self, eval_ctx=None):
773 eval_ctx = get_eval_context(self, eval_ctx)
774 return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200775
776
777class Not(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200778 """Negate the expression."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200779 operator = 'not'
780
781
Armin Ronachere791c2a2008-04-07 18:39:54 +0200782class Neg(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200783 """Make the expression negative."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200784 operator = '-'
785
786
Armin Ronachere791c2a2008-04-07 18:39:54 +0200787class Pos(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200788 """Make the expression positive (noop for most expressions)"""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200789 operator = '+'
Armin Ronacher023b5e92008-05-08 11:03:10 +0200790
791
792# Helpers for extensions
793
794
795class EnvironmentAttribute(Expr):
796 """Loads an attribute from the environment object. This is useful for
797 extensions that want to call a callback stored on the environment.
798 """
799 fields = ('name',)
800
801
802class ExtensionAttribute(Expr):
803 """Returns the attribute of an extension bound to the environment.
804 The identifier is the identifier of the :class:`Extension`.
Armin Ronacherb9e78752008-05-10 23:36:28 +0200805
806 This node is usually constructed by calling the
807 :meth:`~jinja2.ext.Extension.attr` method on an extension.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200808 """
Armin Ronacher6df604e2008-05-23 22:18:38 +0200809 fields = ('identifier', 'name')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200810
811
812class ImportedName(Expr):
813 """If created with an import name the import name is returned on node
814 access. For example ``ImportedName('cgi.escape')`` returns the `escape`
815 function from the cgi module on evaluation. Imports are optimized by the
816 compiler so there is no need to assign them to local variables.
817 """
818 fields = ('importname',)
819
820
821class InternalName(Expr):
822 """An internal name in the compiler. You cannot create these nodes
Armin Ronacher762079c2008-05-08 23:57:56 +0200823 yourself but the parser provides a
824 :meth:`~jinja2.parser.Parser.free_identifier` method that creates
Armin Ronacher023b5e92008-05-08 11:03:10 +0200825 a new identifier for you. This identifier is not available from the
826 template and is not threated specially by the compiler.
827 """
828 fields = ('name',)
829
830 def __init__(self):
831 raise TypeError('Can\'t create internal names. Use the '
832 '`free_identifier` method on a parser.')
833
834
835class MarkSafe(Expr):
836 """Mark the wrapped expression as safe (wrap it as `Markup`)."""
837 fields = ('expr',)
838
Armin Ronacher8346bd72010-03-14 19:43:47 +0100839 def as_const(self, eval_ctx=None):
840 eval_ctx = get_eval_context(self, eval_ctx)
841 return Markup(self.expr.as_const(eval_ctx))
Armin Ronacher023b5e92008-05-08 11:03:10 +0200842
843
Armin Ronacher4da90342010-05-29 17:35:10 +0200844class MarkSafeIfAutoescape(Expr):
845 """Mark the wrapped expression as safe (wrap it as `Markup`) but
846 only if autoescaping is active.
847
848 .. versionadded:: 2.5
849 """
850 fields = ('expr',)
851
852 def as_const(self, eval_ctx=None):
853 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacherffaa2e72010-05-29 20:57:16 +0200854 if eval_ctx.volatile:
855 raise Impossible()
Armin Ronacher4da90342010-05-29 17:35:10 +0200856 expr = self.expr.as_const(eval_ctx)
857 if eval_ctx.autoescape:
858 return Markup(expr)
859 return expr
860
861
Armin Ronacher6df604e2008-05-23 22:18:38 +0200862class ContextReference(Expr):
Armin Ronachercedb4822010-03-24 10:53:22 +0100863 """Returns the current template context. It can be used like a
864 :class:`Name` node, with a ``'load'`` ctx and will return the
865 current :class:`~jinja2.runtime.Context` object.
866
867 Here an example that assigns the current template name to a
868 variable named `foo`::
869
870 Assign(Name('foo', ctx='store'),
871 Getattr(ContextReference(), 'name'))
872 """
Armin Ronacher6df604e2008-05-23 22:18:38 +0200873
874
Armin Ronachered1e0d42008-05-18 20:25:28 +0200875class Continue(Stmt):
876 """Continue a loop."""
877
878
879class Break(Stmt):
880 """Break a loop."""
881
882
Armin Ronacher271a0eb2009-02-11 22:49:08 +0100883class Scope(Stmt):
884 """An artificial scope."""
885 fields = ('body',)
886
887
Armin Ronacher8346bd72010-03-14 19:43:47 +0100888class EvalContextModifier(Stmt):
Armin Ronacher30fda272010-03-15 03:06:04 +0100889 """Modifies the eval context. For each option that should be modified,
890 a :class:`Keyword` has to be added to the :attr:`options` list.
891
892 Example to change the `autoescape` setting::
893
894 EvalContextModifier(options=[Keyword('autoescape', Const(True))])
895 """
Armin Ronacher8346bd72010-03-14 19:43:47 +0100896 fields = ('options',)
897
898
899class ScopedEvalContextModifier(EvalContextModifier):
Armin Ronacher30fda272010-03-15 03:06:04 +0100900 """Modifies the eval context and reverts it later. Works exactly like
901 :class:`EvalContextModifier` but will only modify the
Armin Ronacher0dbaf392010-03-15 10:06:53 +0100902 :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.
Armin Ronacher30fda272010-03-15 03:06:04 +0100903 """
Armin Ronacher8346bd72010-03-14 19:43:47 +0100904 fields = ('body',)
905
906
Armin Ronacher8a1d27f2008-05-19 08:37:19 +0200907# make sure nobody creates custom nodes
908def _failing_new(*args, **kwargs):
909 raise TypeError('can\'t create custom node types')
910NodeType.__new__ = staticmethod(_failing_new); del _failing_new