o
    8ήc$`                     @   s   d dl mZ d dlmZ d dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dlmZmZ d dlmZmZ d dlmZ d dlmZ dd	lmZmZ d d
lmZ G dd deZG dd deZG dd deZG dd deZG dd deZdS )    )defaultdict)SequenceN)typeserrors)
Conversionrules)	templates)order_by_target_specificity   )typeofPurpose)utilsc                   @   (   e Zd ZdZdd Zdd Zdd ZdS )	Ratingpromotesafe_convertunsafe_convertc                 C   s   d| _ d| _d| _d S Nr   r   self r   @/tmp/pip-target-vg8gfxp4/lib/python/numba/core/typing/context.py__init__   s   
zRating.__init__c                 C   s   | j | j| jfS )z]Returns a tuple suitable for comparing with the worse situation
        start first.
        )r   r   r   r   r   r   r   astuple   s   zRating.astuplec                 C   sH   t | t |ur
tS t }| j|j |_| j|j |_| j|j |_|S N)typeNotImplementedr   r   r   r   )r   otherrsumr   r   r   __add__!   s   zRating.__add__N)__name__
__module____qualname__	__slots__r   r   r    r   r   r   r   r      s
    r   c                   @   sN   e Zd ZdZdd Zdd Zdd Zejdd	 Z	d
d Z
dd Zdd ZdS )	CallStackz#
    A compile-time call stack
    c                 C   s   g | _ t | _d S r   )_stack	threadingRLock_lockr   r   r   r   r   0   s   zCallStack.__init__c                 C   s   | j t| | d  S )zy
        Returns item in the stack where index=0 is the top and index=1 is
        the second item from the top.
        r
   )r&   len)r   indexr   r   r   __getitem__4   s   zCallStack.__getitem__c                 C   s
   t | jS r   )r*   r&   r   r   r   r   __len__;   s   
zCallStack.__len__c                 c   sv    |  |j|rd}t|| j  | jt|||| zd V  W | j	  | j
  d S | j	  | j
  w )Nz2compiler re-entrant to the same function signature)matchfuncr   NumbaRuntimeErrorr)   acquirer&   append	CallFramepoprelease)r   target	typeinferfunc_idargsmsgr   r   r   register>   s   



zCallStack.registerc                 c   s"    | D ]}|j j|u r|V  qdS )zg
        Yields frame that matches the function object starting from the top
        of stack.
        N)r8   r/   )r   py_funcframer   r   r   finditerL   s   zCallStack.finditerc                 C   s&   zt | |W S  ty   Y dS w )zZ
        Returns the first result from `.finditer(py_func)`; or None if no match.
        N)nextr>   StopIteration)r   r<   r   r   r   	findfirstU   s
   zCallStack.findfirstc                 C   s&   |  |D ]}|j|kr|  S qdS )z
        Returns first function that matches *py_func* and the arguments types in
        *args*; or, None if no match.
        N)r>   r9   )r   r<   r9   r=   r   r   r   r.   ^   s
   
zCallStack.matchN)r!   r"   r#   __doc__r   r,   r-   
contextlibcontextmanagerr;   r>   rA   r.   r   r   r   r   r%   +   s    
		r%   c                   @   r   )	r3   z#
    A compile-time call frame
    c                 C   s$   || _ || _|| _|| _t | _d S r   )r7   r8   r9   r6   set_inferred_retty)r   r6   r7   r8   r9   r   r   r   r   l   s
   zCallFrame.__init__c                 C   s   d | j| jS )NzCallFrame({}, {}))formatr8   r9   r   r   r   r   __repr__s      zCallFrame.__repr__c                 C   s0   d}| j | t| j |krd}t|dS )ztAdd *return_type* to the list of inferred return-types.
        If there are too many, raise `TypingError`.
           z3Return type of recursive function does not convergeN)rF   addr*   r   TypingError)r   return_typeRETTY_LIMITmr   r   r   add_return_typev   s   
zCallFrame.add_return_typeN)r!   r"   r#   rB   r   rH   rP   r   r   r   r   r3   h   s
    r3   c                   @   s>  e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dMd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!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> Z!d?d@ Z"	A	BdNdCdDZ#dEdF Z$	A	BdOdGdHZ%dIdJ Z&dKdL Z'dS )PBaseContextzEA typing context for storing function typing constrain template.
    c                 C   s@   i | _ tt| _tt| _t | _tj	| _
t | _|   d S r   )_registriesr   list
_functions_attributesr   
UniqueDict_globalsr   default_type_managertmr%   	callstackinitr   r   r   r   r      s   


zBaseContext.__init__c                 C      dS )zR
        Initialize the typing context.  Can be overridden by subclasses.
        Nr   r   r   r   r   r[          zBaseContext.initc                 C   s   |    |   dS )zy
        Refresh context with new declarations from known registries.
        Useful for third-party extensions.
        N)load_additional_registries_load_builtinsr   r   r   r   refresh   s   zBaseContext.refreshc           	      C   s   g }g }d}t |tjr| \}}|| n)|| jv r6| j| D ]}|p*t|d}|t|dg  q"nd}||j	|d |rSdg}|D ]
}|d	| qHd
|S )	zH
        Returns a string description of the type of a function
        Fgenericcasesz2No type info available for {func!r} as a callable.)r/   zKnown signatures:z * {0}
)
isinstancer   Callableget_call_signaturesextendrT   hasattrgetattrr2   rG   join)	r   r/   descdefnsparamsigstplr:   sigr   r   r   explain_function_type   s$   

z!BaseContext.explain_function_typec              
   C   sx   z	|  |||}W n tjy  } z
|}d}W Y d}~nd}~ww d}|dur)|S | |||}|du r:|dur:||S )zt
        Resolve function type *func* for argument types *args* and *kws*.
        A signature is returned.
        N)_resolve_user_function_typer   rL   _resolve_builtin_function_type)r   r/   r9   kwsreselast_exceptionr   r   r   resolve_function_type   s   z!BaseContext.resolve_function_typec           	      C   sp   || j v r4| j | }|D ])}dD ]"}|r|||}ndd |D }|||}|d ur2|    S qqd S d S )NTFc                 S   s   g | ]}t |qS r   )r   	unliteral).0ar   r   r   
<listcomp>   s    z>BaseContext._resolve_builtin_function_type.<locals>.<listcomp>)rT   apply)	r   r/   r9   rt   rl   defnsupport_literalsru   	fixedargsr   r   r   rs      s   

z*BaseContext._resolve_builtin_function_typeNc                 C   sb   |  |}|d ur|}t|tjr"| |d}|d ur"| |||S t|tjr/|| ||S d S )N__call__)_lookup_globalrd   r   Typeresolve_getattrrx   re   get_call_type)r   r/   r9   rt   literalsfuncty	func_typer   r   r   rr      s   
z'BaseContext._resolve_user_function_typec                 c   sZ    || j v r| j | D ]}|V  qdS t|jD ]}|| j v r*| j | D ]}|V  q$qdS )zE
        Get matching AttributeTemplates for the Numba type.
        N)rU   r   __mro__)r   typattrinfoclsr   r   r   _get_attribute_templates   s   

z$BaseContext._get_attribute_templatesc                    sh    fdd}||}|dur|S |t |}|dur|S t|t jr0| }|dur2|S dS dS )z
        Resolve getting the attribute *attr* (a string) on the Numba type.
        The attribute's type is returned, or None if resolution failed.
        c                    s    |  }|r|d S d S )NrM   )find_matching_getattr_template)r   outattrr   r   r   core  s   z)BaseContext.resolve_getattr.<locals>.coreN)r   rz   rd   Moduleresolve_module_constants)r   r   r   r   r   attrtyr   r   r   r     s   zBaseContext.resolve_getattrc           	      C   s`   t | |}ddlm} || }t|||d}|D ]}|||}|d ur-||d  S qd S )Nr   )get_local_target)fnkey)templaterM   )rS   r   numba.core.target_extensionr   r	   resolve)	r   r   r   r   r   	target_hworderr   rM   r   r   r   r     s   
