babel extraction can now properly extract newstyle gettext calls.
[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         f = _binop_to_func[self.operator]
376         try:
377             return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))
378         except:
379             raise Impossible()
380
381
382 class UnaryExpr(Expr):
383     """Baseclass for all unary expressions."""
384     fields = ('node',)
385     operator = None
386     abstract = True
387
388     def as_const(self, eval_ctx=None):
389         eval_ctx = get_eval_context(self, eval_ctx)
390         f = _uaop_to_func[self.operator]
391         try:
392             return f(self.node.as_const(eval_ctx))
393         except:
394             raise Impossible()
395
396
397 class Name(Expr):
398     """Looks up a name or stores a value in a name.
399     The `ctx` of the node can be one of the following values:
400
401     -   `store`: store a value in the name
402     -   `load`: load that name
403     -   `param`: like `store` but if the name was defined as function parameter.
404     """
405     fields = ('name', 'ctx')
406
407     def can_assign(self):
408         return self.name not in ('true', 'false', 'none',
409                                  'True', 'False', 'None')
410
411
412 class Literal(Expr):
413     """Baseclass for literals."""
414     abstract = True
415
416
417 class Const(Literal):
418     """All constant values.  The parser will return this node for simple
419     constants such as ``42`` or ``"foo"`` but it can be used to store more
420     complex values such as lists too.  Only constants with a safe
421     representation (objects where ``eval(repr(x)) == x`` is true).
422     """
423     fields = ('value',)
424
425     def as_const(self, eval_ctx=None):
426         return self.value
427
428     @classmethod
429     def from_untrusted(cls, value, lineno=None, environment=None):
430         """Return a const object if the value is representable as
431         constant value in the generated code, otherwise it will raise
432         an `Impossible` exception.
433         """
434         from compiler import has_safe_repr
435         if not has_safe_repr(value):
436             raise Impossible()
437         return cls(value, lineno=lineno, environment=environment)
438
439
440 class TemplateData(Literal):
441     """A constant template string."""
442     fields = ('data',)
443
444     def as_const(self, eval_ctx=None):
445         eval_ctx = get_eval_context(self, eval_ctx)
446         if eval_ctx.volatile:
447             raise Impossible()
448         if eval_ctx.autoescape:
449             return Markup(self.data)
450         return self.data
451
452
453 class Tuple(Literal):
454     """For loop unpacking and some other things like multiple arguments
455     for subscripts.  Like for :class:`Name` `ctx` specifies if the tuple
456     is used for loading the names or storing.
457     """
458     fields = ('items', 'ctx')
459
460     def as_const(self, eval_ctx=None):
461         eval_ctx = get_eval_context(self, eval_ctx)
462         return tuple(x.as_const(eval_ctx) for x in self.items)
463
464     def can_assign(self):
465         for item in self.items:
466             if not item.can_assign():
467                 return False
468         return True
469
470
471 class List(Literal):
472     """Any list literal such as ``[1, 2, 3]``"""
473     fields = ('items',)
474
475     def as_const(self, eval_ctx=None):
476         eval_ctx = get_eval_context(self, eval_ctx)
477         return [x.as_const(eval_ctx) for x in self.items]
478
479
480 class Dict(Literal):
481     """Any dict literal such as ``{1: 2, 3: 4}``.  The items must be a list of
482     :class:`Pair` nodes.
483     """
484     fields = ('items',)
485
486     def as_const(self, eval_ctx=None):
487         eval_ctx = get_eval_context(self, eval_ctx)
488         return dict(x.as_const(eval_ctx) for x in self.items)
489
490
491 class Pair(Helper):
492     """A key, value pair for dicts."""
493     fields = ('key', 'value')
494
495     def as_const(self, eval_ctx=None):
496         eval_ctx = get_eval_context(self, eval_ctx)
497         return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)
498
499
500 class Keyword(Helper):
501     """A key, value pair for keyword arguments where key is a string."""
502     fields = ('key', 'value')
503
504     def as_const(self, eval_ctx=None):
505         eval_ctx = get_eval_context(self, eval_ctx)
506         return self.key, self.value.as_const(eval_ctx)
507
508
509 class CondExpr(Expr):
510     """A conditional expression (inline if expression).  (``{{
511     foo if bar else baz }}``)
512     """
513     fields = ('test', 'expr1', 'expr2')
514
515     def as_const(self, eval_ctx=None):
516         eval_ctx = get_eval_context(self, eval_ctx)
517         if self.test.as_const(eval_ctx):
518             return self.expr1.as_const(eval_ctx)
519
520         # if we evaluate to an undefined object, we better do that at runtime
521         if self.expr2 is None:
522             raise Impossible()
523
524         return self.expr2.as_const(eval_ctx)
525
526
527 class Filter(Expr):
528     """This node applies a filter on an expression.  `name` is the name of
529     the filter, the rest of the fields are the same as for :class:`Call`.
530
531     If the `node` of a filter is `None` the contents of the last buffer are
532     filtered.  Buffers are created by macros and filter blocks.
533     """
534     fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
535
536     def as_const(self, eval_ctx=None):
537         eval_ctx = get_eval_context(self, eval_ctx)
538         if eval_ctx.volatile or self.node is None:
539             raise Impossible()
540         # we have to be careful here because we call filter_ below.
541         # if this variable would be called filter, 2to3 would wrap the
542         # call in a list beause it is assuming we are talking about the
543         # builtin filter function here which no longer returns a list in
544         # python 3.  because of that, do not rename filter_ to filter!
545         filter_ = self.environment.filters.get(self.name)
546         if filter_ is None or getattr(filter_, 'contextfilter', False):
547             raise Impossible()
548         obj = self.node.as_const(eval_ctx)
549         args = [x.as_const(eval_ctx) for x in self.args]
550         if getattr(filter_, 'evalcontextfilter', False):
551             args.insert(0, eval_ctx)
552         elif getattr(filter_, 'environmentfilter', False):
553             args.insert(0, self.environment)
554         kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
555         if self.dyn_args is not None:
556             try:
557                 args.extend(self.dyn_args.as_const(eval_ctx))
558             except:
559                 raise Impossible()
560         if self.dyn_kwargs is not None:
561             try:
562                 kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
563             except:
564                 raise Impossible()
565         try:
566             return filter_(obj, *args, **kwargs)
567         except:
568             raise Impossible()
569
570
571 class Test(Expr):
572     """Applies a test on an expression.  `name` is the name of the test, the
573     rest of the fields are the same as for :class:`Call`.
574     """
575     fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
576
577
578 class Call(Expr):
579     """Calls an expression.  `args` is a list of arguments, `kwargs` a list
580     of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
581     and `dyn_kwargs` has to be either `None` or a node that is used as
582     node for dynamic positional (``*args``) or keyword (``**kwargs``)
583     arguments.
584     """
585     fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
586
587     def as_const(self, eval_ctx=None):
588         eval_ctx = get_eval_context(self, eval_ctx)
589         if eval_ctx.volatile:
590             raise Impossible()
591         obj = self.node.as_const(eval_ctx)
592
593         # don't evaluate context functions
594         args = [x.as_const(eval_ctx) for x in self.args]
595         if isinstance(obj, _context_function_types):
596             if getattr(obj, 'contextfunction', False):
597                 raise Impossible()
598             elif getattr(obj, 'evalcontextfunction', False):
599                 args.insert(0, eval_ctx)
600             elif getattr(obj, 'environmentfunction', False):
601                 args.insert(0, self.environment)
602
603         kwargs = dict(x.as_const(eval_ctx) for x in self.kwargs)
604         if self.dyn_args is not None:
605             try:
606                 args.extend(self.dyn_args.as_const(eval_ctx))
607             except:
608                 raise Impossible()
609         if self.dyn_kwargs is not None:
610             try:
611                 kwargs.update(self.dyn_kwargs.as_const(eval_ctx))
612             except:
613                 raise Impossible()
614         try:
615             return obj(*args, **kwargs)
616         except:
617             raise Impossible()
618
619
620 class Getitem(Expr):
621     """Get an attribute or item from an expression and prefer the item."""
622     fields = ('node', 'arg', 'ctx')
623
624     def as_const(self, eval_ctx=None):
625         eval_ctx = get_eval_context(self, eval_ctx)
626         if self.ctx != 'load':
627             raise Impossible()
628         try:
629             return self.environment.getitem(self.node.as_const(eval_ctx),
630                                             self.arg.as_const(eval_ctx))
631         except:
632             raise Impossible()
633
634     def can_assign(self):
635         return False
636
637
638 class Getattr(Expr):
639     """Get an attribute or item from an expression that is a ascii-only
640     bytestring and prefer the attribute.
641     """
642     fields = ('node', 'attr', 'ctx')
643
644     def as_const(self, eval_ctx=None):
645         if self.ctx != 'load':
646             raise Impossible()
647         try:
648             eval_ctx = get_eval_context(self, eval_ctx)
649             return self.environment.getattr(self.node.as_const(eval_ctx),
650                                             self.attr)
651         except:
652             raise Impossible()
653
654     def can_assign(self):
655         return False
656
657
658 class Slice(Expr):
659     """Represents a slice object.  This must only be used as argument for
660     :class:`Subscript`.
661     """
662     fields = ('start', 'stop', 'step')
663
664     def as_const(self, eval_ctx=None):
665         eval_ctx = get_eval_context(self, eval_ctx)
666         def const(obj):
667             if obj is None:
668                 return None
669             return obj.as_const(eval_ctx)
670         return slice(const(self.start), const(self.stop), const(self.step))
671
672
673 class Concat(Expr):
674     """Concatenates the list of expressions provided after converting them to
675     unicode.
676     """
677     fields = ('nodes',)
678
679     def as_const(self, eval_ctx=None):
680         eval_ctx = get_eval_context(self, eval_ctx)
681         return ''.join(unicode(x.as_const(eval_ctx)) for x in self.nodes)
682
683
684 class Compare(Expr):
685     """Compares an expression with some other expressions.  `ops` must be a
686     list of :class:`Operand`\s.
687     """
688     fields = ('expr', 'ops')
689
690     def as_const(self, eval_ctx=None):
691         eval_ctx = get_eval_context(self, eval_ctx)
692         result = value = self.expr.as_const(eval_ctx)
693         try:
694             for op in self.ops:
695                 new_value = op.expr.as_const(eval_ctx)
696                 result = _cmpop_to_func[op.op](value, new_value)
697                 value = new_value
698         except:
699             raise Impossible()
700         return result
701
702
703 class Operand(Helper):
704     """Holds an operator and an expression."""
705     fields = ('op', 'expr')
706
707 if __debug__:
708     Operand.__doc__ += '\nThe following operators are available: ' + \
709         ', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
710                   set(_uaop_to_func) | set(_cmpop_to_func)))
711
712
713 class Mul(BinExpr):
714     """Multiplies the left with the right node."""
715     operator = '*'
716
717
718 class Div(BinExpr):
719     """Divides the left by the right node."""
720     operator = '/'
721
722
723 class FloorDiv(BinExpr):
724     """Divides the left by the right node and truncates conver the
725     result into an integer by truncating.
726     """
727     operator = '//'
728
729
730 class Add(BinExpr):
731     """Add the left to the right node."""
732     operator = '+'
733
734
735 class Sub(BinExpr):
736     """Substract the right from the left node."""
737     operator = '-'
738
739
740 class Mod(BinExpr):
741     """Left modulo right."""
742     operator = '%'
743
744
745 class Pow(BinExpr):
746     """Left to the power of right."""
747     operator = '**'
748
749
750 class And(BinExpr):
751     """Short circuited AND."""
752     operator = 'and'
753
754     def as_const(self, eval_ctx=None):
755         eval_ctx = get_eval_context(self, eval_ctx)
756         return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)
757
758
759 class Or(BinExpr):
760     """Short circuited OR."""
761     operator = 'or'
762
763     def as_const(self, eval_ctx=None):
764         eval_ctx = get_eval_context(self, eval_ctx)
765         return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)
766
767
768 class Not(UnaryExpr):
769     """Negate the expression."""
770     operator = 'not'
771
772
773 class Neg(UnaryExpr):
774     """Make the expression negative."""
775     operator = '-'
776
777
778 class Pos(UnaryExpr):
779     """Make the expression positive (noop for most expressions)"""
780     operator = '+'
781
782
783 # Helpers for extensions
784
785
786 class EnvironmentAttribute(Expr):
787     """Loads an attribute from the environment object.  This is useful for
788     extensions that want to call a callback stored on the environment.
789     """
790     fields = ('name',)
791
792
793 class ExtensionAttribute(Expr):
794     """Returns the attribute of an extension bound to the environment.
795     The identifier is the identifier of the :class:`Extension`.
796
797     This node is usually constructed by calling the
798     :meth:`~jinja2.ext.Extension.attr` method on an extension.
799     """
800     fields = ('identifier', 'name')
801
802
803 class ImportedName(Expr):
804     """If created with an import name the import name is returned on node
805     access.  For example ``ImportedName('cgi.escape')`` returns the `escape`
806     function from the cgi module on evaluation.  Imports are optimized by the
807     compiler so there is no need to assign them to local variables.
808     """
809     fields = ('importname',)
810
811
812 class InternalName(Expr):
813     """An internal name in the compiler.  You cannot create these nodes
814     yourself but the parser provides a
815     :meth:`~jinja2.parser.Parser.free_identifier` method that creates
816     a new identifier for you.  This identifier is not available from the
817     template and is not threated specially by the compiler.
818     """
819     fields = ('name',)
820
821     def __init__(self):
822         raise TypeError('Can\'t create internal names.  Use the '
823                         '`free_identifier` method on a parser.')
824
825
826 class MarkSafe(Expr):
827     """Mark the wrapped expression as safe (wrap it as `Markup`)."""
828     fields = ('expr',)
829
830     def as_const(self, eval_ctx=None):
831         eval_ctx = get_eval_context(self, eval_ctx)
832         return Markup(self.expr.as_const(eval_ctx))
833
834
835 class MarkSafeIfAutoescape(Expr):
836     """Mark the wrapped expression as safe (wrap it as `Markup`) but
837     only if autoescaping is active.
838
839     .. versionadded:: 2.5
840     """
841     fields = ('expr',)
842
843     def as_const(self, eval_ctx=None):
844         eval_ctx = get_eval_context(self, eval_ctx)
845         if eval_ctx.volatile:
846             raise Impossible()
847         expr = self.expr.as_const(eval_ctx)
848         if eval_ctx.autoescape:
849             return Markup(expr)
850         return expr
851
852
853 class ContextReference(Expr):
854     """Returns the current template context.  It can be used like a
855     :class:`Name` node, with a ``'load'`` ctx and will return the
856     current :class:`~jinja2.runtime.Context` object.
857
858     Here an example that assigns the current template name to a
859     variable named `foo`::
860
861         Assign(Name('foo', ctx='store'),
862                Getattr(ContextReference(), 'name'))
863     """
864
865
866 class Continue(Stmt):
867     """Continue a loop."""
868
869
870 class Break(Stmt):
871     """Break a loop."""
872
873
874 class Scope(Stmt):
875     """An artificial scope."""
876     fields = ('body',)
877
878
879 class EvalContextModifier(Stmt):
880     """Modifies the eval context.  For each option that should be modified,
881     a :class:`Keyword` has to be added to the :attr:`options` list.
882
883     Example to change the `autoescape` setting::
884
885         EvalContextModifier(options=[Keyword('autoescape', Const(True))])
886     """
887     fields = ('options',)
888
889
890 class ScopedEvalContextModifier(EvalContextModifier):
891     """Modifies the eval context and reverts it later.  Works exactly like
892     :class:`EvalContextModifier` but will only modify the
893     :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.
894     """
895     fields = ('body',)
896
897
898 # make sure nobody creates custom nodes
899 def _failing_new(*args, **kwargs):
900     raise TypeError('can\'t create custom node types')
901 NodeType.__new__ = staticmethod(_failing_new); del _failing_new