
    shZJ                     @   S SK JrJrJrJrJr  S SKJr  S SKJ	r	  S SK
Jr  S SKr " S S\5      r\R                  " \5      S 5       rS	 rS
 r " S S\5      r\" 5       r " S S\5      r\" 5       r " S S\5      r\" 5       rS rS rS r " S S\5      r\" 5       rg)    )typeserrorsirsigutilsir_utils)typeof_impl)find_region_inout_vars)build_definitionsNc                   .    \ rS rSrSrSrS rS rS rSr	g)	WithContext   zPA dummy object for use as contextmanager.
This can be used as a contextmanager.
Fc                     g N selfs    k/Users/tiagomarins/Projetos/claudeai/copy_bank/venv/lib/python3.13/site-packages/numba/core/withcontexts.py	__enter__WithContext.__enter__           c                     g r   r   r   typvaltbs       r   __exit__WithContext.__exit__   r   r   c                     [         e)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_bodyWithContext.mutate_with_body   s
     "!r   r   N)
__name__
__module____qualname____firstlineno____doc__is_callabler   r   r(   __static_attributes__r   r   r   r   r      s     K"r   r   c                 .    [         R                  " U 5      $ r   )r   ContextManager)r   cs     r   typeof_contextmanagerr4   &   s    $$r   c                 X    U R                  S5      (       d  U R                  S5      S   $ g)z.Get parent of the variable given its name
    $.r   N)
startswithsplit)names    r   _get_var_parentr;   +   s,     ??3zz# ##  r   c                     U H  nX	 M     g)z-Remove keys in *to_clear* from *blocks*.
    Nr   )r"   to_clearbs      r   _clear_blocksr?   4   s     I r   c                       \ rS rSrSrS rSrg)_ByPassContextType;   zWA simple context-manager that tells the compiler to bypass the body
