
    XhS                        d dl mZmZmZmZmZmZmZmZm	Z	m
Z
 d dlmZ ddlmZ ddlmZmZ ddlmZmZ ddlmZ d dlmZmZ d d	lmZmZ  ed
      Z ed      Z ed      Z ed      Z  ed      Z!edef   Z"ee"e#f   Z$ G d d      Z% e%       Z& G d d      Z' G d de'eeeef         Z(d;dZ) G d de(      Z* G d deeef         Z+ G d de(eef         Z, G d de(eef         Z- G d  d!e(      Z. G d" d#      Z/ G d$ d%e/eee         Z0 G d& d'e/ee         Z1 G d( d)e'eeeef         Z2eee2   ege!f   Z3d*e3d+e3fd,Z4d- Z5 G d. d/      Z6d0 Z7d1 Z8d2 Z9d3 Z:d<d4e;d5e;d6e;d7ee   d+ee$ge$f   f
d8Z< G d9 d:e(      Z=y)=    )
TypeVarTupleListCallableGenericTypeUnionOptionalAnycast)ABC   )combine_alternatives)TreeBranch)
VisitErrorGrammarError)Token)wrapsupdate_wrapper)
getmembersgetmro	_Return_T	_Return_V_Leaf_T_Leaf_U_R.c                       e Zd ZdZd Zy)_DiscardTypea  When the Discard value is returned from a transformer callback,
    that node is discarded and won't appear in the parent.

    Note:
        This feature is disabled when the transformer is provided to Lark
        using the ``transformer`` keyword (aka Tree-less LALR mode).

    Example:
        ::

            class T(Transformer):
                def ignore_tree(self, children):
                    return Discard

                def IGNORE_TOKEN(self, token):
                    return Discard
    c                      y)Nzlark.visitors.Discard )selfs    A/var/www/html/myenv/lib/python3.12/site-packages/lark/visitors.py__repr__z_DiscardType.__repr__(   s    &    N)__name__
__module____qualname____doc__r$   r!   r%   r#   r   r      s    $'r%   r   c                   &    e Zd ZdZed        Zd Zy)_Decoratablez4Provides support for decorating methods with @v_argsc           	         t        |       }|d   | u sJ |dd  D ch c]  }t        |      D ]  \  }}|	  }}}}t        |       D ]w  \  }}|j                  d      s||v r|| j                  vr*t	        |      s6t        | j                  |   t              rTt        | |t        | j                  |   |             y | S c c}}}w )Nr   r   _)r   r   
startswith__dict__callable
isinstance_VArgsWrappersetattr)clsvisit_wrappermro_clsnamer-   
libmembersvalues           r#   _apply_v_argsz_Decoratable._apply_v_args2   s    Sk1v}}'*12wOOtj>NO74dOdO
O%c? 	QKD% s#
(:t3<<?WE? #,,t,m<C}S\\$-?OP	Q 
 Ps   Cc                     | S Nr!   r4   r-   s     r#   __class_getitem__z_Decoratable.__class_getitem__F       
r%   N)r&   r'   r(   r)   classmethodr;   r?   r!   r%   r#   r+   r+   /   s    : &r%   r+   c                   v    e Zd ZdZdZddeddfdZddZd Zd	 Z	d
 Z
