U
    di                  
   @   s<  d dl Z d dlZd dlZd dlmZ d dlmZ d dlmZm	Z	m
Z
mZmZ d dlZddlmZ e rnd dlZG dd deZd	d
 eeD Zddddddddddg
Zd\aZd\aZG dd deZG dd deZG dd deZdd Z dd  Z!d!d" Z"d#d$ Z#d%d& Z$d'd( Z%d)d* Z&d+d, Z'd-d. Z(d/d0 Z)d1d2 Z*d3d4 Z+d5d6 Z,d7d8 Z-d9d: Z.d;d< Z/d=d> Z0d?d@ Z1dAdB Z2dCdD Z3dEdF Z4dGdH Z5dIdJ Z6dKdL Z7dMdN Z8dOdP Z9efe j:e
e;ef e
e;e	f e
e;e	f ee; dQdRdSZ<dddefe;ee
e;e	f  ee
e;e	f  ee
e;ef  ee; dTdUdVZ=dS )W    N)Mapping)import_module)AnyCallableDictListOptional   )is_pandas_availablec                   @   s   e Zd ZdZdS )InterpreterErrorz
    An error raised when the interpretor cannot evaluate a Python expression, due to syntax error or unsupported
    operations.
    N)__name__
__module____qualname____doc__ r   r   J/tmp/pip-unpacked-wheel-bm_b0l5e/transformers/agents/python_interpreter.pyr   !   s   r   c                 C   s8   i | ]0}t tt|trttt|tr|tt|qS r   )
isinstancegetattrbuiltinstype
issubclassBaseException).0namer   r   r   
<dictcomp>*   s
     r   randomcollectionsmathtimequeue	itertoolsrestatZ
statisticsunicodedata) iP  )r   i c                   @   s   e Zd ZdS )BreakExceptionNr   r   r   r   r   r   r   r%   B   s   r%   c                   @   s   e Zd ZdS )ContinueExceptionNr&   r   r   r   r   r'   F   s   r'   c                   @   s   e Zd Zdd ZdS )ReturnExceptionc                 C   s
   || _ d S N)value)selfr*   r   r   r   __init__K   s    zReturnException.__init__N)r   r   r   r,   r   r   r   r   r(   J   s   r(   c                 C   s,   t | tr| S t| dr t| S tdd S )N__iter__zObject is not iterable)r   listhasattrr   )objr   r   r   get_iterableO   s
    

r1   c                 C   sx   t | j|||}t| jtjr$| S t| jtjr6|S t| jtjrJ| S t| jtjr^| S t	d| jj
j dd S )NzUnary operation  is not supported.)evaluate_astoperandr   opastZUSubZUAddZNotZInvertr   	__class__r   )
expressionstatestatic_toolscustom_toolsr4   r   r   r   evaluate_unaryopX   s    r<   c                    s*   dd j j D   fdd}|S )Nc                 S   s   g | ]
}|j qS r   argr   r>   r   r   r   
<listcomp>g   s     z#evaluate_lambda.<locals>.<listcomp>c                     s4     }t | D ]\}}|||< qtj|S r)   )copyzipr3   body)values	new_stater>   r*   argsr;   lambda_expressionr9   r:   r   r   lambda_funci   s    
z$evaluate_lambda.<locals>.lambda_func)rG   )rH   r9   r:   r;   rI   r   rF   r   evaluate_lambdaf   s    rJ   c              	   C   s   d}d}t | j|||r| jD ]H}zt |||| W q tk
rL   Y  d S  tk
rd   Y  qhY qX q|d7 }||krtd| dqd S )Ni  r      zMaximum number of z" iterations in While loop exceeded)r3   testrC   r%   r'   r   )Z
while_loopr9   r:   r;   Zmax_iterationsZ
iterationsnoder   r   r   evaluate_whiler   s    
rN   c                    s    fdd}|S )Nc               
      sn    }dd jjD } fddjjD }tt|t| d  |}t|| D ]\}}|||< qZ| D ]\}}|||< qtjjrjjj}| ||< jj	rjj	j}	|||	< | D ]\}}||kr|||< qjjrjjd jdkr| r| d |d< | d j