of the with-block.
c                 `   Ub   eUR                   nUR                  U    V	s0 s H  n	[        U	5      U	_M     n
n	UR                  U    V	s0 s H  n	[        U	5      U	_M     nn	[        [        U5       V	s0 s H
  oU	   X   _M     nn	[        X#XL5        [        X%5        g s  sn	f s  sn	f s  sn	f r   )variable_lifetimelivemapr;   filterbool_bypass_with_contextr?   )r   r!   r"   r#   r$   r%   r&   r'   vltkinmapoutmapforwardvarss                r   r(   #_ByPassContextType.mutate_with_body?   s    }}''03I0FG0F1#Q&0FG14W1EF1EA/!$a'1EF4:44HI4HqQx*4HIVEf* HFIs   B!B&6B+r   Nr*   r+   r,   r-   r.   r(   r0   r   r   r   rA   rA   ;   s    
+r   rA   c                       \ rS rSrSrS rSrg)_CallContextTypeO   ziA simple context-manager that tells the compiler to lift the body of the
with-block as another function.
c           	      H   Ub   eUR                   n[        UUR                  UU[        U5      S9u  pU Vs0 s H  oX+   _M	     nn[	        XUX5        UR                  U[        U	5      [        U	5      SS9nU" U5      n[        XX4X5      nXU'   [        X%5        U$ s  snf )Nr"   rE   callfromreturntobody_block_idsTr"   	arg_names	arg_countforce_non_generator)
rD   r	   rE   set_mutate_with_block_calleederivetuplelen_mutate_with_block_callerr?   )r   r!   r"   r#   r$   r%   r&   r'   rI   inputsoutputsrJ   lifted_blks	lifted_ir
dispatchernewblks                   r   r(   !_CallContextType.mutate_with_bodyS   s    }}''0KK{+ .99[&)|[9!+'"(	3 NNFm&k $	 # 	 (	2
*	F #yf*) :s   Br   NrO   r   r   r   rQ   rQ   O   s    !r   rQ   c                   4    \ rS rSrSrSrS rS rS rS r	Sr
g	)
_ObjModeContextTypez   a  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                 8   U(       a  [         R                  " S5      e0 nS nUR                  5        GH?  u  p[        U
[        R
                  5      (       aC  [        U
R                  [        5      (       a$  [        R                  " U
R                  5      Xy'   Mh  [        U
[        R                  5      (       a   XjR                     n
XU	'   M  [        U
[        R                  5      (       a   XZR                     n
XU	'   M  [        U
[        R                  5      (       aH  U
R                  S:X  a8   UR!                  U
R                  5      n[#        XR$                  5      nXU	'   GM7  U" U	S	US9  GMB     UR                  5        H  u  pU R+                  XU5        M     U$ ! [         a    U" U	SU
R                  < S3US9   Nf = f! [         a    U" U	SU
R                  < S3US9   Nf = f! [         R&                  [(        4 a    U" U	SUS9   GM  f = f)
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                 :    [         R                  " SU < SU 3US9e)Nz Error handling objmode argument z. loc)r   CompilerErrorvarnamemsgro   s      r   report_error8_ObjModeContextType._legalize_args.<locals>.report_error   s(    &&6wkC5I r   zFreevar z is not defined.rq   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   rp   items
isinstancer   Constvaluestrr   _parse_signature_stringFreeVarr:   KeyErrorGlobalExpropinfer_constantrv   attrConstantInferenceErrorAttributeError_legalize_arg_type)r   r!   argskwargsro   func_globalsfunc_closurestypeannsrt   rJ   vbase_objr   r:   s                 r   _legalize_args"_ObjModeContextType._legalize_args   s   & &&J  	 LLNDA!RXX&&:aggs+C+C&>>qwwGArzz**%ff-A  Aryy))$VV,A  Arww''ADDI,=
&&55agg>H!(FF3C #&QK3 I #Z ")ID##Ds3 * U     !&qvvj0@A     !%affZ/?@ 55~F   !Is6   ;F$/G30G2$!GG!G/.G/2"HHc                     [        USS5      (       a1  SSU< SU S3S/n[        R                  " SR                  U5      US	9eg
)zLegalize 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: r7   z"Reflected types are not supported. rn   N)rv   r   rp   join)r   r:   r   ro   msgbufs        r   r   &_ObjModeContextType._legalize_arg_type	  s[     3U++)D8 $((+uA/4	F &&sxx'7SAA ,r   c           	      (   UR                   R                  R                  R                  nUR                   R                  R                  n	UR                   R                  R
                  n
U	b(  0 n[        X5       H  u  p UR                  nXU'   M     O0 nU(       a  US   OSnU(       a  US   O0 nU R                  UUUX#   R                  U
US9nUR                  n[        UUR                  UU[        U5      S9u  nnS n[!        [#        UU5      5      n[        U5      [        U5      -
  nU(       a'  Sn[$        R&                  " UR)                  U5      5      e[*        R,                  US	'   [        U5      [        U5      -
  nU(       a6  S
n[/        U5      n[$        R&                  " UR)                  UUS   5      5      e[*        R0                  " U Vs/ s H  nUU   PM
     sn5      nU Vs0 s H	  nUUU   _M     nn[3        UX4UU5        UR5                  U[7        U5      [9        U5      SS9n U" U SUS9n![;        U!X#UUU5      n"U"X#'   [=        X%5        U!$ ! [         a  n[        U5      S:w  a  e  S nAGM  S nAff = fs  snf s  snf )NzCell is emptyr   r   r   )r!   r   r   ro   r   r   rT   c                 ,    U R                  SS5      S   $ )Nr7      r   )r9   )xs    r   strip_var_ver;_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   TrX   )
objectmodeoutput_types)func_idfunc__code__co_freevars__closure____globals__zipcell_contents
ValueErrorr{   r   ro   rD   r	   rE   r\   listmapr   TypingErrorformatr   int32sortedTupler]   r^   r_   r`   ra   r?   )#r   r!   r"   r#   r$   r%   r&   r'   	cellnamesclosuresr   r   cellnameclosurecellvaler   r   r   rI   rb   rc   r   stripped_outsextra_annotatedrs   not_annotated
stable_annr   outtuprJ   rd   re   rf   rg   s#                                      r   r(   $_ObjModeContextType.mutate_with_body  s   OO((11==	??''33++77M%(%=!6%33G /6(+ &> M %uV}2$)xr&&w,0.4+1+<+@+@4@5B ' ) ''0KK{+	& S89 h-#m*<<H  $$SZZ%@AA  ++M*S]:0 
  .J$$SZZ
