
    J/PhZJ                     z   d dl 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 d dlZ G d de          Z ej        e          d             Zd	 Zd
 Z G d de          Z e            Z G d de          Z e            Z G d de          Z e            Zd Zd Zd Z G d de          Z e            ZdS )    )typeserrorsirsigutilsir_utils)typeof_impl)find_region_inout_vars)build_definitionsNc                   (    e Zd ZdZdZd Zd Zd ZdS )WithContextzXA dummy object for use as contextmanager.
    This can be used as a contextmanager.
    Fc                     d S N selfs    W/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/numba/core/withcontexts.py	__enter__zWithContext.__enter__           c                     d S r   r   r   typvaltbs       r   __exit__zWithContext.__exit__   r   r   c                     t           )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-manager.
        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`.
        )NotImplementedError)r   func_irblocks	blk_startblk_endbody_blocksdispatcher_factoryextras           r   mutate_with_bodyzWithContext.mutate_with_body   s
     "!r   N)__name__
__module____qualname____doc__is_callabler   r   r%   r   r   r   r   r      sR          K    " " " " "r   r   c                 *    t          j        |           S r   )r   ContextManager)r   cs     r   typeof_contextmanagerr.   &   s    $$$r   c                 f    |                      d          s|                     d          d         S dS )z.Get parent of the variable given its name
    $.r   N)
startswithsplit)names    r   _get_var_parentr5   +   s9     ??3 $zz#  ##$ $r   c                     |D ]}| |= dS )z-Remove keys in *to_clear* from *blocks*.
    Nr   )r   to_clearbs      r   _clear_blocksr9   4   s&       1II r   c                       e Zd ZdZd ZdS )_ByPassContextTypez_A simple context-manager that tells the compiler to bypass the body
    of the with-block.
    c                   
 |J |j         }d |j        |         D             
d |j        |         D             
fdt          t                    D             }	t	          ||||	           t          ||           d S )Nc                 .    i | ]}t          |          |S r   r5   .0ks     r   
<dictcomp>z7_ByPassContextType.mutate_with_body.<locals>.<dictcomp>D   s"    GGG1##QGGGr   c                 .    i | ]}t          |          |S r   r>   r?   s     r   rB   z7_ByPassContextType.mutate_with_body.<locals>.<dictcomp>E   s"    FFFA/!$$aFFFr   c                 .    i | ]}|         |         S r   r   )r@   rA   inmapoutmaps     r   rB   z7_ByPassContextType.mutate_with_body.<locals>.<dictcomp>F   s#    IIIquQxIIIr   )variable_lifetimelivemapfilterbool_bypass_with_contextr9   )r   r   r   r    r!   r"   r#   r$   vltforwardvarsrE   rF   s             @@r   r%   z#_ByPassContextType.mutate_with_body?   s    }}}'GGI0FGGGFFW1EFFFIIIIIF44H4HIIIVYEEEfk*****r   Nr&   r'   r(   r)   r%   r   r   r   r;   r;   ;   s-         
+ 
+ 
+ 
+ 
+r   r;   c                       e Zd ZdZd ZdS )_CallContextTypezqA simple context-manager that tells the compiler to lift the body of the
    with-block as another function.
    c           	         |J |j         }t          |j        ||t          |                    \  }	}
fd|D             }t	          ||||	|
           |                    |t          |	          t          |	          d          } ||          }t          ||||	|
          }||<   t          |           |S )Nr   rH   callfromreturntobody_block_idsc                 "    i | ]}||         S r   r   r@   rA   r   s     r   rB   z5_CallContextType.mutate_with_body.<locals>.<dictcomp>`       999q&)999r   Tr   	arg_names	arg_countforce_non_generator)
