comparison venv/lib/python2.7/site-packages/jinja2/nodes.py @ 0:d67268158946 draft

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