z*BaseContext.find_matching_getattr_templatec                 C   s<   |  |D ]}|||}|durttj||  S qdS )z
        Resolve setting the attribute *attr* (a string) on the *target* type
        to the given *value* type.
        A function signature is returned, or None if resolution failed.
        N)r   r   r   	signaturer   void)r   r6   r   valuer   
expectedtyr   r   r   resolve_setattr0  s   zBaseContext.resolve_setattrc                 C   s.   t |tjr
J |||f}d}| d||S )Nr   static_getitemrd   r   r   rx   )r   r   r+   r9   rt   r   r   r   resolve_static_getitem=  s   z"BaseContext.resolve_static_getitemc                 C   s0   t |tjr
J ||||f}i }| d||S )Nstatic_setitemr   )r   r6   r+   r   r9   rt   r   r   r   resolve_static_setitemC  s   
z"BaseContext.resolve_static_setitemc                 C   s8   t |tjs
J || tj}|| |||fi }|S r   )rd   r   r   resolve_value_typeoperatorsetitemr   )r   r6   r+   r   fntyrp   r   r   r   resolve_setitemI  s   zBaseContext.resolve_setitemc                 C   s*   ||f}i }|  tj}|| ||}|S r   )r   r   delitemr   )r   r6   r+   r9   rt   r   rp   r   r   r   resolve_delitemO  s
   zBaseContext.resolve_delitemc                 C   s>   t |tjsJ t|j|}z| |W S  ty   Y dS w )zb
        Resolve module-level global constants.
        Return None or the attribute type
        N)rd   r   r   ri   pymodr   
