B
     \+                 @   s   d dl mZmZmZmZmZ d dlmZ ddlm	Z	 G dd de
Zeedd Zd	d
 Zdd ZG dd deZe ZG dd deZe ZG dd deZe Zdd Zdd Zdd ZdS )    )irir_utilstypeserrorssigutils)typeof_impl   )find_region_inout_varsc               @   s,   e Zd ZdZdZdd Zdd Zdd Zd	S )
WithContextzXA dummy object for use as contextmanager.
    This can be used as a contextmanager.
    Fc             C   s   d S )N )selfr   r   1lib/python3.7/site-packages/numba/withcontexts.py	__enter__   s    zWithContext.__enter__c             C   s   d S )Nr   )r   typvaltbr   r   r   __exit__   s    zWithContext.__exit__c             C   s   t dS )a  Mutate the *blocks* to implement this contextmanager.

        Parameters
        ----------
        func_ir : FunctionIR
        blocks : dict[ir.Block]
        blk_start, blk_end : int
            labels of the starting and ending block of the context-maanger.
        body_block: sequence[int]
            A sequence of int's representing labels of the with-body
        dispatcher_factory : callable
            A callable that takes a `FunctionIR` and returns a `Dispatcher`.
        N)NotImplementedError)r   func_irblocks	blk_startblk_endbody_blocksdispatcher_factoryextrar   r   r   mutate_with_body   s    zWithContext.mutate_with_bodyN)__name__
__module____qualname____doc__is_callabler   r   r   r   r   r   r   r
      s
   r
   c             C   s
   t | S )N)r   ZContextManager)r   cr   r   r   typeof_contextmanager$   s    r"   c             C   s   |  ds| dd S dS )z.Get parent of the variable given its name
    $.r   N)
startswithsplit)namer   r   r   _get_var_parent)   s    
r(   c             C   s   x|D ]
}| |= qW dS )z-Remove keys in *to_clear* from *blocks*.
    Nr   )r   Zto_clearbr   r   r   _clear_blocks2   s    
r*   c               @   s   e Zd ZdZdd ZdS )_ByPassContextTypez_A simple context-manager that tells the compiler to bypass the body
    of the with-block.
    c       
         sp   |d kst |j}dd |j| D  dd |j| D  fddttD }	t||||	 t|| d S )Nc             S   s   i | ]}|t |qS r   )r(   ).0kr   r   r   
<dictcomp>B   s    z7_ByPassContextType.mutate_with_body.<locals>.<dictcomp>c             S   s   i | ]}|t |qS r   )r(   )r,   r-   r   r   r   r.   C   s    c                s   i | ]}|  | qS r   r   )r,   r-   )inmapoutmapr   r   r.   D   s    )AssertionErrorvariable_lifetimelivemapfilterbool_bypass_with_contextr*   )
r   r   r   r   r   r   r   r   vltforwardvarsr   )r/   r0   r   r   =   s    z#_ByPassContextType.mutate_with_bodyN)r   r   r   r   r   r   r   r   r   r+   9   s   r+   c               @   s   e Zd ZdZdd ZdS )_CallContextTypezqA simple context-manager that tells the compiler to lift the body of the
    with-block as another function.
    c                s   |d kst |j}t |j||t|d\}	}
 fdd|D }t||||	|
 |j|t|	t|	dd}||}t	| |||	|
}| |< t
 | |S )N)r   r3   callfromreturntobody_block_idsc                s   i | ]} | |qS r   r   )r,   r-   )r   r   r   r.   ^   s    z5_CallContextType.mutate_with_body.<locals>.<dictcomp>T)r   	arg_names	arg_countforce_non_generator)r1   r2   r	   r3   set_mutate_with_block_calleederivetuplelen_mutate_with_block_callerr*   )r   r   r   r   r   r   r   r   r7   inputsoutputslifted_blks	lifted_ir
dispatchernewblkr   )r   r   r   Q   s,    
z!_CallContextType.mutate_with_bodyN)r   r   r   r   r   r   r   r   r   r9   M   s   r9   c               @   s,   e Zd ZdZdZdd Zdd Zdd Zd	S )
_ObjModeContextTypea  Creates a contextmanager to be used inside jitted functions to enter
    *object-mode* for using interpreter features.  The body of the with-context
    is lifted into a function that is compiled in *object-mode*.  This
    transformation process is limited and cannot process all possible
    Python code.  However, users can wrap complicated logic in another
    Python function, which will then be executed by the interpreter.

    Use this as a function that takes keyword arguments only.
    The argument names must correspond to the output variables from the
    with-block.  Their respective values are strings representing the expected
    types.  When exiting the with-context, the output variables are cast
    to the expected nopython types according to the annotation.  This process
    is the same as passing Python objects into arguments of a nopython
    function.

    Example::

        import numpy as np
        from numba import njit, objmode

        def bar(x):
            # This code is executed by the interpreter.
            return np.asarray(list(reversed(x.tolist())))

        @njit
        def foo():
            x = np.arange(5)
            y = np.zeros_like(x)
            with objmode(y='intp[:]'):  # annotate return type
                # this region is executed by object-mode.
                y += bar(x)
            return y

    .. note:: Known limitations:

        - with-block cannot use incoming list objects.
        - with-block cannot use incoming function objects.
        - with-block cannot ``yield``, ``break``, ``return`` or ``raise``           such that the execution will leave the with-block immediately.
        - with-block cannot contain `with` statements.
        - random number generator states do not synchronize; i.e.           nopython-mode and object-mode uses different RNG states.

    .. note:: When used outside of no-python mode, the context-manager has no
        effect.

    .. warning:: This feature is experimental.  The supported features may
        change with or without notice.

    Tc             C   s~   |dkri S t |d dkr&td|d }i }xF| D ]:\}}t|tjr\t|jtsftdt	