dee   defdZ	 	 	 	 	 	 ddZd Zd Zy)Transformera  Transformers work bottom-up (or depth-first), starting with visiting the leaves and working
    their way up until ending at the root of the tree.

    For each node visited, the transformer will call the appropriate method (callbacks), according to the
    node's ``data``, and use the returned value to replace the node, thereby creating a new tree structure.

    Transformers can be used to implement map & reduce patterns. Because nodes are reduced from leaf to root,
    at any point the callbacks may assume the children have already been transformed (if applicable).

    If the transformer cannot find a method with the right name, it will instead call ``__default__``, which by
    default creates a copy of the node.

    To discard a node, return Discard (``lark.visitors.Discard``).

    ``Transformer`` can do anything ``Visitor`` can do, but because it reconstructs the tree,
    it is slightly less efficient.

    A transformer without methods essentially performs a non-memoized partial deepcopy.

    All these classes implement the transformer interface:

    - ``Transformer`` - Recursively transforms the tree. This is the one you probably want.
    - ``Transformer_InPlace`` - Non-recursive. Changes the tree in-place instead of returning new instances
    - ``Transformer_InPlaceRecursive`` - Recursive. Changes the tree in-place instead of returning new instances

    Parameters:
        visit_tokens (bool, optional): Should the transformer visit tokens in addition to rules.
                                       Setting this to ``False`` is slightly faster. Defaults to ``True``.
                                       (For processing ignored tokens, use the ``lexer_callbacks`` options)

    Tvisit_tokensreturnNc                     || _         y r=   )__visit_tokens__)r"   rD   s     r#   __init__zTransformer.__init__l   s
     ,r%   c                    ||n|j                   }	 t        | |j                        }	 t        |dd       }|(|j                  ||j                  ||j                        S  ||      S # t
        $ r  t        $ r}t        |j                  ||      d }~ww xY w# t        $ r* | j                  |j                  ||j                        cY S w xY wNr5   )
childrengetattrdatar5   metar   	Exceptionr   AttributeError__default__)r"   treenew_childrenrK   fwrapperes          r#   _call_userfunczTransformer._call_userfunco   s    #/#;<	5dii(A	5!!_d;&??1dii499MMX;&  5 D!445  	D##DIIxCC	Ds.   B 6A(  A( (B:BB0CCc                     	 t        | |j                        }	  ||      S # t        $ r  t        $ r}t	        |j                  ||      d }~ww xY w# t
        $ r | j                  |      cY S w xY wr=   )rL   typer   rO   r   rP   __default_token__)r"   tokenrT   rV   s       r#   _call_userfunc_tokenz Transformer._call_userfunc_token   st    
	7ejj)A7x  7 UA667  	1))%00	1s%   A ! AA

AA/.A/c              #      K   |D ]a  }t        |t              r| j                  |      }n0| j                  r"t        |t              r| j                  |      }n|}|t        us^| c y wr=   )r1   r   _transform_treerG   r   r\   Discard)r"   rK   cress       r#   _transform_childrenzTransformer._transform_children   sc      		A!T"**1-&&:a+?//2'!			s   A A*#A*c                 n    t        | j                  |j                              }| j                  ||      S r=   listrb   rK   rW   )r"   rR   rK   s      r#   r^   zTransformer._transform_tree   s.    00?@""422r%   rR   c                 h    t        | j                  |g            }|syt        |      dk(  sJ |d   S )z5Transform the given tree, and return the final resultNr   r   )re   rb   len)r"   rR   ra   s      r#   	transformzTransformer.transform   s8    4++TF343x1}}1vr%   c                     t        | |      S )zFChain two transformers together, returning a new transformer.
        )TransformerChainr"   others     r#   __mul__zTransformer.__mul__   s      e,,r%   c                     t        |||      S )zDefault function that is called if there is no attribute matching ``data``

        Can be overridden. Defaults to creating a new copy of the tree node (i.e. ``return Tree(data, children, meta)``)
        r   )r"   rM   rK   rN   s       r#   rQ   zTransformer.__default__   s    
 D(D))r%   c                     |S )zDefault function that is called if there is no attribute matching ``token.type``

        Can be overridden. Defaults to returning the token as-is.
        r!   )r"   r[   s     r#   rZ   zTransformer.__default_token__   s	    
 r%   )Tr=   )r"   z#Transformer[_Leaf_T, Tree[_Leaf_U]]rl   zMUnion[Transformer[_Leaf_U, _Return_V], TransformerChain[_Leaf_U, _Return_V,]]rE   $TransformerChain[_Leaf_T, _Return_V])r&   r'   r(   r)   rG   boolrH   rW   r\   rb   r^   r   r   r   rh   rm   rQ   rZ   r!   r%   r#   rC   rC   J   sv    > -d -D -5&7
