o
    .d                     @  s*  d Z ddlmZ ddlZddlmZ ddlmZ ddlmZ ddlm	Z	 ddlm
Z
 dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlm Z  ddlm!Z! ddl"mZ# ddl"m$Z$ ddl"m%Z% ddl&m'Z' erddl(m)Z) dd l*m+Z+ e,d!Z-G d"d# d#e.Z/ee.e0f Z1e	e/e
e1 f Z2	 eee
e1 f Z3e	e.e
e1 f Z4	 G d$d% d%Z5G d&d' d'Z6G d(d) d)Z7G d*d+ d+e7Z8G d,d- d-Z9dS ).zLAnalyze template variables, tags and filters by traversing a template's AST.    )annotationsN)defaultdict)TYPE_CHECKING)DefaultDict)Dict)List)Optional)Set)Tuple)	BlockNode)	ChildNode)Node)	ParseTree)Context)ReadOnlyChainMap)
StopRender)TemplateInheritanceError)TemplateNotFound)TemplateTraversalError)
Expression)FilteredExpression)
Identifier)IdentifierPathElement)IdentifierTuple)StringLiteral)_BlockStackItem)stack_blocks)	TOKEN_TAG)Literal)BoundTemplatez(\.|\[)c                      s>   e Zd ZdZd fddZd fd	d
ZedddZ  ZS )ReferencedVariablez:A str subclass for variables found during static analysis.objobjectreturnc                   s   t  | |}||_|S N)super__new__r!   )clsr!   _str	__class__ N/var/www/Matress/matenv/lib/python3.10/site-packages/liquid/static_analysis.pyr&   .   s   zReferencedVariable.__new___Nonec                   s<   t    |  t| jtr| j | _d S t| jf| _d S r$   )r%   __init__
isinstancer!   r   as_tuple_partsstr)selfr-   r)   r+   r,   r/   3   s
   
zReferencedVariable.__init__r   c                 C  s   | j S )a  A tuple representation of the variable's parts.

        `parts` might contain nested tuples for nested variables. For example, the
        variable `some[foo.bar[a.b]].other` as a tuple would look like this:

            ("some", ("foo", "bar", ("a", "b")), "other.thing")
        )r2   r4   r+   r+   r,   parts;   s   	zReferencedVariable.parts)r!   r"   r#   r    )r-   r"   r#   r.   )r#   r   )	__name__
__module____qualname____doc__r&   r/   propertyr6   __classcell__r+   r+   r)   r,   r    +   s    r    c                   @  s   e Zd ZdZdZdd
dZdS )ContextualTemplateAnalysisav  The result of analyzing a template using `BoundTemplate.analyze_with_context`.

    Each of the following properties is a dictionary mapping variable or filter names
    to the number of times that variable was referenced.

    Attributes:
        all_variables (Dict[str, int]): All variables references along a path through
            the template's syntax tree.
        local_variables (Dict[str, int]): The names of variables assigned using the
            built-in `assign` `capture`, `increment` or `decrement` tags, or any custom
            tag that uses `Context.assign()`.
        undefined_variables (Dict[str, int]): The names of variables that could not be
            resolved. If a name is referenced before it is assigned, it will appear in
            `undefined` and `assigns`.
        filters (Dict[str, int]): Names of filters found during contextual analysis.
    all_variableslocal_variablesundefined_variablesfiltersr?   Dict[str, int]r@   rA   rB   r#   r.   c                C  s   || _ || _|| _|| _d S r$   r>   )r4   r?   r@   rA   rB   r+   r+   r,   r/   h   s   
