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