|j||< q<W |S )z;
        Legalize arguments to the context-manager
        Nargsr   z8objectmode context doesn't take any positional argumentskwargsz@objectmode context requires constants string for type annotation)rD   r   ZCompilerErroritems
isinstancer   ZConstvaluestrr   Z_parse_signature_string)r   r   locZ
callkwargstypeannsr-   vr   r   r   _legalize_args   s    z"_ObjModeContextType._legalize_argsc                s&  | j | | jd|j}t |j||t|d\}	}
dd }tt||
}tt| }|rtd}t	|
|t|t }|rd}t	|
|tfdd|D } fd	d
|D }t||||	|
 |j|t|	t|	dd}||d|d}t| |||	|
}| |< t | |S )N)rS   )r   r3   r:   r;   r<   c             S   s   |  ddd S )Nr$   r   r   )r&   )xr   r   r   strip_var_ver   s    z;_ObjModeContextType.mutate_with_body.<locals>.strip_var_verzkInvalid type annotation on non-outgoing variables: {}.Suggestion: remove annotation of the listed variablesz1missing type annotation on outgoing variables: {}c                s   g | ]} | qS r   r   )r,   rU   )rT   r   r   
<listcomp>   s    z8_ObjModeContextType.mutate_with_body.<locals>.<listcomp>c                s   i | ]} | |qS r   r   )r,   r-   )r   r   r   r.      s    z8_ObjModeContextType.mutate_with_body.<locals>.<dictcomp>T)r   r=   r>   r?   )Z
objectmodeZoutput_types)rV   rS   r2   r	   r3   r@   listmapr   ZTypingErrorformatr   ZTuplerA   rB   rC   rD   rE   r*   )r   r   r   r   r   r   r   r   r7   rF   rG   rX   Zstripped_outsZextra_annotatedmsgZnot_annotatedZouttuprH   rI   rJ   rK   r   )r   rT   r   r      sD    
z$_ObjModeContextType.mutate_with_bodyc             O   s   | S )Nr   )r   rM   rN   r   r   r   __call__   s    z_ObjModeContextType.__call__N)r   r   r   r   r    rV   r   r^   r   r   r   r   rL   x   s
   2;rL   c       
      C   sz   | | }|j }|j}tj||d}x6| D ]*\}}	|tj||||	|d q,W |tj||d || |< dS )zGiven the starting and ending block of the with-context,
    replaces the head block with a new block that jumps to the end.

    *blocks* is modified inplace.
    )scoperS   )rQ   targetrS   )r`   rS   N)	r_   rS   r   BlockrO   appendZAssignZ	get_exactZJump)
r   r   r   r8   sblkr_   rS   rK   r-   rU   r   r   r   r6     s    r6   c       
      C   s:   || }|j }|j}tj||d}	tj|	| |||d |	S )ak  Make a new block that calls into the lifeted with-context.

    Parameters
    ----------
    dispatcher : Dispatcher
    blocks : dict[ir.Block]
    blk_start, blk_end : int
        labels of the starting and ending block of the context-manager.
    inputs: sequence[str]
        Input variable names
    outputs: sequence[str]
        Output variable names
    )r_   rS   )newblockZcallee
label_nextrF   rG   )r_   rS   r   ra   r   Zfill_block_with_call)
rJ   r   r   r   rF   rG   rc   r_   rS   rd   r   r   r   rE     s    rE   c       	      C   sZ   t | }| | }|j}|j}tjtj||d||d| |< tjtj||d|d| |< dS )aF  Mutate *blocks* for the callee of a with-context.

    Parameters
    ----------
    blocks : dict[ir.Block]
    blk_start, blk_end : int
        labels of the starting and ending block of the context-manager.
    inputs: sequence[str]
        Input variable names
    outputs: sequence[str]
        Output variable names
    )r_   rS   )blockrF   re   )rf   rG   N)minr_   rS   r   Zfill_callee_prologuer   ra   Zfill_callee_epilogue)	r   r   r   rF   rG   Zhead_blkZtemp_blkr_   rS   r   r   r   rA   8  s    rA   N)Znumbar   r   r   r   r   Znumba.typing.typeofr   Z
transformsr	   objectr
   registerr"   r(   r*   r+   Zbypass_contextr9   Zcall_contextrL   Zobjmode_contextr6   rE   rA   r   r   r   r   <module>   s    	( 