|d< d }
z jD ]}t|| }
q&W n* tk
rh } z
|j}
W 5 d }~X Y nX |
S )Nc                 S   s   g | ]
}|j qS r   r=   r?   r   r   r   r@      s     z5create_function.<locals>.new_func.<locals>.<listcomp>c                    s   g | ]}t | qS r   r3   )r   dr;   r9   r:   r   r   r@      s     r   r+   r7   )rA   rG   defaultsdictrB   lenitemsvarargr>   kwargr7   rC   r3   r(   r*   )rG   kwargsZ
func_state	arg_namesZdefault_valuesrR   r   r*   Zvararg_nameZ
kwarg_nameresultstmter;   func_defr9   r:   r   r   new_func   s8    





z!create_function.<locals>.new_funcr   )r^   r9   r:   r;   r_   r   r]   r   create_function   s    ,r`   c                 C   s.   i }|  D ]\}}|||< qt| t||S r)   )rU   r   tuple)
class_nameclass_basesZ
class_body
class_dictkeyr*   r   r   r   create_class   s    
rf   c                 C   s   t | ||||| j< || j S r)   )r`   r   )r^   r9   r:   r;   r   r   r   evaluate_function_def   s    rg   c           
         s   | j } fdd| jD }i }| jD ]}t|tjrNt| ||j < q(t|tjr|jD ]J}t|tj	rt