ValueError)r   r   r   attrvalr   r   r   r   V  s   z$BaseContext.resolve_module_constantsc                 C   sH   zt |tjW S  ty#   tj|r"t tjj|ddtj Y S  w )z
        Return the numba type of a Python value that is being used
        as a function argument.  Integer types will all be considered
        int64, regardless of size.

        ValueError is raised for unsupported types.
        F)sync)r   r   argumentr   numbacudais_cuda_arrayas_cuda_array)r   valr   r   r   resolve_argument_typeb  s   z!BaseContext.resolve_argument_typec              
   C   sl   z	t |tj}W |S  ty  } zt|}W Y d}~nd}~ww t|tjr)|S | 	|}|dur4|S |)z
        Return the numba type of a Python value that is being used
        as a runtime constant.
        ValueError is raised for unsupported types.
        N)
r   r   constantr   r   erase_tracebackrd   r   ExternalFunction_get_global_type)r   r   tyrv   
typeof_excr   r   r   r   v  s   
zBaseContext.resolve_value_typec                 C   s    t |}|du r| |S |S )zGResolve value type and prefer Literal types whenever possible.
        N)r   maybe_literalr   )r   r   litr   r   r   !resolve_value_type_prefer_literal  s   

z-BaseContext.resolve_value_type_prefer_literalc                 C   s0   |  |}|d ur|S t|tjrt|S d S r   )r   rd   pytypes
ModuleTyper   r   )r   gvr   r   r   r   r     s   

zBaseContext._get_global_typec                 C   s@   ddl m}m}m} ddl m}m} ddlm} | t	j
 d S )Nr   )builtins	arraydecl
npdatetime)ctypes_utilsbufproto)eh)numba.core.typingr   r   r   r   r   numba.core.unsafer   install_registryr   builtin_registry)r   r   r   r   r   r   r   r   r   r   r_     s   zBaseContext._load_builtinsc                 C   r\   )zT
        Load target-specific registries.  Can be overridden by subclasses.
        Nr   r   r   r   r   r^     r]   z&BaseContext.load_additional_registriesc                 C   s   z| j | }W n ty   t|}|| j |< Y nw |dD ]	}| ||  q |dD ]	}| ||  q/|dD ]0\}}| |}|du rR| || q>|	|}|du rct
d||f | | | || q>dS )z~
        Install a *registry* (a templates.Registry instance) of function,
        attribute and global declarations.
        	functions
attributesglobalsNzcannot augment %s with %s)rR   KeyErrorr   RegistryLoadernew_registrationsinsert_functioninsert_attributesr   insert_globalaugment	TypeError_remove_global_insert_global)r   registryloaderftclsr   gtyexistingnewtyr   r   r   r     s,   



zBaseContext.install_registryc                 C   sH   zt |}W n	 ty   Y nw z| j|dW S  ty#   Y dS w )zD
        Look up the registered type for global value *gv*.
        N)weakrefrefr   rW   getr   r   r   r   r   r     s   zBaseContext._lookup_globalc                 C   sB   | j jfdd}zt||}W n	 ty   Y nw || j |< dS )zr
        Register type *gty* for value *gv*.  Only a weak reference
        to *gv* is kept, if possible.
        c                 S   s   ||  d S r   r   )wrr4   r   r   r   on_disposal  s   z/BaseContext._insert_global.<locals>.on_disposalN)rW   r4   r   r   r   )r   r   r   r   r   r   r   r     s   zBaseContext._insert_globalc                 C   s.   zt |}W n	 ty   Y nw | j|= dS )zC
        Remove the registered type for global value *gv*.
        N)r   r   r   rW   r   r   r   r   r     s   zBaseContext._remove_globalc                 C   s   |  || d S r   )r   )r   r   r   r   r   r   r     rI   zBaseContext.insert_globalc                 C      |j }| j| | d S r   )keyrU   r2   )r   atr   r   r   r   r        zBaseContext.insert_attributesc                 C   r   r   )r   rT   r2   )r   ftr   r   r   r   r     r   zBaseContext.insert_functionc                 C   s   |  |t| dS )zInsert a user function.

        Args
        ----
        - fn:
            object used as callee
        - ft:
            function template
        N)r   r   Function)r   fnr   r   r   r   insert_user_function  s   
z BaseContext.insert_user_functionc                 C   sb   ||krt jS | j||}|dur|S || |}|| |}|du r&|S |du r,|S t||S )z
        Check whether conversion is possible from *fromty* to *toty*.
        If successful, return a numba.typeconv.Conversion instance;
        otherwise None is returned.
        N)r   exactrY   check_compatiblecan_convert_tocan_convert_frommin)r   fromtytotyconvforwardbackwardr   r   r   can_convert  s   