rG   r	   rH   set_mutate_with_block_calleederivetuplelen_mutate_with_block_callerr9   )r   r   r   r    r!   r"   r#   r$   rL   inputsoutputslifted_blks	lifted_ir
dispatchernewblks     `            r   r%   z!_CallContextType.mutate_with_bodyS   s    }}}'0K{++   :999[999!+y'"('	3 	3 	3 NNFmm&kk $	 #  	 ('	22
*	7FG  #yfk***r   NrN   r   r   r   rP   rP   O   s-         ! ! ! ! !r   rP   c                   .    e Zd ZdZdZd Zd Zd Z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 can be:

    1. strings representing the expected types; i.e. ``"float32"``.
    2. compile-time bound global or nonlocal variables referring to the
       expected type. The variables are read at compile time.

    When exiting the with-context, the output variables are converted
    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, types

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

        # Output type as global variable
        out_ty = types.intp[:]

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

    .. 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                    |rt          j        d          i }d }|                                D ]\  }	}
t          |
t          j                  r7t          |
j        t                    rt          j	        |
j                  ||	<   Wt          |
t          j
                  r<	 ||
j                 }
n'# t          $ r  ||	d|
j        d|           Y nw xY w|
||	<   t          |
t          j                  r=	 ||
j                 }
n'# t          $ r  ||	d|
j        d|           Y nw xY w|
||	<   t          |
t          j                  rm|
j        dk    rb	 |                    |
j                  }t#          ||
j                  }|||	<   `# t           j        t(          f$ r  ||	d|           Y w xY w ||	d	|           |                                D ]\  }}|                     |||           |S )
a>  
        Legalize arguments to the context-manager

        Parameters
        ----------
        func_ir: FunctionIR
        args: tuple
            Positional arguments to the with-context call as IR nodes.
        kwargs: dict
            Keyword arguments to the with-context call as IR nodes.
        loc: numba.core.ir.Loc
            Source location of the with-context call.
        func_globals: dict
            The globals dictionary of the calling function.
        func_closures: dict
            The resolved closure variables of the calling function.
        z8objectmode context doesn't take any positional argumentsc                 :    t          j        d| d| |          )Nz Error handling objmode argument z. loc)r   CompilerErrorvarnamemsgrn   s      r   report_errorz8_ObjModeContextType._legalize_args.<locals>.report_error   s2    &IwIICII   r   zFreevar z is not defined.rp   zGlobal getattrz+Getattr cannot be resolved at compile-time.z}The value must be a compile-time constant either as a non-local variable or a getattr expression that refers to a Numba type.)r   ro   items
isinstancer   Constvaluestrr   _parse_signature_stringFreeVarr4   KeyErrorGlobalExpropinfer_constantrt   attrConstantInferenceErrorAttributeError_legalize_arg_type)r   r   argskwargsrn   func_globalsfunc_closurestypeannsrs   rA   vbase_objr   r4   s                 r   _legalize_argsz"_ObjModeContextType._legalize_args   s   &  	&J   	 	 	 LLNN *	 *	DAq!RX&& ):ags+C+C )&>qwGGArz** '%af-AA    L !AqvAAA       Ary)) $QV,AA    L !@af@@@       Arw'' ADI,=,=
&&55ag>>H!(AF33C #&HQKK 5~F    L !I      3      ")) 	4 	4ID###D#s3333s6   "B00!CC8D!D*)D*/F$F87F8c                     t          |dd          r5dd|d| ddg}t          j        d                    |          |	          d
S )a  Legalize the argument type

        Parameters
        ----------
        name: str
            argument name.
        typ: numba.core.types.Type
            argument type.
        loc: numba.core.ir.Loc
            source location for error reporting.
        	reflectedFzObjmode context failed.z	Argument z% is declared as an unsupported type: r1   z"Reflected types are not supported. rm   N)rt   r   ro   join)r   r4   r   rn   msgbufs        r   r   z&_ObjModeContextType._legalize_arg_type	  sy     3U++ 	B)/D / /(+/ / /5	F &sxx'7'7SAAAA	B 	Br   c           	          |j         j        j        j        }|j         j        j        }	|j         j        j        }
