blob: b6696c7e6d16bb106e2ca8f4c8571644b777665b [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
Armin Ronacher1da23d12010-04-05 18:11:18 +020075 def __init__(self, environment, template_name=None):
76 if callable(environment.autoescape):
77 self.autoescape = environment.autoescape(template_name)
78 else:
79 self.autoescape = environment.autoescape
Armin Ronacher8346bd72010-03-14 19:43:47 +010080 self.volatile = False
81
82 def save(self):
83 return self.__dict__.copy()
84
85 def revert(self, old):
86 self.__dict__.clear()
87 self.__dict__.update(old)
88
89
90def get_eval_context(node, ctx):
91 if ctx is None:
92 if node.environment is None:
93 raise RuntimeError('if no eval context is passed, the '
94 'node must have an attached '
95 'environment.')
96 return EvalContext(node.environment)
97 return ctx
98
99
Armin Ronacher07bc6842008-03-31 14:18:49 +0200100class Node(object):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200101 """Baseclass for all Jinja2 nodes. There are a number of nodes available
102 of different types. There are three major types:
103
104 - :class:`Stmt`: statements
105 - :class:`Expr`: expressions
106 - :class:`Helper`: helper nodes
107 - :class:`Template`: the outermost wrapper node
108
109 All nodes have fields and attributes. Fields may be other nodes, lists,
110 or arbitrary values. Fields are passed to the constructor as regular
111 positional arguments, attributes as keyword arguments. Each node has
112 two attributes: `lineno` (the line number of the node) and `environment`.
113 The `environment` attribute is set at the end of the parsing process for
114 all nodes automatically.
115 """
Armin Ronacher07bc6842008-03-31 14:18:49 +0200116 __metaclass__ = NodeType
Armin Ronachere791c2a2008-04-07 18:39:54 +0200117 fields = ()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200118 attributes = ('lineno', 'environment')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200119 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200120
Armin Ronacher023b5e92008-05-08 11:03:10 +0200121 def __init__(self, *fields, **attributes):
Armin Ronacher69e12db2008-05-12 09:00:03 +0200122 if self.abstract:
123 raise TypeError('abstract nodes are not instanciable')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200124 if fields:
125 if len(fields) != len(self.fields):
Armin Ronachere791c2a2008-04-07 18:39:54 +0200126 if not self.fields:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200127 raise TypeError('%r takes 0 arguments' %
128 self.__class__.__name__)
129 raise TypeError('%r takes 0 or %d argument%s' % (
130 self.__class__.__name__,
Armin Ronachere791c2a2008-04-07 18:39:54 +0200131 len(self.fields),
132 len(self.fields) != 1 and 's' or ''
Armin Ronacher07bc6842008-03-31 14:18:49 +0200133 ))
Armin Ronacher023b5e92008-05-08 11:03:10 +0200134 for name, arg in izip(self.fields, fields):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200135 setattr(self, name, arg)
Armin Ronachere791c2a2008-04-07 18:39:54 +0200136 for attr in self.attributes:
Armin Ronacher023b5e92008-05-08 11:03:10 +0200137 setattr(self, attr, attributes.pop(attr, None))
138 if attributes:
139 raise TypeError('unknown attribute %r' %
140 iter(attributes).next())
Armin Ronacher07bc6842008-03-31 14:18:49 +0200141
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200142 def iter_fields(self, exclude=None, only=None):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200143 """This method iterates over all fields that are defined and yields
Armin Ronacher3da90312008-05-23 16:37:28 +0200144 ``(key, value)`` tuples. Per default all fields are returned, but
145 it's possible to limit that to some fields by providing the `only`
146 parameter or to exclude some using the `exclude` parameter. Both
147 should be sets or tuples of field names.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200148 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200149 for name in self.fields:
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200150 if (exclude is only is None) or \
151 (exclude is not None and name not in exclude) or \
152 (only is not None and name in only):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200153 try:
154 yield name, getattr(self, name)
155 except AttributeError:
156 pass
Armin Ronacher07bc6842008-03-31 14:18:49 +0200157
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200158 def iter_child_nodes(self, exclude=None, only=None):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200159 """Iterates over all direct child nodes of the node. This iterates
160 over all fields and yields the values of they are nodes. If the value
161 of a field is a list all the nodes in that list are returned.
162 """
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200163 for field, item in self.iter_fields(exclude, only):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200164 if isinstance(item, list):
165 for n in item:
166 if isinstance(n, Node):
167 yield n
168 elif isinstance(item, Node):
169 yield item
170
Armin Ronachere791c2a2008-04-07 18:39:54 +0200171 def find(self, node_type):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200172 """Find the first node of a given type. If no such node exists the
173 return value is `None`.
174 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200175 for result in self.find_all(node_type):
176 return result
177
178 def find_all(self, node_type):
Armin Ronacher63cf9b82009-07-26 10:33:36 +0200179 """Find all the nodes of a given type. If the type is a tuple,
180 the check is performed for any of the tuple items.
181 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200182 for child in self.iter_child_nodes():
183 if isinstance(child, node_type):
184 yield child
185 for result in child.find_all(node_type):
186 yield result
187
188 def set_ctx(self, ctx):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200189 """Reset the context of a node and all child nodes. Per default the
190 parser will all generate nodes that have a 'load' context as it's the
191 most common one. This method is used in the parser to set assignment
192 targets and other nodes to a store context.
Armin Ronachere791c2a2008-04-07 18:39:54 +0200193 """
194 todo = deque([self])
195 while todo:
196 node = todo.popleft()
197 if 'ctx' in node.fields:
198 node.ctx = ctx
199 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200200 return self
Armin Ronachere791c2a2008-04-07 18:39:54 +0200201
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200202 def set_lineno(self, lineno, override=False):
203 """Set the line numbers of the node and children."""
204 todo = deque([self])
205 while todo:
206 node = todo.popleft()
207 if 'lineno' in node.attributes:
208 if node.lineno is None or override:
209 node.lineno = lineno
210 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200211 return self
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200212
Armin Ronacherd55ab532008-04-09 16:13:39 +0200213 def set_environment(self, environment):
214 """Set the environment for all nodes."""
215 todo = deque([self])
216 while todo:
217 node = todo.popleft()
218 node.environment = environment
219 todo.extend(node.iter_child_nodes())
Armin Ronacher023b5e92008-05-08 11:03:10 +0200220 return self
Armin Ronacherd55ab532008-04-09 16:13:39 +0200221
Armin Ronacher69e12db2008-05-12 09:00:03 +0200222 def __eq__(self, other):
Armin Ronacherb3a1fcf2008-05-15 11:04:14 +0200223 return type(self) is type(other) and \
224 tuple(self.iter_fields()) == tuple(other.iter_fields())
Armin Ronacher69e12db2008-05-12 09:00:03 +0200225
226 def __ne__(self, other):
227 return not self.__eq__(other)
228
Armin Ronacher07bc6842008-03-31 14:18:49 +0200229 def __repr__(self):
230 return '%s(%s)' % (
231 self.__class__.__name__,
232 ', '.join('%s=%r' % (arg, getattr(self, arg, None)) for
Armin Ronachere791c2a2008-04-07 18:39:54 +0200233 arg in self.fields)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200234 )
235
236
237class Stmt(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200238 """Base node for all statements."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200239 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200240
241
242class Helper(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200243 """Nodes that exist in a specific context only."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200244 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200245
246
247class Template(Node):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200248 """Node that represents a template. This must be the outermost node that
249 is passed to the compiler.
250 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200251 fields = ('body',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200252
253
254class Output(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200255 """A node that holds multiple expressions which are then printed out.
256 This is used both for the `print` statement and the regular template data.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200257 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200258 fields = ('nodes',)
259
Armin Ronacher07bc6842008-03-31 14:18:49 +0200260
261class Extends(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200262 """Represents an extends statement."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200263 fields = ('template',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200264
265
266class For(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200267 """The for loop. `target` is the target for the iteration (usually a
268 :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list
269 of nodes that are used as loop-body, and `else_` a list of nodes for the
270 `else` block. If no else node exists it has to be an empty list.
271
272 For filtered nodes an expression can be stored as `test`, otherwise `None`.
273 """
Armin Ronacherfdf95302008-05-11 22:20:51 +0200274 fields = ('target', 'iter', 'body', 'else_', 'test', 'recursive')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200275
276
277class If(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200278 """If `test` is true, `body` is rendered, else `else_`."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200279 fields = ('test', 'body', 'else_')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200280
281
282class Macro(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200283 """A macro definition. `name` is the name of the macro, `args` a list of
284 arguments and `defaults` a list of defaults if there are any. `body` is
285 a list of nodes for the macro body.
286 """
Armin Ronacher8efc5222008-04-08 14:47:40 +0200287 fields = ('name', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200288
289
290class CallBlock(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200291 """Like a macro without a name but a call instead. `call` is called with
292 the unnamed macro as `caller` argument this node holds.
293 """
Armin Ronacherc9705c22008-04-27 21:28:03 +0200294 fields = ('call', 'args', 'defaults', 'body')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200295
296
Armin Ronacher07bc6842008-03-31 14:18:49 +0200297class FilterBlock(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200298 """Node for filter sections."""
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200299 fields = ('body', 'filter')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200300
301
302class Block(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200303 """A node that represents a block."""
Armin Ronacher74a0cd92009-02-19 15:56:53 +0100304 fields = ('name', 'body', 'scoped')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200305
306
307class Include(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200308 """A node that represents the include tag."""
Armin Ronacher37f58ce2008-12-27 13:10:38 +0100309 fields = ('template', 'with_context', 'ignore_missing')
Armin Ronacher0611e492008-04-25 23:44:14 +0200310
311
312class Import(Stmt):
313 """A node that represents the import tag."""
Armin Ronacherea847c52008-05-02 20:04:32 +0200314 fields = ('template', 'target', 'with_context')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200315
316
Armin Ronacher0611e492008-04-25 23:44:14 +0200317class FromImport(Stmt):
318 """A node that represents the from import tag. It's important to not
319 pass unsafe names to the name attribute. The compiler translates the
320 attribute lookups directly into getattr calls and does *not* use the
Armin Ronacherb9388772008-06-25 20:43:18 +0200321 subscript callback of the interface. As exported variables may not
Armin Ronacher0611e492008-04-25 23:44:14 +0200322 start with double underscores (which the parser asserts) this is not a
323 problem for regular Jinja code, but if this node is used in an extension
324 extra care must be taken.
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200325
326 The list of names may contain tuples if aliases are wanted.
Armin Ronacher0611e492008-04-25 23:44:14 +0200327 """
Armin Ronacherea847c52008-05-02 20:04:32 +0200328 fields = ('template', 'names', 'with_context')
Armin Ronacher0611e492008-04-25 23:44:14 +0200329
330
Armin Ronacher07bc6842008-03-31 14:18:49 +0200331class ExprStmt(Stmt):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200332 """A statement that evaluates an expression and discards the result."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200333 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200334
335
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200336class Assign(Stmt):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200337 """Assigns an expression to a target."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200338 fields = ('target', 'node')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200339
340
Armin Ronacher07bc6842008-03-31 14:18:49 +0200341class Expr(Node):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200342 """Baseclass for all expressions."""
Armin Ronacher023b5e92008-05-08 11:03:10 +0200343 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200344
Armin Ronacher8346bd72010-03-14 19:43:47 +0100345 def as_const(self, eval_ctx=None):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200346 """Return the value of the expression as constant or raise
Armin Ronacher8346bd72010-03-14 19:43:47 +0100347 :exc:`Impossible` if this was not possible.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200348
Armin Ronacher8346bd72010-03-14 19:43:47 +0100349 An :class:`EvalContext` can be provided, if none is given
350 a default context is created which requires the nodes to have
351 an attached environment.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200352
Armin Ronacher8346bd72010-03-14 19:43:47 +0100353 .. versionchanged:: 2.4
354 the `eval_ctx` parameter was added.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200355 """
356 raise Impossible()
357
358 def can_assign(self):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200359 """Check if it's possible to assign something to this node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200360 return False
361
362
363class BinExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200364 """Baseclass for all binary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200365 fields = ('left', 'right')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200366 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200367 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200368
Armin Ronacher8346bd72010-03-14 19:43:47 +0100369 def as_const(self, eval_ctx=None):
370 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200371 f = _binop_to_func[self.operator]
372 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100373 return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))
Armin Ronacher07bc6842008-03-31 14:18:49 +0200374 except:
Armin Ronacher07bc6842008-03-31 14:18:49 +0200375 raise Impossible()
376
377
378class UnaryExpr(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200379 """Baseclass for all unary expressions."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200380 fields = ('node',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200381 operator = None
Armin Ronacher69e12db2008-05-12 09:00:03 +0200382 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200383
Armin Ronacher8346bd72010-03-14 19:43:47 +0100384 def as_const(self, eval_ctx=None):
385 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200386 f = _uaop_to_func[self.operator]
387 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100388 return f(self.node.as_const(eval_ctx))
Armin Ronacher07bc6842008-03-31 14:18:49 +0200389 except:
390 raise Impossible()
391
392
393class Name(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200394 """Looks up a name or stores a value in a name.
395 The `ctx` of the node can be one of the following values:
396
397 - `store`: store a value in the name
398 - `load`: load that name
399 - `param`: like `store` but if the name was defined as function parameter.
400 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200401 fields = ('name', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200402
403 def can_assign(self):
Armin Ronacher9bb7e472008-05-28 11:26:59 +0200404 return self.name not in ('true', 'false', 'none',
405 'True', 'False', 'None')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200406
407
408class Literal(Expr):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200409 """Baseclass for literals."""
Armin Ronacher69e12db2008-05-12 09:00:03 +0200410 abstract = True
Armin Ronacher07bc6842008-03-31 14:18:49 +0200411
412
413class Const(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200414 """All constant values. The parser will return this node for simple
415 constants such as ``42`` or ``"foo"`` but it can be used to store more
416 complex values such as lists too. Only constants with a safe
417 representation (objects where ``eval(repr(x)) == x`` is true).
418 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200419 fields = ('value',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200420
Armin Ronacher8346bd72010-03-14 19:43:47 +0100421 def as_const(self, eval_ctx=None):
Armin Ronacher07bc6842008-03-31 14:18:49 +0200422 return self.value
423
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200424 @classmethod
Armin Ronacherd55ab532008-04-09 16:13:39 +0200425 def from_untrusted(cls, value, lineno=None, environment=None):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200426 """Return a const object if the value is representable as
427 constant value in the generated code, otherwise it will raise
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200428 an `Impossible` exception.
429 """
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200430 from compiler import has_safe_repr
431 if not has_safe_repr(value):
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200432 raise Impossible()
Armin Ronacherd55ab532008-04-09 16:13:39 +0200433 return cls(value, lineno=lineno, environment=environment)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200434
Armin Ronacher07bc6842008-03-31 14:18:49 +0200435
Armin Ronacher5411ce72008-05-25 11:36:22 +0200436class TemplateData(Literal):
437 """A constant template string."""
438 fields = ('data',)
439
Armin Ronacher8346bd72010-03-14 19:43:47 +0100440 def as_const(self, eval_ctx=None):
441 if get_eval_context(self, eval_ctx).autoescape:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200442 return Markup(self.data)
443 return self.data
444
445
Armin Ronacher07bc6842008-03-31 14:18:49 +0200446class Tuple(Literal):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200447 """For loop unpacking and some other things like multiple arguments
Armin Ronacher023b5e92008-05-08 11:03:10 +0200448 for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
449 is used for loading the names or storing.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200450 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200451 fields = ('items', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200452
Armin Ronacher8346bd72010-03-14 19:43:47 +0100453 def as_const(self, eval_ctx=None):
454 eval_ctx = get_eval_context(self, eval_ctx)
455 return tuple(x.as_const(eval_ctx) for x in self.items)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200456
457 def can_assign(self):
458 for item in self.items:
459 if not item.can_assign():
460 return False
461 return True
462
463
464class List(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200465 """Any list literal such as ``[1, 2, 3]``"""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200466 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200467
Armin Ronacher8346bd72010-03-14 19:43:47 +0100468 def as_const(self, eval_ctx=None):
469 eval_ctx = get_eval_context(self, eval_ctx)
470 return [x.as_const(eval_ctx) for x in self.items]
Armin Ronacher07bc6842008-03-31 14:18:49 +0200471
472
473class Dict(Literal):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200474 """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
475 :class:`Pair` nodes.
476 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200477 fields = ('items',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200478
Armin Ronacher8346bd72010-03-14 19:43:47 +0100479 def as_const(self, eval_ctx=None):
480 eval_ctx = get_eval_context(self, eval_ctx)
481 return dict(x.as_const(eval_ctx) for x in self.items)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200482
483
484class Pair(Helper):
Armin Ronacher8efc5222008-04-08 14:47:40 +0200485 """A key, value pair for dicts."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200486 fields = ('key', 'value')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200487
Armin Ronacher8346bd72010-03-14 19:43:47 +0100488 def as_const(self, eval_ctx=None):
489 eval_ctx = get_eval_context(self, eval_ctx)
490 return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200491
492
Armin Ronacher8efc5222008-04-08 14:47:40 +0200493class Keyword(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200494 """A key, value pair for keyword arguments where key is a string."""
Armin Ronacher8efc5222008-04-08 14:47:40 +0200495 fields = ('key', 'value')
496
Armin Ronacher8346bd72010-03-14 19:43:47 +0100497 def as_const(self, eval_ctx=None):
498 eval_ctx = get_eval_context(self, eval_ctx)
499 return self.key, self.value.as_const(eval_ctx)
Armin Ronacher335b87a2008-09-21 17:08:48 +0200500
Armin Ronacher8efc5222008-04-08 14:47:40 +0200501
Armin Ronacher07bc6842008-03-31 14:18:49 +0200502class CondExpr(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200503 """A conditional expression (inline if expression). (``{{
504 foo if bar else baz }}``)
505 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200506 fields = ('test', 'expr1', 'expr2')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200507
Armin Ronacher8346bd72010-03-14 19:43:47 +0100508 def as_const(self, eval_ctx=None):
509 eval_ctx = get_eval_context(self, eval_ctx)
510 if self.test.as_const(eval_ctx):
511 return self.expr1.as_const(eval_ctx)
Armin Ronacher547d0b62008-07-04 16:35:10 +0200512
513 # if we evaluate to an undefined object, we better do that at runtime
514 if self.expr2 is None:
515 raise Impossible()
516
Armin Ronacher8346bd72010-03-14 19:43:47 +0100517 return self.expr2.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200518
519
520class Filter(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200521 """This node applies a filter on an expression. `name` is the name of
522 the filter, the rest of the fields are the same as for :class:`Call`.
Armin Ronacher105f0dc2008-05-23 16:12:47 +0200523
524 If the `node` of a filter is `None` the contents of the last buffer are
525 filtered. Buffers are created by macros and filter blocks.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200526 """
Armin Ronacherd55ab532008-04-09 16:13:39 +0200527 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200528
Armin Ronacher8346bd72010-03-14 19:43:47 +0100529 def as_const(self, eval_ctx=None):
530 eval_ctx = get_eval_context(self, eval_ctx)
531 if eval_ctx.volatile or self.node is None:
Armin Ronacherfa865fb2008-04-12 22:11:53 +0200532 raise Impossible()
Armin Ronacher0d242be2010-02-10 01:35:13 +0100533 # we have to be careful here because we call filter_ below.
534 # if this variable would be called filter, 2to3 would wrap the
535 # call in a list beause it is assuming we are talking about the
536 # builtin filter function here which no longer returns a list in
537 # python 3. because of that, do not rename filter_ to filter!
538 filter_ = self.environment.filters.get(self.name)
539 if filter_ is None or getattr(filter_, 'contextfilter', False):
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200540 raise Impossible()
Armin Ronacher8346bd72010-03-14 19:43:47 +0100541 obj = self.node.as_const(eval_ctx)
542 args = [x.as_const(eval_ctx) for x in self.args]
543 if getattr(filter_, 'evalcontextfilter', False):
544 args.insert(0, eval_ctx)
545 elif getattr(filter_, 'environmentfilter', False):
Armin Ronacher9a027f42008-04-17 11:13:40 +0200546 args.insert(0, self.environment)
Armin Ronacher8346bd72010-03-14 19:43:47 +0100547 kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
Armin Ronacherd55ab532008-04-09 16:13:39 +0200548 if self.dyn_args is not None:
549 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100550 args.extend(self.dyn_args.as_const(eval_ctx))
Armin Ronacherd55ab532008-04-09 16:13:39 +0200551 except:
552 raise Impossible()
553 if self.dyn_kwargs is not None:
554 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100555 kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
Armin Ronacherd55ab532008-04-09 16:13:39 +0200556 except:
557 raise Impossible()
558 try:
Armin Ronacher0d242be2010-02-10 01:35:13 +0100559 return filter_(obj, *args, **kwargs)
Armin Ronacherd55ab532008-04-09 16:13:39 +0200560 except:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200561 raise Impossible()
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200562
563
Armin Ronacher07bc6842008-03-31 14:18:49 +0200564class Test(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200565 """Applies a test on an expression. `name` is the name of the test, the
566 rest of the fields are the same as for :class:`Call`.
567 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200568 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200569
570
571class Call(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200572 """Calls an expression. `args` is a list of arguments, `kwargs` a list
573 of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
574 and `dyn_kwargs` has to be either `None` or a node that is used as
575 node for dynamic positional (``*args``) or keyword (``**kwargs``)
576 arguments.
577 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200578 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200579
Armin Ronacher8346bd72010-03-14 19:43:47 +0100580 def as_const(self, eval_ctx=None):
581 eval_ctx = get_eval_context(self, eval_ctx)
582 if eval_ctx.volatile:
583 raise Impossible()
584 obj = self.node.as_const(eval_ctx)
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200585
586 # don't evaluate context functions
Armin Ronacher8346bd72010-03-14 19:43:47 +0100587 args = [x.as_const(eval_ctx) for x in self.args]
Armin Ronacherfd310492008-05-25 00:16:51 +0200588 if getattr(obj, 'contextfunction', False):
589 raise Impossible()
Armin Ronacher8346bd72010-03-14 19:43:47 +0100590 elif getattr(obj, 'evalcontextfunction', False):
591 args.insert(0, eval_ctx)
Armin Ronacherfd310492008-05-25 00:16:51 +0200592 elif getattr(obj, 'environmentfunction', False):
593 args.insert(0, self.environment)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200594
Armin Ronacher8346bd72010-03-14 19:43:47 +0100595 kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200596 if self.dyn_args is not None:
597 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100598 args.extend(self.dyn_args.as_const(eval_ctx))
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200599 except:
600 raise Impossible()
601 if self.dyn_kwargs is not None:
602 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100603 kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200604 except:
605 raise Impossible()
606 try:
607 return obj(*args, **kwargs)
608 except:
Christoph Hacke9e43bb2008-04-13 23:35:48 +0200609 raise Impossible()
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200610
Armin Ronacher07bc6842008-03-31 14:18:49 +0200611
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200612class Getitem(Expr):
Armin Ronacherb9388772008-06-25 20:43:18 +0200613 """Get an attribute or item from an expression and prefer the item."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200614 fields = ('node', 'arg', 'ctx')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200615
Armin Ronacher8346bd72010-03-14 19:43:47 +0100616 def as_const(self, eval_ctx=None):
617 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200618 if self.ctx != 'load':
619 raise Impossible()
Armin Ronacher07bc6842008-03-31 14:18:49 +0200620 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100621 return self.environment.getitem(self.node.as_const(eval_ctx),
622 self.arg.as_const(eval_ctx))
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200623 except:
624 raise Impossible()
625
626 def can_assign(self):
627 return False
628
629
630class Getattr(Expr):
Armin Ronacherb9388772008-06-25 20:43:18 +0200631 """Get an attribute or item from an expression that is a ascii-only
632 bytestring and prefer the attribute.
633 """
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200634 fields = ('node', 'attr', 'ctx')
635
Armin Ronacher8346bd72010-03-14 19:43:47 +0100636 def as_const(self, eval_ctx=None):
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200637 if self.ctx != 'load':
638 raise Impossible()
639 try:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100640 eval_ctx = get_eval_context(self, eval_ctx)
641 return self.environment.getattr(self.node.as_const(eval_ctx), arg)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200642 except:
643 raise Impossible()
644
645 def can_assign(self):
Armin Ronacher4f7d2d52008-04-22 10:40:26 +0200646 return False
Armin Ronacher07bc6842008-03-31 14:18:49 +0200647
648
649class Slice(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200650 """Represents a slice object. This must only be used as argument for
651 :class:`Subscript`.
652 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200653 fields = ('start', 'stop', 'step')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200654
Armin Ronacher8346bd72010-03-14 19:43:47 +0100655 def as_const(self, eval_ctx=None):
656 eval_ctx = get_eval_context(self, eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200657 def const(obj):
658 if obj is None:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100659 return None
660 return obj.as_const(eval_ctx)
Armin Ronacher4dfc9752008-04-09 15:03:29 +0200661 return slice(const(self.start), const(self.stop), const(self.step))
662
Armin Ronacher07bc6842008-03-31 14:18:49 +0200663
664class Concat(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200665 """Concatenates the list of expressions provided after converting them to
666 unicode.
667 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200668 fields = ('nodes',)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200669
Armin Ronacher8346bd72010-03-14 19:43:47 +0100670 def as_const(self, eval_ctx=None):
671 eval_ctx = get_eval_context(self, eval_ctx)
672 return ''.join(unicode(x.as_const(eval_ctx)) for x in self.nodes)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200673
674
675class Compare(Expr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200676 """Compares an expression with some other expressions. `ops` must be a
677 list of :class:`Operand`\s.
678 """
Armin Ronachere791c2a2008-04-07 18:39:54 +0200679 fields = ('expr', 'ops')
Armin Ronacher07bc6842008-03-31 14:18:49 +0200680
Armin Ronacher8346bd72010-03-14 19:43:47 +0100681 def as_const(self, eval_ctx=None):
682 eval_ctx = get_eval_context(self, eval_ctx)
683 result = value = self.expr.as_const(eval_ctx)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200684 try:
685 for op in self.ops:
Armin Ronacher8346bd72010-03-14 19:43:47 +0100686 new_value = op.expr.as_const(eval_ctx)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200687 result = _cmpop_to_func[op.op](value, new_value)
688 value = new_value
689 except:
690 raise Impossible()
Armin Ronacher625215e2008-04-13 16:31:08 +0200691 return result
692
Armin Ronacher07bc6842008-03-31 14:18:49 +0200693
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200694class Operand(Helper):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200695 """Holds an operator and an expression."""
Armin Ronachere791c2a2008-04-07 18:39:54 +0200696 fields = ('op', 'expr')
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200697
Armin Ronacher023b5e92008-05-08 11:03:10 +0200698if __debug__:
699 Operand.__doc__ += '\nThe following operators are available: ' + \
700 ', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
701 set(_uaop_to_func) | set(_cmpop_to_func)))
702
Armin Ronacher82b3f3d2008-03-31 20:01:08 +0200703
Armin Ronacher07bc6842008-03-31 14:18:49 +0200704class Mul(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200705 """Multiplies the left with the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200706 operator = '*'
707
708
709class Div(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200710 """Divides the left by the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200711 operator = '/'
712
713
714class FloorDiv(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200715 """Divides the left by the right node and truncates conver the
716 result into an integer by truncating.
717 """
Armin Ronacher07bc6842008-03-31 14:18:49 +0200718 operator = '//'
719
720
721class Add(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200722 """Add the left to the right node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200723 operator = '+'
724
725
726class Sub(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200727 """Substract the right from the left node."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200728 operator = '-'
729
730
731class Mod(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200732 """Left modulo right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200733 operator = '%'
734
735
736class Pow(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200737 """Left to the power of right."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200738 operator = '**'
739
740
741class And(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200742 """Short circuited AND."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200743 operator = 'and'
744
Armin Ronacher8346bd72010-03-14 19:43:47 +0100745 def as_const(self, eval_ctx=None):
746 eval_ctx = get_eval_context(self, eval_ctx)
747 return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200748
749
750class Or(BinExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200751 """Short circuited OR."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200752 operator = 'or'
753
Armin Ronacher8346bd72010-03-14 19:43:47 +0100754 def as_const(self, eval_ctx=None):
755 eval_ctx = get_eval_context(self, eval_ctx)
756 return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200757
758
759class Not(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200760 """Negate the expression."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200761 operator = 'not'
762
763
Armin Ronachere791c2a2008-04-07 18:39:54 +0200764class Neg(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200765 """Make the expression negative."""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200766 operator = '-'
767
768
Armin Ronachere791c2a2008-04-07 18:39:54 +0200769class Pos(UnaryExpr):
Armin Ronacher023b5e92008-05-08 11:03:10 +0200770 """Make the expression positive (noop for most expressions)"""
Armin Ronacher07bc6842008-03-31 14:18:49 +0200771 operator = '+'
Armin Ronacher023b5e92008-05-08 11:03:10 +0200772
773
774# Helpers for extensions
775
776
777class EnvironmentAttribute(Expr):
778 """Loads an attribute from the environment object. This is useful for
779 extensions that want to call a callback stored on the environment.
780 """
781 fields = ('name',)
782
783
784class ExtensionAttribute(Expr):
785 """Returns the attribute of an extension bound to the environment.
786 The identifier is the identifier of the :class:`Extension`.
Armin Ronacherb9e78752008-05-10 23:36:28 +0200787
788 This node is usually constructed by calling the
789 :meth:`~jinja2.ext.Extension.attr` method on an extension.
Armin Ronacher023b5e92008-05-08 11:03:10 +0200790 """
Armin Ronacher6df604e2008-05-23 22:18:38 +0200791 fields = ('identifier', 'name')
Armin Ronacher023b5e92008-05-08 11:03:10 +0200792
793
794class ImportedName(Expr):
795 """If created with an import name the import name is returned on node
796 access. For example ``ImportedName('cgi.escape')`` returns the `escape`
797 function from the cgi module on evaluation. Imports are optimized by the
798 compiler so there is no need to assign them to local variables.
799 """
800 fields = ('importname',)
801
802
803class InternalName(Expr):
804 """An internal name in the compiler. You cannot create these nodes
Armin Ronacher762079c2008-05-08 23:57:56 +0200805 yourself but the parser provides a
806 :meth:`~jinja2.parser.Parser.free_identifier` method that creates
Armin Ronacher023b5e92008-05-08 11:03:10 +0200807 a new identifier for you. This identifier is not available from the
808 template and is not threated specially by the compiler.
809 """
810 fields = ('name',)
811
812 def __init__(self):
813 raise TypeError('Can\'t create internal names. Use the '
814 '`free_identifier` method on a parser.')
815
816
817class MarkSafe(Expr):
818 """Mark the wrapped expression as safe (wrap it as `Markup`)."""
819 fields = ('expr',)
820
Armin Ronacher8346bd72010-03-14 19:43:47 +0100821 def as_const(self, eval_ctx=None):
822 eval_ctx = get_eval_context(self, eval_ctx)
823 return Markup(self.expr.as_const(eval_ctx))
Armin Ronacher023b5e92008-05-08 11:03:10 +0200824
825
Armin Ronacher6df604e2008-05-23 22:18:38 +0200826class ContextReference(Expr):
Armin Ronachercedb4822010-03-24 10:53:22 +0100827 """Returns the current template context. It can be used like a
828 :class:`Name` node, with a ``'load'`` ctx and will return the
829 current :class:`~jinja2.runtime.Context` object.
830
831 Here an example that assigns the current template name to a
832 variable named `foo`::
833
834 Assign(Name('foo', ctx='store'),
835 Getattr(ContextReference(), 'name'))
836 """
Armin Ronacher6df604e2008-05-23 22:18:38 +0200837
838
Armin Ronachered1e0d42008-05-18 20:25:28 +0200839class Continue(Stmt):
840 """Continue a loop."""
841
842
843class Break(Stmt):
844 """Break a loop."""
845
846
Armin Ronacher271a0eb2009-02-11 22:49:08 +0100847class Scope(Stmt):
848 """An artificial scope."""
849 fields = ('body',)
850
851
Armin Ronacher8346bd72010-03-14 19:43:47 +0100852class EvalContextModifier(Stmt):
Armin Ronacher30fda272010-03-15 03:06:04 +0100853 """Modifies the eval context. For each option that should be modified,
854 a :class:`Keyword` has to be added to the :attr:`options` list.
855
856 Example to change the `autoescape` setting::
857
858 EvalContextModifier(options=[Keyword('autoescape', Const(True))])
859 """
Armin Ronacher8346bd72010-03-14 19:43:47 +0100860 fields = ('options',)
861
862
863class ScopedEvalContextModifier(EvalContextModifier):
Armin Ronacher30fda272010-03-15 03:06:04 +0100864 """Modifies the eval context and reverts it later. Works exactly like
865 :class:`EvalContextModifier` but will only modify the
Armin Ronacher0dbaf392010-03-15 10:06:53 +0100866 :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.
Armin Ronacher30fda272010-03-15 03:06:04 +0100867 """
Armin Ronacher8346bd72010-03-14 19:43:47 +0100868 fields = ('body',)
869
870
Armin Ronacher8a1d27f2008-05-19 08:37:19 +0200871# make sure nobody creates custom nodes
872def _failing_new(*args, **kwargs):
873 raise TypeError('can\'t create custom node types')
874NodeType.__new__ = staticmethod(_failing_new); del _failing_new