zBaseContext.can_convertTFc           	      C   s   t |t |kr
dS t }t||D ]V\}}| ||}|du r# dS |s-|tjkr- dS |r7|tjkr7 dS |tjkrD| jd7  _q|tjkrQ| j	d7  _	q|tjkr^| j
d7  _
q|tjkrdqtd||S )z
        Rate the actual arguments for compatibility against the formal
        arguments.  A Rating instance is returned, or None if incompatible.
        Nr
   unreachable)r*   r   zipr   r   unsafer   r   safer   r   	Exception)	r   
actualargs
formalargsunsafe_castingexact_match_requiredrateactualformalr   r   r   r   _rate_arguments  s*   




zBaseContext._rate_argumentsc                 C   sx   t |t |kr
dS t||D ]*\}}| j||durq| ||}|du r* dS |tjus1J | j||| qdS )z
        Install possible conversions from the actual argument types to
        the formal argument types in the C++ type manager.
        Return True if all arguments can be converted.
        FNT)r*   r   rY   r   r   r   r   set_compatible)r   r  r  r  r  r   r   r   r   install_possible_conversions=  s   z(BaseContext.install_possible_conversionsc                 C   s   |rJ d||d}g }	|D ]#}
t |t |
jkr2| j||
jfi |}|dur2|	| |
f q|	jdd d |	rt|	d \}}|srg }|	D ]\}}
||krS n||
 qIt |dkrr||d	tt|f}d
| }t	||S dS )aS  
        Given actual *args* and *kws*, find the best matching
        signature in *cases*, or None if none matches.
        *key* is used for error reporting purposes.
        If *allow_ambiguous* is False, a tie in the best matches
        will raise an error.
        If *unsafe_casting* is False, unsafe casting is forbidden.
        z(Keyword arguments are not supported, yet)r  r  Nc                 S   s   | d S r   r   )ir   r   r   <lambda>i  s    z.BaseContext.resolve_overload.<locals>.<lambda>r   r   r
   rc   z#Ambiguous overloading for %s %s:
%s)
r*   r9   r  r2   r   sortrj   mapstrr   )r   r   rb   r9   rt   allow_ambiguousr  r  options
candidatescaserating	best_ratebesttiedr  r:   r   r   r   resolve_overloadP  s4   zBaseContext.resolve_overloadc                 G   sL   dd }t ||d}|d }|dd  D ]}| ||}|d u r# |S q|S )Nc                 S   s   t | ddS )zfUses bitwidth to order numeric-types.
            Fallback to stable, deterministic sort.
            bitwidthr   )ri   )objr   r   r   keyfunc  s   z(BaseContext.unify_types.<locals>.keyfuncr  r   r
   )sortedunify_pairs)r   typelistr  unifiedtpr   r   r   unify_types  s   zBaseContext.unify_typesc                 C   s   ||kr|S |t ju r|S |t ju r|S || |}|dur |S || |}|dur,|S | j||d}|dur>|tjkr>|S | j||d}|durP|tjkrP|S t|t js\t|t jrlt |}t |}| 	||S dS )zr
        Try to unify the two given types.  A third type is returned,
        or None in case of failure.
        N)r   r   )
r   	undefinedunifyr   r   r   rd   Literalrz   r  )r   firstsecondr   r   r   r   r   r    s2   




zBaseContext.unify_pairsr   ry   )TTF)(r!   r"   r#   rB   r   r[   r`   rq   rx   rs   rr   r   r   r   r   r   r   r   r   r   r   r   r   r   r_   r^   r   r   r   r   r   r   r   r   r   r  r
  r  r"  r  r   r   r   r   rQ      sT    	
	


/rQ   c                   @   s   e Zd Zdd ZdS )Contextc           
      C   s   ddl m}m}m}m}m}m}m}m}m	}	 | 
|j | 
|j | 
|j | 
|j | 
|j | 
|j | 
|j | 
|j | 
|	j d S )Nr
   )	
cffi_utils	cmathdeclenumdecllistdeclmathdeclnpydecl
randomdeclsetdecldictdecl) r)  r*  r+  r,  r-  r.  r/  r0  r1  r   r   )
r   r)  r*  r+  r,  r-  r.  r/  r0  r1  r   r   r   r^     s   ,z"Context.load_additional_registriesN)r!   r"   r#   r^   r   r   r   r   r(    s    r(  )collectionsr   collections.abcr   r   r   r   r'   rC   r   r   
numba.corer   numba.core.typeconvr   r   r   r   numba.core.utilsr	   r   r   r   objectr   r%   r3   rQ   r(  r   r   r   r   <module>   s.    =    ;