o
    ŀga                     @  sB  d Z ddlmZ ddlZddlmZmZ ddlmZ ddl	Z	ddl
mZmZmZ ddlZddlmZ ddlm  mZ ddlmZmZmZmZ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&m'Z' dd
l(m)Z) ddl*m+Z+ dCddZ,dCddZ-dCddZ.dd Z/dd Z0e0e.e-e,e&fdDddZ1dd Z2e2e3Z4e2e5Z6e7dd  d!d  e8eD D Z9e9fd"d#Z:e7d$d  e9D Z;e:ej<Z=e:ej>Z?e:ej@ZAe:ejBZCe:ejDZEe:ejFZGe:ejHZIe:ejJZKe:ejLZMe:ejNZOe:ejPZQe:ejZRe:ejSZTe7g d%ZUe7g d&ZVe?e=B eOB eQB eRB eTB eCB eVB eU ZWe;eW eUB ZXeWeX@ ZYd'eY ZZeYr2J eZdEd*d+Z[ed,Z\dFd0d1Z]d2d3 Z^ee#d4Z_d5d6 Z`e]eWe`e_G d7d8 d8ejaZbe7g d9Zce7ee Zde]eWecB eEe7g d:B  G d;d< d<ebZee]eWecB e7d=gB G d>d? d?ebZfG d@dA dAZgefeedBZhdS )Gz
:func:`~pandas.eval` parsers.
    )annotationsN)partialreduce	iskeyword)CallableClassVarTypeVar)UndefinedVariableError)ARITH_OPS_SYMSBOOL_OPS_SYMSCMP_OPS_SYMS	LOCAL_TAGMATHOPS