3d7m 	 -7-b- 
0-*r%   rC   Nc                 *   | 
t               } |j                         D ]s  \  }}t        |      D ]`  }t        ||      }t	        |      s|j                  d      s|dk(  r2|dz   |z   }t        | |      rt        d|z        t        | ||       b u | S )ab  Merge a collection of transformers into the base_transformer, each into its own 'namespace'.

    When called, it will collect the methods from each transformer, and assign them to base_transformer,
    with their name prefixed with the given keyword, as ``prefix__methodname``.

    This function is especially useful for processing grammars that import other grammars,
    thereby creating some of their rules in a 'namespace'. (i.e with a consistent name prefix).
    In this case, the key for the transformer should match the name of the imported grammar.

    Parameters:
        base_transformer (Transformer, optional): The transformer that all other transformers will be added to.
        **transformers_to_merge: Keyword arguments, in the form of ``name_prefix = transformer``.

    Raises:
        AttributeError: In case of a name collision in the merged methods

    Example:
        ::

            class TBase(Transformer):
                def start(self, children):
                    return children[0] + 'bar'

            class TImportedGrammar(Transformer):
                def foo(self, children):
                    return "foo"

            composed_transformer = merge_transformers(TBase(), imported=TImportedGrammar())

            t = Tree('start', [ Tree('imported__foo', []) ])

            assert composed_transformer.transform(t) == 'foobar'

    r-   rh   __z0Cannot merge: method '%s' appears more than once)	rC   itemsdirrL   r0   r.   hasattrrP   r3   )base_transformertransformers_to_mergeprefixtransformermethod_namemethodprefixed_methods          r#   merge_transformersr      s    F &=4::< ?{+ 
	?K[+6FF#%%c*k[.H$tmk9O'9$%WZi%ijj$ov>
	?? r%   c                       e Zd ZddZy)InlineTransformerNc                     ||n|j                   }	 t        | |j                        } || S # t        $ r* | j	                  |j                  ||j
                        cY S w xY wr=   )rK   rL   rM   rP   rQ   rN   )r"   rR   rS   rK   rT   s        r#   rW   z InlineTransformer._call_userfunc   sc    #/#;<	 dii(A h<  	D##DIIxCC	Ds   - 0A A r=   )r&   r'   r(   rW   r!   r%   r#   r   r      s     r%   r   c                   J    e Zd ZU ded<   d	dZdee   defdZ	 	 	 	 	 	 d
dZ	y)rj   z0Tuple[Union[Transformer, TransformerChain], ...]transformersrE   Nc                     || _         y r=   )r   )r"   r   s     r#   rH   zTransformerChain.__init__  s
    (r%   rR   c                 f    | j                   D ]  }|j                  |      } t        t        |      S r=   )r   rh   r   r   )r"   rR   ts      r#   rh   zTransformerChain.transform  s2    "" 	%A;;t$D	%It$$r%   c                 .    t        | j                  |fz    S r=   )rj   r   rk   s     r#   rm   zTransformerChain.__mul__  s      !2!2eX!=>>r%   )r   z$Union[Transformer, TransformerChain]rE   N)r"   z(TransformerChain[_Leaf_T, Tree[_Leaf_U]]rl   zLUnion[Transformer[_Leaf_U, _Return_V], TransformerChain[_Leaf_U, _Return_V]]rE   rq   )
r&   r'   r(   __annotations__rH   r   r   r   rh   rm   r!   r%   r#   rj   rj      sC    DD)%d7m %	 %
?<?a? 
0?r%   rj   c                   ,    e Zd ZdZd Zdee   defdZy)Transformer_InPlacezSame as Transformer, but non-recursive, and changes the tree in-place instead of returning new instances

    Useful for huge trees. Conservative in memory.
    c                 $    | j                  |      S r=   )rW   r"   rR   s     r#   r^   z#Transformer_InPlace._transform_tree      ""4((r%   rR   rE   c                     |j                         D ]+  }t        | j                  |j                              |_        - | j	                  |      S r=   )iter_subtreesre   rb   rK   r^   r"   rR   subtrees      r#   rh   zTransformer_InPlace.transform  sM    ))+ 	PG#D$<$<W=M=M$NOG	P ##D))r%   N)	r&   r'   r(   r)   r^   r   r   r   rh   r!   r%   r#   r   r     s#    )*d7m *	 *r%   r   c                   &    e Zd ZdZdee   defdZy)Transformer_NonRecursivezSame as Transformer but non-recursive.

    Like Transformer, it doesn't change the original tree.

    Useful for huge trees.
    rR   rE   c                 Z   g }|g}|rC|j                         }|j                  |       t        |t              r||j                  z  }|rCg }t        |      D ]  }t        |t              rSt        |j                        }|r|| d  }|| d = ng }| j                  ||      }	|	t        usT|j                  |	       f| j                  r<t        |t              r,| j                  |      }	|	t        us|j                  |	       |j                  |        |\  }
t        t        |
      S r=   )popappendr1   r   rK   reversedrg   rW   r_   rG   r   r\   r   r   )r"   rR   rev_postfixqr   stackxsizeargsra   results              r#   rh   z"Transformer_NonRecursive.transform)  s   $(6Aq!!T"QZZ	  +& 	 A!T"1:: $=DtefD))!T2g%LL%&&:a+?//2g%LL%Q%	 (  Iv&&r%   N)r&   r'   r(   r)   r   r   r   rh   r!   r%   r#   r   r   !  s    $'d7m $'	 $'r%   r   c                       e Zd ZdZd Zy)Transformer_InPlaceRecursivez`Same as Transformer, recursive, but changes the tree in-place instead of returning new instancesc                 v    t        | j                  |j                              |_        | j                  |      S r=   rd   r   s     r#   r^   z,Transformer_InPlaceRecursive._transform_treeR  s.    T55dmmDE""4((r%   N)r&   r'   r(   r)   r^   r!   r%   r#   r   r   P  s
    f)r%   r   c                       e Zd Zd Zd Zd Zy)VisitorBasec                 P     t        | |j                  | j                        |      S r=   )rL   rM   rQ   r   s     r#   rW   zVisitorBase._call_userfuncZ  s"    9wtTYY(8(89$??r%   c                     |S )zDefault function that is called if there is no attribute matching ``tree.data``

        Can be overridden. Defaults to doing nothing.
        r!   r   s     r#   rQ   zVisitorBase.__default__]  s	    
 r%   c                     | S r=   r!   r>   s     r#   r?   zVisitorBase.__class_getitem__d  r@   r%   N)r&   r'   r(   rW   rQ   r?   r!   r%   r#   r   r   Y  s    @r%   r   c                   H    e Zd ZdZdee   dee   fdZdee   dee   fdZy)VisitorzTree visitor, non-recursive (can handle huge trees).

    Visiting a node calls its methods (provided by the user via inheritance) according to ``tree.data``
    rR   rE   c                 R    |j                         D ]  }| j                  |        |S zJVisits the tree, starting with the leaves and finally the root (bottom-up))r   rW   r   s      r#   visitzVisitor.visitn  s-    ))+ 	)G(	)r%   c                 R    |j                         D ]  }| j                  |        |S zIVisit the tree, starting at the root, and ending at the leaves (top-down))iter_subtrees_topdownrW   r   s      r#   visit_topdownzVisitor.visit_topdownt  s-    113 	)G(	)r%   Nr&   r'   r(   r)   r   r   r   r   r!   r%   r#   r   r   h  s=    
