1 # -*- coding: utf-8 -*-
6 This module implements additional nodes derived from the ast base node.
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.
12 :copyright: 2008 by Armin Ronacher.
13 :license: BSD, see LICENSE for more details.
17 from types import FunctionType
18 from itertools import chain, izip
19 from collections import deque
20 from jinja2.utils import Markup
25 '/': operator.truediv,
26 '//': operator.floordiv,
46 'in': lambda a, b: a in b,
47 'notin': lambda a, b: a not in b
51 class Impossible(Exception):
52 """Raised if the node could not perform a requested action."""
56 """A metaclass for nodes that handles the field and attribute
57 inheritance. fields and attributes from the parent class are
58 automatically forwarded to the child."""
60 def __new__(cls, name, bases, d):
61 for attr in 'fields', 'attributes':
63 storage.extend(getattr(bases[0], attr, ()))
64 storage.extend(d.get(attr, ()))
65 assert len(bases) == 1, 'multiple inheritance not allowed'
66 assert len(storage) == len(set(storage)), 'layout conflict'
67 d[attr] = tuple(storage)
68 d.setdefault('abstract', False)
69 return type.__new__(cls, name, bases, d)
73 """Baseclass for all Jinja2 nodes. There are a number of nodes available
74 of different types. There are three major types:
76 - :class:`Stmt`: statements
77 - :class:`Expr`: expressions
78 - :class:`Helper`: helper nodes
79 - :class:`Template`: the outermost wrapper node
81 All nodes have fields and attributes. Fields may be other nodes, lists,
82 or arbitrary values. Fields are passed to the constructor as regular
83 positional arguments, attributes as keyword arguments. Each node has
84 two attributes: `lineno` (the line number of the node) and `environment`.
85 The `environment` attribute is set at the end of the parsing process for
86 all nodes automatically.
88 __metaclass__ = NodeType
90 attributes = ('lineno', 'environment')
93 def __init__(self, *fields, **attributes):
95 raise TypeError('abstract nodes are not instanciable')
97 if len(fields) != len(self.fields):
99 raise TypeError('%r takes 0 arguments' %
100 self.__class__.__name__)
101 raise TypeError('%r takes 0 or %d argument%s' % (
102 self.__class__.__name__,
104 len(self.fields) != 1 and 's' or ''
106 for name, arg in izip(self.fields, fields):
107 setattr(self, name, arg)
108 for attr in self.attributes:
109 setattr(self, attr, attributes.pop(attr, None))
111 raise TypeError('unknown attribute %r' %
112 iter(attributes).next())
114 def iter_fields(self, exclude=None, only=None):
115 """This method iterates over all fields that are defined and yields
116 ``(key, value)`` tuples. Per default all fields are returned, but
117 it's possible to limit that to some fields by providing the `only`
118 parameter or to exclude some using the `exclude` parameter. Both
119 should be sets or tuples of field names.
121 for name in self.fields:
122 if (exclude is only is None) or \
123 (exclude is not None and name not in exclude) or \
124 (only is not None and name in only):
126 yield name, getattr(self, name)
127 except AttributeError:
130 def iter_child_nodes(self, exclude=None, only=None):
131 """Iterates over all direct child nodes of the node. This iterates
132 over all fields and yields the values of they are nodes. If the value
133 of a field is a list all the nodes in that list are returned.
135 for field, item in self.iter_fields(exclude, only):
136 if isinstance(item, list):
138 if isinstance(n, Node):
140 elif isinstance(item, Node):
143 def find(self, node_type):
144 """Find the first node of a given type. If no such node exists the
145 return value is `None`.
147 for result in self.find_all(node_type):
150 def find_all(self, node_type):
151 """Find all the nodes of a given type."""
152 for child in self.iter_child_nodes():
153 if isinstance(child, node_type):
155 for result in child.find_all(node_type):
159 """Return a deep copy of the node."""
160 result = object.__new__(self.__class__)
161 for field, value in self.iter_fields():
162 if isinstance(value, Node):
163 new_value = value.copy()
164 elif isinstance(value, list):
167 if isinstance(item, Node):
171 new_value.append(item)
173 new_value = copy(value)
174 setattr(result, field, new_value)
175 for attr in self.attributes:
177 setattr(result, attr, getattr(self, attr))
178 except AttributeError:
182 def set_ctx(self, ctx):
183 """Reset the context of a node and all child nodes. Per default the
184 parser will all generate nodes that have a 'load' context as it's the
185 most common one. This method is used in the parser to set assignment
186 targets and other nodes to a store context.
190 node = todo.popleft()
191 if 'ctx' in node.fields:
193 todo.extend(node.iter_child_nodes())
196 def set_lineno(self, lineno, override=False):
197 """Set the line numbers of the node and children."""
200 node = todo.popleft()
201 if 'lineno' in node.attributes:
202 if node.lineno is None or override:
204 todo.extend(node.iter_child_nodes())
207 def set_environment(self, environment):
208 """Set the environment for all nodes."""
211 node = todo.popleft()
212 node.environment = environment
213 todo.extend(node.iter_child_nodes())
216 def __eq__(self, other):
217 return type(self) is type(other) and \
218 tuple(self.iter_fields()) == tuple(other.iter_fields())
220 def __ne__(self, other):
221 return not self.__eq__(other)
225 self.__class__.__name__,
226 ', '.join('%s=%r' % (arg, getattr(self, arg, None)) for
232 """Base node for all statements."""
237 """Nodes that exist in a specific context only."""
241 class Template(Node):
242 """Node that represents a template. This must be the outermost node that
243 is passed to the compiler.
249 """A node that holds multiple expressions which are then printed out.
250 This is used both for the `print` statement and the regular template data.
256 """Represents an extends statement."""
257 fields = ('template',)
261 """The for loop. `target` is the target for the iteration (usually a
262 :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list
263 of nodes that are used as loop-body, and `else_` a list of nodes for the
264 `else` block. If no else node exists it has to be an empty list.
266 For filtered nodes an expression can be stored as `test`, otherwise `None`.
268 fields = ('target', 'iter', 'body', 'else_', 'test', 'recursive')
272 """If `test` is true, `body` is rendered, else `else_`."""
273 fields = ('test', 'body', 'else_')
277 """A macro definition. `name` is the name of the macro, `args` a list of
278 arguments and `defaults` a list of defaults if there are any. `body` is
279 a list of nodes for the macro body.
281 fields = ('name', 'args', 'defaults', 'body')
284 class CallBlock(Stmt):
285 """Like a macro without a name but a call instead. `call` is called with
286 the unnamed macro as `caller` argument this node holds.
288 fields = ('call', 'args', 'defaults', 'body')
292 """Allows defining own variables."""
293 fields = ('name', 'expr')
296 class FilterBlock(Stmt):
297 """Node for filter sections."""
298 fields = ('body', 'filter')
302 """A node that represents a block."""
303 fields = ('name', 'body')
307 """A node that represents the include tag."""
308 fields = ('template', 'with_context')
312 """A node that represents the import tag."""
313 fields = ('template', 'target', 'with_context')
316 class FromImport(Stmt):
317 """A node that represents the from import tag. It's important to not
318 pass unsafe names to the name attribute. The compiler translates the
319 attribute lookups directly into getattr calls and does *not* use the
320 subscribe callback of the interface. As exported variables may not
321 start with double underscores (which the parser asserts) this is not a
322 problem for regular Jinja code, but if this node is used in an extension
323 extra care must be taken.
325 The list of names may contain tuples if aliases are wanted.
327 fields = ('template', 'names', 'with_context')
330 class ExprStmt(Stmt):
331 """A statement that evaluates an expression and discards the result."""
336 """Assigns an expression to a target."""
337 fields = ('target', 'node')
341 """Baseclass for all expressions."""
345 """Return the value of the expression as constant or raise
346 :exc:`Impossible` if this was not possible:
348 >>> Add(Const(23), Const(42)).as_const()
350 >>> Add(Const(23), Name('var', 'load')).as_const()
351 Traceback (most recent call last):
355 This requires the `environment` attribute of all nodes to be
356 set to the environment that created the nodes.
360 def can_assign(self):
361 """Check if it's possible to assign something to this node."""
366 """Baseclass for all binary expressions."""
367 fields = ('left', 'right')
372 f = _binop_to_func[self.operator]
374 return f(self.left.as_const(), self.right.as_const())
379 class UnaryExpr(Expr):
380 """Baseclass for all unary expressions."""
386 f = _uaop_to_func[self.operator]
388 return f(self.node.as_const())
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:
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.
401 fields = ('name', 'ctx')
403 def can_assign(self):
404 return self.name not in ('true', 'false', 'none')
408 """Baseclass for literals."""
412 class Const(Literal):
413 """All constant values. The parser will return this node for simple
414 constants such as ``42`` or ``"foo"`` but it can be used to store more
415 complex values such as lists too. Only constants with a safe
416 representation (objects where ``eval(repr(x)) == x`` is true).
424 def from_untrusted(cls, value, lineno=None, environment=None):
425 """Return a const object if the value is representable as
426 constant value in the generated code, otherwise it will raise
427 an `Impossible` exception.
429 from compiler import has_safe_repr
430 if not has_safe_repr(value):
432 return cls(value, lineno=lineno, environment=environment)
435 class Tuple(Literal):
436 """For loop unpacking and some other things like multiple arguments
437 for subscripts. Like for :class:`Name` `ctx` specifies if the tuple
438 is used for loading the names or storing.
440 fields = ('items', 'ctx')
443 return tuple(x.as_const() for x in self.items)
445 def can_assign(self):
446 for item in self.items:
447 if not item.can_assign():
453 """Any list literal such as ``[1, 2, 3]``"""
457 return [x.as_const() for x in self.items]
461 """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
467 return dict(x.as_const() for x in self.items)
471 """A key, value pair for dicts."""
472 fields = ('key', 'value')
475 return self.key.as_const(), self.value.as_const()
478 class Keyword(Helper):
479 """A key, value pair for keyword arguments where key is a string."""
480 fields = ('key', 'value')
483 class CondExpr(Expr):
484 """A conditional expression (inline if expression). (``{{
485 foo if bar else baz }}``)
487 fields = ('test', 'expr1', 'expr2')
490 if self.test.as_const():
491 return self.expr1.as_const()
492 return self.expr2.as_const()
496 """This node applies a filter on an expression. `name` is the name of
497 the filter, the rest of the fields are the same as for :class:`Call`.
499 If the `node` of a filter is `None` the contents of the last buffer are
500 filtered. Buffers are created by macros and filter blocks.
502 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
504 def as_const(self, obj=None):
505 if self.node is obj is None:
507 filter = self.environment.filters.get(self.name)
508 if filter is None or getattr(filter, 'contextfilter', False):
511 obj = self.node.as_const()
512 args = [x.as_const() for x in self.args]
513 if getattr(filter, 'environmentfilter', False):
514 args.insert(0, self.environment)
515 kwargs = dict(x.as_const() for x in self.kwargs)
516 if self.dyn_args is not None:
518 args.extend(self.dyn_args.as_const())
521 if self.dyn_kwargs is not None:
523 kwargs.update(self.dyn_kwargs.as_const())
527 return filter(obj, *args, **kwargs)
533 """Applies a test on an expression. `name` is the name of the test, the
534 rest of the fields are the same as for :class:`Call`.
536 fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
540 """Calls an expression. `args` is a list of arguments, `kwargs` a list
541 of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`
542 and `dyn_kwargs` has to be either `None` or a node that is used as
543 node for dynamic positional (``*args``) or keyword (``**kwargs``)
546 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')
549 obj = self.node.as_const()
551 # don't evaluate context functions
552 args = [x.as_const() for x in self.args]
553 if type(obj) is FunctionType:
554 if getattr(obj, 'contextfunction', False):
556 elif obj.environmentfunction:
557 args.insert(0, self.environment)
559 kwargs = dict(x.as_const() for x in self.kwargs)
560 if self.dyn_args is not None:
562 args.extend(self.dyn_args.as_const())
565 if self.dyn_kwargs is not None:
567 kwargs.update(self.dyn_kwargs.as_const())
571 return obj(*args, **kwargs)
576 class Subscript(Expr):
577 """Subscribe an expression by an argument. This node performs a dict
578 and an attribute lookup on the object whatever succeeds.
580 fields = ('node', 'arg', 'ctx')
583 if self.ctx != 'load':
586 return self.environment.subscribe(self.node.as_const(),
591 def can_assign(self):
596 """Represents a slice object. This must only be used as argument for
599 fields = ('start', 'stop', 'step')
605 return obj.as_const()
606 return slice(const(self.start), const(self.stop), const(self.step))
610 """Concatenates the list of expressions provided after converting them to
616 return ''.join(unicode(x.as_const()) for x in self.nodes)
620 """Compares an expression with some other expressions. `ops` must be a
621 list of :class:`Operand`\s.
623 fields = ('expr', 'ops')
626 result = value = self.expr.as_const()
629 new_value = op.expr.as_const()
630 result = _cmpop_to_func[op.op](value, new_value)
637 class Operand(Helper):
638 """Holds an operator and an expression."""
639 fields = ('op', 'expr')
642 Operand.__doc__ += '\nThe following operators are available: ' + \
643 ', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |
644 set(_uaop_to_func) | set(_cmpop_to_func)))
648 """Multiplies the left with the right node."""
653 """Divides the left by the right node."""
657 class FloorDiv(BinExpr):
658 """Divides the left by the right node and truncates conver the
659 result into an integer by truncating.
665 """Add the left to the right node."""
670 """Substract the right from the left node."""
675 """Left modulo right."""
680 """Left to the power of right."""
685 """Short circuited AND."""
689 return self.left.as_const() and self.right.as_const()
693 """Short circuited OR."""
697 return self.left.as_const() or self.right.as_const()
700 class Not(UnaryExpr):
701 """Negate the expression."""
705 class Neg(UnaryExpr):
706 """Make the expression negative."""
710 class Pos(UnaryExpr):
711 """Make the expression positive (noop for most expressions)"""
715 # Helpers for extensions
718 class EnvironmentAttribute(Expr):
719 """Loads an attribute from the environment object. This is useful for
720 extensions that want to call a callback stored on the environment.
725 class ExtensionAttribute(Expr):
726 """Returns the attribute of an extension bound to the environment.
727 The identifier is the identifier of the :class:`Extension`.
729 This node is usually constructed by calling the
730 :meth:`~jinja2.ext.Extension.attr` method on an extension.
732 fields = ('identifier', 'name')
735 class ImportedName(Expr):
736 """If created with an import name the import name is returned on node
737 access. For example ``ImportedName('cgi.escape')`` returns the `escape`
738 function from the cgi module on evaluation. Imports are optimized by the
739 compiler so there is no need to assign them to local variables.
741 fields = ('importname',)
744 class InternalName(Expr):
745 """An internal name in the compiler. You cannot create these nodes
746 yourself but the parser provides a
747 :meth:`~jinja2.parser.Parser.free_identifier` method that creates
748 a new identifier for you. This identifier is not available from the
749 template and is not threated specially by the compiler.
754 raise TypeError('Can\'t create internal names. Use the '
755 '`free_identifier` method on a parser.')
758 class MarkSafe(Expr):
759 """Mark the wrapped expression as safe (wrap it as `Markup`)."""
763 return Markup(self.expr.as_const())
766 class ContextReference(Expr):
767 """Returns the current template context."""
770 class Continue(Stmt):
771 """Continue a loop."""
778 # make sure nobody creates custom nodes
779 def _failing_new(*args, **kwargs):
780 raise TypeError('can\'t create custom node types')
781 NodeType.__new__ = staticmethod(_failing_new); del _failing_new