blob: afc735542c308ae3cce74e316b2b859fef84d9cc [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):
71 """Holds evaluation time information"""
72
73 def __init__(self, environment):
74 self.autoescape = environment.autoescape
75 self.volatile = False
76
77 def save(self):
78 return self.__dict__.copy()
79
80 def revert(self, old):
81 self.__dict__.clear()
82 self.__dict__.update(old)
83
84
85def get_eval_context(node, ctx):
86 if ctx is None:
87 if node.environment is None:
88 raise RuntimeError('if no eval context is passed, the '
89 'node must have an attached '
90 'environment.')
91 return EvalContext(node.environment)
92 return ctx
93
94
Armin Ronacher07bc6842008-03-31 14:18:49 +020095class Node(object):
Armin Ronacher023b5e92008-05-08 11:03:10 +020096 """Baseclass for all Jinja2 nodes. There are a number of nodes available
97 of different types. There are three major types:
98
99 - :class:`Stmt`: statements
100 - :class:`Expr`: expressions
101 - :class:`Helper`: helper nodes
102 - :class:`Template`: the outermost wrapper node
103
104 All nodes have fields and attributes. Fields may be other nodes, lists,
105 or arbitrary values. Fields are passed to the constructor as regular
106 positional arguments, attributes as keyword arguments. Each node has
107 two attributes: `lineno` (the line number of the node) and `environment`.
108 The `environment` attribute is set at the end of the parsing process for
109 all nodes automatically.
110 """
Armin Ronacher07bc6842008-03-31 14:18:49 +0200111 __metaclass__ = NodeType
Armin Ronachere791c2a2008-04-07 18:39:54 +0200112 fields = ()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200113 attributes = ('lineno', 'environment')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200114 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200115
Armin Ronacher023b5e92008-05-08 11:03:10 +0200116 def __init__(self, *fields, **attributes):
Armin Ronacher69e12db2008-05-12 09:00:03 +0200117 if self.abstract:
118 raise TypeError('abstract nodes are not instanciable')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200119 if fields:
120 if len(fields) != len(self.fields):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200121 if not self.fields:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200122 raise TypeError('%r takes 0 arguments' %
123 self.__class__.__name__)
124 raise TypeError('%r takes 0 or %d argument%s' % (
125 self.__class__.__name__,
Armin Ronachere791c2a2008-04-07 18:39:54 +0200126 len(self.fields),
127 len(self.fields) != 1 and 's' or ''
Armin Ronacher07bc6842008-03-31 14:18:49 +0200128 ))
Armin Ronacher023b5e92008-05-08 11:03:10 +0200129 for name, arg in izip(self.fields, fields):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200130 setattr(self, name, arg)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200131 for attr in self.attributes:
Armin Ronacher023b5e92008-05-08 11:03:10 +0200132 setattr(self, attr, attributes.pop(attr, None))
133 if attributes:
134 raise TypeError('unknown attribute %r' %
135 iter(attributes).next())
Armin Ronacher07bc6842008-03-31 14:18:49 +0200136
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200137 def iter_fields(self, exclude=None, only=None):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200138 """This method iterates over all fields that are defined and yields
Armin Ronacher3da90312008-05-23 16:37:28 +0200139 ``(key, value)`` tuples. Per default all fields are returned, but
140 it's possible to limit that to some fields by providing the `only`
141 parameter or to exclude some using the `exclude` parameter. Both
142 should be sets or tuples of field names.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200143 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200144 for name in self.fields:
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200145 if (exclude is only is None) or \
146 (exclude is not None and name not in exclude) or \
147 (only is not None and name in only):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200148 try:
149 yield name, getattr(self, name)
150 except AttributeError:
151 pass
Armin Ronacher07bc6842008-03-31 14:18:49 +0200152
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200153 def iter_child_nodes(self, exclude=None, only=None):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200154 """Iterates over all direct child nodes of the node. This iterates
155 over all fields and yields the values of they are nodes. If the value
156 of a field is a list all the nodes in that list are returned.
157 """
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200158 for field, item in self.iter_fields(exclude, only):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200159 if isinstance(item, list):
160 for n in item:
161 if isinstance(n, Node):
162 yield n
163 elif isinstance(item, Node):
164 yield item
165
Armin Ronachere791c2a2008-04-07 18:39:54 +0200166 def find(self, node_type):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200167 """Find the first node of a given type. If no such node exists the
168 return value is `None`.
169 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200170 for result in self.find_all(node_type):
171 return result
172
173 def find_all(self, node_type):
Armin Ronacher63cf9b82009-07-26 10:33:36 +0200174 """Find all the nodes of a given type. If the type is a tuple,
175 the check is performed for any of the tuple items.
176 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200177 for child in self.iter_child_nodes():
178 if isinstance(child, node_type):
179 yield child
180 for result in child.find_all(node_type):
181 yield result
182
183 def set_ctx(self, ctx):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200184 """Reset the context of a node and all child nodes. Per default the
185 parser will all generate nodes that have a 'load' context as it's the
186 most common one. This method is used in the parser to set assignment
187 targets and other nodes to a store context.
Armin Ronachere791c2a2008-04-07 18:39:54 +0200188 """
189 todo = deque([self])
190 while todo:
191 node = todo.popleft()
192 if 'ctx' in node.fields:
193 node.ctx = ctx
194 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200195 return self
Armin Ronachere791c2a2008-04-07 18:39:54 +0200196
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200197 def set_lineno(self, lineno, override=False):
198 """Set the line numbers of the node and children."""
199 todo = deque([self])
200 while todo:
201 node = todo.popleft()
202 if 'lineno' in node.attributes:
203 if node.lineno is None or override:
204 node.lineno = lineno
205 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200206 return self
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200207
Armin Ronacherd55ab532008-04-09 16:13:39 +0200208 def set_environment(self, environment):
209 """Set the environment for all nodes."""
210 todo = deque([self])
211 while todo:
212 node = todo.popleft()
213 node.environment = environment
214 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200215 return self
Armin Ronacherd55ab532008-04-09 16:13:39 +0200216
Armin Ronacher69e12db2008-05-12 09:00:03 +0200217 def __eq__(self, other):
Armin Ronacherb3a1fcf2008-05-15 11:04:14 +0200218 return type(self) is type(other) and \
219 tuple(self.iter_fields()) == tuple(other.iter_fields())
Armin Ronacher69e12db2008-05-12 09:00:03 +0200220
221 def __ne__(self, other):
222 return not self.__eq__(other)
223
Armin Ronacher07bc6842008-03-31 14:18:49 +0200224 def __repr__(self):
225 return '%s(%s)' % (
226 self.__class__.__name__,
227 ', '.join('%s=%r' % (arg, getattr(self, arg, None)) for
Armin Ronachere791c2a2008-04-07 18:39:54 +0200228 arg in self.fields)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200229 )
230
231
232class Stmt(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200233 """Base node for all statements."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200234 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200235
236
237class Helper(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200238 """Nodes that exist in a specific context only."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200239 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200240
241
242class Template(Node):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200243 """Node that represents a template. This must be the outermost node that
244 is passed to the compiler.
245 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200246 fields = ('body',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200247
248
249class Output(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200250 """A node that holds multiple expressions which are then printed out.
251 This is used both for the `print` statement and the regular template data.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200252 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200253 fields = ('nodes',)
254
Armin Ronacher07bc6842008-03-31 14:18:49 +0200255
256class Extends(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200257 """Represents an extends statement."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200258 fields = ('template',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200259
260
261class For(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200262 """The for loop. `target` is the target for the iteration (usually a
263 :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list
264 of nodes that are used as loop-body, and `else_` a list of nodes for the
265 `else` block. If no else node exists it has to be an empty list.
266
267 For filtered nodes an expression can be stored as `test`, otherwise `None`.
268 """
Armin Ronacherfdf95302008-05-11 22:20:51 +0200269 fields = ('target', 'iter', 'body', 'else_', 'test', 'recursive')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200270
271
272class If(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200273 """If `test` is true, `body` is rendered, else `else_`."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200274 fields = ('test', 'body', 'else_')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200275
276
277class Macro(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200278 """A macro definition. `name` is the name of the macro, `args` a list of
279 arguments and `defaults` a list of defaults if there are any. `body` is
280 a list of nodes for the macro body.
281 """
Armin Ronacher8efc5222008-04-08 14:47:40 +0200282 fields = ('name', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200283
284
285class CallBlock(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200286 """Like a macro without a name but a call instead. `call` is called with
287 the unnamed macro as `caller` argument this node holds.
288 """
Armin Ronacherc9705c22008-04-27 21:28:03 +0200289 fields = ('call', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200290
291
Armin Ronacher07bc6842008-03-31 14:18:49 +0200292class FilterBlock(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200293 """Node for filter sections."""
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200294 fields = ('body', 'filter')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200295
296
297class Block(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200298 """A node that represents a block."""
Armin Ronacher74a0cd92009-02-19 15:56:53 +0100299 fields = ('name', 'body', 'scoped')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200300
301
302class Include(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200303 """A node that represents the include tag."""
Armin Ronacher37f58ce2008-12-27 13:10:38 +0100304 fields = ('template', 'with_context', 'ignore_missing')
Armin Ronacher0611e492008-04-25 23:44:14 +0200305
306
307class Import(Stmt):
308 """A node that represents the import tag."""
Armin Ronacherea847c52008-05-02 20:04:32 +0200309 fields = ('template', 'target', 'with_context')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200310
311
Armin Ronacher0611e492008-04-25 23:44:14 +0200312class FromImport(Stmt):
313 """A node that represents the from import tag. It's important to not
314 pass unsafe names to the name attribute. The compiler translates the
315 attribute lookups directly into getattr calls and does *not* use the
Armin Ronacherb9388772008-06-25 20:43:18 +0200316 subscript callback of the interface. As exported variables may not
Armin Ronacher0611e492008-04-25 23:44:14 +0200317 start with double underscores (which the parser asserts) this is not a
318 problem for regular Jinja code, but if this node is used in an extension
319 extra care must be taken.
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200320
321 The list of names may contain tuples if aliases are wanted.
Armin Ronacher0611e492008-04-25 23:44:14 +0200322 """
Armin Ronacherea847c52008-05-02 20:04:32 +0200323 fields = ('template', 'names', 'with_context')
Armin Ronacher0611e492008-04-25 23:44:14 +0200324
325
Armin Ronacher07bc6842008-03-31 14:18:49 +0200326class ExprStmt(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200327 """A statement that evaluates an expression and discards the result."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200328 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200329
330
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200331class Assign(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200332 """Assigns an expression to a target."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200333 fields = ('target', 'node')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200334
335
Armin Ronacher07bc6842008-03-31 14:18:49 +0200336class Expr(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200337 """Baseclass for all expressions."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200338 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200339
Armin Ronacher8346bd72010-03-14 19:43:47 +0100340 def as_const(self, eval_ctx=None):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200341 """Return the value of the expression as constant or raise
Armin Ronacher8346bd72010-03-14 19:43:47 +0100342 :exc:`Impossible` if this was not possible.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200343
Armin Ronacher8346bd72010-03-14 19:43:47 +0100344 An :class:`EvalContext` can be provided, if none is given
345 a default context is created which requires the nodes to have
346 an attached environment.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200347
Armin Ronacher8346bd72010-03-14 19:43:47 +0100348 .. versionchanged:: 2.4
349 the `eval_ctx` parameter was added.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200350 """
351 raise Impossible()
352
353 def can_assign(self):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200354 """Check if it's possible to assign something to this node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200355 return False
356
357
358class BinExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200359 """Baseclass for all binary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200360 fields = ('left', 'right')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200361 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200362 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200363
Armin Ronacher8346bd72010-03-14 19:43:47 +0100364 def as_const(self, eval_ctx=None):
365 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200366 f = _binop_to_func[self.operator]
367 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100368 return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))
Armin Ronacher07bc6842008-03-31 14:18:49 +0200369 except:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200370 raise Impossible()
371
372
373class UnaryExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200374 """Baseclass for all unary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200375 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200376 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200377 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200378
Armin Ronacher8346bd72010-03-14 19:43:47 +0100379 def as_const(self, eval_ctx=None):
380 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200381 f = _uaop_to_func[self.operator]
382 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100383 return f(self.node.as_const(eval_ctx))
Armin Ronacher07bc6842008-03-31 14:18:49 +0200384 except:
385 raise Impossible()
386
387
388class Name(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200389 """Looks up a name or stores a value in a name.
390 The `ctx` of the node can be one of the following values:
391
392 - `store`: store a value in the name
393 - `load`: load that name
394 - `param`: like `store` but if the name was defined as function parameter.
395 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200396 fields = ('name', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200397
398 def can_assign(self):
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200399 return self.name not in ('true', 'false', 'none',
400 'True', 'False', 'None')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200401
402
403class Literal(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200404 """Baseclass for literals."""
Armin Ronacher69e12db2008-05-12 09:00:03 +0200405 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200406
407
408class Const(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200409 """All constant values. The parser will return this node for simple
410 constants such as ``42`` or ``"foo"`` but it can be used to store more
411 complex values such as lists too. Only constants with a safe
412 representation (objects where ``eval(repr(x)) == x`` is true).
413 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200414 fields = ('value',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200415
Armin Ronacher8346bd72010-03-14 19:43:47 +0100416 def as_const(self, eval_ctx=None):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200417 return self.value
418
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200419 @classmethod
Armin Ronacherd55ab532008-04-09 16:13:39 +0200420 def from_untrusted(cls, value, lineno=None, environment=None):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200421 """Return a const object if the value is representable as
422 constant value in the generated code, otherwise it will raise
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200423 an `Impossible` exception.
424 """
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200425 from compiler import has_safe_repr
426 if not has_safe_repr(value):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200427 raise Impossible()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200428 return cls(value, lineno=lineno, environment=environment)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200429
Armin Ronacher07bc6842008-03-31 14:18:49 +0200430
Armin Ronacher5411ce72008-05-25 11:36:22 +0200431class TemplateData(Literal):
432 """A constant template string."""
433 fields = ('data',)
434
Armin Ronacher8346bd72010-03-14 19:43:47 +0100435 def as_const(self, eval_ctx=None):
436 if get_eval_context(self, eval_ctx).autoescape:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200437 return Markup(self.data)
438 return self.data
439
440
Armin Ronacher07bc6842008-03-31 14:18:49 +0200441class Tuple(Literal):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200442 """For loop unpacking and some other things like multiple arguments
Armin Ronacher023b5e92008-05-08 11:03:10 +0200443 for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
444 is used for loading the names or storing.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200445 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200446 fields = ('items', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200447
Armin Ronacher8346bd72010-03-14 19:43:47 +0100448 def as_const(self, eval_ctx=None):
449 eval_ctx = get_eval_context(self, eval_ctx)
450 return tuple(x.as_const(eval_ctx) for x in self.items)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200451
452 def can_assign(self):
453 for item in self.items:
454 if not item.can_assign():
455 return False
456 return True
457
458
459class List(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200460 """Any list literal such as ``[1, 2, 3]``"""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200461 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200462
Armin Ronacher8346bd72010-03-14 19:43:47 +0100463 def as_const(self, eval_ctx=None):
464 eval_ctx = get_eval_context(self, eval_ctx)
465 return [x.as_const(eval_ctx) for x in self.items]
Armin Ronacher07bc6842008-03-31 14:18:49 +0200466
467
468class Dict(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200469 """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
470 :class:`Pair` nodes.
471 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200472 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200473
Armin Ronacher8346bd72010-03-14 19:43:47 +0100474 def as_const(self, eval_ctx=None):
475 eval_ctx = get_eval_context(self, eval_ctx)
476 return dict(x.as_const(eval_ctx) for x in self.items)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200477
478
479class Pair(Helper):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200480 """A key, value pair for dicts."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200481 fields = ('key', 'value')
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 self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200486
487
Armin Ronacher8efc5222008-04-08 14:47:40 +0200488class Keyword(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200489 """A key, value pair for keyword arguments where key is a string."""
Armin Ronacher8efc5222008-04-08 14:47:40 +0200490 fields = ('key', 'value')
491
Armin Ronacher8346bd72010-03-14 19:43:47 +0100492 def as_const(self, eval_ctx=None):
493 eval_ctx = get_eval_context(self, eval_ctx)
494 return self.key, self.value.as_const(eval_ctx)
Armin Ronacher335b87a2008-09-21 17:08:48 +0200495
Armin Ronacher8efc5222008-04-08 14:47:40 +0200496
Armin Ronacher07bc6842008-03-31 14:18:49 +0200497class CondExpr(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200498 """A conditional expression (inline if expression). (``{{
499 foo if bar else baz }}``)
500 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200501 fields = ('test', 'expr1', 'expr2')
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 if self.test.as_const(eval_ctx):
506 return self.expr1.as_const(eval_ctx)
Armin Ronacher547d0b62008-07-04 16:35:10 +0200507
508 # if we evaluate to an undefined object, we better do that at runtime
509 if self.expr2 is None:
510 raise Impossible()
511
Armin Ronacher8346bd72010-03-14 19:43:47 +0100512 return self.expr2.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200513
514
515class Filter(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200516 """This node applies a filter on an expression. `name` is the name of
517 the filter, the rest of the fields are the same as for :class:`Call`.
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200518
519 If the `node` of a filter is `None` the contents of the last buffer are
520 filtered. Buffers are created by macros and filter blocks.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200521 """
Armin Ronacherd55ab532008-04-09 16:13:39 +0200522 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
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 eval_ctx.volatile or self.node is None:
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200527 raise Impossible()
Armin Ronacher0d242be2010-02-10 01:35:13 +0100528 # we have to be careful here because we call filter_ below.
529 # if this variable would be called filter, 2to3 would wrap the
530 # call in a list beause it is assuming we are talking about the
531 # builtin filter function here which no longer returns a list in
532 # python 3. because of that, do not rename filter_ to filter!
533 filter_ = self.environment.filters.get(self.name)
534 if filter_ is None or getattr(filter_, 'contextfilter', False):
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200535 raise Impossible()
Armin Ronacher8346bd72010-03-14 19:43:47 +0100536 obj = self.node.as_const(eval_ctx)
537 args = [x.as_const(eval_ctx) for x in self.args]
538 if getattr(filter_, 'evalcontextfilter', False):
539 args.insert(0, eval_ctx)
540 elif getattr(filter_, 'environmentfilter', False):
Armin Ronacher9a027f42008-04-17 11:13:40 +0200541 args.insert(0, self.environment)
Armin Ronacher8346bd72010-03-14 19:43:47 +0100542 kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
Armin Ronacherd55ab532008-04-09 16:13:39 +0200543 if self.dyn_args is not None:
544 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100545 args.extend(self.dyn_args.as_const(eval_ctx))
Armin Ronacherd55ab532008-04-09 16:13:39 +0200546 except:
547 raise Impossible()
548 if self.dyn_kwargs is not None:
549 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100550 kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
Armin Ronacherd55ab532008-04-09 16:13:39 +0200551 except:
552 raise Impossible()
553 try:
Armin Ronacher0d242be2010-02-10 01:35:13 +0100554 return filter_(obj, *args, **kwargs)
Armin Ronacherd55ab532008-04-09 16:13:39 +0200555 except:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200556 raise Impossible()
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200557
558
Armin Ronacher07bc6842008-03-31 14:18:49 +0200559class Test(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200560 """Applies a test on an expression. `name` is the name of the test, the
561 rest of the fields are the same as for :class:`Call`.
562 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200563 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200564
565
566class Call(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200567 """Calls an expression. `args` is a list of arguments, `kwargs` a list
568 of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
569 and `dyn_kwargs` has to be either `None` or a node that is used as
570 node for dynamic positional (``*args``) or keyword (``**kwargs``)
571 arguments.
572 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200573 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200574
Armin Ronacher8346bd72010-03-14 19:43:47 +0100575 def as_const(self, eval_ctx=None):
576 eval_ctx = get_eval_context(self, eval_ctx)
577 if eval_ctx.volatile:
578 raise Impossible()
579 obj = self.node.as_const(eval_ctx)
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200580
581 # don't evaluate context functions
Armin Ronacher8346bd72010-03-14 19:43:47 +0100582 args = [x.as_const(eval_ctx) for x in self.args]
Armin Ronacherfd310492008-05-25 00:16:51 +0200583 if getattr(obj, 'contextfunction', False):
584 raise Impossible()
Armin Ronacher8346bd72010-03-14 19:43:47 +0100585 elif getattr(obj, 'evalcontextfunction', False):
586 args.insert(0, eval_ctx)
Armin Ronacherfd310492008-05-25 00:16:51 +0200587 elif getattr(obj, 'environmentfunction', False):
588 args.insert(0, self.environment)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200589
Armin Ronacher8346bd72010-03-14 19:43:47 +0100590 kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200591 if self.dyn_args is not None:
592 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100593 args.extend(self.dyn_args.as_const(eval_ctx))
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200594 except:
595 raise Impossible()
596 if self.dyn_kwargs is not None:
597 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100598 kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200599 except:
600 raise Impossible()
601 try:
602 return obj(*args, **kwargs)
603 except:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200604 raise Impossible()
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200605
Armin Ronacher07bc6842008-03-31 14:18:49 +0200606
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200607class Getitem(Expr):
Armin Ronacherb9388772008-06-25 20:43:18 +0200608 """Get an attribute or item from an expression and prefer the item."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200609 fields = ('node', 'arg', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200610
Armin Ronacher8346bd72010-03-14 19:43:47 +0100611 def as_const(self, eval_ctx=None):
612 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200613 if self.ctx != 'load':
614 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200615 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100616 return self.environment.getitem(self.node.as_const(eval_ctx),
617 self.arg.as_const(eval_ctx))
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200618 except:
619 raise Impossible()
620
621 def can_assign(self):
622 return False
623
624
625class Getattr(Expr):
Armin Ronacherb9388772008-06-25 20:43:18 +0200626 """Get an attribute or item from an expression that is a ascii-only
627 bytestring and prefer the attribute.
628 """
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200629 fields = ('node', 'attr', 'ctx')
630
Armin Ronacher8346bd72010-03-14 19:43:47 +0100631 def as_const(self, eval_ctx=None):
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200632 if self.ctx != 'load':
633 raise Impossible()
634 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100635 eval_ctx = get_eval_context(self, eval_ctx)
636 return self.environment.getattr(self.node.as_const(eval_ctx), arg)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200637 except:
638 raise Impossible()
639
640 def can_assign(self):
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200641 return False
Armin Ronacher07bc6842008-03-31 14:18:49 +0200642
643
644class Slice(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200645 """Represents a slice object. This must only be used as argument for
646 :class:`Subscript`.
647 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200648 fields = ('start', 'stop', 'step')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200649
Armin Ronacher8346bd72010-03-14 19:43:47 +0100650 def as_const(self, eval_ctx=None):
651 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200652 def const(obj):
653 if obj is None:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100654 return None
655 return obj.as_const(eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200656 return slice(const(self.start), const(self.stop), const(self.step))
657
Armin Ronacher07bc6842008-03-31 14:18:49 +0200658
659class Concat(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200660 """Concatenates the list of expressions provided after converting them to
661 unicode.
662 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200663 fields = ('nodes',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200664
Armin Ronacher8346bd72010-03-14 19:43:47 +0100665 def as_const(self, eval_ctx=None):
666 eval_ctx = get_eval_context(self, eval_ctx)
667 return ''.join(unicode(x.as_const(eval_ctx)) for x in self.nodes)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200668
669
670class Compare(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200671 """Compares an expression with some other expressions. `ops` must be a
672 list of :class:`Operand`\s.
673 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200674 fields = ('expr', 'ops')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200675
Armin Ronacher8346bd72010-03-14 19:43:47 +0100676 def as_const(self, eval_ctx=None):
677 eval_ctx = get_eval_context(self, eval_ctx)
678 result = value = self.expr.as_const(eval_ctx)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200679 try:
680 for op in self.ops:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100681 new_value = op.expr.as_const(eval_ctx)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200682 result = _cmpop_to_func[op.op](value, new_value)
683 value = new_value
684 except:
685 raise Impossible()
Armin Ronacher625215e2008-04-13 16:31:08 +0200686 return result
687
Armin Ronacher07bc6842008-03-31 14:18:49 +0200688
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200689class Operand(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200690 """Holds an operator and an expression."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200691 fields = ('op', 'expr')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200692
Armin Ronacher023b5e92008-05-08 11:03:10 +0200693if __debug__:
694 Operand.__doc__ += '\nThe following operators are available: ' + \
695 ', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
696 set(_uaop_to_func) | set(_cmpop_to_func)))
697
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200698
Armin Ronacher07bc6842008-03-31 14:18:49 +0200699class Mul(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200700 """Multiplies the left with the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200701 operator = '*'
702
703
704class Div(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200705 """Divides the left by the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200706 operator = '/'
707
708
709class FloorDiv(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200710 """Divides the left by the right node and truncates conver the
711 result into an integer by truncating.
712 """
Armin Ronacher07bc6842008-03-31 14:18:49 +0200713 operator = '//'
714
715
716class Add(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200717 """Add the left to the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200718 operator = '+'
719
720
721class Sub(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200722 """Substract the right from the left node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200723 operator = '-'
724
725
726class Mod(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200727 """Left modulo right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200728 operator = '%'
729
730
731class Pow(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200732 """Left to the power of right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200733 operator = '**'
734
735
736class And(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200737 """Short circuited AND."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200738 operator = 'and'
739
Armin Ronacher8346bd72010-03-14 19:43:47 +0100740 def as_const(self, eval_ctx=None):
741 eval_ctx = get_eval_context(self, eval_ctx)
742 return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200743
744
745class Or(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200746 """Short circuited OR."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200747 operator = 'or'
748
Armin Ronacher8346bd72010-03-14 19:43:47 +0100749 def as_const(self, eval_ctx=None):
750 eval_ctx = get_eval_context(self, eval_ctx)
751 return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200752
753
754class Not(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200755 """Negate the expression."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200756 operator = 'not'
757
758
Armin Ronachere791c2a2008-04-07 18:39:54 +0200759class Neg(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200760 """Make the expression negative."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200761 operator = '-'
762
763
Armin Ronachere791c2a2008-04-07 18:39:54 +0200764class Pos(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200765 """Make the expression positive (noop for most expressions)"""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200766 operator = '+'
Armin Ronacher023b5e92008-05-08 11:03:10 +0200767
768
769# Helpers for extensions
770
771
772class EnvironmentAttribute(Expr):
773 """Loads an attribute from the environment object. This is useful for
774 extensions that want to call a callback stored on the environment.
775 """
776 fields = ('name',)
777
778
779class ExtensionAttribute(Expr):
780 """Returns the attribute of an extension bound to the environment.
781 The identifier is the identifier of the :class:`Extension`.
Armin Ronacherb9e78752008-05-10 23:36:28 +0200782
783 This node is usually constructed by calling the
784 :meth:`~jinja2.ext.Extension.attr` method on an extension.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200785 """
Armin Ronacher6df604e2008-05-23 22:18:38 +0200786 fields = ('identifier', 'name')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200787
788
789class ImportedName(Expr):
790 """If created with an import name the import name is returned on node
791 access. For example ``ImportedName('cgi.escape')`` returns the `escape`
792 function from the cgi module on evaluation. Imports are optimized by the
793 compiler so there is no need to assign them to local variables.
794 """
795 fields = ('importname',)
796
797
798class InternalName(Expr):
799 """An internal name in the compiler. You cannot create these nodes
Armin Ronacher762079c2008-05-08 23:57:56 +0200800 yourself but the parser provides a
801 :meth:`~jinja2.parser.Parser.free_identifier` method that creates
Armin Ronacher023b5e92008-05-08 11:03:10 +0200802 a new identifier for you. This identifier is not available from the
803 template and is not threated specially by the compiler.
804 """
805 fields = ('name',)
806
807 def __init__(self):
808 raise TypeError('Can\'t create internal names. Use the '
809 '`free_identifier` method on a parser.')
810
811
812class MarkSafe(Expr):
813 """Mark the wrapped expression as safe (wrap it as `Markup`)."""
814 fields = ('expr',)
815
Armin Ronacher8346bd72010-03-14 19:43:47 +0100816 def as_const(self, eval_ctx=None):
817 eval_ctx = get_eval_context(self, eval_ctx)
818 return Markup(self.expr.as_const(eval_ctx))
Armin Ronacher023b5e92008-05-08 11:03:10 +0200819
820
Armin Ronacher6df604e2008-05-23 22:18:38 +0200821class ContextReference(Expr):
822 """Returns the current template context."""
823
824
Armin Ronachered1e0d42008-05-18 20:25:28 +0200825class Continue(Stmt):
826 """Continue a loop."""
827
828
829class Break(Stmt):
830 """Break a loop."""
831
832
Armin Ronacher271a0eb2009-02-11 22:49:08 +0100833class Scope(Stmt):
834 """An artificial scope."""
835 fields = ('body',)
836
837
Armin Ronacher8346bd72010-03-14 19:43:47 +0100838class EvalContextModifier(Stmt):
839 """Modifies the eval context"""
840 fields = ('options',)
841
842
843class ScopedEvalContextModifier(EvalContextModifier):
844 """Modifies the eval context and reverts it later."""
845 fields = ('body',)
846
847
Armin Ronacher8a1d27f2008-05-19 08:37:19 +0200848# make sure nobody creates custom nodes
849def _failing_new(*args, **kwargs):
850 raise TypeError('can\'t create custom node types')
851NodeType.__new__ = staticmethod(_failing_new); del _failing_new