z#ContextualTemplateAnalysis.__init__N)
r?   rC   r@   rC   rA   rC   rB   rC   r#   r.   r7   r8   r9   r:   	__slots__r/   r+   r+   r+   r,   r=   T   s    r=   c                   @  s   e Zd ZdZdZdddZdS )TemplateAnalysisa  The result of analyzing a template using `BoundTemplate.analyze`.

    Each of the following properties is a dictionary mapping variable, tag or filter
    names to a list of tuples. Each tuple holds the location of a reference to the name
    as (template name, line number). If a name is referenced multiple times, it will
    appear multiple times in the list. If a name is referenced before it is "assigned",
    it will appear in `local_variables` and `global_variables`.

    Attributes:
        variables (Refs): All referenced variables, whether they are in scope or not.
            Including references to names such as `forloop` from the `for` tag.
        local_variables (Refs): Template variables that are added to the template local
            scope, whether they are subsequently used or not.
        global_variables (Refs): Template variables that, on the given line number and
            "file", are out of scope or are assumed to be "global". That is, expected to
            be included by the application developer rather than a template author.
        failed_visits (NameRefs): Names of AST `Node` and `Expression` objects that
            could not be visited, probably because they do not implement a `children`
            method.
        unloadable_partials (NameRefs): Names or identifiers of partial templates that
            could not be loaded. This will be empty if `follow_partials` is `False`.
        filters (NameRefs): All filters found during static analysis.
        tags: All tags found during static analysis.
    	variablesr@   global_variablesfailed_visitsunloadable_partialsrB   tagsrH   Refsr@   rI   rJ   NameRefsrK   rB   rL   r#   r.   c                C  s.   || _ || _|| _|| _|| _|| _|| _d S r$   rG   )r4   rH   r@   rI   rJ   rK   rB   rL   r+   r+   r,   r/      s   
zTemplateAnalysis.__init__N)rH   rM   r@   rM   rI   rM   rJ   rN   rK   rN   rB   rN   rL   rN   r#   r.   rD   r+   r+   r+   r,   rF   v   s    
rF   c                   @  s  e Zd ZdZdddddddUddZdVddZdVddZdWddZdWddZdXd d!Z	dXd"d#Z
dYd'd(ZdXd)d*ZdXd+d,ZdXd-d.ZdXd/d0ZdZd1d2ZdZd3d4Zd[d8d9Zd\d@dAZd\dBdCZ	d]d^dHdIZdWdJdKZd_dMdNZd`dOdPZdXdQdRZdXdSdTZdS )a_TemplateCountera  Count references to variable names in a Liquid template.

    Args:
        template: The Liquid template to analyze.
        follow_partials: If `True`, the reference counter will try to load partial
            templates and count variable references in those partials too. Default's to
            `True`.
        raise_for_failures: If `True`, will raise an exception if an `ast.Node` or
            `expression.Expression` does not define a `children()` method, or if a
            partial template can not be loaded.

            When `False`, no exception is raised and a mapping of failed
            nodes/expressions is available as the `failed_visits` property. A mapping of
            unloadable partial templates are stored in the `unloadable_partials`
            property.
    TN)follow_partialsraise_for_failuresscopetemplate_localspartialstemplater   rP   boolrQ   rR   Optional[ReadOnlyChainMap]rS   Optional[IdentifierMap]rT   4Optional[List[Tuple[str, Optional[Dict[str, str]]]]]r#   r.   c                C  s   || _ | j jpd| _|| _|| _|d ur|ntt| _tt| _tt| _	tt| _
tt| _tt| _tt| _|d ur?|nt | _|d urI|ng | _t| j j| _d S Nz<string>)rU   name_template_namerP   rQ   r   listrS   template_globalsrH   rB   rL   rJ   rK   r   _scope	_partialsr   env_empty_context)r4   rU   rP   rQ   rR   rS   rT   r+   r+   r,   r/      s   






z_TemplateCounter.__init__c              	   C  s>   | j jjD ]}z| | W q ty   Y  nw |   | S )zTraverse the template's syntax tree and count variables as we go.

        It is not safe to call this method multiple times.
        )rU   tree