JqM%JKK =A=ahqk=AB-89[q&)|[9!+y"('	3 NNFm&k $	 # 	 (	d5;=
 +7FG #f*k " 1v0 1~ B9s$   I!J
5J!
J+JJc                     U $ r   r   r   r   r   s      r   __call___ObjModeContextType.__call__  s    r   r   N)r*   r+   r,   r-   r.   r/   r   r   r(   r   r0   r   r   r   rj   rj   z   s(    :v KObB*`Dr   rj   c           	      j   X   nUR                   nUR                  n[        R                  " XVS9nUR	                  5        HH  u  pUR                  [        R                  " UR                  U5      UR                  U	5      US95        MJ     UR                  [        R                  " X&S95        XpU'   g)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.
scopero   )rz   targetro   )r   ro   N)	r   ro   r   Blockrw   appendAssign	get_exactJump)
r"   r#   r$   rM   sblkr   ro   rg   rJ   r   s
             r   rH   rH     s     DJJE
((CXXE+F!!#biieooa&8',q'9$') 	* $ MM"''239r   c                     X   nUR                   nUR                  n[        R                  " XxS9n	[        R
                  " U	U UUUS9  U	$ )a?  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_nextrb   rc   )r   ro   r   r   r   fill_block_with_call)
rf   r"   r#   r$   rb   rc   r   r   ro   r   s
             r   ra   ra     sP     DJJE
((Cxxe-H!!
 Or   c                 2   U (       d  [         R                  " S5      e[        U 5      nX   nUR                  nUR                  n[
        R                  " [        R                  " XxS9UUS9X'   [
        R                  " [        R                  " XxS9US9X'   g)a  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   )blockrb   r   )r   rc   N)
r   NumbaValueErrorminr   ro   r   fill_callee_prologuer   r   fill_callee_epilogue)	r"   r#   r$   rb   rc   head_blktemp_blkr   ro   s	            r   r]   r]     s     $$%FGG6{HHNNE
,,C 55hhU,
F
 33hhU,FOr   c                   2    \ rS rSrSr S rS rS rS rSr	g)	_ParallelChunksizei  Tc           	         [         R                  " USUS9  Uc   eUS   n[        U5      S:X  d   eUS   n	X#   R                  n
X#   R                  n[        U	[        R                  5      (       a!  [        R                  " XR                  U5      n	/ n/ nU
R                  SU5      nUR                  [        R                  " [        R                  " S[        U5      X5      5        [        R                  R!                  USU5      nU
R                  S	U5      nUR                  [        R                  " UUU5      5        U
R                  S
U5      nU
R                  SU5      nUR                  [        R                  " U	UU5      5        [        R                  R#                  UU/SU5      nUR                  [        R                  " UUU5      5        [        R                  R#                  UU/SU5      nUR                  [        R                  " UUU5      5        X#   R$                  SS U-   X#   R$                  S   /-   X#   l        XU   R$                  -   X$   l        ['        U5      Ul        [         R                  " USUS9  g )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_irr`   r   ro   rx   r   ArgVarr:   redefiner   r   r   r   r   rv   callbodyr
   _definitions)r   r!   r"   r#   r$   r%   r&   r'   r   argr   ro   	set_staterestore_stategvarspcattrspcvarorig_pc_varcs_varspc_callrestore_spc_calls                        r   r(   #_ParallelChunksize.mutate_with_body  s$   )>vN   V}4yA~~1g!''##c266""&&#.C	 ~~h,299WeS#A4MN''//$(@#F,7FC89nnZ5	3/34577<<"c:8[#>?77<<r3GRYY'7cJK"("3"8"82">"+#,#)#4#9#9"#=">#?  -g/C/CC08)=fMr   c                     [        U5      S:w  d  U(       d  [        US   [        5      (       d  [        S5      eUS   U l        U $ )zfAct 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.)r`   rx   intr   	chunksizer   s      r   r   _ParallelChunksize.__call__  sE     t9>V:d1gs+C+C 8 9 9 ar   c                 x    [         R                  " 5       U l        [         R                  " U R                  5        g r   )r   get_parallel_chunksizeorig_chunksizer   r   r   s    r   r   _ParallelChunksize.__enter__  s%    #::<$$T^^4r   c                 D    [         R                  " U R                  5        g r   )r   r   r   r   s       r   r   _ParallelChunksize.__exit__  s    $$T%8%89r   )r   r   N)
r*   r+   r,   r-   r/   r(   r   r   r   r0   r   r   r   r   r     s"    K
%NN	5:r   r   )
numba.corer   r   r   r   r   numba.core.typing.typeofr   numba.core.transformsr	   numba.core.ir_utilsr
   r   objectr   registerr4   r;   r?   rA   bypass_contextrQ   call_contextrj   objmode_contextrH   ra   r]   r   parallel_chunksizer   r   r   <module>r     s    < < 0 8 1 "& "< k"% #%$+ +" $%%{ %P  !H+ HV &'$<<?: ?:B () r   