|	Qi }t          ||	          D ]=\  }}	 |j        }|||<   # t          $ r}t          |          dk    r Y d }~6d }~ww xY wni }|r|d         nd}|r|d         ni }| 
                    ||||         j        |
|           |j        }t          |j        ||t          |                    \  }}d }t!          t#          ||                    }t                     t          |          z
  }|r)d}t%          j        |                    |                    t*          j         d	<   t          |          t                     z
  }|r?d
}t/          |          }t%          j        |                    ||d                             t+          j         fd|D                       }fd|D             }t3          |||||           |                    |t7          |          t9          |          d          } ||d|          }t;          |||||          }||<   t=          |           |S )NzCell is emptyr   r   r   )r   r   r   rn   r   r   rR   c                 :    |                      dd          d         S )Nr1      r   )r3   )xs    r   strip_var_verz;_ObjModeContextType.mutate_with_body.<locals>.strip_var_verG  s    773??1%%r   zkInvalid type annotation on non-outgoing variables: {}.Suggestion: remove annotation of the listed variablesz$cpzrMissing type annotation on outgoing variable(s): {0}

Example code: with objmode({1}='<add_type_as_string_here>')
r   c                      g | ]
}|         S r   r   )r@   r   r   s     r   
<listcomp>z8_ObjModeContextType.mutate_with_body.<locals>.<listcomp>h  s    AAAahqkAAAr   c                 "    i | ]}||         S r   r   rW   s     r   rB   z8_ObjModeContextType.mutate_with_body.<locals>.<dictcomp>j  rX   r   TrY   )
objectmodeoutput_types)func_idfunc__code__co_freevars__closure____globals__zipcell_contents
ValueErrorry   r   rn   rG   r	   rH   r]   listmapr   TypingErrorformatr   int32sortedTupler^   r_   r`   ra   rb   r9   )!r   r   r   r    r!   r"   r#   r$   	cellnamesclosuresr   r   cellnameclosurecellvaler   r   rL   rc   rd   r   stripped_outsextra_annotatedrr   not_annotated
stable_annouttupre   rf   rg   rh   r   s!     `                             @r   r%   z$_ObjModeContextType.mutate_with_body  s$   O(1=	?'3+7M%(H%=%= 6 6!'6%3G /6M(++ "   1vv00 100006 M %-uV}}2$)1xr&&w,0.4+1)+<+@4@5B ' ) ) '0K{++  	& 	& 	& S8899 h--#m*<*<< 	BH  $SZZ%@%@AAA  +M**S]]: 	L0 
  ..J$SZZ
JqM%J%JKKK AAAA=AAABB9999[999!+y'"('	3 	3 	3 NNFmm&kk $	 #  	 ('	d5;= = =
 +	7FG  #yfk***s   A""
B
,BB
c                     | S r   r   r   r   r   s      r   __call__z_ObjModeContextType.__call__  s    r   N)	r&   r'   r(   r)   r*   r   r   r%   r   r   r   r   rj   rj   z   sm        : :v KO O ObB B B*` ` `D    r   rj   c           	         | |         }|j         }|j        }t          j        ||          }|                                D ]U\  }}	|                    t          j        |                    |          |                    |	          |                     V|                    t          j        ||                     || |<   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.
    scopern   )rx   targetrn   )r   rn   N)	r   rn   r   Blockru   appendAssign	get_exactJump)
r   r    r!   rM   sblkr   rn   rh   rA   r   s
             r   rK   rK     s     )DJE