statements_analyzer   _raise_for_failuresr4   noder+   r+   r,   analyze   s   z_TemplateCounter.analyzec              	     sF   | j jjD ]}z
| |I dH  W q ty   Y  nw |   | S )z9An async version of `_TemplateVariableCounter.analyze()`.N)rU   rc   rd   _analyze_asyncr   rf   rg   r+   r+   r,   analyze_async   s   z_TemplateCounter.analyze_asyncrh   r   c                 C  s*  |  | z| }W n ty'   |jj}| j| | j| j	f Y d S w |D ]h}| 
| | | | | |jrJ| jdd |jD  | jr|jdkrX| | n)|jdkrc| | n|jdkrs| || j td|jd urtd|j d|jr| |j |jr| j  q*d S )	Nc                 S     i | ]}|d qS r$   r+   .0nr+   r+   r,   
<dictcomp>      z-_TemplateCounter._analyze.<locals>.<dictcomp>includerenderextendsstop static analysisunknown load mode '')
_count_tagchildrenNotImplementedErrorr*   r7   rJ   appendr\   tokenlinenum_analyze_expression_expression_hook_update_template_scopeblock_scoper_   pushrP   	load_mode_analyze_include_analyze_render#_analyze_template_inheritance_chainrU   r   r   rh   re   popr4   rh   ry   r[   childr+   r+   r,   re     s@   








z_TemplateCounter._analyzec                   sJ  |  | z| }W n ty(   |jj}| j| | j| j	f Y d S w |D ]w}| 
| | |I d H  | | |jrN| jdd |jD  | jr|jdkr_| |I d H  n/|jdkrm| |I d H  n!|jdkr| || jI d H  td|jd urtd|j d|jr| |jI d H  |jr| j  q+d S )	Nc                 S  rl   r$   r+   rm   r+   r+   r,   rp   =  rq   z3_TemplateCounter._analyze_async.<locals>.<dictcomp>rr   rs   rt   ru   rv   rw   )rx   ry   rz   r*   r7   rJ   r{   r\   r|   r}   r~   _async_expression_hookr   r   r_   r   rP   r   _analyze_include_async_analyze_render_async)_analyze_template_inheritance_chain_asyncrU   r   r   rh   rj   r   r   r+   r+   r,   rj   -  sF   








z_TemplateCounter._analyze_asyncr   r   c                 C  s   |j sd S z| |j }W n ty(   |j jj}| j| | j|jf Y d S w |j	D ]}| j
| | j|jf q,|j	D ](}tt|dd }|| jvrftt|gd| jvrf| j| | j|jf q>|jD ]}| j| | j|jf qjd S )N   r   path)
expression_update_expression_refsrz   r*   r7   rJ   r{   r\   r}   variable_referencesrH   RE_SPLIT_IDENTsplitr3   r_   r   r   rS   r^   filter_referencesrB   )r4   r   refsr[   ref_reff_refr+   r+   r,   r~   U  s,   




z$_TemplateCounter._analyze_expressionc                 C  s>   |j sd S |j D ]}| jtt|gd | j|jf qd S )Nr   )template_scoperS   r   r   r{   r\   r}   )r4   r   r[   r+   r+   r,   r   r  s   

z'_TemplateCounter._update_template_scoper   r   
Referencesc                 C  s\   t  }t|tr|| t|tr|dd |jD  | D ]
}|| 	| q!|S )z9Return a list of references used in the given expression.c                 S  s   g | ]}|j qS r+   )r[   )rn   fr+   r+   r,   
<listcomp>  rq   z<_TemplateCounter._update_expression_refs.<locals>.<listcomp>)
r   r0   r   append_variabler   append_filtersrB   ry   extendr   )r4   r   r   exprr+   r+   r,   r   {  s   


z(_TemplateCounter._update_expression_refsc                 C  s   |  |d\}}|d u s|d u rd S z| ||| j|}W n
 ty'   Y d S w t|| j| j| j| j| j	d
 }| | d S Nrr   rP   rR   rS   rQ   rT   )_make_load_context_get_templater\   r   rO   rP   r_   rS   rQ   r`   ri   _update_reference_countersr4   r   r[   load_contextrU   r   r+   r+   r,   r     s*   
	z!_TemplateCounter._analyze_includec                   s   |  |d\}}|d u s|d u rd S z| ||| j|I d H }W n
 ty+   Y d S w t|| j| j| j| j| j	d
 I d H }| | d S r   )r   _get_template_asyncr\   r   rO   rP   r_   rS   rQ   r`   rk   r   r   r+   r+   r,   r     s,   
	z'_TemplateCounter._analyze_include_asyncc                 C  s   |  |d\}}|d u s|d u rd S z| ||| j|}W n
 ty'   Y d S w |jr3dd |jD ni }t|| jt|| j| j	d
 }| | d S )Nrs   c                 S  rl   r$   r+   rm   r+   r+   r,   rp     rq   z4_TemplateCounter._analyze_render.<locals>.<dictcomp>rP   rR   rQ   rT   )r   r   r\   r   r   rO   rP   r   rQ   r`   ri   r   r4   r   r[   r   rU   rR   r   r+   r+   r,   r     s*   
z _TemplateCounter._analyze_renderc                   s   |  |d\}}|d u s|d u rd S z| ||| j|I d H }W n
 ty+   Y d S w |jr7dd |jD ni }t|| jt|| j| j	d
 I d H }| | d S )Nrs   c                 S  rl   r$   r+   rm   r+   r+   r,   rp     rq   z:_TemplateCounter._analyze_render_async.<locals>.<dictcomp>r   )r   r   r\   r   r   rO   rP   r   rQ   r`   rk   r   r   r+   r+   r,   r     s,   