$w- DM $w- DM r%   r   c                   H    e Zd ZdZdee   dee   fdZdee   dee   fdZy)Visitor_RecursivezBottom-up visitor, recursive.

    Visiting a node calls its methods (provided by the user via inheritance) according to ``tree.data``

    Slightly faster than the non-recursive version.
    rR   rE   c                     |j                   D ]$  }t        |t              s| j                  |       & | j	                  |       |S r   )rK   r1   r   r   rW   r"   rR   childs      r#   r   zVisitor_Recursive.visit  s@    ]] 	"E%&

5!	" 	D!r%   c                     | j                  |       |j                  D ]$  }t        |t              s| j	                  |       & |S r   )rW   rK   r1   r   r   r   s      r#   r   zVisitor_Recursive.visit_topdown  sB    D!]] 	*E%&""5)	* r%   Nr   r!   r%   r#   r   r   {  s=    $w- DM g 4= r%   r   c                   Z    e Zd ZdZdee   defdZdee   fdZdee   de	fdZ
d Zd Zy	)
Interpretera   Interpreter walks the tree starting at the root.

    Visits the tree, starting with the root and finally the leaves (top-down)

    For each tree node, it calls its methods (provided by user via inheritance) according to ``tree.data``.

    Unlike ``Transformer`` and ``Visitor``, the Interpreter doesn't automatically visit its sub-branches.
    The user has to explicitly call ``visit``, ``visit_children``, or use the ``@visit_children_decor``.
    This allows the user to implement branching and loops.
    rR   rE   c                 $    | j                  |      S r=   )_visit_treer   s     r#   r   zInterpreter.visit  s     %%r%   c                     t        | |j                        }t        |dd       }|2|j                  ||j                  |j                  |j                        S  ||      S rJ   )rL   rM   r5   rK   rN   )r"   rR   rT   rU   s       r#   r   zInterpreter._visit_tree  sP    D$))$!_d3??1dii		JJT7Nr%   c                     |j                   D cg c]%  }t        |t              r| j                  |      n|' c}S c c}w r=   )rK   r1   r   r   r   s      r#   visit_childrenzInterpreter.visit_children  s?    !]], ,6eT+B  'M , 	, ,s   *<c                     | j                   S r=   )rQ   )r"   r8   s     r#   __getattr__zInterpreter.__getattr__  s    r%   c                 $    | j                  |      S r=   r   r   s     r#   rQ   zInterpreter.__default__  r   r%   N)r&   r'   r(   r)   r   r   r   r   r   r   r   r   rQ   r!   r%   r#   r   r     sO    	&$w- &I &W ,4= ,T , )r%   r   funcrE   c                 .     t                fd       }|S )zSee Interpreterc                 8    | j                  |      } | |      S r=   r   )r4   rR   valuesr   s      r#   innerz#visit_children_decor.<locals>.inner  s     ##D)C  r%   )r   )r   r   s   ` r#   visit_children_decorr     s     
