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