"""AST nodes generated by the parser for the compiler. Also provides
some node tree helper functions used by the parser and compiler in order
to normalize nodes. """ import inspect import operator import typing as t from collections import deque
from markupsafe import Markup
from .utils import _PassArg
if t.TYPE_CHECKING: import typing_extensions as te from .environment import Environment
_cmpop_to_func: t.Dict[str, t.Callable[[t.Any, t.Any], t.Any]] = { "eq": operator.eq, "ne": operator.ne, "gt": operator.gt, "gteq": operator.ge, "lt": operator.lt, "lteq": operator.le, "in": lambda a, b: a in b, "notin": lambda a, b: a notin b,
}
class Impossible(Exception): """Raised if the node could not perform a requested action."""
class NodeType(type): """A metaclass for nodes that handles the field and attribute
inheritance. fields and attributes from the parent class are
automatically forwarded to the child."""
def get_eval_context(node: "Node", ctx: t.Optional[EvalContext]) -> EvalContext: if ctx isNone: if node.environment isNone: raise RuntimeError( "if no eval context is passed, the node must have an" " attached environment."
) return EvalContext(node.environment) return ctx
class Node(metaclass=NodeType): """Baseclass for all Jinja nodes. There are a number of nodes available
of different types. There are four major types:
All nodes have fields and attributes. Fields may be other nodes, lists, or arbitrary values. Fields are passed to the constructor as regular
positional arguments, attributes as keyword arguments. Each node has
two attributes: `lineno` (the line number of the node) and `environment`.
The `environment` attribute is set at the end of the parsing process for
all nodes automatically. """
lineno: int
environment: t.Optional["Environment"]
def __init__(self, *fields: t.Any, **attributes: t.Any) -> None: if self.abstract: raise TypeError("abstract nodes are not instantiable") if fields: if len(fields) != len(self.fields): ifnot self.fields: raise TypeError(f"{type(self).__name__!r} takes 0 arguments") raise TypeError(
f"{type(self).__name__!r} takes 0 or {len(self.fields)}"
f" argument{'s' if len(self.fields) != 1 else ''}"
) for name, arg in zip(self.fields, fields):
setattr(self, name, arg) for attr in self.attributes:
setattr(self, attr, attributes.pop(attr, None)) if attributes: raise TypeError(f"unknown attribute {next(iter(attributes))!r}")
def iter_fields(
self,
exclude: t.Optional[t.Container[str]] = None,
only: t.Optional[t.Container[str]] = None,
) -> t.Iterator[t.Tuple[str, t.Any]]: """This method iterates over all fields that are defined and yields
``(key, value)`` tuples. Per default all fields are returned, but
it's possible to limit that to some fields by providing the `only`
parameter or to exclude some using the `exclude` parameter. Both
should be sets or tuples of field names. """ for name in self.fields: if (
(exclude isNoneand only isNone) or (exclude isnotNoneand name notin exclude) or (only isnotNoneand name in only)
): try: yield name, getattr(self, name) except AttributeError: pass
def iter_child_nodes(
self,
exclude: t.Optional[t.Container[str]] = None,
only: t.Optional[t.Container[str]] = None,
) -> t.Iterator["Node"]: """Iterates over all direct child nodes of the node. This iterates
over all fields and yields the values of they are nodes. If the value
of a field is a list all the nodes in that list are returned. """ for _, item in self.iter_fields(exclude, only): if isinstance(item, list): for n in item: if isinstance(n, Node): yield n elif isinstance(item, Node): yield item
def find(self, node_type: t.Type[_NodeBound]) -> t.Optional[_NodeBound]: """Find the first node of a given type. If no such node exists the return value is `None`. """ for result in self.find_all(node_type): return result
returnNone
def find_all(
self, node_type: t.Union[t.Type[_NodeBound], t.Tuple[t.Type[_NodeBound], ...]]
) -> t.Iterator[_NodeBound]: """Find all the nodes of a given type. If the type is a tuple,
the check is performed for any of the tuple items. """ for child in self.iter_child_nodes(): if isinstance(child, node_type): yield child # type: ignore yieldfrom child.find_all(node_type)
def set_ctx(self, ctx: str) -> "Node": """Reset the context of a node and all child nodes. Per default the
parser will all generate nodes that have a 'load' context as it's the
most common one. This method is used in the parser to set assignment
targets and other nodes to a store context. """
todo = deque([self]) while todo:
node = todo.popleft() if"ctx"in node.fields:
node.ctx = ctx # type: ignore
todo.extend(node.iter_child_nodes()) return self
def set_lineno(self, lineno: int, override: bool = False) -> "Node": """Set the line numbers of the node and children."""
todo = deque([self]) while todo:
node = todo.popleft() if"lineno"in node.attributes: if node.lineno isNoneor override:
node.lineno = lineno
todo.extend(node.iter_child_nodes()) return self
def set_environment(self, environment: "Environment") -> "Node": """Set the environment for all nodes."""
todo = deque([self]) while todo:
node = todo.popleft()
node.environment = environment
todo.extend(node.iter_child_nodes()) return self
buf.append(f"nodes.{type(node).__name__}(") ifnot node.fields:
buf.append(")") return for idx, field in enumerate(node.fields): if idx:
buf.append(", ")
value = getattr(node, field) if isinstance(value, list):
buf.append("[") for idx, item in enumerate(value): if idx:
buf.append(", ")
_dump(item)
buf.append("]") else:
_dump(value)
buf.append(")")
class Stmt(Node): """Base node for all statements."""
abstract = True
class Helper(Node): """Nodes that exist in a specific context only."""
abstract = True
class Template(Node): """Node that represents a template. This must be the outermost node that is passed to the compiler. """
fields = ("body",)
body: t.List[Node]
class Output(Stmt): """A node that holds multiple expressions which are then printed out.
This is used both for the `print` statement and the regular template data. """
fields = ("nodes",)
nodes: t.List["Expr"]
class Extends(Stmt): """Represents an extends statement."""
fields = ("template",)
template: "Expr"
classFor(Stmt): """The for loop. `target` is the target for the iteration (usually a
:class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list
of nodes that are used as loop-body, and `else_` a list of nodes for the
`else` block. If no else node exists it has to be an empty list.
For filtered nodes an expression can be stored as `test`, otherwise `None`. """
class Macro(Stmt): """A macro definition. `name` is the name of the macro, `args` a list of
arguments and `defaults` a list of defaults if there are any. `body` is
a list of nodes for the macro body. """
class CallBlock(Stmt): """Like a macro without a name but a call instead. `call` is called with
the unnamed macro as `caller` argument this node holds. """
classWith(Stmt): """Specific node for with statements. In older versions of Jinja the with statement was implemented on the base of the `Scope` node instead.
class FromImport(Stmt): """A node that represents the from import tag. It's important to not pass unsafe names to the name attribute. The compiler translates the
attribute lookups directly into getattr calls and does *not* use the
subscript callback of the interface. As exported variables may not
start with double underscores (which the parser asserts) this isnot a
problem for regular Jinja code, but if this node is used in an extension
extra care must be taken.
The list of names may contain tuples if aliases are wanted. """
class Expr(Node): """Baseclass for all expressions."""
abstract = True
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any: """Return the value of the expression as constant or raise
:exc:`Impossible` if this was not possible.
An :class:`EvalContext` can be provided, ifnoneis given
a default context is created which requires the nodes to have
an attached environment.
.. versionchanged:: 2.4
the `eval_ctx` parameter was added. """ raise Impossible()
def can_assign(self) -> bool: """Check if it's possible to assign something to this node.""" returnFalse
class BinExpr(Expr): """Baseclass for all binary expressions."""
# intercepted operators cannot be folded at compile time if (
eval_ctx.environment.sandboxed and self.operator in eval_ctx.environment.intercepted_binops # type: ignore
): raise Impossible()
f = _binop_to_func[self.operator] try: return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx)) except Exception as e: raise Impossible() from e
class UnaryExpr(Expr): """Baseclass for all unary expressions."""
# intercepted operators cannot be folded at compile time if (
eval_ctx.environment.sandboxed and self.operator in eval_ctx.environment.intercepted_unops # type: ignore
): raise Impossible()
f = _uaop_to_func[self.operator] try: return f(self.node.as_const(eval_ctx)) except Exception as e: raise Impossible() from e
class Name(Expr): """Looks up a name or stores a value in a name.
The `ctx` of the node can be one of the following values:
- `store`: store a value in the name
- `load`: load that name
- `param`: like `store` but if the name was defined as function parameter. """
class NSRef(Expr): """Reference to a namespace value assignment"""
fields = ("name", "attr")
name: str
attr: str
def can_assign(self) -> bool: # We don't need any special checks here; NSRef assignments have a # runtime check to ensure the target is a namespace object which will # have been checked already as it is created using a normal assignment # which goes through a `Name` node. returnTrue
class Literal(Expr): """Baseclass for literals."""
abstract = True
class Const(Literal): """All constant values. The parser will return this node for simple
constants such as ``42`` or ``"foo"`` but it can be used to store more
complex values such as lists too. Only constants with a safe
representation (objects where ``eval(repr(x)) == x`` istrue). """
@classmethod def from_untrusted(
cls,
value: t.Any,
lineno: t.Optional[int] = None,
environment: "t.Optional[Environment]" = None,
) -> "Const": """Return a const object if the value is representable as
constant value in the generated code, otherwise it will raise
an `Impossible` exception. """ from .compiler import has_safe_repr
class Tuple(Literal): """For loop unpacking and some other things like multiple arguments for subscripts. Like for :class:`Name` `ctx` specifies if the tuple is used for loading the names or storing. """
# if we evaluate to an undefined object, we better do that at runtime if self.expr2 isNone: raise Impossible()
return self.expr2.as_const(eval_ctx)
def args_as_const(
node: t.Union["_FilterTestCommon", "Call"], eval_ctx: t.Optional[EvalContext]
) -> t.Tuple[t.List[t.Any], t.Dict[t.Any, t.Any]]:
args = [x.as_const(eval_ctx) for x in node.args]
kwargs = dict(x.as_const(eval_ctx) for x in node.kwargs)
if node.dyn_args isnotNone: try:
args.extend(node.dyn_args.as_const(eval_ctx)) except Exception as e: raise Impossible() from e
if node.dyn_kwargs isnotNone: try:
kwargs.update(node.dyn_kwargs.as_const(eval_ctx)) except Exception as e: raise Impossible() from e
if pass_arg is _PassArg.eval_context:
args.insert(0, eval_ctx) elif pass_arg is _PassArg.environment:
args.insert(0, eval_ctx.environment)
try: return func(*args, **kwargs) except Exception as e: raise Impossible() from e
class Filter(_FilterTestCommon): """Apply a filter to an expression. ``name`` is the name of the
filter, the other fields are the same as :class:`Call`.
If ``node`` is ``None``, the filter is being used in a filter block andis applied to the content of the block. """
class Test(_FilterTestCommon): """Apply a test to an expression. ``name`` is the name of the test,
the other field are the same as :class:`Call`.
.. versionchanged:: 3.0
``as_const`` shares the same logic for filters and tests. Tests
check for volatile, async, and ``@pass_context`` etc.
decorators. """
_is_filter = False
class Call(Expr): """Calls an expression. `args` is a list of arguments, `kwargs` a list
of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args` and `dyn_kwargs` has to be either `None` or a node that is used as
node for dynamic positional (``*args``) or keyword (``**kwargs``)
arguments. """
class Neg(UnaryExpr): """Make the expression negative."""
operator = "-"
class Pos(UnaryExpr): """Make the expression positive (noop for most expressions)"""
operator = "+"
# Helpers for extensions
class EnvironmentAttribute(Expr): """Loads an attribute from the environment object. This is useful for
extensions that want to call a callback stored on the environment. """
fields = ("name",)
name: str
class ExtensionAttribute(Expr): """Returns the attribute of an extension bound to the environment.
The identifier is the identifier of the :class:`Extension`.
This node is usually constructed by calling the
:meth:`~jinja2.ext.Extension.attr` method on an extension. """
class ImportedName(Expr): """If created with an import name the import name is returned on node
access. For example ``ImportedName('cgi.escape')`` returns the `escape`
function from the cgi module on evaluation. Imports are optimized by the
compiler so there is no need to assign them to local variables. """
fields = ("importname",)
importname: str
class InternalName(Expr): """An internal name in the compiler. You cannot create these nodes
yourself but the parser provides a
:meth:`~jinja2.parser.Parser.free_identifier` method that creates
a new identifier for you. This identifier isnot available from the
template andisnot treated specially by the compiler. """
fields = ("name",)
name: str
def __init__(self) -> None: raise TypeError( "Can't create internal names. Use the " "`free_identifier` method on a parser."
)
class MarkSafe(Expr): """Mark the wrapped expression as safe (wrap it as `Markup`)."""
class ContextReference(Expr): """Returns the current template context. It can be used like a
:class:`Name` node, with a ``'load'`` ctx and will return the
current :class:`~jinja2.runtime.Context` object.
Here an example that assigns the current template name to a
variable named `foo`::
This is basically equivalent to using the
:func:`~jinja2.pass_context` decorator when using the high-level
API, which causes a reference to the context to be passed as the
first argument to a function. """
class DerivedContextReference(Expr): """Return the current template context including locals. Behaves
exactly like :class:`ContextReference`, but includes local
variables, such asfrom a ``for`` loop.
.. versionadded:: 2.11 """
classContinue(Stmt): """Continue a loop."""
classBreak(Stmt): """Break a loop."""
class Scope(Stmt): """An artificial scope."""
fields = ("body",)
body: t.List[Node]
class OverlayScope(Stmt): """An overlay scope for extensions. This is a largely unoptimized scope
that however can be used to introduce completely arbitrary variables into
a sub scope from a dictionary or dictionary like object. The `context`
field has to evaluate to a dictionary object.
class EvalContextModifier(Stmt): """Modifies the eval context. For each option that should be modified,
a :class:`Keyword` has to be added to the :attr:`options` list.
class ScopedEvalContextModifier(EvalContextModifier): """Modifies the eval context and reverts it later. Works exactly like
:class:`EvalContextModifier` but will only modify the
:class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`. """
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.