|j ||j< q`t|tjr`t
|j ||j< q`q(td|jj q(t|t||}	|	|< |	S )Nc                    s   g | ]}t | qS r   rO   )r   baserQ   r   r   r@      s     z&evaluate_class_def.<locals>.<listcomp>z%Unsupported statement in class body: )r   basesrC   r   r6   FunctionDefrg   AssigntargetsNamer3   r*   id	Attributeattrr   r7   r   r   ra   )
Z	class_defr9   r:   r;   rb   ri   rd   r[   target	new_classr   rQ   r   evaluate_class_def   s     

rs   c                    s   fdd| j }t| j }t| jtjrtt|trht|ts^td| d|| }n|| }n.t| jtj	r|| }nt| jtj
r|| }nt| jtjr|| }nt| jtjr|| }nt| jtjr|| }nt| jtjr|| }nt| jtjr"||@ }nt| jtjr<||B }nft| jtjrV||A }nLt| jtjrp||> }n2t| jtjr||? }ntdt| jj dt| j |  |S )Nc                    s   t | tjr| jdS t | tjrNt| j }t| j }|| S t | tj	rvt| j }t
|| jS t | tjrtfdd| jD S t | tjrfdd| jD S tdd S )Nr   c                 3   s   | ]} |V  qd S r)   r   r   eltget_current_valuer   r   	<genexpr>   s     z@evaluate_augassign.<locals>.get_current_value.<locals>.<genexpr>c                    s   g | ]} |qS r   r   rt   rv   r   r   r@      s     zAevaluate_augassign.<locals>.get_current_value.<locals>.<listcomp>z3AugAssign not supported for {type(target)} targets.)r   r6   rm   getrn   	Subscriptr3   r*   slicero   r   rp   Tuplera   eltsr   r   )rq   r0   re   r;   rw   r9   r:   r   r   rw      s    z-evaluate_augassign.<locals>.get_current_valuezCannot add non-list value z to a list.z
Operation r2   )rq   r3   r*   r   r5   r6   Addr.   r   SubMultDivModPowFloorDivBitAndBitOrBitXorLShiftRShiftr   r   	set_value)r8   r9   r:   r;   Zcurrent_valueZvalue_to_addZupdated_valuer   r~   r   evaluate_augassign   sD    













r   c                 C   sh   t | jtjr2| jD ]}t||||s dS qdS t | jtjrd| jD ]}t||||rF dS qFdS d S NFT)r   r5   r6   AndrD   r3   Or)rM   r9   r:   r;   r*   r   r   r   evaluate_boolop  s    

r   c                 C   sJ  t | j|||}t | j|||}t| jtjr6|| S t| jtjrL|| S t| jtjrb|| S t| jtj	rx|| S t| jtj
r|| S t| jtjr|| S t| jtjr|| S t| jtjr||@ S t| jtjr||B S t| jtj r||A S t| jtjr||> S t| jtjr.||? S tdt| jj dd S )NzBinary operation z is not implemented.)r3   leftrightr   r5   r6   r   r   r   r   r   r   r   r   r   r   r   r   NotImplementedErrorr   r   )Zbinopr9   r:   r;   Zleft_valZ	right_valr   r   r   evaluate_binop  s6    r   c           	      C   s   t | j|||}t| jdkr:| jd }t||||| nt| jt|krltdt| dt| j dg }| jD ]&}t|tjr|	| qv|
| qvt| j|D ]\}}t||||| q|S )NrK   r   zAssign failed: expected z values but got .)r3   r*   rT   rl   r   r   r   r6   StarredextendappendrB   )	Zassignr9   r:   r;   rZ   rq   Zexpanded_valuesZtgtvalr   r   r   evaluate_assignA  s    
 
r   c           	      C   s  t | tjr4| j|kr(td| j d||| j< nt | tjrt |tstt|drlt |tt	fslt|}ntdt
| jt
|krtdt| jD ]\}}t||| ||| qnbt | tjrt| j|||}t| j|||}|||< n,t | tjrt| j|||}t|| j| d S )NzCannot assign to name 'z,': doing this would erase the existing tool!r-   zCannot unpack non-tuple valuez!Cannot unpack tuple of wrong size)r   r6   rm   rn   r   r|   ra   r/   strbytesrT   r}   	enumerater   rz   r3   r*   r{   ro   setattrrp   )	rq   r*   r9   r:   r;   ielemr0   re   r   r   r   r   T  s(    



r   c                    s  t | jtjs.t | jtjs.td| j dt | jtjrt| jj }| jj}t	||sttd| d| t
||}nrt | jtjr| jj}|kr| }nJ|kr| }n8| kr̈ | }n&|tkrt| }ntd| jj dg }| jD ]>}t |tjr&|t|j  q|t|  qg }| jD ]n}t |tjrt|j }	t	|	drt |	ttfrtd|	 ||	 n|t|  qF fdd	| jD }
t |trt|jd
dkr||}t	|dr|j||
 |S |dkr|sTdkrLdkrLtd d S td|d }t |tsptdt|dkrt|S t|dkr|d }t||S tdn8|dkrdtt|}t|d 7 ad S |||
}|S d S )Nz This is not a correct function: z).zObject z has no attribute zIt is not permitted to evaluate other functions than the provided tools or functions defined in previous code (tried to execute r-   z!Cannot unpack non-iterable value c                    s    i | ]}|j t|j qS r   )r>   r3   r*   )r   keywordrQ   r   r   r     s      z!evaluate_call.<locals>.<dictcomp>r   rK   r,   superr7   r+   z#super() needs at least one argumentr   zsuper() argument 1 must be typer	   z!super() takes at most 2 argumentsprint 
)r   funcr6   ro   rm   r   r3   r*   rp   r/   r   rn   ERRORSrG   r   r   r   r   r   keywordsr   rT   r   split__new__r,   r   joinmapPRINT_OUTPUTS)callr9   r:   r;   r0   	func_namer   rG   r>   unpackedrX   clsinstanceoutputr   rQ   r   evaluate_calll  sx    






"





r   c                 C   s  t | j|||}t | j|||}t|tr<t|tr<tdt|tjjj	r\|j
}|j| S t|tjtjtjfrz|| S t|tjjjjr|| S t|tr|| S t|ttf rt| |  krt|k sn td| dt| |t| S t|trJt| |  kr(t|k sBn td| dt| || S ||kr\|| S t|trt|trt|t| }t|dkr||d  S td| d| dd S )	NzLYou're trying to subscript a string with a string index, which is impossiblezIndex z" out of bounds for list of length z$ out of bounds for string of length r   zCould not index z with 'z'.)r3   r{   r*   r   r   r   pdcoreZindexingZ_LocIndexerr0   locZ	DataFrameSeriesnpZndarraygroupbyZgenericZDataFrameGroupByr.   ra   rT   intr   difflibget_close_matcheskeys)Z	subscriptr9   r:   r;   indexr*   Zparent_objectclose_matchesr   r   r   evaluate_subscript  s8    

 $
r   c                 C   s   | j |kr|| j  S | j |kr(|| j  S | j tkr<t| j  S t| j t| }t|dkrj||d  S td| j  dd S )Nr   zThe variable `z` is not defined.)rn   r   r   r   r.   r   rT   r   )r   r9   r:   r;   r   r   r   r   evaluate_name  s    





r   c                    sn  t | j } fdd| jD }dd | jD }d}|}t||D ]\}	}
|	tjkrh||
k}n|	tjkr|||
k}n|	tjkr||
k }n|	tj	kr||
k}n|	tj
kr||
k}nv|	tjkr||
k}nb|	tjkr||
k}nN|	tjkr||
k	}n:|	tjkr
||
k}n$|	tjkr ||
k}ntd|	 ||@ }|
}t|trJ|sJ qPqJt|ttjfrf|S | S )Nc                    s   g | ]}t | qS r   rO   )r   crQ   r   r   r@     s     z&evaluate_condition.<locals>.<listcomp>c                 S   s   g | ]}t |qS r   )r   )r   r5   r   r   r   r@     s     TzOperator not supported: )r3   r   comparatorsopsrB   r6   ZEqZNotEqZLtZLtEZGtZGtEZIsZIsNotZInZNotInr   r   boolr   r   all)	conditionr9   r:   r;   r   r   r   rZ   Zcurrent_leftr5   Z
comparatorZcurrent_resultr   rQ   r   evaluate_condition  s@    

















r   c                 C   sj   d }t | j|||}|r@| jD ]}t ||||}|d k	r|}qn&| jD ]}t ||||}|d k	rF|}qF|S r)   )r3   rL   rC   orelse)Zif_statementr9   r:   r;   rZ   test_resultlineline_resultr   r   r   evaluate_if  s    

r   c           	   
   C   s   d }t | j|||}|D ]x}t| j|||| | jD ]T}zt ||||}|d k	rT|}W q4 tk
rp   Y  qY q4 tk
r   Y q4Y q4X q4q qq|S r)   )r3   iterr   rq   rC   r%   r'   )	Zfor_loopr9   r:   r;   rZ   iteratorcounterrM   r   r   r   r   evaluate_for!  s     

r   c                    s     fddj d|S )Nc           	         s   |t | krtj|gS | | }t|j|}g }|D ]~}|  t|jtjr~t	|jj
D ]\}}||  |j< qdn| |jj< t fdd|jD r>|| |d   q>|S )Nc                 3   s   | ]}t | V  qd S r)   rO   r   Z	if_clauser;   rE   r:   r   r   rx   C  s     z<evaluate_listcomp.<locals>.inner_evaluate.<locals>.<genexpr>rK   )rT   r3   ru   r   rA   r   rq   r6   r|   r   r}   rn   r   ifsr   )	
generatorsr   Zcurrent_state	generator
iter_valuerZ   r*   idxr   r;   inner_evaluatelistcompr:   )rE   r   r   6  s    z)evaluate_listcomp.<locals>.inner_evaluater   )r   )r   r9   r:   r;   r   r   r   evaluate_listcomp5  s    r   c                 C   s   zz| jD ]}t|||| q
W n tk
r } znd}| jD ]V}|jd ks`t|t|j|||r<d}|jrt|||j< |jD ]}t|||| qz qq<|s|W 5 d }~X Y n"X | jr| jD ]}t|||| qW 5 | j r| j D ]}t|||| qX d S r   )	Z	finalbodyr3   rC   	Exceptionhandlersr   r   r   r   )Ztry_noder9   r:   r;   r[   r\   matchedhandlerr   r   r   evaluate_tryJ  s*    

 



