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) 2017 by the Jinja Team. 13 :license: BSD, see LICENSE for more details. 14""" 15import types 16import operator 17 18from collections import deque 19from jinja2.utils import Markup 20from jinja2._compat import izip, with_metaclass, text_type, PY2 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 55class Impossible(Exception): 56 """Raised if the node could not perform a requested action.""" 57 58 59class 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 76class 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 97def 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 107class 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 def dump(self): 246 def _dump(node): 247 if not isinstance(node, Node): 248 buf.append(repr(node)) 249 return 250 251 buf.append('nodes.%s(' % node.__class__.__name__) 252 if not node.fields: 253 buf.append(')') 254 return 255 for idx, field in enumerate(node.fields): 256 if idx: 257 buf.append(', ') 258 value = getattr(node, field) 259 if isinstance(value, list): 260 buf.append('[') 261 for idx, item in enumerate(value): 262 if idx: 263 buf.append(', ') 264 _dump(item) 265 buf.append(']') 266 else: 267 _dump(value) 268 buf.append(')') 269 buf = [] 270 _dump(self) 271 return ''.join(buf) 272 273 274 275class Stmt(Node): 276 """Base node for all statements.""" 277 abstract = True 278 279 280class Helper(Node): 281 """Nodes that exist in a specific context only.""" 282 abstract = True 283 284 285class Template(Node): 286 """Node that represents a template. This must be the outermost node that 287 is passed to the compiler. 288 """ 289 fields = ('body',) 290 291 292class Output(Stmt): 293 """A node that holds multiple expressions which are then printed out. 294 This is used both for the `print` statement and the regular template data. 295 """ 296 fields = ('nodes',) 297 298 299class Extends(Stmt): 300 """Represents an extends statement.""" 301 fields = ('template',) 302 303 304class For(Stmt): 305 """The for loop. `target` is the target for the iteration (usually a 306 :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list 307 of nodes that are used as loop-body, and `else_` a list of nodes for the 308 `else` block. If no else node exists it has to be an empty list. 309 310 For filtered nodes an expression can be stored as `test`, otherwise `None`. 311 """ 312 fields = ('target', 'iter', 'body', 'else_', 'test', 'recursive') 313 314 315class If(Stmt): 316 """If `test` is true, `body` is rendered, else `else_`.""" 317 fields = ('test', 'body', 'elif_', 'else_') 318 319 320class Macro(Stmt): 321 """A macro definition. `name` is the name of the macro, `args` a list of 322 arguments and `defaults` a list of defaults if there are any. `body` is 323 a list of nodes for the macro body. 324 """ 325 fields = ('name', 'args', 'defaults', 'body') 326 327 328class CallBlock(Stmt): 329 """Like a macro without a name but a call instead. `call` is called with 330 the unnamed macro as `caller` argument this node holds. 331 """ 332 fields = ('call', 'args', 'defaults', 'body') 333 334 335class FilterBlock(Stmt): 336 """Node for filter sections.""" 337 fields = ('body', 'filter') 338 339 340class With(Stmt): 341 """Specific node for with statements. In older versions of Jinja the 342 with statement was implemented on the base of the `Scope` node instead. 343 344 .. versionadded:: 2.9.3 345 """ 346 fields = ('targets', 'values', 'body') 347 348 349class Block(Stmt): 350 """A node that represents a block.""" 351 fields = ('name', 'body', 'scoped') 352 353 354class Include(Stmt): 355 """A node that represents the include tag.""" 356 fields = ('template', 'with_context', 'ignore_missing') 357 358 359class Import(Stmt): 360 """A node that represents the import tag.""" 361 fields = ('template', 'target', 'with_context') 362 363 364class FromImport(Stmt): 365 """A node that represents the from import tag. It's important to not 366 pass unsafe names to the name attribute. The compiler translates the 367 attribute lookups directly into getattr calls and does *not* use the 368 subscript callback of the interface. As exported variables may not 369 start with double underscores (which the parser asserts) this is not a 370 problem for regular Jinja code, but if this node is used in an extension 371 extra care must be taken. 372 373 The list of names may contain tuples if aliases are wanted. 374 """ 375 fields = ('template', 'names', 'with_context') 376 377 378class ExprStmt(Stmt): 379 """A statement that evaluates an expression and discards the result.""" 380 fields = ('node',) 381 382 383class Assign(Stmt): 384 """Assigns an expression to a target.""" 385 fields = ('target', 'node') 386 387 388class AssignBlock(Stmt): 389 """Assigns a block to a target.""" 390 fields = ('target', 'filter', 'body') 391 392 393class Expr(Node): 394 """Baseclass for all expressions.""" 395 abstract = True 396 397 def as_const(self, eval_ctx=None): 398 """Return the value of the expression as constant or raise 399 :exc:`Impossible` if this was not possible. 400 401 An :class:`EvalContext` can be provided, if none is given 402 a default context is created which requires the nodes to have 403 an attached environment. 404 405 .. versionchanged:: 2.4 406 the `eval_ctx` parameter was added. 407 """ 408 raise Impossible() 409 410 def can_assign(self): 411 """Check if it's possible to assign something to this node.""" 412 return False 413 414 415class BinExpr(Expr): 416 """Baseclass for all binary expressions.""" 417 fields = ('left', 'right') 418 operator = None 419 abstract = True 420 421 def as_const(self, eval_ctx=None): 422 eval_ctx = get_eval_context(self, eval_ctx) 423 # intercepted operators cannot be folded at compile time 424 if self.environment.sandboxed and \ 425 self.operator in self.environment.intercepted_binops: 426 raise Impossible() 427 f = _binop_to_func[self.operator] 428 try: 429 return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx)) 430 except Exception: 431 raise Impossible() 432 433 434class UnaryExpr(Expr): 435 """Baseclass for all unary expressions.""" 436 fields = ('node',) 437 operator = None 438 abstract = True 439 440 def as_const(self, eval_ctx=None): 441 eval_ctx = get_eval_context(self, eval_ctx) 442 # intercepted operators cannot be folded at compile time 443 if self.environment.sandboxed and \ 444 self.operator in self.environment.intercepted_unops: 445 raise Impossible() 446 f = _uaop_to_func[self.operator] 447 try: 448 return f(self.node.as_const(eval_ctx)) 449 except Exception: 450 raise Impossible() 451 452 453class Name(Expr): 454 """Looks up a name or stores a value in a name. 455 The `ctx` of the node can be one of the following values: 456 457 - `store`: store a value in the name 458 - `load`: load that name 459 - `param`: like `store` but if the name was defined as function parameter. 460 """ 461 fields = ('name', 'ctx') 462 463 def can_assign(self): 464 return self.name not in ('true', 'false', 'none', 465 'True', 'False', 'None') 466 467 468class NSRef(Expr): 469 """Reference to a namespace value assignment""" 470 fields = ('name', 'attr') 471 472 def can_assign(self): 473 # We don't need any special checks here; NSRef assignments have a 474 # runtime check to ensure the target is a namespace object which will 475 # have been checked already as it is created using a normal assignment 476 # which goes through a `Name` node. 477 return True 478 479 480class Literal(Expr): 481 """Baseclass for literals.""" 482 abstract = True 483 484 485class Const(Literal): 486 """All constant values. The parser will return this node for simple 487 constants such as ``42`` or ``"foo"`` but it can be used to store more 488 complex values such as lists too. Only constants with a safe 489 representation (objects where ``eval(repr(x)) == x`` is true). 490 """ 491 fields = ('value',) 492 493 def as_const(self, eval_ctx=None): 494 rv = self.value 495 if PY2 and type(rv) is text_type and \ 496 self.environment.policies['compiler.ascii_str']: 497 try: 498 rv = rv.encode('ascii') 499 except UnicodeError: 500 pass 501 return rv 502 503 @classmethod 504 def from_untrusted(cls, value, lineno=None, environment=None): 505 """Return a const object if the value is representable as 506 constant value in the generated code, otherwise it will raise 507 an `Impossible` exception. 508 """ 509 from .compiler import has_safe_repr 510 if not has_safe_repr(value): 511 raise Impossible() 512 return cls(value, lineno=lineno, environment=environment) 513 514 515class TemplateData(Literal): 516 """A constant template string.""" 517 fields = ('data',) 518 519 def as_const(self, eval_ctx=None): 520 eval_ctx = get_eval_context(self, eval_ctx) 521 if eval_ctx.volatile: 522 raise Impossible() 523 if eval_ctx.autoescape: 524 return Markup(self.data) 525 return self.data 526 527 528class Tuple(Literal): 529 """For loop unpacking and some other things like multiple arguments 530 for subscripts. Like for :class:`Name` `ctx` specifies if the tuple 531 is used for loading the names or storing. 532 """ 533 fields = ('items', 'ctx') 534 535 def as_const(self, eval_ctx=None): 536 eval_ctx = get_eval_context(self, eval_ctx) 537 return tuple(x.as_const(eval_ctx) for x in self.items) 538 539 def can_assign(self): 540 for item in self.items: 541 if not item.can_assign(): 542 return False 543 return True 544 545 546class List(Literal): 547 """Any list literal such as ``[1, 2, 3]``""" 548 fields = ('items',) 549 550 def as_const(self, eval_ctx=None): 551 eval_ctx = get_eval_context(self, eval_ctx) 552 return [x.as_const(eval_ctx) for x in self.items] 553 554 555class Dict(Literal): 556 """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of 557 :class:`Pair` nodes. 558 """ 559 fields = ('items',) 560 561 def as_const(self, eval_ctx=None): 562 eval_ctx = get_eval_context(self, eval_ctx) 563 return dict(x.as_const(eval_ctx) for x in self.items) 564 565 566class Pair(Helper): 567 """A key, value pair for dicts.""" 568 fields = ('key', 'value') 569 570 def as_const(self, eval_ctx=None): 571 eval_ctx = get_eval_context(self, eval_ctx) 572 return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx) 573 574 575class Keyword(Helper): 576 """A key, value pair for keyword arguments where key is a string.""" 577 fields = ('key', 'value') 578 579 def as_const(self, eval_ctx=None): 580 eval_ctx = get_eval_context(self, eval_ctx) 581 return self.key, self.value.as_const(eval_ctx) 582 583 584class CondExpr(Expr): 585 """A conditional expression (inline if expression). (``{{ 586 foo if bar else baz }}``) 587 """ 588 fields = ('test', 'expr1', 'expr2') 589 590 def as_const(self, eval_ctx=None): 591 eval_ctx = get_eval_context(self, eval_ctx) 592 if self.test.as_const(eval_ctx): 593 return self.expr1.as_const(eval_ctx) 594 595 # if we evaluate to an undefined object, we better do that at runtime 596 if self.expr2 is None: 597 raise Impossible() 598 599 return self.expr2.as_const(eval_ctx) 600 601 602def args_as_const(node, eval_ctx): 603 args = [x.as_const(eval_ctx) for x in node.args] 604 kwargs = dict(x.as_const(eval_ctx) for x in node.kwargs) 605 606 if node.dyn_args is not None: 607 try: 608 args.extend(node.dyn_args.as_const(eval_ctx)) 609 except Exception: 610 raise Impossible() 611 612 if node.dyn_kwargs is not None: 613 try: 614 kwargs.update(node.dyn_kwargs.as_const(eval_ctx)) 615 except Exception: 616 raise Impossible() 617 618 return args, kwargs 619 620 621class Filter(Expr): 622 """This node applies a filter on an expression. `name` is the name of 623 the filter, the rest of the fields are the same as for :class:`Call`. 624 625 If the `node` of a filter is `None` the contents of the last buffer are 626 filtered. Buffers are created by macros and filter blocks. 627 """ 628 629 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs') 630 631 def as_const(self, eval_ctx=None): 632 eval_ctx = get_eval_context(self, eval_ctx) 633 634 if eval_ctx.volatile or self.node is None: 635 raise Impossible() 636 637 # we have to be careful here because we call filter_ below. 638 # if this variable would be called filter, 2to3 would wrap the 639 # call in a list beause it is assuming we are talking about the 640 # builtin filter function here which no longer returns a list in 641 # python 3. because of that, do not rename filter_ to filter! 642 filter_ = self.environment.filters.get(self.name) 643 644 if filter_ is None or getattr(filter_, 'contextfilter', False): 645 raise Impossible() 646 647 # We cannot constant handle async filters, so we need to make sure 648 # to not go down this path. 649 if ( 650 eval_ctx.environment.is_async 651 and getattr(filter_, 'asyncfiltervariant', False) 652 ): 653 raise Impossible() 654 655 args, kwargs = args_as_const(self, eval_ctx) 656 args.insert(0, self.node.as_const(eval_ctx)) 657 658 if getattr(filter_, 'evalcontextfilter', False): 659 args.insert(0, eval_ctx) 660 elif getattr(filter_, 'environmentfilter', False): 661 args.insert(0, self.environment) 662 663 try: 664 return filter_(*args, **kwargs) 665 except Exception: 666 raise Impossible() 667 668 669class Test(Expr): 670 """Applies a test on an expression. `name` is the name of the test, the 671 rest of the fields are the same as for :class:`Call`. 672 """ 673 674 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs') 675 676 def as_const(self, eval_ctx=None): 677 test = self.environment.tests.get(self.name) 678 679 if test is None: 680 raise Impossible() 681 682 eval_ctx = get_eval_context(self, eval_ctx) 683 args, kwargs = args_as_const(self, eval_ctx) 684 args.insert(0, self.node.as_const(eval_ctx)) 685 686 try: 687 return test(*args, **kwargs) 688 except Exception: 689 raise Impossible() 690 691 692class Call(Expr): 693 """Calls an expression. `args` is a list of arguments, `kwargs` a list 694 of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args` 695 and `dyn_kwargs` has to be either `None` or a node that is used as 696 node for dynamic positional (``*args``) or keyword (``**kwargs``) 697 arguments. 698 """ 699 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs') 700 701 702class Getitem(Expr): 703 """Get an attribute or item from an expression and prefer the item.""" 704 fields = ('node', 'arg', 'ctx') 705 706 def as_const(self, eval_ctx=None): 707 eval_ctx = get_eval_context(self, eval_ctx) 708 if self.ctx != 'load': 709 raise Impossible() 710 try: 711 return self.environment.getitem(self.node.as_const(eval_ctx), 712 self.arg.as_const(eval_ctx)) 713 except Exception: 714 raise Impossible() 715 716 def can_assign(self): 717 return False 718 719 720class Getattr(Expr): 721 """Get an attribute or item from an expression that is a ascii-only 722 bytestring and prefer the attribute. 723 """ 724 fields = ('node', 'attr', 'ctx') 725 726 def as_const(self, eval_ctx=None): 727 if self.ctx != 'load': 728 raise Impossible() 729 try: 730 eval_ctx = get_eval_context(self, eval_ctx) 731 return self.environment.getattr(self.node.as_const(eval_ctx), 732 self.attr) 733 except Exception: 734 raise Impossible() 735 736 def can_assign(self): 737 return False 738 739 740class Slice(Expr): 741 """Represents a slice object. This must only be used as argument for 742 :class:`Subscript`. 743 """ 744 fields = ('start', 'stop', 'step') 745 746 def as_const(self, eval_ctx=None): 747 eval_ctx = get_eval_context(self, eval_ctx) 748 def const(obj): 749 if obj is None: 750 return None 751 return obj.as_const(eval_ctx) 752 return slice(const(self.start), const(self.stop), const(self.step)) 753 754 755class Concat(Expr): 756 """Concatenates the list of expressions provided after converting them to 757 unicode. 758 """ 759 fields = ('nodes',) 760 761 def as_const(self, eval_ctx=None): 762 eval_ctx = get_eval_context(self, eval_ctx) 763 return ''.join(text_type(x.as_const(eval_ctx)) for x in self.nodes) 764 765 766class Compare(Expr): 767 """Compares an expression with some other expressions. `ops` must be a 768 list of :class:`Operand`\\s. 769 """ 770 fields = ('expr', 'ops') 771 772 def as_const(self, eval_ctx=None): 773 eval_ctx = get_eval_context(self, eval_ctx) 774 result = value = self.expr.as_const(eval_ctx) 775 try: 776 for op in self.ops: 777 new_value = op.expr.as_const(eval_ctx) 778 result = _cmpop_to_func[op.op](value, new_value) 779 value = new_value 780 except Exception: 781 raise Impossible() 782 return result 783 784 785class Operand(Helper): 786 """Holds an operator and an expression.""" 787 fields = ('op', 'expr') 788 789if __debug__: 790 Operand.__doc__ += '\nThe following operators are available: ' + \ 791 ', '.join(sorted('``%s``' % x for x in set(_binop_to_func) | 792 set(_uaop_to_func) | set(_cmpop_to_func))) 793 794 795class Mul(BinExpr): 796 """Multiplies the left with the right node.""" 797 operator = '*' 798 799 800class Div(BinExpr): 801 """Divides the left by the right node.""" 802 operator = '/' 803 804 805class FloorDiv(BinExpr): 806 """Divides the left by the right node and truncates conver the 807 result into an integer by truncating. 808 """ 809 operator = '//' 810 811 812class Add(BinExpr): 813 """Add the left to the right node.""" 814 operator = '+' 815 816 817class Sub(BinExpr): 818 """Subtract the right from the left node.""" 819 operator = '-' 820 821 822class Mod(BinExpr): 823 """Left modulo right.""" 824 operator = '%' 825 826 827class Pow(BinExpr): 828 """Left to the power of right.""" 829 operator = '**' 830 831 832class And(BinExpr): 833 """Short circuited AND.""" 834 operator = 'and' 835 836 def as_const(self, eval_ctx=None): 837 eval_ctx = get_eval_context(self, eval_ctx) 838 return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx) 839 840 841class Or(BinExpr): 842 """Short circuited OR.""" 843 operator = 'or' 844 845 def as_const(self, eval_ctx=None): 846 eval_ctx = get_eval_context(self, eval_ctx) 847 return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx) 848 849 850class Not(UnaryExpr): 851 """Negate the expression.""" 852 operator = 'not' 853 854 855class Neg(UnaryExpr): 856 """Make the expression negative.""" 857 operator = '-' 858 859 860class Pos(UnaryExpr): 861 """Make the expression positive (noop for most expressions)""" 862 operator = '+' 863 864 865# Helpers for extensions 866 867 868class EnvironmentAttribute(Expr): 869 """Loads an attribute from the environment object. This is useful for 870 extensions that want to call a callback stored on the environment. 871 """ 872 fields = ('name',) 873 874 875class ExtensionAttribute(Expr): 876 """Returns the attribute of an extension bound to the environment. 877 The identifier is the identifier of the :class:`Extension`. 878 879 This node is usually constructed by calling the 880 :meth:`~jinja2.ext.Extension.attr` method on an extension. 881 """ 882 fields = ('identifier', 'name') 883 884 885class ImportedName(Expr): 886 """If created with an import name the import name is returned on node 887 access. For example ``ImportedName('cgi.escape')`` returns the `escape` 888 function from the cgi module on evaluation. Imports are optimized by the 889 compiler so there is no need to assign them to local variables. 890 """ 891 fields = ('importname',) 892 893 894class InternalName(Expr): 895 """An internal name in the compiler. You cannot create these nodes 896 yourself but the parser provides a 897 :meth:`~jinja2.parser.Parser.free_identifier` method that creates 898 a new identifier for you. This identifier is not available from the 899 template and is not threated specially by the compiler. 900 """ 901 fields = ('name',) 902 903 def __init__(self): 904 raise TypeError('Can\'t create internal names. Use the ' 905 '`free_identifier` method on a parser.') 906 907 908class MarkSafe(Expr): 909 """Mark the wrapped expression as safe (wrap it as `Markup`).""" 910 fields = ('expr',) 911 912 def as_const(self, eval_ctx=None): 913 eval_ctx = get_eval_context(self, eval_ctx) 914 return Markup(self.expr.as_const(eval_ctx)) 915 916 917class MarkSafeIfAutoescape(Expr): 918 """Mark the wrapped expression as safe (wrap it as `Markup`) but 919 only if autoescaping is active. 920 921 .. versionadded:: 2.5 922 """ 923 fields = ('expr',) 924 925 def as_const(self, eval_ctx=None): 926 eval_ctx = get_eval_context(self, eval_ctx) 927 if eval_ctx.volatile: 928 raise Impossible() 929 expr = self.expr.as_const(eval_ctx) 930 if eval_ctx.autoescape: 931 return Markup(expr) 932 return expr 933 934 935class ContextReference(Expr): 936 """Returns the current template context. It can be used like a 937 :class:`Name` node, with a ``'load'`` ctx and will return the 938 current :class:`~jinja2.runtime.Context` object. 939 940 Here an example that assigns the current template name to a 941 variable named `foo`:: 942 943 Assign(Name('foo', ctx='store'), 944 Getattr(ContextReference(), 'name')) 945 """ 946 947 948class Continue(Stmt): 949 """Continue a loop.""" 950 951 952class Break(Stmt): 953 """Break a loop.""" 954 955 956class Scope(Stmt): 957 """An artificial scope.""" 958 fields = ('body',) 959 960 961class OverlayScope(Stmt): 962 """An overlay scope for extensions. This is a largely unoptimized scope 963 that however can be used to introduce completely arbitrary variables into 964 a sub scope from a dictionary or dictionary like object. The `context` 965 field has to evaluate to a dictionary object. 966 967 Example usage:: 968 969 OverlayScope(context=self.call_method('get_context'), 970 body=[...]) 971 972 .. versionadded:: 2.10 973 """ 974 fields = ('context', 'body') 975 976 977class EvalContextModifier(Stmt): 978 """Modifies the eval context. For each option that should be modified, 979 a :class:`Keyword` has to be added to the :attr:`options` list. 980 981 Example to change the `autoescape` setting:: 982 983 EvalContextModifier(options=[Keyword('autoescape', Const(True))]) 984 """ 985 fields = ('options',) 986 987 988class ScopedEvalContextModifier(EvalContextModifier): 989 """Modifies the eval context and reverts it later. Works exactly like 990 :class:`EvalContextModifier` but will only modify the 991 :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`. 992 """ 993 fields = ('body',) 994 995 996# make sure nobody creates custom nodes 997def _failing_new(*args, **kwargs): 998 raise TypeError('can\'t create custom node types') 999NodeType.__new__ = staticmethod(_failing_new); del _failing_new 1000