(CXEs+++F!!## * *1bieooa&8&8',q'9'9$') ) ) 	* 	* 	* 	* MM"'c222333F9r   c                     ||         }|j         }|j        }t          j        ||          }	t	          j        |	| |||           |	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   )newblockcallee
label_nextrc   rd   )r   rn   r   r   r   fill_block_with_call)
rg   r   r    r!   rc   rd   r   r   rn   r   s
             r   rb   rb     s`     )DJE
(Cxe---H!
 
 
 
 Or   c                 2   | st          j        d          t          |           }| |         }|j        }|j        }t          j        t          j        ||          ||          | |<   t          j	        t          j        ||          |          | |<   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
    zNo blocks in with-context blockr   )blockrc   r   )r   rd   N)
r   NumbaValueErrorminr   rn   r   fill_callee_prologuer   r   fill_callee_epilogue)	r   r    r!   rc   rd   head_blktemp_blkr   rn   s	            r   r^   r^     s      H$%FGGG6{{HhHNE
,C 5hU,,,
 
 
F9
 3hU,,,  F7OOOr   c                   ,    e Zd ZdZ	 d Zd Zd Zd ZdS )_ParallelChunksizeTc           	      r   t          j        |d|           |J |d         }t          |          dk    sJ |d         }	||         j        }
||         j        }t          |	t          j                  rt          j        |
|	j	        |          }	g }g }|

                    d|          }|                    t          j        t          j        dt          |          ||                     t          j                            |d|          }|

                    d	|          }|                    t          j        |||                     |

                    d
|          }|

                    d|          }|                    t          j        |	||                     t          j                            ||gd|          }|                    t          j        |||                     t          j                            ||gd|          }|                    t          j        |||                     ||         j        dd         |z   ||         j        d         gz   ||         _        |||         j        z   ||         _        t'          |          |_        t          j        |d|           d S )NzBefore with changes)r   r   r   r   z$ngvarnumbaset_parallel_chunksizez$spcz$save_pcz$cs_varr   zAfter with changes)r   dprint_func_irra   r   rn   rv   r   ArgVarr4   redefiner   r   r}   r   r~   rt   callbodyr
   _definitions)r   r   r   r    r!   r"   r#   r$   r   argr   rn   	set_staterestore_stategvarspcattrspcvarorig_pc_varcs_varspc_callrestore_spc_calls                        r   r%   z#_ParallelChunksize.mutate_with_body  sv   )>vNNNN   V}4yyA~~~~1gy!'Y#c26"" 	/&#..C	 ~~h,,29WeS#A#A4MMNNN'//$(@#FF,,7FC88999nnZ55	3//3445557<<"c::8[#>>???7<<r3GGRY'7cJJKKK"("3"82">"+#,#))#4#9"#=">#?y  -vg/CCw088)=fMMMMMMr   c                     t          |          dk    s|st          |d         t                    st          d          |d         | _        | S )zvAct like a function and enforce the contract that
        setting the chunksize takes only one integer input.
        r   r   z8parallel_chunksize takes only a single integer argument.)ra   rv   intr   	chunksizer   s      r   r   z_ParallelChunksize.__call__  sR     t99>>V>:d1gs+C+C> 8 9 9 9 ar   c                 h    t          j                    | _        t          j        | j                   d S r   )r   get_parallel_chunksizeorig_chunksizer   r   r   s    r   r   z_ParallelChunksize.__enter__  s,    #:<<$T^44444r   c                 8    t          j        | j                   d S r   )r   r   r   r   s       r   r   z_ParallelChunksize.__exit__  s    $T%899999r   N)r&   r'   r(   r*   r%   r   r   r   r   r   r   r   r     s^        K
%N %N %NN	 	 	5 5 5: : : : :r   r   )
numba.corer   r   r   r   r   numba.core.typing.typeofr   numba.core.transformsr	   numba.core.ir_utilsr
   r   objectr   registerr.   r5   r9   r;   bypass_contextrP   call_contextrj   objmode_contextrK   rb   r^   r   parallel_chunksizer   r   r   <module>r      s   < < < < < < < < < < < < < < 0 0 0 0 0 0 8 8 8 8 8 8 1 1 1 1 1 1 " " " " "& " " "< k""% % #"%$ $ $  + + + + + + + +" $#%%% % % % %{ % % %P  !!H H H H H+ H H HV &%''  $  <  <?: ?: ?: ?: ?: ?: ?: ?:B ('))   r   