blob: d6157a44e51d3bd250b613ebb7954d668ff43851 [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 Ronacherd84ec462008-04-29 13:43:16 +020018from jinja2.utils import Markup
Armin Ronacher07bc6842008-03-31 14:18:49 +020019
20
21_binop_to_func = {
22 '*': operator.mul,
23 '/': operator.truediv,
24 '//': operator.floordiv,
25 '**': operator.pow,
26 '%': operator.mod,
27 '+': operator.add,
28 '-': operator.sub
29}
30
31_uaop_to_func = {
32 'not': operator.not_,
33 '+': operator.pos,
34 '-': operator.neg
35}
36
Armin Ronacher625215e2008-04-13 16:31:08 +020037_cmpop_to_func = {
38 'eq': operator.eq,
39 'ne': operator.ne,
40 'gt': operator.gt,
41 'gteq': operator.ge,
42 'lt': operator.lt,
43 'lteq': operator.le,
Armin Ronacherb5124e62008-04-25 00:36:14 +020044 'in': lambda a, b: a in b,
45 'notin': lambda a, b: a not in b
Armin Ronacher625215e2008-04-13 16:31:08 +020046}
47
Armin Ronacher07bc6842008-03-31 14:18:49 +020048
49class Impossible(Exception):
Armin Ronacher8efc5222008-04-08 14:47:40 +020050 """Raised if the node could not perform a requested action."""
Armin Ronacher07bc6842008-03-31 14:18:49 +020051
52
53class NodeType(type):
Armin Ronacher8efc5222008-04-08 14:47:40 +020054 """A metaclass for nodes that handles the field and attribute
55 inheritance. fields and attributes from the parent class are
56 automatically forwarded to the child."""
Armin Ronacher07bc6842008-03-31 14:18:49 +020057
58 def __new__(cls, name, bases, d):
Armin Ronachere791c2a2008-04-07 18:39:54 +020059 for attr in 'fields', 'attributes':
Armin Ronacher07bc6842008-03-31 14:18:49 +020060 storage = []
Armin Ronacher7324eb82008-04-21 07:55:52 +020061 storage.extend(getattr(bases[0], attr, ()))
Armin Ronacher07bc6842008-03-31 14:18:49 +020062 storage.extend(d.get(attr, ()))
Armin Ronacher7324eb82008-04-21 07:55:52 +020063 assert len(bases) == 1, 'multiple inheritance not allowed'
64 assert len(storage) == len(set(storage)), 'layout conflict'
Armin Ronacher07bc6842008-03-31 14:18:49 +020065 d[attr] = tuple(storage)
Armin Ronacher023b5e92008-05-08 11:03:10 +020066 d.setdefault('abstract', False)
Armin Ronacher7324eb82008-04-21 07:55:52 +020067 return type.__new__(cls, name, bases, d)
Armin Ronacher07bc6842008-03-31 14:18:49 +020068
69
Armin Ronacher8346bd72010-03-14 19:43:47 +010070class EvalContext(object):
Armin Ronacher30fda272010-03-15 03:06:04 +010071 """Holds evaluation time information. Custom attributes can be attached
72 to it in extensions.
73 """
Armin Ronacher8346bd72010-03-14 19:43:47 +010074
75 def __init__(self, environment):
76 self.autoescape = environment.autoescape
77 self.volatile = False
78
79 def save(self):
80 return self.__dict__.copy()
81
82 def revert(self, old):
83 self.__dict__.clear()
84 self.__dict__.update(old)
85
86
87def get_eval_context(node, ctx):
88 if ctx is None:
89 if node.environment is None:
90 raise RuntimeError('if no eval context is passed, the '
91 'node must have an attached '
92 'environment.')
93 return EvalContext(node.environment)
94 return ctx
95
96
Armin Ronacher07bc6842008-03-31 14:18:49 +020097class Node(object):
Armin Ronacher023b5e92008-05-08 11:03:10 +020098 """Baseclass for all Jinja2 nodes. There are a number of nodes available
99 of different types. There are three major types:
100
101 - :class:`Stmt`: statements
102 - :class:`Expr`: expressions
103 - :class:`Helper`: helper nodes
104 - :class:`Template`: the outermost wrapper node
105
106 All nodes have fields and attributes. Fields may be other nodes, lists,
107 or arbitrary values. Fields are passed to the constructor as regular
108 positional arguments, attributes as keyword arguments. Each node has
109 two attributes: `lineno` (the line number of the node) and `environment`.
110 The `environment` attribute is set at the end of the parsing process for
111 all nodes automatically.
112 """
Armin Ronacher07bc6842008-03-31 14:18:49 +0200113 __metaclass__ = NodeType
Armin Ronachere791c2a2008-04-07 18:39:54 +0200114 fields = ()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200115 attributes = ('lineno', 'environment')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200116 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200117
Armin Ronacher023b5e92008-05-08 11:03:10 +0200118 def __init__(self, *fields, **attributes):
Armin Ronacher69e12db2008-05-12 09:00:03 +0200119 if self.abstract:
120 raise TypeError('abstract nodes are not instanciable')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200121 if fields:
122 if len(fields) != len(self.fields):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200123 if not self.fields:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200124 raise TypeError('%r takes 0 arguments' %
125 self.__class__.__name__)
126 raise TypeError('%r takes 0 or %d argument%s' % (
127 self.__class__.__name__,
Armin Ronachere791c2a2008-04-07 18:39:54 +0200128 len(self.fields),
129 len(self.fields) != 1 and 's' or ''
Armin Ronacher07bc6842008-03-31 14:18:49 +0200130 ))
Armin Ronacher023b5e92008-05-08 11:03:10 +0200131 for name, arg in izip(self.fields, fields):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200132 setattr(self, name, arg)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200133 for attr in self.attributes:
Armin Ronacher023b5e92008-05-08 11:03:10 +0200134 setattr(self, attr, attributes.pop(attr, None))
135 if attributes:
136 raise TypeError('unknown attribute %r' %
137 iter(attributes).next())
Armin Ronacher07bc6842008-03-31 14:18:49 +0200138
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200139 def iter_fields(self, exclude=None, only=None):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200140 """This method iterates over all fields that are defined and yields
Armin Ronacher3da90312008-05-23 16:37:28 +0200141 ``(key, value)`` tuples. Per default all fields are returned, but
142 it's possible to limit that to some fields by providing the `only`
143 parameter or to exclude some using the `exclude` parameter. Both
144 should be sets or tuples of field names.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200145 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200146 for name in self.fields:
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200147 if (exclude is only is None) or \
148 (exclude is not None and name not in exclude) or \
149 (only is not None and name in only):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200150 try:
151 yield name, getattr(self, name)
152 except AttributeError:
153 pass
Armin Ronacher07bc6842008-03-31 14:18:49 +0200154
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200155 def iter_child_nodes(self, exclude=None, only=None):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200156 """Iterates over all direct child nodes of the node. This iterates
157 over all fields and yields the values of they are nodes. If the value
158 of a field is a list all the nodes in that list are returned.
159 """
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200160 for field, item in self.iter_fields(exclude, only):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200161 if isinstance(item, list):
162 for n in item:
163 if isinstance(n, Node):
164 yield n
165 elif isinstance(item, Node):
166 yield item
167
Armin Ronachere791c2a2008-04-07 18:39:54 +0200168 def find(self, node_type):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200169 """Find the first node of a given type. If no such node exists the
170 return value is `None`.
171 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200172 for result in self.find_all(node_type):
173 return result
174
175 def find_all(self, node_type):
Armin Ronacher63cf9b82009-07-26 10:33:36 +0200176 """Find all the nodes of a given type. If the type is a tuple,
177 the check is performed for any of the tuple items.
178 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200179 for child in self.iter_child_nodes():
180 if isinstance(child, node_type):
181 yield child
182 for result in child.find_all(node_type):
183 yield result
184
185 def set_ctx(self, ctx):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200186 """Reset the context of a node and all child nodes. Per default the
187 parser will all generate nodes that have a 'load' context as it's the
188 most common one. This method is used in the parser to set assignment
189 targets and other nodes to a store context.
Armin Ronachere791c2a2008-04-07 18:39:54 +0200190 """
191 todo = deque([self])
192 while todo:
193 node = todo.popleft()
194 if 'ctx' in node.fields:
195 node.ctx = ctx
196 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200197 return self
Armin Ronachere791c2a2008-04-07 18:39:54 +0200198
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200199 def set_lineno(self, lineno, override=False):
200 """Set the line numbers of the node and children."""
201 todo = deque([self])
202 while todo:
203 node = todo.popleft()
204 if 'lineno' in node.attributes:
205 if node.lineno is None or override:
206 node.lineno = lineno
207 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200208 return self
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200209
Armin Ronacherd55ab532008-04-09 16:13:39 +0200210 def set_environment(self, environment):
211 """Set the environment for all nodes."""
212 todo = deque([self])
213 while todo:
214 node = todo.popleft()
215 node.environment = environment
216 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200217 return self
Armin Ronacherd55ab532008-04-09 16:13:39 +0200218
Armin Ronacher69e12db2008-05-12 09:00:03 +0200219 def __eq__(self, other):
Armin Ronacherb3a1fcf2008-05-15 11:04:14 +0200220 return type(self) is type(other) and \
221 tuple(self.iter_fields()) == tuple(other.iter_fields())
Armin Ronacher69e12db2008-05-12 09:00:03 +0200222
223 def __ne__(self, other):
224 return not self.__eq__(other)
225
Armin Ronacher07bc6842008-03-31 14:18:49 +0200226 def __repr__(self):
227 return '%s(%s)' % (
228 self.__class__.__name__,
229 ', '.join('%s=%r' % (arg, getattr(self, arg, None)) for
Armin Ronachere791c2a2008-04-07 18:39:54 +0200230 arg in self.fields)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200231 )
232
233
234class Stmt(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200235 """Base node for all statements."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200236 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200237
238
239class Helper(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200240 """Nodes that exist in a specific context only."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200241 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200242
243
244class Template(Node):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200245 """Node that represents a template. This must be the outermost node that
246 is passed to the compiler.
247 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200248 fields = ('body',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200249
250
251class Output(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200252 """A node that holds multiple expressions which are then printed out.
253 This is used both for the `print` statement and the regular template data.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200254 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200255 fields = ('nodes',)
256
Armin Ronacher07bc6842008-03-31 14:18:49 +0200257
258class Extends(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200259 """Represents an extends statement."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200260 fields = ('template',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200261
262
263class For(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200264 """The for loop. `target` is the target for the iteration (usually a
265 :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list
266 of nodes that are used as loop-body, and `else_` a list of nodes for the
267 `else` block. If no else node exists it has to be an empty list.
268
269 For filtered nodes an expression can be stored as `test`, otherwise `None`.
270 """
Armin Ronacherfdf95302008-05-11 22:20:51 +0200271 fields = ('target', 'iter', 'body', 'else_', 'test', 'recursive')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200272
273
274class If(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200275 """If `test` is true, `body` is rendered, else `else_`."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200276 fields = ('test', 'body', 'else_')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200277
278
279class Macro(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200280 """A macro definition. `name` is the name of the macro, `args` a list of
281 arguments and `defaults` a list of defaults if there are any. `body` is
282 a list of nodes for the macro body.
283 """
Armin Ronacher8efc5222008-04-08 14:47:40 +0200284 fields = ('name', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200285
286
287class CallBlock(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200288 """Like a macro without a name but a call instead. `call` is called with
289 the unnamed macro as `caller` argument this node holds.
290 """
Armin Ronacherc9705c22008-04-27 21:28:03 +0200291 fields = ('call', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200292
293
Armin Ronacher07bc6842008-03-31 14:18:49 +0200294class FilterBlock(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200295 """Node for filter sections."""
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200296 fields = ('body', 'filter')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200297
298
299class Block(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200300 """A node that represents a block."""
Armin Ronacher74a0cd92009-02-19 15:56:53 +0100301 fields = ('name', 'body', 'scoped')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200302
303
304class Include(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200305 """A node that represents the include tag."""
Armin Ronacher37f58ce2008-12-27 13:10:38 +0100306 fields = ('template', 'with_context', 'ignore_missing')
Armin Ronacher0611e492008-04-25 23:44:14 +0200307
308
309class Import(Stmt):
310 """A node that represents the import tag."""
Armin Ronacherea847c52008-05-02 20:04:32 +0200311 fields = ('template', 'target', 'with_context')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200312
313
Armin Ronacher0611e492008-04-25 23:44:14 +0200314class FromImport(Stmt):
315 """A node that represents the from import tag. It's important to not
316 pass unsafe names to the name attribute. The compiler translates the
317 attribute lookups directly into getattr calls and does *not* use the
Armin Ronacherb9388772008-06-25 20:43:18 +0200318 subscript callback of the interface. As exported variables may not
Armin Ronacher0611e492008-04-25 23:44:14 +0200319 start with double underscores (which the parser asserts) this is not a
320 problem for regular Jinja code, but if this node is used in an extension
321 extra care must be taken.
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200322
323 The list of names may contain tuples if aliases are wanted.
Armin Ronacher0611e492008-04-25 23:44:14 +0200324 """
Armin Ronacherea847c52008-05-02 20:04:32 +0200325 fields = ('template', 'names', 'with_context')
Armin Ronacher0611e492008-04-25 23:44:14 +0200326
327
Armin Ronacher07bc6842008-03-31 14:18:49 +0200328class ExprStmt(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200329 """A statement that evaluates an expression and discards the result."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200330 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200331
332
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200333class Assign(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200334 """Assigns an expression to a target."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200335 fields = ('target', 'node')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200336
337
Armin Ronacher07bc6842008-03-31 14:18:49 +0200338class Expr(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200339 """Baseclass for all expressions."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200340 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200341
Armin Ronacher8346bd72010-03-14 19:43:47 +0100342 def as_const(self, eval_ctx=None):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200343 """Return the value of the expression as constant or raise
Armin Ronacher8346bd72010-03-14 19:43:47 +0100344 :exc:`Impossible` if this was not possible.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200345
Armin Ronacher8346bd72010-03-14 19:43:47 +0100346 An :class:`EvalContext` can be provided, if none is given
347 a default context is created which requires the nodes to have
348 an attached environment.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200349
Armin Ronacher8346bd72010-03-14 19:43:47 +0100350 .. versionchanged:: 2.4
351 the `eval_ctx` parameter was added.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200352 """
353 raise Impossible()
354
355 def can_assign(self):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200356 """Check if it's possible to assign something to this node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200357 return False
358
359
360class BinExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200361 """Baseclass for all binary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200362 fields = ('left', 'right')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200363 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200364 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200365
Armin Ronacher8346bd72010-03-14 19:43:47 +0100366 def as_const(self, eval_ctx=None):
367 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200368 f = _binop_to_func[self.operator]
369 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100370 return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))
Armin Ronacher07bc6842008-03-31 14:18:49 +0200371 except:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200372 raise Impossible()
373
374
375class UnaryExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200376 """Baseclass for all unary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200377 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200378 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200379 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200380
Armin Ronacher8346bd72010-03-14 19:43:47 +0100381 def as_const(self, eval_ctx=None):
382 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200383 f = _uaop_to_func[self.operator]
384 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100385 return f(self.node.as_const(eval_ctx))
Armin Ronacher07bc6842008-03-31 14:18:49 +0200386 except:
387 raise Impossible()
388
389
390class Name(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200391 """Looks up a name or stores a value in a name.
392 The `ctx` of the node can be one of the following values:
393
394 - `store`: store a value in the name
395 - `load`: load that name
396 - `param`: like `store` but if the name was defined as function parameter.
397 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200398 fields = ('name', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200399
400 def can_assign(self):
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200401 return self.name not in ('true', 'false', 'none',
402 'True', 'False', 'None')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200403
404
405class Literal(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200406 """Baseclass for literals."""
Armin Ronacher69e12db2008-05-12 09:00:03 +0200407 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200408
409
410class Const(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200411 """All constant values. The parser will return this node for simple
412 constants such as ``42`` or ``"foo"`` but it can be used to store more
413 complex values such as lists too. Only constants with a safe
414 representation (objects where ``eval(repr(x)) == x`` is true).
415 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200416 fields = ('value',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200417
Armin Ronacher8346bd72010-03-14 19:43:47 +0100418 def as_const(self, eval_ctx=None):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200419 return self.value
420
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200421 @classmethod
Armin Ronacherd55ab532008-04-09 16:13:39 +0200422 def from_untrusted(cls, value, lineno=None, environment=None):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200423 """Return a const object if the value is representable as
424 constant value in the generated code, otherwise it will raise
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200425 an `Impossible` exception.
426 """
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200427 from compiler import has_safe_repr
428 if not has_safe_repr(value):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200429 raise Impossible()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200430 return cls(value, lineno=lineno, environment=environment)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200431
Armin Ronacher07bc6842008-03-31 14:18:49 +0200432
Armin Ronacher5411ce72008-05-25 11:36:22 +0200433class TemplateData(Literal):
434 """A constant template string."""
435 fields = ('data',)
436
Armin Ronacher8346bd72010-03-14 19:43:47 +0100437 def as_const(self, eval_ctx=None):
438 if get_eval_context(self, eval_ctx).autoescape:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200439 return Markup(self.data)
440 return self.data
441
442
Armin Ronacher07bc6842008-03-31 14:18:49 +0200443class Tuple(Literal):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200444 """For loop unpacking and some other things like multiple arguments
Armin Ronacher023b5e92008-05-08 11:03:10 +0200445 for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
446 is used for loading the names or storing.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200447 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200448 fields = ('items', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200449
Armin Ronacher8346bd72010-03-14 19:43:47 +0100450 def as_const(self, eval_ctx=None):
451 eval_ctx = get_eval_context(self, eval_ctx)
452 return tuple(x.as_const(eval_ctx) for x in self.items)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200453
454 def can_assign(self):
455 for item in self.items:
456 if not item.can_assign():
457 return False
458 return True
459
460
461class List(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200462 """Any list literal such as ``[1, 2, 3]``"""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200463 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200464
Armin Ronacher8346bd72010-03-14 19:43:47 +0100465 def as_const(self, eval_ctx=None):
466 eval_ctx = get_eval_context(self, eval_ctx)
467 return [x.as_const(eval_ctx) for x in self.items]
Armin Ronacher07bc6842008-03-31 14:18:49 +0200468
469
470class Dict(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200471 """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
472 :class:`Pair` nodes.
473 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200474 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200475
Armin Ronacher8346bd72010-03-14 19:43:47 +0100476 def as_const(self, eval_ctx=None):
477 eval_ctx = get_eval_context(self, eval_ctx)
478 return dict(x.as_const(eval_ctx) for x in self.items)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200479
480
481class Pair(Helper):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200482 """A key, value pair for dicts."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200483 fields = ('key', 'value')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200484
Armin Ronacher8346bd72010-03-14 19:43:47 +0100485 def as_const(self, eval_ctx=None):
486 eval_ctx = get_eval_context(self, eval_ctx)
487 return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200488
489
Armin Ronacher8efc5222008-04-08 14:47:40 +0200490class Keyword(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200491 """A key, value pair for keyword arguments where key is a string."""
Armin Ronacher8efc5222008-04-08 14:47:40 +0200492 fields = ('key', 'value')
493
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 self.key, self.value.as_const(eval_ctx)
Armin Ronacher335b87a2008-09-21 17:08:48 +0200497
Armin Ronacher8efc5222008-04-08 14:47:40 +0200498
Armin Ronacher07bc6842008-03-31 14:18:49 +0200499class CondExpr(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200500 """A conditional expression (inline if expression). (``{{
501 foo if bar else baz }}``)
502 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200503 fields = ('test', 'expr1', 'expr2')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200504
Armin Ronacher8346bd72010-03-14 19:43:47 +0100505 def as_const(self, eval_ctx=None):
506 eval_ctx = get_eval_context(self, eval_ctx)
507 if self.test.as_const(eval_ctx):
508 return self.expr1.as_const(eval_ctx)
Armin Ronacher547d0b62008-07-04 16:35:10 +0200509
510 # if we evaluate to an undefined object, we better do that at runtime
511 if self.expr2 is None:
512 raise Impossible()
513
Armin Ronacher8346bd72010-03-14 19:43:47 +0100514 return self.expr2.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200515
516
517class Filter(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200518 """This node applies a filter on an expression. `name` is the name of
519 the filter, the rest of the fields are the same as for :class:`Call`.
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200520
521 If the `node` of a filter is `None` the contents of the last buffer are
522 filtered. Buffers are created by macros and filter blocks.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200523 """
Armin Ronacherd55ab532008-04-09 16:13:39 +0200524 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200525
Armin Ronacher8346bd72010-03-14 19:43:47 +0100526 def as_const(self, eval_ctx=None):
527 eval_ctx = get_eval_context(self, eval_ctx)
528 if eval_ctx.volatile or self.node is None:
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200529 raise Impossible()
Armin Ronacher0d242be2010-02-10 01:35:13 +0100530 # we have to be careful here because we call filter_ below.
531 # if this variable would be called filter, 2to3 would wrap the
532 # call in a list beause it is assuming we are talking about the
533 # builtin filter function here which no longer returns a list in
534 # python 3. because of that, do not rename filter_ to filter!
535 filter_ = self.environment.filters.get(self.name)
536 if filter_ is None or getattr(filter_, 'contextfilter', False):
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200537 raise Impossible()
Armin Ronacher8346bd72010-03-14 19:43:47 +0100538 obj = self.node.as_const(eval_ctx)
539 args = [x.as_const(eval_ctx) for x in self.args]
540 if getattr(filter_, 'evalcontextfilter', False):
541 args.insert(0, eval_ctx)
542 elif getattr(filter_, 'environmentfilter', False):
Armin Ronacher9a027f42008-04-17 11:13:40 +0200543 args.insert(0, self.environment)
Armin Ronacher8346bd72010-03-14 19:43:47 +0100544 kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
Armin Ronacherd55ab532008-04-09 16:13:39 +0200545 if self.dyn_args is not None:
546 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100547 args.extend(self.dyn_args.as_const(eval_ctx))
Armin Ronacherd55ab532008-04-09 16:13:39 +0200548 except:
549 raise Impossible()
550 if self.dyn_kwargs is not None:
551 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100552 kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
Armin Ronacherd55ab532008-04-09 16:13:39 +0200553 except:
554 raise Impossible()
555 try:
Armin Ronacher0d242be2010-02-10 01:35:13 +0100556 return filter_(obj, *args, **kwargs)
Armin Ronacherd55ab532008-04-09 16:13:39 +0200557 except:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200558 raise Impossible()
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200559
560
Armin Ronacher07bc6842008-03-31 14:18:49 +0200561class Test(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200562 """Applies a test on an expression. `name` is the name of the test, the
563 rest of the fields are the same as for :class:`Call`.
564 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200565 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200566
567
568class Call(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200569 """Calls an expression. `args` is a list of arguments, `kwargs` a list
570 of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
571 and `dyn_kwargs` has to be either `None` or a node that is used as
572 node for dynamic positional (``*args``) or keyword (``**kwargs``)
573 arguments.
574 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200575 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200576
Armin Ronacher8346bd72010-03-14 19:43:47 +0100577 def as_const(self, eval_ctx=None):
578 eval_ctx = get_eval_context(self, eval_ctx)
579 if eval_ctx.volatile:
580 raise Impossible()
581 obj = self.node.as_const(eval_ctx)
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200582
583 # don't evaluate context functions
Armin Ronacher8346bd72010-03-14 19:43:47 +0100584 args = [x.as_const(eval_ctx) for x in self.args]
Armin Ronacherfd310492008-05-25 00:16:51 +0200585 if getattr(obj, 'contextfunction', False):
586 raise Impossible()
Armin Ronacher8346bd72010-03-14 19:43:47 +0100587 elif getattr(obj, 'evalcontextfunction', False):
588 args.insert(0, eval_ctx)
Armin Ronacherfd310492008-05-25 00:16:51 +0200589 elif getattr(obj, 'environmentfunction', False):
590 args.insert(0, self.environment)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200591
Armin Ronacher8346bd72010-03-14 19:43:47 +0100592 kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200593 if self.dyn_args is not None:
594 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100595 args.extend(self.dyn_args.as_const(eval_ctx))
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200596 except:
597 raise Impossible()
598 if self.dyn_kwargs is not None:
599 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100600 kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200601 except:
602 raise Impossible()
603 try:
604 return obj(*args, **kwargs)
605 except:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200606 raise Impossible()
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200607
Armin Ronacher07bc6842008-03-31 14:18:49 +0200608
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200609class Getitem(Expr):
Armin Ronacherb9388772008-06-25 20:43:18 +0200610 """Get an attribute or item from an expression and prefer the item."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200611 fields = ('node', 'arg', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200612
Armin Ronacher8346bd72010-03-14 19:43:47 +0100613 def as_const(self, eval_ctx=None):
614 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200615 if self.ctx != 'load':
616 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200617 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100618 return self.environment.getitem(self.node.as_const(eval_ctx),
619 self.arg.as_const(eval_ctx))
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200620 except:
621 raise Impossible()
622
623 def can_assign(self):
624 return False
625
626
627class Getattr(Expr):
Armin Ronacherb9388772008-06-25 20:43:18 +0200628 """Get an attribute or item from an expression that is a ascii-only
629 bytestring and prefer the attribute.
630 """
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200631 fields = ('node', 'attr', 'ctx')
632
Armin Ronacher8346bd72010-03-14 19:43:47 +0100633 def as_const(self, eval_ctx=None):
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200634 if self.ctx != 'load':
635 raise Impossible()
636 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100637 eval_ctx = get_eval_context(self, eval_ctx)
638 return self.environment.getattr(self.node.as_const(eval_ctx), arg)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200639 except:
640 raise Impossible()
641
642 def can_assign(self):
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200643 return False
Armin Ronacher07bc6842008-03-31 14:18:49 +0200644
645
646class Slice(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200647 """Represents a slice object. This must only be used as argument for
648 :class:`Subscript`.
649 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200650 fields = ('start', 'stop', 'step')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200651
Armin Ronacher8346bd72010-03-14 19:43:47 +0100652 def as_const(self, eval_ctx=None):
653 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200654 def const(obj):
655 if obj is None:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100656 return None
657 return obj.as_const(eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200658 return slice(const(self.start), const(self.stop), const(self.step))
659
Armin Ronacher07bc6842008-03-31 14:18:49 +0200660
661class Concat(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200662 """Concatenates the list of expressions provided after converting them to
663 unicode.
664 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200665 fields = ('nodes',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200666
Armin Ronacher8346bd72010-03-14 19:43:47 +0100667 def as_const(self, eval_ctx=None):
668 eval_ctx = get_eval_context(self, eval_ctx)
669 return ''.join(unicode(x.as_const(eval_ctx)) for x in self.nodes)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200670
671
672class Compare(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200673 """Compares an expression with some other expressions. `ops` must be a
674 list of :class:`Operand`\s.
675 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200676 fields = ('expr', 'ops')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200677
Armin Ronacher8346bd72010-03-14 19:43:47 +0100678 def as_const(self, eval_ctx=None):
679 eval_ctx = get_eval_context(self, eval_ctx)
680 result = value = self.expr.as_const(eval_ctx)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200681 try:
682 for op in self.ops:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100683 new_value = op.expr.as_const(eval_ctx)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200684 result = _cmpop_to_func[op.op](value, new_value)
685 value = new_value
686 except:
687 raise Impossible()
Armin Ronacher625215e2008-04-13 16:31:08 +0200688 return result
689
Armin Ronacher07bc6842008-03-31 14:18:49 +0200690
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200691class Operand(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200692 """Holds an operator and an expression."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200693 fields = ('op', 'expr')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200694
Armin Ronacher023b5e92008-05-08 11:03:10 +0200695if __debug__:
696 Operand.__doc__ += '\nThe following operators are available: ' + \
697 ', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
698 set(_uaop_to_func) | set(_cmpop_to_func)))
699
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200700
Armin Ronacher07bc6842008-03-31 14:18:49 +0200701class Mul(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200702 """Multiplies the left with the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200703 operator = '*'
704
705
706class Div(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200707 """Divides the left by the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200708 operator = '/'
709
710
711class FloorDiv(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200712 """Divides the left by the right node and truncates conver the
713 result into an integer by truncating.
714 """
Armin Ronacher07bc6842008-03-31 14:18:49 +0200715 operator = '//'
716
717
718class Add(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200719 """Add the left to the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200720 operator = '+'
721
722
723class Sub(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200724 """Substract the right from the left node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200725 operator = '-'
726
727
728class Mod(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200729 """Left modulo right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200730 operator = '%'
731
732
733class Pow(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200734 """Left to the power of right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200735 operator = '**'
736
737
738class And(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200739 """Short circuited AND."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200740 operator = 'and'
741
Armin Ronacher8346bd72010-03-14 19:43:47 +0100742 def as_const(self, eval_ctx=None):
743 eval_ctx = get_eval_context(self, eval_ctx)
744 return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200745
746
747class Or(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200748 """Short circuited OR."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200749 operator = 'or'
750
Armin Ronacher8346bd72010-03-14 19:43:47 +0100751 def as_const(self, eval_ctx=None):
752 eval_ctx = get_eval_context(self, eval_ctx)
753 return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200754
755
756class Not(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200757 """Negate the expression."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200758 operator = 'not'
759
760
Armin Ronachere791c2a2008-04-07 18:39:54 +0200761class Neg(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200762 """Make the expression negative."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200763 operator = '-'
764
765
Armin Ronachere791c2a2008-04-07 18:39:54 +0200766class Pos(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200767 """Make the expression positive (noop for most expressions)"""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200768 operator = '+'
Armin Ronacher023b5e92008-05-08 11:03:10 +0200769
770
771# Helpers for extensions
772
773
774class EnvironmentAttribute(Expr):
775 """Loads an attribute from the environment object. This is useful for
776 extensions that want to call a callback stored on the environment.
777 """
778 fields = ('name',)
779
780
781class ExtensionAttribute(Expr):
782 """Returns the attribute of an extension bound to the environment.
783 The identifier is the identifier of the :class:`Extension`.
Armin Ronacherb9e78752008-05-10 23:36:28 +0200784
785 This node is usually constructed by calling the
786 :meth:`~jinja2.ext.Extension.attr` method on an extension.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200787 """
Armin Ronacher6df604e2008-05-23 22:18:38 +0200788 fields = ('identifier', 'name')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200789
790
791class ImportedName(Expr):
792 """If created with an import name the import name is returned on node
793 access. For example ``ImportedName('cgi.escape')`` returns the `escape`
794 function from the cgi module on evaluation. Imports are optimized by the
795 compiler so there is no need to assign them to local variables.
796 """
797 fields = ('importname',)
798
799
800class InternalName(Expr):
801 """An internal name in the compiler. You cannot create these nodes
Armin Ronacher762079c2008-05-08 23:57:56 +0200802 yourself but the parser provides a
803 :meth:`~jinja2.parser.Parser.free_identifier` method that creates
Armin Ronacher023b5e92008-05-08 11:03:10 +0200804 a new identifier for you. This identifier is not available from the
805 template and is not threated specially by the compiler.
806 """
807 fields = ('name',)
808
809 def __init__(self):
810 raise TypeError('Can\'t create internal names. Use the '
811 '`free_identifier` method on a parser.')
812
813
814class MarkSafe(Expr):
815 """Mark the wrapped expression as safe (wrap it as `Markup`)."""
816 fields = ('expr',)
817
Armin Ronacher8346bd72010-03-14 19:43:47 +0100818 def as_const(self, eval_ctx=None):
819 eval_ctx = get_eval_context(self, eval_ctx)
820 return Markup(self.expr.as_const(eval_ctx))
Armin Ronacher023b5e92008-05-08 11:03:10 +0200821
822
Armin Ronacher6df604e2008-05-23 22:18:38 +0200823class ContextReference(Expr):
824 """Returns the current template context."""
825
826
Armin Ronachered1e0d42008-05-18 20:25:28 +0200827class Continue(Stmt):
828 """Continue a loop."""
829
830
831class Break(Stmt):
832 """Break a loop."""
833
834
Armin Ronacher271a0eb2009-02-11 22:49:08 +0100835class Scope(Stmt):
836 """An artificial scope."""
837 fields = ('body',)
838
839
Armin Ronacher8346bd72010-03-14 19:43:47 +0100840class EvalContextModifier(Stmt):
Armin Ronacher30fda272010-03-15 03:06:04 +0100841 """Modifies the eval context. For each option that should be modified,
842 a :class:`Keyword` has to be added to the :attr:`options` list.
843
844 Example to change the `autoescape` setting::
845
846 EvalContextModifier(options=[Keyword('autoescape', Const(True))])
847 """
Armin Ronacher8346bd72010-03-14 19:43:47 +0100848 fields = ('options',)
849
850
851class ScopedEvalContextModifier(EvalContextModifier):
Armin Ronacher30fda272010-03-15 03:06:04 +0100852 """Modifies the eval context and reverts it later. Works exactly like
853 :class:`EvalContextModifier` but will only modify the
854 :class:`EvalContext` for nodes in the :attr:`body`.
855 """
Armin Ronacher8346bd72010-03-14 19:43:47 +0100856 fields = ('body',)
857
858
Armin Ronacher8a1d27f2008-05-19 08:37:19 +0200859# make sure nobody creates custom nodes
860def _failing_new(*args, **kwargs):
861 raise TypeError('can\'t create custom node types')
862NodeType.__new__ = staticmethod(_failing_new); del _failing_new