4[! ! Lr%   c                 b    	 | j                   } ||      S # t        $ r t        | |      cY S w xY wr=   )r;   rP   r2   )objr5   _applys      r#   r;   r;     s=    %"" m$$  1S-001s    ..c                   R    e Zd ZU dZeed<   dedeeeeegef   fdZ	d Z
d
dZd	 Zy)r2   aQ  
    A wrapper around a Callable. It delegates `__call__` to the Callable.
    If the Callable has a `__get__`, that is also delegate and the resulting function is wrapped.
    Otherwise, we use the original function mirroring the behaviour without a __get__.
    We also have the visit_wrapper attribute to be used by Transformers.
    	base_funcr   r5   c                 p    t        |t              r|j                  }|| _        || _        t	        | |       y r=   )r1   r2   r   r5   r   )r"   r   r5   s      r#   rH   z_VArgsWrapper.__init__  s.    dM*>>D*tT"r%   c                 &     | j                   |i |S r=   )r   )r"   r   kwargss      r#   __call__z_VArgsWrapper.__call__  s    t~~t.v..r%   Nc                     	 t        | j                        j                  }t         || j                  ||      | j                        S # t
        $ r | cY S w xY wr=   )rY   r   __get__r2   r5   rP   )r"   instanceownergs       r#   r   z_VArgsWrapper.__get__  sV    	Y T^^$,,A !4>>8U!CTEWEWXX  	K	s   A	 	AAc                     	 t        | j                        j                  } || j                  ||       y # t        $ r Y y w xY wr=   )rY   r   __set_name__rP   )r"   r   r8   rT   s       r#   r   z_VArgsWrapper.__set_name__  sA    	+T^^$11A dnneT*  		s   6 	AAr=   )r&   r'   r(   r)   r   r   strre   r   rH   r   r   r   r!   r%   r#   r2   r2     sG     #X #h#tUX?Y[^?^6_ #/Y+r%   r2   c                      | | S r=   r!   )rT   _datarK   _metas       r#   _vargs_inliner     s    h<r%   c                      | |g| S r=   r!   rT   r   rK   rN   s       r#   _vargs_meta_inliner     s    THr%   c                      | ||      S r=   r!   r   s       r#   _vargs_metar     s    T8r%   c                 (     | t        |||            S r=   ro   )rT   rM   rK   rN   s       r#   _vargs_treer     s    T$$'((r%   inlinerN   rR   rU   c                     |r|s| rt        d      d|r| rt        nt        n| rt        n|rt        |t        d      |fd}|S )a  A convenience decorator factory for modifying the behavior of user-supplied visitor methods.

    By default, callback methods of transformers/visitors accept one argument - a list of the node's children.

    ``v_args`` can modify this behavior. When used on a transformer/visitor class definition,
    it applies to all the callback methods inside it.

    ``v_args`` can be applied to a single method, or to an entire class. When applied to both,
    the options given to the method take precedence.

    Parameters:
        inline (bool, optional): Children are provided as ``*args`` instead of a list argument (not recommended for very long lists).
        meta (bool, optional): Provides two arguments: ``meta`` and ``children`` (instead of just the latter)
        tree (bool, optional): Provides the entire tree as the argument, instead of the children.
        wrapper (function, optional): Provide a function to decorate all methods.

    Example:
        ::

            @v_args(inline=True)
            class SolveArith(Transformer):
                def add(self, left, right):
                    return left + right

                @v_args(meta=True)
                def mul(self, meta, children):
                    logger.info(f'mul at line {meta.line}')
                    left, right = children
                    return left * right


            class ReverseNotation(Transformer_InPlace):
                @v_args(tree=True)
                def tree_node(self, tree):
                    tree.children = tree.children[::-1]
    z@Visitor functions cannot combine 'tree' with 'meta' or 'inline'.Nz;Cannot use 'wrapper' along with 'tree', 'meta' or 'inline'.c                     t        |       S r=   )r;   )r   r   s    r#   _visitor_args_decz!v_args.<locals>._visitor_args_dec9  s    S$''r%   )
