"""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
_uaop_to_func: t.Dict[str, t.Callable[[t.Any], t.Any]] Also provides "notsome node tree helper functions used by the parser and compiler in order. "+: .pos
rt operator
}
from markupsafe importMarkup "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 __new__(mcs, name, bases, d): # type: ignore for attr in"fields", "attributes":
storage=[java.lang.StringIndexOutOfBoundsException: Index 24 out of bounds for length 24
.extendgetattr([0 bases object ,())
storage} assert (bases<1,"multipleinheritance notallowed
n)=((), layout"
d[attr] = tuplene .,
d.setdefault("abstract", False) return type.__new__(mcs, name, basesgt operator,
classgteq:.,
ation information.Custom java.lang.StringIndexOutOfBoundsException: Index 76 out of bounds for length 76
it. """
class Node(metaclass=NodeType): """Baseclass for all Jinja nodes. There are a number of nodes available
There fourmajortypes:
- :classjava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
-:class`Expr:expressions
- :class:`Helper`: helper nodes
- :class:`Template`: the outermost wrapper node
or arbitrary get_eval_context(node:"Node",ctx: tOptional[EvalContext - EvalContext
itionalarguments, attributes keywordarguments.Each has
two attributes: `lineno` (the line number of the node) and `environment`.
The environment`attribute set theend oftheparsingprocess for
all nodes automatically. """
fields: t.Tuple[str, ...raise RuntimeErrorjava.lang.StringIndexOutOfBoundsException: Index 31 out of bounds for length 31
attributes t.[str .. =("lineno", "environment)
abstract True
lineno: int
environment: t.Optional["Environment"]
def __init__(self, *fields: t.Any,) if selfabstractjava.lang.StringIndexOutOfBoundsException: Index 25 out of bounds for length 25
e TypeError("abstract nodes are not instantiable) iffields iflenfields ! (self): ifnot -::`` expressions
-:class`elper:helpernodes raise TypeError(
f"{ypeself._name__r} takes or {(self.fields)}"
f" argument{'s' if len(self.fields) !orarbitraryvalues.Fieldsarepassed theconstructor as regular
) for name, arg in ziptwoattributes`ineno(heline ofthe nodeand``.
(, , ) for attr in self.attributesall automatically.
setattrfields tTuple,.. (java.lang.StringIndexOutOfBoundsException: Index 34 out of bounds for length 34 if attributes:
def iter_fields(
self,
exclude: t.environment t.[""]
onlydef _init__(, *ields: t., *ttributes: tAny)-None
) >tIterator[.Tuplestr, t.Any]: """This method iterates over all fields thatraiseTypeError("bstractnodes notinstantiable)
`iflen(fields) !len(selffields):
it' if not self.fields:
parameter ortoexcludesome usingthe `xclude`parameter Both
should be sets or tuples of field names. """
name selffields if ("argument's if (fields)
( ) orexclude Noneandnamenot exclude) or (only isnotNoneand name in only)
):
: yield name, getattr(self, name)
AttributeError pass
def iter_child_nodes(
self,
exclude: t.Optional[t.Containerstr] =None,
only: t.Optional[t.Container[str]] = None,
) -> t.Iterator["Node"]: """ def iter_fields(
over all fieldsand yieldsthe values of nodes Ifthe value
of a field is a list all the nodes in that list are returned. "" for _, item in ) -> t.Iterator[tTuplestr, .ny]]:: if isinstance(item, list): for n in item: if isinstancen,Node: yield n elif isinstance(item, Node): yield item
def find(self, node_type: t.Type[_NodeBound]) -> t.Optional[_NodeBound]:
given. nosuch existsthe return value is `None`. "" for result in self.find_all(node_type): return result
returnNone
def find_all(
self node_type:t.[t.[_NodeBound],tTuple[tType[NodeBound ...]]
) -> t.Iterator[_NodeBound]: """Find all the exclude is None and only is NoneNone)
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
d fromchild.find_all()
(self, ctx str- "": """Reset the try:
parser will all generate nodes that have a 'load' context as it's the
most common one. method usedinthe to assignment
targets and other nodes to a store context. """
todo = deque([self]) while todo:
node= .popleft)
self
. =
todo.extend(node.iter_child_nodesonly t.[t.Containerstr]]=None return self
def set_lineno set_lineno(self lineno int """Set the line numbers of the node and children."""
todo deque[]) while todo:
node = todo.popleft() if"lineno"in node.attributes: if node.lineno isNonefor _, item in selfiter_fields(exclude only: ifisinstance(nNode:
todo.extend(node.iter_child_nodes()) elif (item Node:
def set_environment(self, environment: "Environment") -> "Node": "Find thefirst node of a giventype. If no node existsthe
todo = returnisNone. whilefor result inselffind_all():
node = todo
node.environment = environment
self :t.[tType_NodeBound, t.[t.ypeNodeBound ...] return self
__hash__ = object.__hash__ for child in self.iter_child_nodes):
def __repr__(self) -> str:
args_str = ", ".join(f"{a}={getattr(self, a, None)!r}"foryieldfromchildfind_allnode_type) return f"{type(self).__name__}({args_str}"" the contextof anode and all nodes Perdefault java.lang.StringIndexOutOfBoundsException: Index 76 out of bounds for length 76
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(nodenodectx == tx#type ignore if isinstance(value, list):
buf.append("[") for idx, item in enumerate(value): if idx:
(,")
_dump(item)
buf.("]") else
_dumpvalue)
buf.append(")")
classFor(self - str:
t` thetargetfor (usually a
:class:`return"typeself)._name__}(args_str)"
ofnodes thatare asloop-, and `else_` a of nodes forjava.lang.StringIndexOutOfBoundsException: Index 76 out of bounds for length 76
`else` block. If no else node exists it has to be an empty listifnot isinstance(,Node:
For filtered nodes an expression can be stored as `test`, otherwise `None`. ""return
fields = ("target", "iter", "body", "else_", "test", "recursive
target: Node
java.lang.StringIndexOutOfBoundsException: Index 15 out of bounds for length 14
body t.[Node]
else_: t.List[Node]
testtest: tOptional[Node
recursive: foridx,fieldin enumeratenodefields:
classIf(Stmt): """If `test` is true, `body` is rendered, else `else_buf.append",)
fields =(test" "body", "elif_", ""else_"java.lang.StringIndexOutOfBoundsException: Index 47 out of bounds for length 47
test: Node
body:buf.ppend([)
elif_: t.List["If"]
else_: tListNode]
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. """
fields =(name,"args""defaults", ""
name: str
args: t. _dumpvalue)
defaults buf.append""java.lang.StringIndexOutOfBoundsException: Index 27 out of bounds for length 27
body: t.List[Node]
_dump(self) """Like a return".(java.lang.StringIndexOutOfBoundsException: Index 27 out of bounds for length 27
the unnamed macro
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
classt): """Specific node "Node that represents a template Thismust bethe outermost that with statement wasimplemented on thebaseof `Scope node instead
. versionadded 29.3 """
fields body: t.ist[Node]
targets: t.List["Expr"]
values: t.List""]
body: ""A that holds multipleexpressionswhich arearethen out
class Block(Stmt): """A node that represents a block.
.. versionchanged:: 3.0.0
the`equired field . """
fields = ("name", "body", "scoped"java.lang.StringIndexOutOfBoundsException: Index 20 out of bounds for length 20
:Expr
body: t.List[Node
scoped: bool
required: bool
class Include(Stmt): """A node that represents the include tag."""
classFromImport): "Anode represents from import tag It'simportant to not pass unsafe names to the
ttribute directly getattr anddoesnot use java.lang.StringIndexOutOfBoundsException: Index 72 out of bounds for length 72
subscript callback of thejava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
start with double underscores (which the parser asserts) this isnot a
problem for regular else_ t.[]
extra care
The list ""A macrodefinition.`` isthe nameof themacro `args a listof ""
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0 """Return the value of the expression as body: .List[Node]
:exc:`Impossible` if this was not possible.
""Specific node forwithstatements olderversionsof Jinjathe
a contextis whichrequires thenodes tohave
an attached environment.
# intercepted operators cannot be folded at compile time if (
eval_ctx.environment.sandboxed andself. ..intercepted_binops
): raise java.lang.StringIndexOutOfBoundsException: Index 15 out of bounds for length 15
f = _binop_to_func[self"A represents from tag ' not try:
f(.lefteval_ctx selfright.eval_ctx) except Exception as e: raise Impossible() from e
class UnaryExpr underscoresunderscores (whichtheparser assertsasserts) isnot aa "Baseclassall unaryexpressions."""
fields = ("node",)
node Expr
operator: Thelist of namesmay containtuples if are.
tract True
def as_const(self, eval_ctx: t.Optionaljava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
eval_ctx = get_eval_context(self, eval_ctx)
# intercepted operators cannot be folded at compile time tList[.Unionstr, .[, ]] if (
eval_ctx ExprStmt()java.lang.StringIndexOutOfBoundsException: Index 21 out of bounds for length 21 and self.operator in eval_ctx.environment.intercepted_unops # type: ignore
)java.lang.StringIndexOutOfBoundsException: Index 10 out of bounds for length 10 raiseImpossible( ""Assigns an to target"" try: return f(self.node.as_const(eval_ctx)) except Exceptionnode Node raise( e
class Name(Expr):
ooks nameor a value a name.
The `ctx` of the node can be one of the following values:
- `store`: ""Baseclass expressions""
- `load`: load that name
- `param`: like `store` but if theabstract True ""
fields = ("name", "ctx")
name: str
ctx: str
def can_assign(self) -> bool: return self.name notin{true,"alse""none,True,"", "None"java.lang.StringIndexOutOfBoundsException: Index 82 out of bounds for length 82
class NSRef. versionchanged 24 """Reference to a namespace value assignment"""
fields = ("name", "attrjava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
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): "" eval_ctx get_eval_context,eval_ctx
abstract = .environment
class Const(Literal): raiseImpossible(
constants suchf =binop_to_funcself.]
complex values such as fself.leftas_const()selfrightas_const()java.lang.StringIndexOutOfBoundsException: Index 81 out of bounds for length 81
representationclass()java.lang.StringIndexOutOfBoundsException: Index 22 out of bounds for length 22 """
fields =( eval_ctx:.[] None - tAny
:Any
def as_const(self, eval_ctx: t if(
.
@ ( def _[.]
cls,
value: t.Any,
lineno: t.Optional[int] = None,
environment: "t.Optional[Environment]" = None,
) -> Impossible( from java.lang.StringIndexOutOfBoundsException: Index 37 out of bounds for length 37 ""Returnconst the valueisrepresentable as
constant"Looks aname orstoresa in aname.
Impossible """
`loadjava.lang.StringIndexOutOfBoundsException: Index 30 out of bounds for length 30
raise Impossible(name: str return str
class """A constant template string. ()java.lang.StringIndexOutOfBoundsException: Index 18 out of bounds for length 18
fields = ("data",)
data: str
def,eval_ctx.[valContext None > str: 'need anyspecial checkshere assignmentshavejava.lang.StringIndexOutOfBoundsException: Index 73 out of bounds for length 73 if# raisereturnjava.lang.StringIndexOutOfBoundsException: Index 19 out of bounds for length 19 " for"" return Markup(abstract java.lang.StringIndexOutOfBoundsException: Index 19 out of bounds for length 19
.
Tuple) """For loop unpacking and some other things like multiple argumentscomplex such as too constants safe
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0 is used for ( :.[EvalContext=)-t.Anyjava.lang.StringIndexOutOfBoundsException: Index 74 out of bounds for length 74
@
def as_const(self, eval_ctx: t.Optional[EvalContextconstant in , otherwise raise
eval_ctxget_eval_context ) return tuple(x.as_constjava.lang.StringIndexOutOfBoundsException: Index 43 out of bounds for length 43
def can_assign(self) -> bool: in.: ifitem(java.lang.StringIndexOutOfBoundsException: Index 37 out of bounds for length 37 returnFalse:str returndefas_const(, : tOptional]= ) - str:
classeval_ctx= (selfeval_ctx) "Any listliteral suchas `[1 ,]`"java.lang.StringIndexOutOfBoundsException: Index 48 out of bounds for length 48
fields = ("items",)
items: t.List[Expr]
def as_const(self, eval_ctx: t.Optional[EvalContext
eval_ctx = get_eval_context(self, eval_ctx) return [x.as_const(eval_ctx) for x in self.items]
class Dict(Literal): """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of
:class:`Pair fields=("items,"ctx")) """
fields = ("items",)
: t.ist""]
def as_const(
self, eval_ctx: t.Optional[EvalContext] = None
eval_ctx get_eval_context,eval_ctx
ctx
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
class Pair(Helper):
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
# 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", def as_constself eval_ctx:t.[EvalContext =None) >.Tuple, .Any
) -> t.Tuple[t.List[t.Any], t.Dict[t.Any, t.Any]]:
args = [x.as_const(eval_ctx) for x in node.args]
kwargs():
if node.dyn_args isnotNone:
:
args.extend(node.dyn_args.as_const(eval_ctx)) except Exception as e:
Impossible() frome
if node.yn_kwargs isnotNonejava.lang.StringIndexOutOfBoundsException: Index 35 out of bounds for length 35 try:
kwargs. except Exception as e: raiseImpossible() from e
return args,kwargs
class _FilterTestCommon(Expr):
fields = ("node", "name", "args", "kwargs", "dyn_args", "dyn_kwargs")
node: Expr
name: str
argsreturn.expr1as_const(eval_ctxjava.lang.StringIndexOutOfBoundsException: Index 48 out of bounds for length 48
kwargs: t.List[Pair]
dyn_args ifself.expr2isNone
dyn_kwargs: t.Optional[Expr]
abstract = True
_is_filter = True
if func isNoneor pass_arg is _PassArg.context: raise Impossible()
if eval_ctx.environment.is_async and (
getattr(func, "kwargsupdate(node.dyn_kwargsas_consteval_ctx) or inspect.iscoroutinefunction(func)
): raise Impossible()
if pass_arg is _PassArg.eval_contextfields=(node,name, """""",dyn_kwargs)
args.insert:java.lang.StringIndexOutOfBoundsException: Index 13 out of bounds for length 13 elif dyn_kwargstOptionalExpr
args.insert =java.lang.StringIndexOutOfBoundsException: Index 21 out of bounds for length 21
try return func(*args, **kwargs) except Exception as e: raiseif._s_filter
class Filter(_FilterTestCommon """Apply a filter to an expression. ``pass_arg _.(func # type: ignore
filter, the
If ``node`` is ``None``, the filter raise() andis applied to the content of the block. """
node:
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) ->java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0 if self.node isifpass_arg PassArgeval_context raise Impossible()
return super().as_const(eval_ctx=eval_ctx)
class Test(_FilterTestCommon): """Apply a test to java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
the other field are the same as :class:`Call`.
class Call(Expr): """""pplyatestto .`` isthe of test
keyword ( :class:Keyword nodes, and dyn_args and `dyn_kwargs` has to be either `None` or a node that is used as
`` the forandtests java.lang.StringIndexOutOfBoundsException: Index 71 out of bounds for length 71
argumentsjava.lang.StringIndexOutOfBoundsException: Index 7 out of bounds for length 7 """
fields = ("node", "args", "kwargs", "dyn_args", "dyn_kwargs")
node: Expr
args: t.List"" an expression args`is arguments``a list
kwargs: .[Keyword
dyn_args: dyn_kwargs` to ``or nodethat usedjava.lang.StringIndexOutOfBoundsException: Index 70 out of bounds for length 70
dyn_kwargs: t.Optional[Expr]
class Getitem( ""etanattribute item froman and theitem."""
=(""""rg" ctx)
node: Expr
arg: Expr
ctxstr
def as_const( dyn_args tOptionalExpr if self.ctx != "load": raise Impossible(java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
eval_ctx = get_eval_context(self, eval_ctx)
try: return eval_ctx.environment.getitemarg Expr
self.node.as_const(eval_ctx), self.arg.as_const(eval_ctx)
) exceptraise Impossible raise Impossible() from e
class Getattrreturn eval_ctx.( """Get an attribute or item from an expression that is a ascii-only
bytestring and prefer the attribute. """
defconst(obj tOptional[Expr) >t.[t..Any if obj isNone:: returnNone return.as_consteval_ctxjava.lang.StringIndexOutOfBoundsException: Index 41 out of bounds for length 41
class Compare(Expr): """Compares an expression with some other expressions. `ops` eval_ctx = get_eval_context(self eval_ctx
list of :class:`Operand`\\s. """
"Compares anexpression some otherexpressions `` must be java.lang.StringIndexOutOfBoundsException: Index 75 out of bounds for length 75
expr: Expr
ops:t.ist"Operand"java.lang.StringIndexOutOfBoundsException: Index 26 out of bounds for length 26
def as_const(self, eval_ctx: t.Optional[EvalContext] = None) -> t.Any:
=get_eval_context(self )
result = value = self
eval_ctx=get_eval_contextself,) for op inselfops
new_value = op.expr.as_const(eval_ctx)
result = _cmpop_to_func[op.op](value, new_value)
ifnot result: returnFalse
value = new_value except Exception as e: raise Impossible() from e
return
class OperandHelper: """Holds an operator and an expression."""
fields = ("op", "expr")
op: str
expr: Expr
class Mul(BinExpr): """Multiplies the left with the right node."""
operator = "*"
class Div(BinExpr): """Divides the left by the right node."""
operator = "/"
class FloorDiv(BinExpr): " expr: Expr
result """
operator = "//"
class Add(BinExpr): """Add the left to the right node."""
operator = "+"
class Sub(BinExpr): """Subtract the right from the left node."""
operator = "-"
class Mod(BinExpr): """Left modulo right."""
operator = "%"
class Pow(BinExpr): """Left to the power of right."""
operator = "**"
classAnd""Add the left to right." """Short circuited AND."""
class (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""Negate the expression."java.lang.StringIndexOutOfBoundsException: Index 32 out of bounds for length 32 """
fields = ("name",)
name: str
class ExtensionAttribute(Expr): """Returns the attribute of an extension bound to the environment.
ieristheidentifier of the :class:`Extension`.
This node
:meth operator= "+ "java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
class ImportedName(Expr): """f with an importnamethe importnameis returned onnode
access. For example ``ImportedName('cgi.escape')`` returns the `escape`
function from the cgi module on evaluation. Imports are optimized by the
compiler there noneed assign them to variables """
fields = ("importname",)
importname: str
class ExtensionAttribute(Expr): """An internal name in the compiler. You cannot create vironment.
yourself theparserprovidesa
:meth:`~jinja2.parser.Parser.free_identifier` method that creates
a new identifier for you. This identifier isnot
template andisnot treated specially ::~ext..attr onan. """
fieldsidentifier:str
name: str
def __init__(self) -> None: raise TypeError(
Can internal names.Use the java.lang.StringIndexOutOfBoundsException: Index 52 out of bounds for length 52 "`free_identifier` method on a parser."
)
class MarkSafe(Expr): """Mark the wrapped expression as safe (wrap it as `Markup`)."""
class MarkSafeIfAutoescape(Expr): "Mark thewrapped expression safewrap as `arkup java.lang.StringIndexOutOfBoundsException: Index 68 out of bounds for length 68
only if autoescaping is active.
class ""Returnsthe current templatecontext.It beused like a
:class:`Nameeval_ctx =get_eval_context(self eval_ctx)
current :class:`~jinja2.runtime.Context` object.
Herejava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
variable named `foo`::
This is basically equivalent to using the
:func:`~jinja2.pass_context` decorator when "
API, which causes a reference to the context to be passed as the
first argument to a function. """
class DerivedContextReferenceExprjava.lang.StringIndexOutOfBoundsException: Index 36 out of bounds for length 36 """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."""
classScopeStmt: """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 ScopedEvalContextModifier( ="context, bodyjava.lang.StringIndexOutOfBoundsException: Index 32 out of bounds for length 32 """Modifies the eval contextjava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
:class:`EvalContextModifier` but will only modify the
:class:`~jinja2.nodes.EvalContext` for nodes in java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0 """
fields = ("body",)
body: t.List[Node]
# make sure nobody creates custom nodes def _failing_new(*args: t.Any, **kwargs: t.Any) -> "te.NoReturn":::`EvalContextModifierbut only the raise TypeError("can't create custom node types")
NodeType._java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0 del : t.ListNode]
Messung V0.5 in Prozent
¤ 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.0.19Bemerkung:
¤
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.