r   c                 C   sj   | j d k	rt| j |||}nd }| jd k	r<t| j|||}nd }|d k	r^|d k	rX||qf|ntdd S )Nz5Re-raise is not supported without an active exception)excr3   causer   )Z
raise_noder9   r:   r;   r   r   r   r   r   evaluate_raised  s    

r   c                 C   sR   t | j|||}|sN| jr4t | j|||}t|nt| j}td| d S )NzAssertion failed: )r3   rL   msgAssertionErrorr6   Zunparse)Zassert_noder9   r:   r;   r   r   Z	test_coder   r   r   evaluate_assertv  s    
r   c              
   C   s   g }| j D ]P}t|j|||}|jrH| ||jj< |||jj  q
| }|| q
z| jD ]}t|||| qdW nF tk
r }	 z(t	|D ]}
|

t|	|	|	j q W 5 d }	~	X Y nX t	|D ]}
|

d d d  qd S r)   )rU   r3   context_exprZoptional_vars	__enter__rn   r   rC   r   reversed__exit__r   __traceback__)Z	with_noder9   r:   r;   Zcontextsitemr   Zcontext_varr[   r\   contextr   r   r   evaluate_with  s"    

r   c                    s    fdd}t | tjrh| jD ]D}||jrHt|j}|||jpD|j< qtd|j dt  qd S t | tj	r|| j
rt| j
dd | jD d}| jD ]}t||j||jp|j< qntd| j
 d	d S d S )