z&_TemplateCounter._analyze_render_asyncc              	   C  s|  |  |d\}}|d u s|d u rd S | jji |d}tt|jd< t }| j||dd\}}|s2J || z| 	||| j
|}	W n
 tyL   Y d S w | ||	\}
}|
rl|
|v rgtd|
|j|jd||
 |
rz| 	|
|| j
|}	W n
 ty   Y d S w | ||	\}
}|
r|
|v rtd|
||
 |
snt|	|| jtdd i| j| j| j| jd }| | d S )	Nrt   )rU   F
count_tagscircular extends r}   filenameblockr   )r   rb   copyr   r]   tag_namespaceset_stack_blocksaddr   r\   r   r   r}   r[   _InheritanceChainCounterrP   r   r_   rS   rQ   r`   ri   r   r4   rh   rU   r[   r   stack_contextseenextends_namer-   parentparent_template_namer   r+   r+   r,   r     sf   




z4_TemplateCounter._analyze_template_inheritance_chainc              	     s  |  |d\}}|d u s|d u rd S | ji }tt|jd< t }| j||dd\}}|s1J || z| 	||| j
|I d H }	W n
 tyN   Y d S w | ||	\}
}|
rn|
|v ritd|
|j|jd||
 |
rz| 	|
|| j
|I d H }	W n
 ty   Y d S w | ||	\}
}|
r|
|v rtd|
||
 |
spt|	|| jtdd i| j| j| j| jd I d H }| | d S )Nrt   Fr   r   r   r   r   )r   rb   r   r   r]   r   r   r   r   r   r\   r   r   r}   r[   r   rP   r   r_   rS   rQ   r`   rk   r   r   r+   r+   r,   r   *  sl   





z:_TemplateCounter._analyze_template_inheritance_chain_asyncr   'Literal['extends', 'include', 'render'].Tuple[Optional[str], Optional[Dict[str, str]]]c                 C  s   |dkrt |jts| jt|j | j|jf dS t |jts)td|d|jj	}|j
p1i }||f| jv r;dS | j||f ||fS )Nrr   )NNz.can't load from a variable expression when in z mode)r0   r   r   rK   r3   r{   r\   r}   r   valuer   r`   )r4   r   r   r[   r   r+   r+   r,   r   j  s   