REDUCTIONSUNARY_OPS_SYMSBinOpConstantFuncNodeOpTermUnaryOpis_term)clean_backtick_quoted_tokstokenize_string)Scope)printingtoktuple[int, str]returnc                 C  s   | \}}||dkrdfS |fS )a`  
    Rewrite the assignment operator for PyTables expressions that use ``=``
    as a substitute for ``==``.

    Parameters
    ----------
    tok : tuple of int, str
        ints correspond to the all caps constants in the tokenize module

    Returns
    -------
    tuple of int, str
        Either the input or token or the replacement values
    === r   toknumtokvalr"   r"   P/var/www/html/myenv/lib/python3.10/site-packages/pandas/core/computation/expr.py_rewrite_assign1   s   r'   c                 C  sF   | \}}|t jkr|dkrt jdfS |dkrt jdfS ||fS ||fS )aj  
    Replace ``&`` with ``and`` and ``|`` with ``or`` so that bitwise
    precedence is changed to boolean precedence.

    Parameters
    ----------
    tok : tuple of int, str
        ints correspond to the all caps constants in the tokenize module

    Returns
    -------
    tuple of int, str
        Either the input or token or the replacement values
    &and|or)tokenizeOPNAMEr#   r"   r"   r&   _replace_booleansD   s   


r/   c                 C  s,   | \}}|t jkr|dkrt jtfS ||fS )a(  
    Replace local variables with a syntactically valid name.

    Parameters
    ----------
    tok : tuple of int, str
        ints correspond to the all caps constants in the tokenize module

    Returns
    -------
    tuple of int, str
        Either the input or token or the replacement values

    Notes
    -----
    This is somewhat of a hack in that we rewrite a string such as ``'@a'`` as
    ``'__pd_eval_local_a'`` by telling the tokenizer that ``__pd_eval_local_``
    is a ``tokenize.OP`` and to replace the ``'@'`` symbol with it.
    @)r,   r-   r   r#   r"   r"   r&   _replace_locals]   s   
r1   c                   s    fddS )z
    Compose 2 callables.
    c                    s    | i |S Nr"   )argskwargsfgr"   r&   <lambda>{   s    z_compose2.<locals>.<lambda>r"   r5   r"   r5   r&   	_compose2w      r9   c                  G  s   t | dks
J dtt| S )z&
    Compose 2 or more callables.
       z.At least 2 callables must be passed to compose)lenr   r9   )funcsr"   r"   r&   _compose~   s   
r>   sourcestrc                   s,   t  sJ dt fddt| D S )a  
    Compose a collection of tokenization functions.

    Parameters
    ----------
    source : str
        A Python source code string
    f : callable
        This takes a tuple of (toknum, tokval) as its argument and returns a
        tuple with the same structure but possibly different elements. Defaults
        to the composition of ``_rewrite_assign``, ``_replace_booleans``, and
        ``_replace_locals``.

    Returns
    -------
    str
        Valid Python source code

    Notes
    -----
    The `f` parameter can be any callable that takes *and* returns input of the
    form ``(toknum, tokval)``, where ``toknum`` is one of the constants from
    the ``tokenize`` module and ``tokval`` is a string.
    zf must be callablec                 3  s    | ]} |V  qd S r2   r"   .0xr6   r"   r&   	<genexpr>       z_preparse.<locals>.<genexpr>)callabler,   
untokenizer   r?   r6   r"   rD   r&   	_preparse   s   rJ   c                   s    fddS )zO
    Factory for a type checking function of type ``t`` or tuple of types.
    c                   s   t | j S r2   )
isinstancevalue)rC   tr"   r&   r8      s    z_is_type.<locals>.<lambda>r"   rM   r"   rM   r&   _is_type   s   rO   c                 c  s*    | ]}t |trt|tjr|V  qd S r2   )rK   type
issubclassastASTrB   noder"   r"   r&   rE      s    

rE   c                 c  s    | ]}t t|V  qd S r2   )getattrrR   )rB   namer"   r"   r&   rE      s    c                   s    fdd|D }t |S )zE
    Filter out AST nodes that are subclasses of ``superclass``.
    c                 3  s     | ]}t | r|jV  qd S r2   )rQ   __name__rT   
superclassr"   r&   rE      s    z _filter_nodes.<locals>.<genexpr>)	frozenset)rZ   	all_nodes
node_namesr"   rY   r&   _filter_nodes   s   r^   c                 c      | ]}|j V  qd S r2   )rX   rA   r"   r"   r&   rE          )AssignModuleExpr)YieldGeneratorExpIfExpDictCompSetCompReprLambdaSetrS   IsIsNotz$cannot both support and not support 	node_nameCallable[..., None]c                       fdd}|S )zV
    Return a function that raises a NotImplementedError with a passed node name.
    c                   s   t d  d)N'z' nodes are not implemented)NotImplementedError)selfr3   r4   rn   r"   r&   r6        z _node_not_implemented.<locals>.fr"   )rn   r6   r"   rt   r&   _node_not_implemented   s   rv   _Tnodesset[str]Callable[[type[_T]], type[_T]]c                   s   d fdd}|S )z
    Decorator to disallow certain nodes from parsing. Raises a
    NotImplementedError instead.

    Returns
    -------
    callable
    clstype[_T]r   c                   sB   d| _  D ]}t|}d| }|  j |f7  _ t| || q| S )Nr"   visit_)unsupported_nodesrv   setattr)r{   rU   
new_methodrW   rx   r"   r&   
disallowed  s   
zdisallow.<locals>.disallowedN)r{   r|   r   r|   r"   )rx   r   r"   r   r&   disallow  s   
r   c                   s    fdd}|S )zw
    Return a function to create an op class with its symbol already passed.

    Returns
    -------
    callable
    c                   s   t  g|R i |S )z
        Return a partial function with an Op subclass with an operator already passed.

        Returns
        -------
        callable
        )r   )rs   rU   r3   r4   op_class	op_symbolr"   r&   r6   .  s   z_op_maker.<locals>.fr"   )r   r   r6   r"   r   r&   	_op_maker%  s   	
r   )binaryunaryc                   rp   )z9
    Decorator to add default implementation of ops.
    c                   sl      D ]/\}}t| | d}t| | d}|D ]}|| }|d ur2t||}t| d| | qq| S )N_ops_op_nodes_mapr}   )itemsrV   r   r   )r{   op_attr_namer   opsops_mapopop_nodemade_op
op_classesr"   r&   r6   C  s   
zadd_ops.<locals>.fr"   )r   r6   r"   r   r&   add_ops>  s   r   c                   @  s  e Zd ZU dZeZded< eZded< e	e
 e ZdZeeeeZeZdZeeeeZejejejejejejejejiZded< efdFddZdd Zdd Zdd Zdd Z dGddZ!dd Z"dd Z#		dHddZ$d d! Z%d"d# Z&dId%d&Z'dId'd(Z(dId)d*Z)dId+d,Z*dId-d.Z+dId/d0Z,e,Z-d1d2 Z.dId3d4Z/dJd6d7Z0d8d9 Z1d:d; Z2dKd<d=Z3d>d? Z4d@dA Z5dBdC Z6dDdE Z7dS )LBaseExprVisitorz
    Custom ast walker. Parsers of other engines should subclass this class
    if necessary.

    Parameters
    ----------
    env : Scope
    engine : str
    parser : str
    preparser : callable
    zClassVar[type[Term]]
const_type	term_type)GtLtGtELtEEqNotEqInNotInBitAndBitOrAndOrAddSubMultDivPowFloorDivMod)UAddUSubInvertNotztuple[str, ...]r~   r   Nonec                 C  s"   || _ || _|| _|| _d | _d S r2   )envengineparser	preparserassignerrs   r   r   r   r   r"   r"   r&   __init__  s
   
zBaseExprVisitor.__init__c              
   K  s   t |tr1| |}z
tt|}W n ty0 } ztdd | D r*d|_	|d }~ww dt
|j }t| |}||fi |S )Nc                 s  s    | ]}t |V  qd S r2   r   rA   r"   r"   r&   rE     rF   z(BaseExprVisitor.visit.<locals>.<genexpr>z4Python keyword not valid identifier in numexpr queryr}   )rK   r@   r   rR   fix_missing_locationsparseSyntaxErroranysplitmsgrP   rX   rV   )rs   rU   r4   cleanemethodvisitorr"   r"   r&   visit  s   


zBaseExprVisitor.visitc                 K  s2   t |jdkrtd|jd }| j|fi |S )Nr;   z#only a single expression is allowedr   )r<   bodyr   r   )rs   rU   r4   exprr"   r"   r&   visit_Module  s   
zBaseExprVisitor.visit_Modulec                 K  s   | j |jfi |S r2   r   rL   rs   rU   r4   r"   r"   r&   
visit_Expr  s   zBaseExprVisitor.visit_Exprc                 C  s   |j }t|}t|rVt|rV|| jv rVtt||f\}}tt||f\}}	|s.|s.|s.|	r4| j|  }|	rE| j|j	g}
| 
|
| j}|rV| j|j	g}
| 
|
| j}| |}||||fS r2   )r   rP   r   rewrite_mapmap_is_list_is_strr   add_tmprL   r   r   )rs   rU   leftrightop_instanceop_type	left_list
right_listleft_str	right_strrW   r   r"   r"   r&   _rewrite_membership_op  s   
z&BaseExprVisitor._rewrite_membership_opNc                 C  sR   |d u r| j |jdd}|d u r| j |jdd}| |||\}}}}||||fS )Nr   )sider   )r   r   r   r   )rs   rU   r   r   r   r   r"   r"   r&   _maybe_transform_eq_ne  s   z&BaseExprVisitor._maybe_transform_eq_nec                 C  s   t t j}|jr't|dr'|js'|j|kr'| jt |j}| 	|| j}|jrHt|drH|jsH|j|krH| jt |j}| 	|| j}||fS )NrL   )
npdtypefloat32	is_scalarhasattrreturn_typer   r   rL   r   )rs   r   r   f32rW   r"   r"   r&   _maybe_downcast_constants  s(   

z)BaseExprVisitor._maybe_downcast_constantsc                 C  s   | | j| j| j| j|S r2   )evaluater   r   r   r   )rs   binopeval_in_pythonr"   r"   r&   _maybe_eval  s   zBaseExprVisitor._maybe_evalinznot inr!   z!=<>z<=z>=c                 C  s   |||}|j rtd|j d|j d|j d| jdkr6|jtv r)t|dds/t|ddr6| || jS |j|v rA| ||S | jdkr^t|dd t	ksVt|dd t	kr^| ||| S |S )	Nz unsupported operand type(s) for z: 'z' and 'rq   pytablesis_datetimeFr   )
has_invalid_return_type	TypeErrorr   rP   r   r   rV   r   
binary_opsobject)rs   r   r   lhsrhsr   maybe_eval_in_pythonresr"   r"   r&   _maybe_evaluate_binop  s.   
	






z%BaseExprVisitor._maybe_evaluate_binopc                 K  s2   |  |\}}}}| ||\}}| ||||S r2   )r   r   r   )rs   rU   r4   r   r   r   r   r"   r"   r&   visit_BinOp  s   zBaseExprVisitor.visit_BinOpc                 K  s    |  |j}|  |j}||S r2   )r   r   operand)rs   rU   r4   r   r   r"   r"   r&   visit_UnaryOp  s   zBaseExprVisitor.visit_UnaryOpr   c                 K  s   | j |j| jfi |S r2   )r   idr   r   r"   r"   r&   
visit_Name  s   zBaseExprVisitor.visit_Namec                 K     |  |j| jS r2   r   rL   r   r   r"   r"   r&   visit_NameConstant   ru   z"BaseExprVisitor.visit_NameConstantc                 K  r   r2   r   r   r"   r"   r&   	visit_Num$  ru   zBaseExprVisitor.visit_Numc                 K  r   r2   r   r   r"   r"   r&   visit_Constant'  ru   zBaseExprVisitor.visit_Constantc                 K  s   | j |j}| || j S r2   )r   r   sr   rs   rU   r4   rW   r"   r"   r&   	visit_Str+  s   zBaseExprVisitor.visit_Strc                   s*    j  fdd|jD } | j S )Nc                      g | ]
}  | jqS r"   r   r   )rB   r   rs   r"   r&   
<listcomp>0      z.BaseExprVisitor.visit_List.<locals>.<listcomp>)r   r   eltsr   r   r"   r  r&   
visit_List/  s   zBaseExprVisitor.visit_Listc                 K  s   |  |jS )zdf.index[4]r   r   r"   r"   r&   visit_Index5  s   zBaseExprVisitor.visit_Indexc           
   	   K  s   ddl m} | |j}| |j}||| j| j| jd}z|j| }W n ty<   ||| j| j| jd}|| }Y nw | j	|}	| j
|	| jdS )Nr   )eval)
local_dictr   r   )r   )pandasr
  r   rL   slicer   r   r   AttributeErrorr   r   )
rs   rU   r4   pd_evalrL   slobjresultvr   rW   r"   r"   r&   visit_Subscript9  s    zBaseExprVisitor.visit_Subscriptr  c                 K  sZ   |j }|dur| |j}|j}|dur| |j}|j}|dur'| |j}t|||S )zdf.index[slice(4,6)]N)lowerr   rL   upperstepr  )rs   rU   r4   r  r  r  r"   r"   r&   visit_SliceM  s   zBaseExprVisitor.visit_Slicec                 K  s   t |jdkrtdt|jd tjstd| jjdu r"tdz| j	|jd fi |}W n t
y?   |jd j}Y nw t|d|| _| jdu rPtd| j	|jfi |S )	z
        support a single assignment node, like

        c = a + b

        set the assigner at the top level, must be a Name node which
        might or might not exist in the resolvers

        r;   z#can only assign a single expressionr   z5left hand side of an assignment must be a single nameNz%cannot assign without a target objectrW   z@left hand side of an assignment must be a single resolvable name)r<   targetsr   rK   rR   Namer   target
ValueErrorr   r
   r   rV   r   rL   )rs   rU   r4   r   r"   r"   r&   visit_Assign[  s"   

zBaseExprVisitor.visit_Assignc           	      K  s   |j }|j}|j}t|tjr@| |j}zt||}| j	|}| 
|| jW S  ty?   t|tjr>|j|kr>| Y S  w tdt|j )NzInvalid Attribute context )attrrL   ctxrK   rR   Loadr   rV   r   r   r   r  r  r   r  rP   rX   )	rs   rU   r4   r  rL   r  resolvedr  rW   r"   r"   r&   visit_Attributey  s   
zBaseExprVisitor.visit_Attributec                   sp  t |jtjr|jjdkr |j}n.t |jtjstdz |j}W n t	yA   zt
|jj}W n ty>    w Y nw |d u rOtd|jj t|drW|j}t |t
rv fdd|jD }|jrrtd|j d|| S  fd	d|jD }|jD ]!}t |tjstd
|jj d|jr |j j||j< q j||i |} j| jdS )N__call__z"Only named functions are supportedzInvalid function call rL   c                   s   g | ]}  |qS r"   )r   rB   argr  r"   r&   r    s    z.BaseExprVisitor.visit_Call.<locals>.<listcomp>z
Function "z$" does not support keyword argumentsc                   r  r"   r  r#  r  r"   r&   r    r  z keyword error in function call 'rq   )rW   r   )rK   funcrR   	Attributer  r!  r  r   r   r
   r   r   r  r   rL   r3   keywordsrW   keywordr$  r   r   r   )rs   rU   r   r4   r   new_argskeyrW   r"   r  r&   
visit_Call  sP   


zBaseExprVisitor.visit_Callc                 C  s   |S r2   r"   )rs   r   r"   r"   r&   translate_In  s   zBaseExprVisitor.translate_Inc              	   K  s   |j }|j}t|dkr#| |d }tj||j|d d}| |S |j}g }t||D ]\}}	| tj	|	g|| |gd}
|	}|
|
 q-| tjt |dS )Nr;   r   )r   r   r   )comparatorsr   r   )r   values)r   r-  r<   r,  rR   r   r   r   zipCompareappendBoolOpr   )rs   rU   r4   r   compsr   r   r   r.  compnew_noder"   r"   r&   visit_Compare  s   
zBaseExprVisitor.visit_Comparec                 C  s   t |ttfr	|S | |S r2   )rK   r   r   r   )rs   bopr"   r"   r&   _try_visit_binop  s   
z BaseExprVisitor._try_visit_binopc                   s    fdd} j }t||S )Nc                   s<    | } |} ||\}}}}| j||S r2   )r8  r   r   r   )rC   yr   r   r   r   rU   rs   r"   r&   r     s   

z-BaseExprVisitor.visit_BoolOp.<locals>.visitor)r.  r   )rs   rU   r4   r   operandsr"   r:  r&   visit_BoolOp  s   
zBaseExprVisitor.visit_BoolOpr   r   )NN)r   r   )r   r   )r   r  r2   )8rX   
__module____qualname____doc__r   r   __annotations__r   r   r   r   r   r   binary_op_nodesdictr/  binary_op_nodes_mapr   	unary_opsunary_op_nodesunary_op_nodes_maprR   r   r   r   r   r   rJ   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  visit_Tupler	  r  r  r  r!  r+  r,  r6  r8  r<  r"   r"   r"   r&   r   Q  s\   
 

'








3r   )Dictr2  r   r   )r2  r&  r   r   Tuplec                      s2   e Zd Zeeeeeedfd fddZ	  Z
S )PandasExprVisitorrD   r   r   c                   s   t  |||| d S r2   superr   r   	__class__r"   r&   r     s   
zPandasExprVisitor.__init__r=  )rX   r>  r?  r   rJ   r>   r1   r/   r   r   __classcell__r"   r"   rN  r&   rK    s    

rK  r   c                      s(   e Zd Zdddfd	 fddZ  ZS )
PythonExprVisitorNc                 C  s   | S r2   r"   rI   r"   r"   r&   r8     s    zPythonExprVisitor.<lambda>r   r   c                   s   t  j||||d d S )N)r   rL  r   rN  r"   r&   r     s   zPythonExprVisitor.__init__r2   r=  )rX   r>  r?  r   rP  r"   r"   rN  r&   rQ    s    rQ  c                   @  sz   e Zd ZU dZded< ded< ded< 					
ddddZedd Zdd Zd ddZ	d!ddZ
dd Zedd Zd	S )"rc   a  
    Object encapsulating an expression.

    Parameters
    ----------
    expr : str
    engine : str, optional, default 'numexpr'
    parser : str, optional, default 'pandas'
    env : Scope, optional, default None
    level : int, optional, default 2
    r   r   r@   r   r   numexprr  Nr   Scope | Nonelevelintr   r   c                 C  sL   || _ |pt|d d| _|| _|| _t| | j| j| j| _|  | _d S )Nr;   )rT  )	r   r   r   r   r   PARSERS_visitorr   terms)rs   r   r   r   r   rT  r"   r"   r&   r     s   zExpr.__init__c                 C  s   t | jdd S )Nr   )rV   rW  r  r"   r"   r&   r   '  s   zExpr.assignerc                 C  s   |  | jS r2   )rX  r   r  r"   r"   r&   r"  +     zExpr.__call__c                 C  s   t | jS r2   )r   pprint_thingrX  r  r"   r"   r&   __repr__.  rY  zExpr.__repr__c                 C  s
   t | jS r2   )r<   r   r  r"   r"   r&   __len__1  s   
zExpr.__len__c                 C  s   | j | jS )z&
        Parse an expression.
        )rW  r   r   r  r"   r"   r&   r   4  r:   z
Expr.parsec                 C  s2   t | jrt| jjgS tdd t| jD S )z1
        Get the names in an expression.
        c                 s  r_   r2   )rW   )rB   termr"   r"   r&   rE   A  r`   zExpr.names.<locals>.<genexpr>)r   rX  r[   rW   comflattenr  r"   r"   r&   names:  s   
z
Expr.names)rR  r  Nr   )
r   r@   r   r@   r   rS  rT  rU  r   r   )r   r@   )r   rU  )rX   r>  r?  r@  rA  r   propertyr   r"  r[  r\  r   r`  r"   r"   r"   r&   rc     s$   
 