Nc                    s@   |  d  fddtdt d D }tfdd|D S )Nr   c                    s   g | ]}d   d| qS )r   N)r   )r   r   module_pathr   r   r@     s     zCimport_modules.<locals>.check_module_authorized.<locals>.<listcomp>rK   c                 3   s   | ]}| kV  qd S r)   r   )r   subpathauthorized_importsr   r   rx     s     zBimport_modules.<locals>.check_module_authorized.<locals>.<genexpr>)r   rangerT   any)module_nameZmodule_subpathsr   r   r   check_module_authorized  s    
 z/import_modules.<locals>.check_module_authorizedz
Import of z) is not allowed. Authorized imports are: c                 S   s   g | ]
}|j qS r   )r   )r   aliasr   r   r   r@     s     z"import_modules.<locals>.<listcomp>)fromlistzImport from z is not allowed.)r   r6   Importnamesr   r   Zasnamer   r   
ImportFrommodule
__import__r   )r8   r9   r   r   r   r   r   r   r   import_modules  s"    




r  c           
         s   i }| j D ]|}t|j| }|D ]b}| t|j|  t fdd|jD r"t| j }t| j	 }	|	||< q"q
|S )Nc                 3   s   | ]}t | V  qd S r)   rO   r   r   r   r   rx     s     z$evaluate_dictcomp.<locals>.<genexpr>)
r   r3   r   rA   r   rq   r   r   re   r*   )
dictcompr9   r:   r;   rZ   genr   r*   re   r   r   r   r   evaluate_dictcomp  s    
r  )r8   r9   r:   r;   r   c           	         s`  t tkrtdt dt d7 a t| tjr:t|  S t| tjrTt|  S t| tj	rnt
|  S t| tjr| jS t| tjrt fdd| jD S t| tjtjfrt|  S t| tjrt|  S t| tjr t| j S t| tjrt|  S t| tjr4t n(t| tjrLt nt| tjrht|  S t| tjrt |  S t| tj!rt"|  S t| tj#rt$|  S t| tj%r fdd| j&D } fdd| j'D }t(t)||S t| tj*r&t| j S t| tj+rBt,|  S t| tj-r`t| j S t| tj.r|t/|  S t0td	rt| tj1rt| j S t| tj2rd
3 fdd| j'D S t| tj4r fdd| jD S t| tj5rt6|  S t| tj7r0t8|  S t| tj9rxt| j: }|rdt| j; S t| j< S nt| tj=rt| j }t>|| j?S t| tj@rtA| jBdk	rt| jB nd| jCdk	rt| jC nd| jDdk	r
t| jD ndS t| tjEr,tF|  S t| tjGrHtH|  S t| tjItjJfrhtK| |S t| tjLrtM|  S t| tjNrtO|  S t| tjPrtQ|  S t| tjRrtS|  S t| tjTrtU|  S t| tjVr fdd| jD S t| tjWrJtX| jrBt| j ndnt| jYjZ ddS )a   
    Evaluate an abstract syntax tree using the content of the variables stored in a state and only evaluating a given
    set of functions.

    This function will recurse trough the nodes of the tree provided.

    Args:
        expression (`ast.AST`):
            The code to evaluate, as an abstract syntax tree.
        state (`Dict[str, Any]`):
            A dictionary mapping variable names to values. The `state` is updated if need be when the evaluation
            encounters assignements.
        static_tools (`Dict[str, Callable]`):
            Functions that may be called during the evaluation. Trying to change one of these static_tools will raise an error.
        custom_tools (`Dict[str, Callable]`):
            Functions that may be called during the evaluation. These static_tools can be overwritten.
        authorized_imports (`List[str]`):
            The list of modules that can be imported by the code. By default, only a few safe modules are allowed.
            Add more at your own risk!
    z(Reached the max number of operations of ze. Maybe there is an infinite loop somewhere in the code, or you're just asking too many calculations.rK   c                 3   s   | ]}t | V  qd S r)   rO   rt   rQ   r   r   rx     s     zevaluate_ast.<locals>.<genexpr>c                    s   g | ]}t | qS r   rO   )r   krQ   r   r   r@   	  s     z evaluate_ast.<locals>.<listcomp>c                    s   g | ]}t | qS r   rO   r   vrQ   r   r   r@   
  s     Indexr$   c                    s   g | ]}t t| qS r   )r   r3   r  rQ   r   r   r@     s     c                    s   g | ]}t | qS r   rO   rt   rQ   r   r   r@     s     Nc                    s   h | ]}t | qS r   rO   rt   rQ   r   r   	<setcomp>I  s     zevaluate_ast.<locals>.<setcomp>r2   )[OPERATIONS_COUNTMAX_OPERATIONSr   r   r6   rk   r   Z	AugAssignr   ZCallr   Constantr*   r|   ra   r}   ZListCompZGeneratorExpr   ZUnaryOpr<   r   r3   ZBoolOpr   ZBreakr%   Continuer'   ZBinOpr   ZComparer   LambdarJ   rj   rg   r   r   rD   rS   rB   ZExprZForr   ZFormattedValueZIfr   r/   r  Z	JoinedStrr   r   rm   r   rz   r   ZIfExprL   rC   r   ro   r   rp   ZSlicer{   lowerupperstepZDictCompr  ZWhilerN   r   r   r  ZClassDefrs   ZTryr   ZRaiser   ZAssertr   ZWithr   SetZReturnr(   r7   r   )	r8   r9   r:   r;   r   r   rD   Ztest_valr*   r   rQ   r   r3     s    


	r3   )coder:   r;   r9   r   c           
      C   sf  zt | }W n0 tk