z#_TemplateCounter._make_load_contextr[   r3   r   Dict[str, str]parent_nameparent_nodec                 C  s>   z| j j|fi |W S  ty   | j| ||jf  w r$   )rb   get_template_with_contextr   rK   r{   r}   r4   r[   r   r   r   r+   r+   r,   r     s   z_TemplateCounter._get_templatec                   sF   z| j j|fi |I d H W S  ty"   | j| ||jf  w r$   )rb   get_template_with_context_asyncr   rK   r{   r}   r   r+   r+   r,   r     s   z$_TemplateCounter._get_template_asyncr   r   r   0Tuple[Optional[str], List[InheritanceBlockNode]]c           	      C  s   |j pd}t||\}}|r |r | }| j|j ||jf |D ]}| }| j|j ||jf q"|r?|j ||fS d |fS rZ   )r[   r   r|   rL   r   r{   r}   evaluate)	r4   r   rU   r   template_nameast_extends_nodeast_block_nodesr|   ast_noder+   r+   r,   r     s   
z_TemplateCounter._stack_blocksc                 C  sB   |  }t|ts|jtkr| j|j | j|j	f d S d S d S r$   )
r|   r0   r   typer   rL   r   r{   r\   r}   )r4   rh   r|   r+   r+   r,   rx     s   z_TemplateCounter._count_tagr   c                 C  s   |j  D ]\}}| j | | q|j D ]\}}| j| | q|j D ]\}}| j| | q)|j D ]\}}| j| | q;|j D ]\}}| j| | qM|j D ]\}}| j| | q_d S r$   )rH   itemsr   r^   rJ   rK   rB   rL   )r4   r   _name_refs	node_namer   filter_nametag_namer+   r+   r,   r     s   z+_TemplateCounter._update_reference_countersc                 C  s   | j r0| jr0tt| j }t| jdkr$| dt| jd  d}n| d}td| | j rb| jrdtt| j }t| jdkrUd| dt| jd  d}nd| d	}td| d S d S )
Nr   z (+z- more) does not implement a 'children' methodz' does not implement a 'children' methodzfailed visit: zpartial template 'z' (+z more) could not be loadedz' could not be loaded)rQ   rJ   nextiterkeyslenr   rK   )r4   
msg_targetmsgr+   r+   r,   rf     s"   
z$_TemplateCounter._raise_for_failuresc                 C  s   d S r$   r+   r4   r   r+   r+   r,   r     s   z!_TemplateCounter._expression_hookc                   s   d S r$   r+   r   r+   r+   r,   r     s   z'_TemplateCounter._async_expression_hook)rU   r   rP   rV   rQ   rV   rR   rW   rS   rX   rT   rY   r#   r.   )r#   rO   rh   r   r#   r.   r   r   r#   r.   )r   r   r#   r   )rh   r   rU   r   r#   r.   )r   r   r   r   r#   r   )
r[   r3   r   r   r   r3   r   r   r#   r   )T)r   r   rU   r   r   rV   r#   r   )r   rO   r#   r.   r#   r.   )r7   r8   r9   r:   r/   ri   rk   re   rj   r~   r   r   r   r   r   r   r   r   r   r   r   r   rx   r   rf   r   r   r+   r+   r+   r,   rO      s>    
.


&
(

	





>
@





rO   c                      s   e Zd Zdddddddd1 fddZd2 fddZd2 fddZd3dd Zd3d!d"Zd4d%d&Zd5d)d*Z	d5d+d,Z
d6d/d0Z  ZS )7r   NT)parent_block_stack_itemrP   rQ   rR   rS   rT   base_templater   r   r   r   Optional[_BlockStackItem]rP   rV   rQ   rR   rW   rS   rX   rT   rY   r#   r.   c          	        s(   || _ || _t j||||||d d S )N)rU   rP   rQ   rR   rS   rT   )r   r   r%   r/   )	r4   r   r   r   rP   rQ   rR   rS   rT   r)   r+   r,   r/     s   
z!_InheritanceChainCounter.__init__rh   r   c                   s    t |tr
| |S t |S r$   )r0   InheritanceBlockNode_analyze_blockr%   re   rg   r)   r+   r,   re     s   

z!_InheritanceChainCounter._analyzec                   s.   t |tr| |I d H S t |I d H S r$   )r0   r   _analyze_block_asyncr%   rj   rg   r)   r+   r,   rj     s   
z'_InheritanceChainCounter._analyze_asyncr   r   c                 C  s~   |j }|sd S | jsd S | |r=| | j}dd | jD }t|| j| jtdd i| j	|| j
| jd }| | d S d S )Nc                 S     i | ]
}t |jd  dqS r   Nr3   r   rn   identr+   r+   r,   rp         z=_InheritanceChainCounter._expression_hook.<locals>.<dictcomp>r   r   )r   r   _contains_super_make_templaterS   r   r   rP   r   r_   rQ   r`   ri   r   r4   r   r   rU   rR   r   r+   r+   r,   r     s(   
	z)_InheritanceChainCounter._expression_hookc                   s   |j }|sd S | jsd S | |rA| | j}dd | jD }t|| j| jtdd i| j	|| j
| jd I d H }| | d S d S )Nc                 S  r   r   r   r   r+   r+   r,   rp   ,  r   zC_InheritanceChainCounter._async_expression_hook.<locals>.<dictcomp>r   r   )r   r   r   r   rS   r   r   rP   r   r_   rQ   r`   rk   r   r   r+   r+   r,   r   "  s*   
	z/_InheritanceChainCounter._async_expression_hookr   r   c                   s\   t |trt|dkrdS t |tr!t |jtr!t|jdkr!dS t fdd| D S )Nzblock.superTc                 3  s    | ]}  |V  qd S r$   )r   )rn   r   r5   r+   r,   	<genexpr>B  s    z;_InheritanceChainCounter._contains_super.<locals>.<genexpr>)r0   r   r3   r   r   anyry   )r4   r   r+   r5   r,   r   8  s   