rc   )pythonr  )r   r   r   r   )r?   r@   r   r@   )rn   r@   r   ro   )rx   ry   r   rz   )ir@  
__future__r   rR   	functoolsr   r   r(  r   r,   typingr   r   r	   numpyr   pandas.errorsr
   pandas.core.commoncorecommonr^  pandas.core.computation.opsr   r   r   r   r   r   r   r   r   r   r   r   r   r   pandas.core.computation.parsingr   r   pandas.core.computation.scoper   pandas.io.formatsr   r'   r/   r1   r9   r>   rJ   rO   listr   r@   r   r[   dir
_all_nodesr^   _all_node_namesmod
_mod_nodesstmt_stmt_nodesr   _expr_nodesexpr_context_expr_context_nodesboolop_boolop_nodesoperator_operator_nodesunaryop_unary_op_nodescmpop_cmp_op_nodescomprehension_comprehension_nodesexcepthandler_handler_nodes	arguments_arguments_nodes_keyword_nodesalias_alias_nodes_hacked_nodes_unsupported_expr_nodes_unsupported_nodes_base_supported_nodesintersection_msgrv   rw   r   r   _op_classesr   NodeVisitorr   _python_not_supported_numexpr_supported_callsrK  rQ  rc   rV  r"   r"   r"   r&   <module>   s    @



"
















   =