a `wy @sPdZddlZddlmZddlmZddlmZddlmZddlm Z dd lm Z ej ej ej ejejejejd Zejejejd Zejejejejejejd d dd dZGdddeZGddde Z!Gddde"Z#ddZ$Gddde e!e"Z%Gddde%Z&Gddde%Z'Gddde%Z(Gd d!d!e&Z)Gd"d#d#e&Z*Gd$d%d%e&Z+Gd&d'd'e&Z,Gd(d)d)e&Z-Gd*d+d+e&Z.Gd,d-d-e&Z/Gd.d/d/e&Z0Gd0d1d1e&Z1Gd2d3d3e&Z2Gd4d5d5e&Z3Gd6d7d7e&Z4Gd8d9d9e&Z5Gd:d;d;e&Z6Gdd?d?e%Z8Gd@dAdAe8Z9GdBdCdCe8Z:GdDdEdEe8Z;GdFdGdGe8ZGdLdMdMe=Z?GdNdOdOe=Z@GdPdQdQe=ZAGdRdSdSe=ZBGdTdUdUe'ZCGdVdWdWe'ZDGdXdYdYe8ZEdZd[ZFGd\d]d]e8ZGGd^d_d_e8ZHGd`dadae8ZIGdbdcdce8ZJGdddedee8ZKGdfdgdge8ZLGdhdidie8ZMGdjdkdke8ZNGdldmdme'ZOGdndodoe9ZRGdpdqdqe9ZSGdrdsdse9ZTGdtdudue9ZUGdvdwdwe9ZVGdxdydye9ZWGdzd{d{e9ZXGd|d}d}e9ZYGd~dde9ZZGddde:Z[Gddde:Z\Gddde:Z]Gddde8Z^Gddde8Z_Gddde8Z`Gddde8ZaGddde8ZbGddde8ZcGddde8ZdGddde8ZeGddde&ZfGddde&ZgGddde&ZhGddde&ZiGddde&ZjGdddejZkddZlemele!_n[ldS)zAST 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. N)deque)Markup)izip)PY2) text_type)with_metaclass)*///**%+-)notrrcCs||vSNabrr0/usr/lib/python3.9/site-packages/jinja2/nodes.py#rcCs||vSrrrrrrr$r)eqnegtZgteqltZlteqinZnotinc@seZdZdZdS) Impossiblez8Raised if the node could not perform a requested action.N__name__ __module__ __qualname____doc__rrrrr(src@seZdZdZddZdS)NodeTypezA metaclass for nodes that handles the field and attribute inheritance. fields and attributes from the parent class are automatically forwarded to the child.cCs^dD]<}g}|t|d|d|||dt|||<q|ddt||||S)N)fields attributesrrabstractF)extendgetattrgettuple setdefaulttype__new__)ZmcsnamebasesdattrZstoragerrrr.1s zNodeType.__new__N)r r!r"r#r.rrrrr$,sr$c@s*eZdZdZd ddZddZddZdS) EvalContextzcHolds evaluation time information. Custom attributes can be attached to it in extensions. NcCs0||_t|jr|||_n|j|_d|_dSNF) environmentcallable autoescapevolatile)selfr5Z template_namerrr__init__Bs  zEvalContext.__init__cCs |jSr)__dict__copyr9rrrsaveJszEvalContext.savecCs|j|j|dSr)r;clearupdate)r9oldrrrrevertMs zEvalContext.revert)N)r r!r"r#r:r>rBrrrrr3=s r3cCs(|dur$|jdurtdt|jS|S)NzIif no eval context is passed, the node must have an attached environment.)r5 RuntimeErrorr3)nodectxrrrget_eval_contextRs  rFc@seZdZdZdZdZdZddZddd Zd d d Z d d Z ddZ ddZ d!ddZ ddZddZddZejZddZddZdS)"NodeaBaseclass for all Jinja nodes. There are a number of nodes available of different types. There are four major types: - :class:`Stmt`: statements - :class:`Expr`: expressions - :class:`Helper`: helper nodes - :class:`Template`: the outermost wrapper node 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. rlinenor5TcOs|jrtd|rt|t|jkrh|js:td|jjtd|jjt|jt|jdkr^dp`dft|j|D]\}}t|||qt|jD]}t||| |dq|rtdt t |dS)Nz#abstract nodes are not instantiablez%r takes 0 argumentsz%r takes 0 or %d argument%srszunknown attribute %r) r' TypeErrorlenr% __class__r rsetattrr&popnextiter)r9r%r&r/argr2rrrr:ss( z Node.__init__Nc csn|jD]b}||urdus@n|dur0||vs@|dur||vrz|t||fVWqtyfYq0qdS)aZThis 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. N)r%r)AttributeError)r9excludeonlyr/rrr iter_fieldss"  zNode.iter_fieldsccsP|||D]>\}}t|tr:|D]}t|tr"|Vq"q t|tr |Vq dS)zIterates 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. N)rW isinstancelistrG)r9rUrV_itemnrrriter_child_nodess    zNode.iter_child_nodescCs||D] }|SdS)ziFind the first node of a given type. If no such node exists the return value is `None`. N)find_all)r9 node_typeresultrrrfindsz Node.findccs8|D]*}t||r|V||D] }|Vq&qdS)zFind all the nodes of a given type. If the type is a tuple, the check is performed for any of the tuple items. N)r]rXr^)r9r_childr`rrrr^s   z Node.find_allcCs:t|g}|r6|}d|jvr&||_||q |S)aReset 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. rE)rpopleftr%rEr(r])r9rEtodorDrrrset_ctxs  z Node.set_ctxFcCsHt|g}|rD|}d|jvr4|jdus.|r4||_||q |S)z.Set the line numbers of the node and children.rIN)rrcr&rIr(r])r9rIoverriderdrDrrr set_linenos  zNode.set_linenocCs0t|g}|r,|}||_||q |S)z"Set the environment for all nodes.)rrcr5r(r])r9r5rdrDrrrset_environments  zNode.set_environmentcCs(t|t|uo&t|t|kSr)r-r+rWr9otherrrr__eq__sz Node.__eq__cCs || Sr)rkrirrr__ne__sz Node.__ne__cs&djjdfddjDfS)Nz%s(%s), c3s"|]}d|t|dfVqdS)z%s=%rN)r)).0rSr=rr rz Node.__repr__..)rNr joinr%r=rr=r__repr__sz Node.__repr__cs$fddg|dS)Ncst|tst|dSd|jj|jsBddSt|jD]p\}}|rbdt||}t|t rdt|D]\}}|rd|qdqL|qLddS)Nz nodes.%s()rm[]) rXrGappendreprrNr r% enumerater)rY)rDidxZfieldvaluer[_dumpbufrrr{s(          zNode.dump.._dumprK)rpr=rrzrdumpsz Node.dump)NN)NN)F)r r!r"r#r%r&r'r:rWr]rar^rergrhrkrlobject__hash__rqr}rrrrrG^s"     rGc@seZdZdZdZdS)StmtzBase node for all statements.TNr r!r"r#r'rrrrr src@seZdZdZdZdS)Helperz,Nodes that exist in a specific context only.TNrrrrrrsrc@seZdZdZdZdS)TemplatezjNode that represents a template. This must be the outermost node that is passed to the compiler. bodyNr r!r"r#r%rrrrrsrc@seZdZdZdZdS)OutputzA node that holds multiple expressions which are then printed out. This is used both for the `print` statement and the regular template data. nodesNrrrrrrsrc@seZdZdZdZdS)Extendsz Represents an extends statement.)templateNrrrrrr&src@seZdZdZdZdS)ForaxThe 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`. )targetrRrelse_test recursiveNrrrrrr,src@seZdZdZdZdS)Ifz4If `test` is true, `body` is rendered, else `else_`.)rrZelif_rNrrrrrr8src@seZdZdZdZdS)MacrozA 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. )r/argsdefaultsrNrrrrrr>src@seZdZdZdZdS) CallBlockzLike a macro without a name but a call instead. `call` is called with the unnamed macro as `caller` argument this node holds. )callrrrNrrrrrrGsrc@seZdZdZdZdS) FilterBlockzNode for filter sections.)rfilterNrrrrrrOsrc@seZdZdZdZdS)WithzSpecific node for with statements. In older versions of Jinja the with statement was implemented on the base of the `Scope` node instead. .. versionadded:: 2.9.3 )targetsvaluesrNrrrrrrUsrc@seZdZdZdZdS)BlockzA node that represents a block.)r/rZscopedNrrrrrr_src@seZdZdZdZdS)Includez'A node that represents the include tag.)r with_contextZignore_missingNrrrrrresrc@seZdZdZdZdS)Importz&A node that represents the import tag.)rrrNrrrrrrksrc@seZdZdZdZdS) FromImportaA 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 is not 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. )rnamesrNrrrrrrqs rc@seZdZdZdZdS)ExprStmtzAA statement that evaluates an expression and discards the result.rDNrrrrrrsrc@seZdZdZdZdS)Assignz"Assigns an expression to a target.)rrDNrrrrrrsrc@seZdZdZdZdS) AssignBlockzAssigns a block to a target.)rrrNrrrrrrsrc@s&eZdZdZdZdddZddZdS) ExprzBaseclass for all expressions.TNcCs tdS)anReturn the value of the expression as constant or raise :exc:`Impossible` if this was not possible. An :class:`EvalContext` can be provided, if none is given a default context is created which requires the nodes to have an attached environment. .. versionchanged:: 2.4 the `eval_ctx` parameter was added. N)rr9eval_ctxrrras_consts z Expr.as_constcCsdS)z8Check if it's possible to assign something to this node.Frr=rrr can_assignszExpr.can_assign)N)r r!r"r#r'rrrrrrrs rc@s&eZdZdZdZdZdZdddZdS)BinExprz%Baseclass for all binary expressions.)leftrightNTcCsjt||}|jjr&|j|jjvr&tt|j}z||j||j |WSt ydtYn0dSr) rFr5 sandboxedoperatorZintercepted_binopsr_binop_to_funcrrr Exceptionr9rfrrrrs    zBinExpr.as_const)Nr r!r"r#r%rr'rrrrrrs rc@s&eZdZdZdZdZdZdddZdS) UnaryExprz$Baseclass for all unary expressions.rNTcCs`t||}|jjr&|j|jjvr&tt|j}z||j|WSt yZtYn0dSr) rFr5rrZintercepted_unopsr _uaop_to_funcrDrrrrrrrs    zUnaryExpr.as_const)Nrrrrrrs rc@seZdZdZdZddZdS)Namea 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. )r/rEcCs |jdvS)N)trueZfalseZnoneTrueFalseNoner/r=rrrrszName.can_assignNr r!r"r#r%rrrrrrsrc@seZdZdZdZddZdS)NSRefz)Reference to a namespace value assignment)r/r2cCsdS)NTrr=rrrrszNSRef.can_assignNrrrrrrsrc@seZdZdZdZdS)LiteralzBaseclass for literals.TNrrrrrrsrc@s,eZdZdZdZdddZed ddZdS) ConstaAll 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`` is true). )ryNcCsH|j}trDt|turD|jjdrDz|d}WntyBYn0|S)Nzcompiler.ascii_strascii)ryrr-rr5Zpoliciesencode UnicodeError)r9rrvrrrrs   zConst.as_constcCs(ddlm}||st||||dS)zReturn a const object if the value is representable as constant value in the generated code, otherwise it will raise an `Impossible` exception. r) has_safe_reprrH)Zcompilerrr)clsryrIr5rrrrfrom_untrusted s zConst.from_untrusted)N)NN)r r!r"r#r%r classmethodrrrrrrs  rc@seZdZdZdZdddZdS) TemplateDatazA constant template string.)dataNcCs,t||}|jrt|jr&t|jS|jSr)rFr8rr7rrrrrrrs   zTemplateData.as_const)Nr r!r"r#r%rrrrrrsrc@s&eZdZdZdZdddZddZdS) TuplezFor 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. )itemsrENcs"t|tfdd|jDS)Nc3s|]}|VqdSrrrnxrrrro2rz!Tuple.as_const..)rFr+rrrrrr0s zTuple.as_constcCs|jD]}|sdSqdS)NFT)rr)r9r[rrrr4s zTuple.can_assign)Nr r!r"r#r%rrrrrrr(s rc@seZdZdZdZdddZdS)Listz&Any list literal such as ``[1, 2, 3]``rNcst|fdd|jDS)Ncsg|]}|qSrrrrrr Brz!List.as_const..)rFrrrrrr@s z List.as_const)Nrrrrrr;src@seZdZdZdZdddZdS)DictzeAny dict literal such as ``{1: 2, 3: 4}``. The items must be a list of :class:`Pair` nodes. rNcs"t|tfdd|jDS)Nc3s|]}|VqdSrrrrrrroNrz Dict.as_const..)rFdictrrrrrrLs z Dict.as_const)NrrrrrrEsrc@seZdZdZdZdddZdS)PairzA key, value pair for dicts.keyryNcCs"t||}|j||j|fSr)rFrrryrrrrrVs z Pair.as_const)NrrrrrrQsrc@seZdZdZdZdddZdS)Keywordz>A key, value pair for keyword arguments where key is a string.rNcCst||}|j|j|fSr)rFrryrrrrrr`s zKeyword.as_const)Nrrrrrr[src@seZdZdZdZdddZdS)CondExprzZA conditional expression (inline if expression). (``{{ foo if bar else baz }}``) )rexpr1expr2NcCs>t||}|j|r"|j|S|jdur2t|j|Sr)rFrrrrrrrrrrls     zCondExpr.as_const)Nrrrrrresrcsfdd|jD}tfdd|jD}|jdurfz||jWntydtYn0|jdurz| |jWntytYn0||fS)Ncsg|]}|qSrrrrrrryrz!args_as_const..c3s|]}|VqdSrrrrrrrozrz args_as_const..) rrkwargsdyn_argsr(rrr dyn_kwargsr@)rDrrrrrr args_as_constxs      rc@seZdZdZdZdddZdS)FilteraThis node applies a filter on an expression. `name` is the name of the filter, the rest of the fields are the same as for :class:`Call`. If the `node` of a filter is `None` the contents of the last buffer are filtered. Buffers are created by macros and filter blocks. rDr/rrrrNcCst||}|js|jdur t|jj|j}|dusHt|dddurNt|jj rht|ddrhtt ||\}}| d|j |t|dddur| d|nt|dddur| d|jz||i|WSt ytYn0dS)NZ contextfilterFTZasyncfiltervariantrZevalcontextfilterZenvironmentfilter)rFr8rDrr5filtersr*r/r)is_asyncrinsertrr)r9rZfilter_rrrrrrs(   zFilter.as_const)Nrrrrrrsrc@seZdZdZdZdddZdS)TestzApplies a test on an expression. `name` is the name of the test, the rest of the fields are the same as for :class:`Call`. rNcCsx|jj|j}|durtt||}t||\}}|d|j |z||i|WSt yrtYn0dS)Nr) r5Ztestsr*r/rrFrrrDrr)r9rrrrrrrrs  z Test.as_const)Nrrrrrrsrc@seZdZdZdZdS)Calla/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. )rDrrrrNrrrrrrsrc@s&eZdZdZdZdddZddZdS) Getitemz@Get an attribute or item from an expression and prefer the item.)rDrSrENcCsXt||}|jdkrtz |j|j||j|WStyRtYn0dSNload) rFrErr5getitemrDrrSrrrrrrs   zGetitem.as_constcCsdSr4rr=rrrrszGetitem.can_assign)Nrrrrrrs rc@s&eZdZdZdZdddZddZdS) GetattrznGet an attribute or item from an expression that is a ascii-only bytestring and prefer the attribute. )rDr2rENcCsR|jdkrtz$t||}|j|j||jWStyLtYn0dSr) rErrFr5r)rDrr2rrrrrrs   zGetattr.as_constcCsdSr4rr=rrrrszGetattr.can_assign)Nrrrrrrs rc@seZdZdZdZdddZdS)Slicez_Represents a slice object. This must only be used as argument for :class:`Subscript`. )startstopstepNcs4t|fdd}t||j||j||jS)Ncs|dur dS|Srr)objrrrconstszSlice.as_const..const)rFslicerrr)r9rrrrrr s  zSlice.as_const)Nrrrrrrsrc@seZdZdZdZdddZdS)ConcatzXConcatenates the list of expressions provided after converting them to unicode. rNcs$t|dfdd|jDS)NrKc3s|]}t|VqdSr)rrrrrrrorz"Concat.as_const..)rFrprrrrrrs zConcat.as_const)Nrrrrrrsrc@seZdZdZdZdddZdS)CompareziCompares an expression with some other expressions. `ops` must be a list of :class:`Operand`\s. )expropsNcCstt||}|j|}}z<|jD]0}|j|}t|j||}|sNWdS|}q"WntyntYn0|Sr4)rFrrr_cmpop_to_funcoprr)r9rr`ryrZ new_valuerrrr)s      zCompare.as_const)Nrrrrrr"src@seZdZdZdZdS)Operandz$Holds an operator and an expression.)rrNrrrrrr<src@seZdZdZdZdS)Mulz(Multiplies the left with the right node.r Nr r!r"r#rrrrrrKsrc@seZdZdZdZdS)Divz#Divides the left by the right node.r NrrrrrrQsrc@seZdZdZdZdS)FloorDivzjDivides the left by the right node and truncates conver the result into an integer by truncating. r NrrrrrrWsrc@seZdZdZdZdS)AddzAdd the left to the right node.rNrrrrrr_src@seZdZdZdZdS)Subz&Subtract the right from the left node.rNrrrrrresrc@seZdZdZdZdS)ModzLeft modulo right.r Nrrrrrrksrc@seZdZdZdZdS)PowzLeft to the power of right.r Nrrrrrrqsrc@seZdZdZdZdddZdS)AndzShort circuited AND.andNcCs"t||}|j|o |j|SrrFrrrrrrrr|s z And.as_const)Nr r!r"r#rrrrrrrwsrc@seZdZdZdZdddZdS)OrzShort circuited OR.orNcCs"t||}|j|p |j|Srrrrrrrs z Or.as_const)Nrrrrrr sr c@seZdZdZdZdS)NotzNegate the expression.rNrrrrrr sr c@seZdZdZdZdS)NegzMake the expression negative.rNrrrrrr sr c@seZdZdZdZdS)Posz8Make the expression positive (noop for most expressions)rNrrrrrr sr c@seZdZdZdZdS)EnvironmentAttributezLoads an attribute from the environment object. This is useful for extensions that want to call a callback stored on the environment. rNrrrrrrsrc@seZdZdZdZdS)ExtensionAttributezReturns 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. )Z identifierr/Nrrrrrrsrc@seZdZdZdZdS) ImportedNamea&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. )Z importnameNrrrrrrsrc@seZdZdZdZddZdS) InternalNamea7An 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 is not available from the template and is not threated specially by the compiler. rcCs tddS)NzKCan't create internal names. Use the `free_identifier` method on a parser.rLr=rrrr:szInternalName.__init__N)r r!r"r#r%r:rrrrrsrc@seZdZdZdZdddZdS)MarkSafez:Mark the wrapped expression as safe (wrap it as `Markup`).rNcCst||}t|j|Sr)rFrrrrrrrrs zMarkSafe.as_const)Nrrrrrrsrc@seZdZdZdZdddZdS)MarkSafeIfAutoescapezMark the wrapped expression as safe (wrap it as `Markup`) but only if autoescaping is active. .. versionadded:: 2.5 rNcCs4t||}|jrt|j|}|jr0t|S|Sr)rFr8rrrr7r)r9rrrrrrs  zMarkSafeIfAutoescape.as_const)Nrrrrrrsrc@seZdZdZdS)ContextReferenceaPReturns 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`:: Assign(Name('foo', ctx='store'), Getattr(ContextReference(), 'name')) This is basically equivalent to using the :func:`~jinja2.contextfunction` decorator when using the high-level API, which causes a reference to the context to be passed as the first argument to a function. Nrrrrrrsrc@seZdZdZdS)DerivedContextReferencezReturn the current template context including locals. Behaves exactly like :class:`ContextReference`, but includes local variables, such as from a ``for`` loop. .. versionadded:: 2.11 Nrrrrrrsrc@seZdZdZdS)ContinuezContinue a loop.Nrrrrrrsrc@seZdZdZdS)Breakz Break a loop.Nrrrrrr src@seZdZdZdZdS)ScopezAn artificial scope.rNrrrrrrsrc@seZdZdZdZdS) OverlayScopeaAn 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. Example usage:: OverlayScope(context=self.call_method('get_context'), body=[...]) .. versionadded:: 2.10 )contextrNrrrrrrs rc@seZdZdZdZdS)EvalContextModifiera Modifies the eval context. For each option that should be modified, a :class:`Keyword` has to be added to the :attr:`options` list. Example to change the `autoescape` setting:: EvalContextModifier(options=[Keyword('autoescape', Const(True))]) )optionsNrrrrrr%src@seZdZdZdZdS)ScopedEvalContextModifierzModifies 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`. rNrrrrrr1srcOs tddS)Nzcan't create custom node typesr)rrrrr _failing_new;sr )or#r collectionsrZ markupsaferZ_compatrrrrmultruedivfloordivpowmodaddsubrnot_posnegrrrrgerlerrrr-r$r~r3rFrGrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrsortedsetrrrrrrrrr r r r rrrrrrrrrrrrrrr  staticmethodr.rrrrs         -    #    /