ValueErrorr   r   r   r   )r   rN   rR   rU   r   r   s        @r#   v_argsr     sf    J [\\D%DD		Z[[(r%   c                   "    e Zd ZdZd Zd Zd Zy)CollapseAmbiguitiesa#  
    Transforms a tree that contains any number of _ambig nodes into a list of trees,
    each one containing an unambiguous tree.

    The length of the resulting list is the product of the length of all _ambig nodes.

    Warning: This may quickly explode for highly ambiguous trees.

    c                     t        |g       S r=   )sum)r"   optionss     r#   _ambigzCollapseAmbiguities._ambigM  s    7Br%   c                 T    t        |      D cg c]  }t        |||       c}S c c}w r=   )r   r   )r"   rM   children_listsrN   rK   s        r#   rQ   zCollapseAmbiguities.__default__P  s%    ;OP^;_`xT8T*```s   %c                     |gS r=   r!   )r"   r   s     r#   rZ   z%CollapseAmbiguities.__default_token__S  s	    s
r%   N)r&   r'   r(   r)   r   rQ   rZ   r!   r%   r#   r   r   C  s     ar%   r   r=   )FFFN)>typingr   r   r   r   r   r   r	   r
   r   r   abcr   utilsr   rR   r   r   
exceptionsr   r   lexerr   	functoolsr   r   inspectr   r   r   r   r   r   r   _FUNCrY   
_DECORATEDr   r_   r+   rC   r   r   rj   r   r   r   r   r   r   r   _InterMethodr   r;   r2   r   r   r   r   rr   r   r   r!   r%   r#   <module>r      s   \ \ \  '  0  , &K 	K 	
)

)
T]i 5$;
' ', . 6q,WWi-?%@ qh2j	  	 ?ww	12 ?&*+gy&89 *,'{7I+=> ,'^); ) k3 0 &WW%5 8"),WWi-?%@ ")J k*I6:;|  %#+ #+L):4 :t :4 :RZ[cRd :px  {E  zF  HR  zR  qS :D+ r%   