sort now also accepts an attribute
[jinja2.git] / jinja2 / nodes.py
1 # -*- 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
12     :copyright: (c) 2010 by the Jinja Team.
13     :license: BSD, see LICENSE for more details.
14 """
15 import operator
16 from itertools import chain, izip
17 from collections import deque
18 from jinja2.utils import Markup, MethodType, FunctionType
19
20
21 #: the types we support for context functions
22 _context_function_types = (FunctionType, MethodType)
23
24
25 _binop_to_func = {
26     '*':        operator.mul,
27     '/':        operator.truediv,
28     '//':       operator.floordiv,
29     '**':       operator.pow,
30     '%':        operator.mod,
31     '+':        operator.add,
32     '-':        operator.sub
33 }
34
35 _uaop_to_func = {
36     'not':      operator.not_,
37     '+':        operator.pos,
38     '-':        operator.neg
39 }
40
41 _cmpop_to_func = {
42     'eq':       operator.eq,
43     'ne':       operator.ne,
44     'gt':       operator.gt,
45     'gteq':     operator.ge,
46     'lt':       operator.lt,
47     'lteq':     operator.le,
48     'in':       lambda a, b: a in b,
49     'notin':    lambda a, b: a not in b
50 }
51
52
53 class Impossible(Exception):
54     """Raised if the node could not perform a requested action."""
55
56
57 class NodeType(type):
58     """A metaclass for nodes that handles the field and attribute
59     inheritance.  fields and attributes from the parent class are
60     automatically forwarded to the child."""
61
62     def __new__(cls, name, bases, d):
63         for attr in 'fields', 'attributes':
64             storage = []
65             storage.extend(getattr(bases[0], attr, ()))
66             storage.extend(d.get(attr, ()))
67             assert len(bases) == 1, 'multiple inheritance not allowed'
68             assert len(storage) == len(set(storage)), 'layout conflict'
69             d[attr] = tuple(storage)
70         d.setdefault('abstract', False)
71         return type.__new__(cls, name, bases, d)
72
73
74 class EvalContext(object):
75     """Holds evaluation time information.  Custom attributes can be attached
76     to it in extensions.
77     """
78
79     def __init__(self, environment, template_name=None):
80         if callable(environment.autoescape):
81             self.autoescape = environment.autoescape(template_name)
82         else:
83             self.autoescape = environment.autoescape
84         self.volatile = False
85
86     def save(self):
87         return self.__dict__.copy()
88
89     def revert(self, old):
90         self.__dict__.clear()
91         self.__dict__.update(old)
92
93
94 def get_eval_context(node, ctx):
95     if ctx is None:
96         if node.environment is None:
97             raise RuntimeError('if no eval context is passed, the '
98                                'node must have an attached '
99                                'environment.')
100         return EvalContext(node.environment)
101     return ctx
102
103
104 class Node(object):
105     """Baseclass for all Jinja2 nodes.  There are a number of nodes available
106     of different types.  There are three major types:
107
108     -   :class:`Stmt`: statements
109     -   :class:`Expr`: expressions
110     -   :class:`Helper`: helper nodes
111     -   :class:`Template`: the outermost wrapper node
112
113     All nodes have fields and attributes.  Fields may be other nodes, lists,
114     or arbitrary values.  Fields are passed to the constructor as regular
115     positional arguments, attributes as keyword arguments.  Each node has
116     two attributes: `lineno` (the line number of the node) and `environment`.
117     The `environment` attribute is set at the end of the parsing process for
118     all nodes automatically.
119     """
120     __metaclass__ = NodeType
121     fields = ()
122     attributes = ('lineno', 'environment')
123     abstract = True
124
125     def __init__(self, *fields, **attributes):
126         if self.abstract:
127             raise TypeError('abstract nodes are not instanciable')
128         if fields:
129             if len(fields) != len(self.fields):
130                 if not self.fields:
131                     raise TypeError('%r takes 0 arguments' %
132                                     self.__class__.__name__)
133                 raise TypeError('%r takes 0 or %d argument%s' % (
134                     self.__class__.__name__,
135                     len(self.fields),
136                     len(self.fields) != 1 and 's' or ''
137                 ))
138             for name, arg in izip(self.fields, fields):
139                 setattr(self, name, arg)
140         for attr in self.attributes:
141             setattr(self, attr, attributes.pop(attr, None))
142         if attributes:
143             raise TypeError('unknown attribute %r' %
144                             iter(attributes).next())
145
146     def iter_fields(self, exclude=None, only=None):
147         """This method iterates over all fields that are defined and yields
148         ``(key, value)`` tuples.  Per default all fields are returned, but
149         it's possible to limit that to some fields by providing the `only`
150         parameter or to exclude some using the `exclude` parameter.  Both
151         should be sets or tuples of field names.
152         """
153         for name in self.fields:
154             if (exclude is only is None) or \
155                (exclude is not None and name not in exclude) or \
156                (only is not None and name in only):
157                 try:
158                     yield name, getattr(self, name)
159                 except AttributeError:
160                     pass
161
162     def iter_child_nodes(self, exclude=None, only=None):
163         """Iterates over all direct child nodes of the node.  This iterates
164         over all fields and yields the values of they are nodes.  If the value
165         of a field is a list all the nodes in that list are returned.
166         """
167         for field, item in self.iter_fields(exclude, only):
168             if isinstance(item, list):
169                 for n in item:
170                     if isinstance(n, Node):
171                         yield n
172             elif isinstance(item, Node):
173                 yield item
174
175     def find(self, node_type):
176         """Find the first node of a given type.  If no such node exists the
177         return value is `None`.
178         """
179         for result in self.find_all(node_type):
180             return result
181
182     def find_all(self, node_type):
183         """Find all the nodes of a given type.  If the type is a tuple,
184         the check is performed for any of the tuple items.
185         """
186         for child in self.iter_child_nodes():
187             if isinstance(child, node_type):
188                 yield child
189             for result in child.find_all(node_type):
190                 yield result
191
192     def set_ctx(self, ctx):
193         """Reset the context of a node and all child nodes.  Per default the
194         parser will all generate nodes that have a 'load' context as it's the
195         most common one.  This method is used in the parser to set assignment
196         targets and other nodes to a store context.
197         """
198         todo = deque([self])
199         while todo:
200             node = todo.popleft()
201             if 'ctx' in node.fields:
202                 node.ctx = ctx
203             todo.extend(node.iter_child_nodes())
204         return self
205
206     def set_lineno(self, lineno, override=False):
207         """Set the line numbers of the node and children."""
208         todo = deque([self])
209         while todo:
210             node = todo.popleft()
211             if 'lineno' in node.attributes:
212                 if node.lineno is None or override:
213                     node.lineno = lineno
214             todo.extend(node.iter_child_nodes())
215         return self
216
217     def set_environment(self, environment):
218         """Set the environment for all nodes."""
219         todo = deque([self])
220         while todo:
221             node = todo.popleft()
222             node.environment = environment
223             todo.extend(node.iter_child_nodes())
224         return self
225
226     def __eq__(self, other):
227         return type(self) is type(other) and \
228                tuple(self.iter_fields()) == tuple(other.iter_fields())
229
230     def __ne__(self, other):
231         return not self.__eq__(other)
232
233     def __repr__(self):
234         return '%s(%s)' % (
235             self.__class__.__name__,
236             ', '.join('%s=%r' % (arg, getattr(self, arg, None)) for
237                       arg in self.fields)
238         )
239
240
241 class Stmt(Node):
242     """Base node for all statements."""
243     abstract = True
244
245
246 class Helper(Node):
247     """Nodes that exist in a specific context only."""
248     abstract = True
249
250
251 class Template(Node):
252     """Node that represents a template.  This must be the outermost node that
253     is passed to the compiler.
254     """
255     fields = ('body',)
256
257
258 class Output(Stmt):
259     """A node that holds multiple expressions which are then printed out.
260     This is used both for the `print` statement and the regular template data.
261     """
262     fields = ('nodes',)
263
264
265 class Extends(Stmt):
266     """Represents an extends statement."""
267     fields = ('template',)
268
269
270 class For(Stmt):
271     """The for loop.  `target` is the target for the iteration (usually a
272     :class:`Name` or :class:`Tuple`), `iter` the iterable.  `body` is a list
273     of nodes that are used as loop-body, and `else_` a list of nodes for the
274     `else` block.  If no else node exists it has to be an empty list.
275
276     For filtered nodes an expression can be stored as `test`, otherwise `None`.
277     """
278     fields = ('target', 'iter', 'body', 'else_', 'test', 'recursive')
279
280
281 class If(Stmt):
282     """If `test` is true, `body` is rendered, else `else_`."""
283     fields = ('test', 'body', 'else_')
284
285
286 class Macro(Stmt):
287     """A macro definition.  `name` is the name of the macro, `args` a list of
288     arguments and `defaults` a list of defaults if there are any.  `body` is
289     a list of nodes for the macro body.
290     """
291     fields = ('name', 'args', 'defaults', 'body')
292
293
294 class CallBlock(Stmt):
295     """Like a macro without a name but a call instead.  `call` is called with
296     the unnamed macro as `caller` argument this node holds.
297     """
298     fields = ('call', 'args', 'defaults', 'body')
299
300
301 class FilterBlock(Stmt):
302     """Node for filter sections."""
303     fields = ('body', 'filter')
304
305
306 class Block(Stmt):
307     """A node that represents a block."""
308     fields = ('name', 'body', 'scoped')
309
310
311 class Include(Stmt):
312     """A node that represents the include tag."""
313     fields = ('template', 'with_context', 'ignore_missing')
314
315
316 class Import(Stmt):
317     """A node that represents the import tag."""
318     fields = ('template', 'target', 'with_context')
319
320
321 class FromImport(Stmt):
322     """A node that represents the from import tag.  It's important to not
323     pass unsafe names to the name attribute.  The compiler translates the
324     attribute lookups directly into getattr calls and does *not* use the
325     subscript callback of the interface.  As exported variables may not
326     start with double underscores (which the parser asserts) this is not a
327     problem for regular Jinja code, but if this node is used in an extension
328     extra care must be taken.
329
330     The list of names may contain tuples if aliases are wanted.
331     """
332     fields = ('template', 'names', 'with_context')
333
334
335 class ExprStmt(Stmt):
336     """A statement that evaluates an expression and discards the result."""
337     fields = ('node',)
338
339
340 class Assign(Stmt):
341     """Assigns an expression to a target."""
342     fields = ('target', 'node')
343
344
345 class Expr(Node):
346     """Baseclass for all expressions."""
347     abstract = True
348
349     def as_const(self, eval_ctx=None):
350         """Return the value of the expression as constant or raise
351         :exc:`Impossible` if this was not possible.
352
353         An :class:`EvalContext` can be provided, if none is given
354         a default context is created which requires the nodes to have
355         an attached environment.
356
357         .. versionchanged:: 2.4
358            the `eval_ctx` parameter was added.
359         """
360         raise Impossible()
361
362     def can_assign(self):
363         """Check if it's possible to assign something to this node."""
364         return False
365
366
367 class BinExpr(Expr):
368     """Baseclass for all binary expressions."""
369     fields = ('left', 'right')
370     operator = None
371     abstract = True
372
373     def as_const(self, eval_ctx=None):
374         eval_ctx = get_eval_context(self, eval_ctx)
375         # intercepted operators cannot be folded at compile time
376         if self.environment.sandboxed and \
377            self.operator in self.environment.intercepted_binops:
378             raise Impossible()
379         f = _binop_to_func[self.operator]
380         try:
381             return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))
382         except Exception:
383             raise Impossible()
384
385
386 class UnaryExpr(Expr):
387     """Baseclass for all unary expressions."""
388     fields = ('node',)
389     operator = None
390     abstract = True
391
392     def as_const(self, eval_ctx=None):
393         eval_ctx = get_eval_context(self, eval_ctx)
394         # intercepted operators cannot be folded at compile time
395         if self.environment.sandboxed and \
396            self.operator in self.environment.intercepted_unops:
397             raise Impossible()
398         f = _uaop_to_func[self.operator]
399         try:
400             return f(self.node.as_const(eval_ctx))
401         except Exception:
402             raise Impossible()
403
404
405 class Name(Expr):
406     """Looks up a name or stores a value in a name.
407     The `ctx` of the node can be one of the following values:
408
409     -   `store`: store a value in the name
410     -   `load`: load that name
411     -   `param`: like `store` but if the name was defined as function parameter.
412     """
413     fields = ('name', 'ctx')
414
415     def can_assign(self):
416         return self.name not in ('true', 'false', 'none',
417                                  'True', 'False', 'None')
418
419
420 class Literal(Expr):
421     """Baseclass for literals."""
422     abstract = True
423
424
425 class Const(Literal):
426     """All constant values.  The parser will return this node for simple
427     constants such as ``42`` or ``"foo"`` but it can be used to store more
428     complex values such as lists too.  Only constants with a safe
429     representation (objects where ``eval(repr(x)) == x`` is true).
430     """
431     fields = ('value',)
432
433     def as_const(self, eval_ctx=None):
434         return self.value
435
436     @classmethod
437     def from_untrusted(cls, value, lineno=None, environment=None):
438         """Return a const object if the value is representable as
439         constant value in the generated code, otherwise it will raise
440         an `Impossible` exception.
441         """
442         from compiler import has_safe_repr
443         if not has_safe_repr(value):
444             raise Impossible()
445         return cls(value, lineno=lineno, environment=environment)
446
447
448 class TemplateData(Literal):
449     """A constant template string."""
450     fields = ('data',)
451
452     def as_const(self, eval_ctx=None):
453         eval_ctx = get_eval_context(self, eval_ctx)
454         if eval_ctx.volatile:
455             raise Impossible()
456         if eval_ctx.autoescape:
457             return Markup(self.data)
458         return self.data
459
460
461 class Tuple(Literal):
462     """For loop unpacking and some other things like multiple arguments
463     for subscripts.  Like for :class:`Name` `ctx` specifies if the tuple
464     is used for loading the names or storing.
465     """
466     fields = ('items', 'ctx')
467
468     def as_const(self, eval_ctx=None):
469         eval_ctx = get_eval_context(self, eval_ctx)
470         return tuple(x.as_const(eval_ctx) for x in self.items)
471
472     def can_assign(self):
473         for item in self.items:
474             if not item.can_assign():
475                 return False
476         return True
477
478
479 class List(Literal):
480     """Any list literal such as ``[1, 2, 3]``"""
481     fields = ('items',)
482
483     def as_const(self, eval_ctx=None):
484         eval_ctx = get_eval_context(self, eval_ctx)
485         return [x.as_const(eval_ctx) for x in self.items]
486
487
488 class Dict(Literal):
489     """Any dict literal such as ``{1: 2, 3: 4}``.  The items must be a list of
490     :class:`Pair` nodes.
491     """
492     fields = ('items',)
493
494     def as_const(self, eval_ctx=None):
495         eval_ctx = get_eval_context(self, eval_ctx)
496         return dict(x.as_const(eval_ctx) for x in self.items)
497
498
499 class Pair(Helper):
500     """A key, value pair for dicts."""
501     fields = ('key', 'value')
502
503     def as_const(self, eval_ctx=None):
504         eval_ctx = get_eval_context(self, eval_ctx)
505         return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)
506
507
508 class Keyword(Helper):
509     """A key, value pair for keyword arguments where key is a string."""
510     fields = ('key', 'value')
511
512     def as_const(self, eval_ctx=None):
513         eval_ctx = get_eval_context(self, eval_ctx)
514         return self.key, self.value.as_const(eval_ctx)
515
516
517 class CondExpr(Expr):
518     """A conditional expression (inline if expression).  (``{{
519     foo if bar else baz }}``)
520     """
521     fields = ('test', 'expr1', 'expr2')
522
523     def as_const(self, eval_ctx=None):
524         eval_ctx = get_eval_context(self, eval_ctx)
525         if self.test.as_const(eval_ctx):
526             return self.expr1.as_const(eval_ctx)
527
528         # if we evaluate to an undefined object, we better do that at runtime
529         if self.expr2 is None:
530             raise Impossible()
531
532         return self.expr2.as_const(eval_ctx)
533
534
535 class Filter(Expr):
536     """This node applies a filter on an expression.  `name` is the name of
537     the filter, the rest of the fields are the same as for :class:`Call`.
538
539     If the `node` of a filter is `None` the contents of the last buffer are
540     filtered.  Buffers are created by macros and filter blocks.
541     """
542     fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
543
544     def as_const(self, eval_ctx=None):
545         eval_ctx = get_eval_context(self, eval_ctx)
546         if eval_ctx.volatile or self.node is None:
547             raise Impossible()
548         # we have to be careful here because we call filter_ below.
549         # if this variable would be called filter, 2to3 would wrap the
550         # call in a list beause it is assuming we are talking about the
551         # builtin filter function here which no longer returns a list in
552         # python 3.  because of that, do not rename filter_ to filter!
553         filter_ = self.environment.filters.get(self.name)
554         if filter_ is None or getattr(filter_, 'contextfilter', False):
555             raise Impossible()
556         obj = self.node.as_const(eval_ctx)
557         args = [x.as_const(eval_ctx) for x in self.args]
558         if getattr(filter_, 'evalcontextfilter', False):
559             args.insert(0, eval_ctx)
560         elif getattr(filter_, 'environmentfilter', False):
561             args.insert(0, self.environment)
562         kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
563         if self.dyn_args is not None:
564             try:
565                 args.extend(self.dyn_args.as_const(eval_ctx))
566             except Exception:
567                 raise Impossible()
568         if self.dyn_kwargs is not None:
569             try:
570                 kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
571             except Exception:
572                 raise Impossible()
573         try:
574             return filter_(obj, *args, **kwargs)
575         except Exception:
576             raise Impossible()
577
578
579 class Test(Expr):
580     """Applies a test on an expression.  `name` is the name of the test, the
581     rest of the fields are the same as for :class:`Call`.
582     """
583     fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
584
585
586 class Call(Expr):
587     """Calls an expression.  `args` is a list of arguments, `kwargs` a list
588     of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
589     and `dyn_kwargs` has to be either `None` or a node that is used as
590     node for dynamic positional (``*args``) or keyword (``**kwargs``)
591     arguments.
592     """
593     fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
594
595     def as_const(self, eval_ctx=None):
596         eval_ctx = get_eval_context(self, eval_ctx)
597         if eval_ctx.volatile:
598             raise Impossible()
599         obj = self.node.as_const(eval_ctx)
600
601         # don't evaluate context functions
602         args = [x.as_const(eval_ctx) for x in self.args]
603         if isinstance(obj, _context_function_types):
604             if getattr(obj, 'contextfunction', False):
605                 raise Impossible()
606             elif getattr(obj, 'evalcontextfunction', False):
607                 args.insert(0, eval_ctx)
608             elif getattr(obj, 'environmentfunction', False):
609                 args.insert(0, self.environment)
610
611         kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
612         if self.dyn_args is not None:
613             try:
614                 args.extend(self.dyn_args.as_const(eval_ctx))
615             except Exception:
616                 raise Impossible()
617         if self.dyn_kwargs is not None:
618             try:
619                 kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
620             except Exception:
621                 raise Impossible()
622         try:
623             return obj(*args, **kwargs)
624         except Exception:
625             raise Impossible()
626
627
628 class Getitem(Expr):
629     """Get an attribute or item from an expression and prefer the item."""
630     fields = ('node', 'arg', 'ctx')
631
632     def as_const(self, eval_ctx=None):
633         eval_ctx = get_eval_context(self, eval_ctx)
634         if self.ctx != 'load':
635             raise Impossible()
636         try:
637             return self.environment.getitem(self.node.as_const(eval_ctx),
638                                             self.arg.as_const(eval_ctx))
639         except Exception:
640             raise Impossible()
641
642     def can_assign(self):
643         return False
644
645
646 class Getattr(Expr):
647     """Get an attribute or item from an expression that is a ascii-only
648     bytestring and prefer the attribute.
649     """
650     fields = ('node', 'attr', 'ctx')
651
652     def as_const(self, eval_ctx=None):
653         if self.ctx != 'load':
654             raise Impossible()
655         try:
656             eval_ctx = get_eval_context(self, eval_ctx)
657             return self.environment.getattr(self.node.as_const(eval_ctx),
658                                             self.attr)
659         except Exception:
660             raise Impossible()
661
662     def can_assign(self):
663         return False
664
665
666 class Slice(Expr):
667     """Represents a slice object.  This must only be used as argument for
668     :class:`Subscript`.
669     """
670     fields = ('start', 'stop', 'step')
671
672     def as_const(self, eval_ctx=None):
673         eval_ctx = get_eval_context(self, eval_ctx)
674         def const(obj):
675             if obj is None:
676                 return None
677             return obj.as_const(eval_ctx)
678         return slice(const(self.start), const(self.stop), const(self.step))
679
680
681 class Concat(Expr):
682     """Concatenates the list of expressions provided after converting them to
683     unicode.
684     """
685     fields = ('nodes',)
686
687     def as_const(self, eval_ctx=None):
688         eval_ctx = get_eval_context(self, eval_ctx)
689         return ''.join(unicode(x.as_const(eval_ctx)) for x in self.nodes)
690
691
692 class Compare(Expr):
693     """Compares an expression with some other expressions.  `ops` must be a
694     list of :class:`Operand`\s.
695     """
696     fields = ('expr', 'ops')
697
698     def as_const(self, eval_ctx=None):
699         eval_ctx = get_eval_context(self, eval_ctx)
700         result = value = self.expr.as_const(eval_ctx)
701         try:
702             for op in self.ops:
703                 new_value = op.expr.as_const(eval_ctx)
704                 result = _cmpop_to_func[op.op](value, new_value)
705                 value = new_value
706         except Exception:
707             raise Impossible()
708         return result
709
710
711 class Operand(Helper):
712     """Holds an operator and an expression."""
713     fields = ('op', 'expr')
714
715 if __debug__:
716     Operand.__doc__ += '\nThe following operators are available: ' + \
717         ', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
718                   set(_uaop_to_func) | set(_cmpop_to_func)))
719
720
721 class Mul(BinExpr):
722     """Multiplies the left with the right node."""
723     operator = '*'
724
725
726 class Div(BinExpr):
727     """Divides the left by the right node."""
728     operator = '/'
729
730
731 class FloorDiv(BinExpr):
732     """Divides the left by the right node and truncates conver the
733     result into an integer by truncating.
734     """
735     operator = '//'
736
737
738 class Add(BinExpr):
739     """Add the left to the right node."""
740     operator = '+'
741
742
743 class Sub(BinExpr):
744     """Substract the right from the left node."""
745     operator = '-'
746
747
748 class Mod(BinExpr):
749     """Left modulo right."""
750     operator = '%'
751
752
753 class Pow(BinExpr):
754     """Left to the power of right."""
755     operator = '**'
756
757
758 class And(BinExpr):
759     """Short circuited AND."""
760     operator = 'and'
761
762     def as_const(self, eval_ctx=None):
763         eval_ctx = get_eval_context(self, eval_ctx)
764         return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)
765
766
767 class Or(BinExpr):
768     """Short circuited OR."""
769     operator = 'or'
770
771     def as_const(self, eval_ctx=None):
772         eval_ctx = get_eval_context(self, eval_ctx)
773         return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
774
775
776 class Not(UnaryExpr):
777     """Negate the expression."""
778     operator = 'not'
779
780
781 class Neg(UnaryExpr):
782     """Make the expression negative."""
783     operator = '-'
784
785
786 class Pos(UnaryExpr):
787     """Make the expression positive (noop for most expressions)"""
788     operator = '+'
789
790
791 # Helpers for extensions
792
793
794 class EnvironmentAttribute(Expr):
795     """Loads an attribute from the environment object.  This is useful for
796     extensions that want to call a callback stored on the environment.
797     """
798     fields = ('name',)
799
800
801 class ExtensionAttribute(Expr):
802     """Returns the attribute of an extension bound to the environment.
803     The identifier is the identifier of the :class:`Extension`.
804
805     This node is usually constructed by calling the
806     :meth:`~jinja2.ext.Extension.attr` method on an extension.
807     """
808     fields = ('identifier', 'name')
809
810
811 class ImportedName(Expr):
812     """If created with an import name the import name is returned on node
813     access.  For example ``ImportedName('cgi.escape')`` returns the `escape`
814     function from the cgi module on evaluation.  Imports are optimized by the
815     compiler so there is no need to assign them to local variables.
816     """
817     fields = ('importname',)
818
819
820 class InternalName(Expr):
821     """An internal name in the compiler.  You cannot create these nodes
822     yourself but the parser provides a
823     :meth:`~jinja2.parser.Parser.free_identifier` method that creates
824     a new identifier for you.  This identifier is not available from the
825     template and is not threated specially by the compiler.
826     """
827     fields = ('name',)
828
829     def __init__(self):
830         raise TypeError('Can\'t create internal names.  Use the '
831                         '`free_identifier` method on a parser.')
832
833
834 class MarkSafe(Expr):
835     """Mark the wrapped expression as safe (wrap it as `Markup`)."""
836     fields = ('expr',)
837
838     def as_const(self, eval_ctx=None):
839         eval_ctx = get_eval_context(self, eval_ctx)
840         return Markup(self.expr.as_const(eval_ctx))
841
842
843 class MarkSafeIfAutoescape(Expr):
844     """Mark the wrapped expression as safe (wrap it as `Markup`) but
845     only if autoescaping is active.
846
847     .. versionadded:: 2.5
848     """
849     fields = ('expr',)
850
851     def as_const(self, eval_ctx=None):
852         eval_ctx = get_eval_context(self, eval_ctx)
853         if eval_ctx.volatile:
854             raise Impossible()
855         expr = self.expr.as_const(eval_ctx)
856         if eval_ctx.autoescape:
857             return Markup(expr)
858         return expr
859
860
861 class ContextReference(Expr):
862     """Returns the current template context.  It can be used like a
863     :class:`Name` node, with a ``'load'`` ctx and will return the
864     current :class:`~jinja2.runtime.Context` object.
865
866     Here an example that assigns the current template name to a
867     variable named `foo`::
868
869         Assign(Name('foo', ctx='store'),
870                Getattr(ContextReference(), 'name'))
871     """
872
873
874 class Continue(Stmt):
875     """Continue a loop."""
876
877
878 class Break(Stmt):
879     """Break a loop."""
880
881
882 class Scope(Stmt):
883     """An artificial scope."""
884     fields = ('body',)
885
886
887 class EvalContextModifier(Stmt):
888     """Modifies the eval context.  For each option that should be modified,
889     a :class:`Keyword` has to be added to the :attr:`options` list.
890
891     Example to change the `autoescape` setting::
892
893         EvalContextModifier(options=[Keyword('autoescape', Const(True))])
894     """
895     fields = ('options',)
896
897
898 class ScopedEvalContextModifier(EvalContextModifier):
899     """Modifies the eval context and reverts it later.  Works exactly like
900     :class:`EvalContextModifier` but will only modify the
901     :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.
902     """
903     fields = ('body',)
904
905
906 # make sure nobody creates custom nodes
907 def _failing_new(*args, **kwargs):
908     raise TypeError('can\'t create custom node types')
909 NodeType.__new__ = staticmethod(_failing_new); del _failing_new