r> } ztd| W 5 d}~X Y nX |dkrLi }|dkrXi }|dkrdi }d}dada|jD ]}zzt|||||}W n t	k
r$ } ztd}	ttdkrtttk r|	dt d	7 }	n|	dtdt  dt d
7 }	|	dt 
| | d| 7 }	t	|	W 5 d}~X Y nX W 5 tttk rBt|d< ntdt dt d |d< X qv|S )a  
    Evaluate a python expression using the content of the variables stored in a state and only evaluating a given set
    of functions.

    This function will recurse through the nodes of the tree provided.

    Args:
        code (`str`):
            The code to evaluate.
        static_tools (`Dict[str, Callable]`):
            The functions that may be called during the evaluation.
            These tools cannot be overwritten in the code: any assignment to their name will raise an error.
        custom_tools (`Dict[str, Callable]`):
            The functions that may be called during the evaluation.
            These tools can be overwritten in the code: any assignment to their name will overwrite them.
        state (`Dict[str, Any]`):
            A dictionary mapping variable names to values. The `state` should contain the initial inputs but will be
            updated by this function to contain all variables as they are evaluated.
            The print outputs will be stored in the state under the key 'print_outputs'.
    z.The code generated by the agent is not valid.
Nr$   r   Zprint_outputsz
_Print outputs were over z* characters, so they have been truncated._zPrint outputs:
z
====
z0 characters, so they have been truncated._
====
z.EXECUTION FAILED:
Evaluation stopped at line 'z"' because of the following error:
)r6   parseSyntaxErrorr   r
  rC   rT   MAX_LEN_OUTPUTr3   r   Zget_source_segment)
r  r:   r;   r9   r   r8   r\   rZ   rM   r   r   r   r   evaluate_python_codeS  s>     




r  )>r6   r   r   collections.abcr   	importlibr   typingr   r   r   r   r   Znumpyr   utilsr
   Zpandasr   
ValueErrorr   dirr   ZLIST_SAFE_MODULESr   r  r
  r  r   r%   r'   r(   r1   r<   rJ   rN   r`   rf   rg   rs   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  ASTr   r3   r  r   r   r   r   <module>   s   		0="O )


 