z(_InheritanceChainCounter._contains_superr   r   c              	   C  st   | j jd }||j d }| |}dd | jD }t|| j | jtdd i| j|| j	| j
|jd }| | d S )Nrt   r   c                 S  r   r   r   r   r+   r+   r,   rp   K  r   z;_InheritanceChainCounter._analyze_block.<locals>.<dictcomp>r   rP   rR   rQ   rT   r   )r   r   r[   r   rS   r   rP   r   r_   rQ   r`   r   ri   r   r4   r   block_stacksblock_stack_itemrU   rR   r   r+   r+   r,   r   D  s"   


z'_InheritanceChainCounter._analyze_blockc              	     s|   | j jd }||j d }| |}dd | jD }t|| j | jtdd i| j|| j	| j
|jd I d H }| | d S )Nrt   r   c                 S  r   r   r   r   r+   r+   r,   rp   `  r   zA_InheritanceChainCounter._analyze_block_async.<locals>.<dictcomp>r   r   )r   r   r[   r   rS   r   rP   r   r_   rQ   r`   r   rk   r   r   r+   r+   r,   r   Y  s$   


z-_InheritanceChainCounter._analyze_block_asyncitemr   c                 C  s,   t  }|jjg|_| jjj| jj||jdS )N)
parse_treer[   )r   r   rd   rU   ra   template_classsource_name)r4   r   r   r+   r+   r,   r   n  s
   z'_InheritanceChainCounter._make_template)r   r   r   r   r   r   rP   rV   rQ   rV   rR   rW   rS   rX   rT   rY   r#   r.   r   r   )r   r   r#   rV   )r   r   r#   r.   )r   r   r#   r   )r7   r8   r9   r/   re   rj   r   r   r   r   r   r   r<   r+   r+   r)   r,   r     s     




r   c                   @  s8   e Zd ZdZdddZddd	ZdddZdddZdS )r   z4Collect references for Template.analyze and friends.r#   r.   c                 C  s   g | _ g | _d S r$   )r   r   r5   r+   r+   r,   r/   y  s   
zReferences.__init__varr   c                 C     | j | dS )zAdd a variable reference.N)r   r{   )r4   r   r+   r+   r,   r   }     zReferences.append_variablerB   	List[str]c                 C  r   )zAdd references to filters.N)r   r   )r4   rB   r+   r+   r,   r     r   zReferences.append_filtersr   c                 C  s    | j |j  | j|j dS )z/Incorporate references from another References.N)r   r   r   )r4   r   r+   r+   r,   r     s   zReferences.extendNr   )r   r   r#   r.   )rB   r   r#   r.   )r   r   r#   r.   )r7   r8   r9   r:   r/   r   r   r   r+   r+   r+   r,   r   v  s    


r   ):r:   
__future__r   recollectionsr   typingr   r   r   r   r   r	   r
   
liquid.astr   r   r   r   liquid.contextr   r   liquid.exceptionsr   r   r   r   liquid.expressionr   r   r   r   r   r   liquid.extra.tags.extendsr   r   r   liquid.tokenr   typing_extensionsr   liquidr   compiler   r3   r    intLocationrM   IdentifierMaprN   r=   rF   rO   r   r   r+   r+   r+   r,   <module>   sh    
"8    @ 