o
    ,wi2                  	   @   s$  d Z ddlZddlZddlZddlmZmZmZmZm	Z	m
Z
mZmZmZmZ ddlZddlZe ZG dd dZe Ze Ze ZdejfddZdejfd	d
ZdefddZdee dedef fddZdeeef fddZdddededeeef fddZ ej!G dd dZ"dS )z;Module for getting (and caching) inspect.Signature objects.    N)
AnyCallableDictGenericListMappingOptionalTupleTypeUnionc                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	NoValuez+Sentinel class for arguments with no value.c                 C   s   dS )Nzfdl.NO_VALUE selfr   r   S/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/fiddle/_src/signatures.py__repr__"   s   zNoValue.__repr__c                 C   s   ~| S )z>Override for deepcopy that does not copy this sentinel object.r   )r   memor   r   r   __deepcopy__%   s   zNoValue.__deepcopy__c                 C   s   | S )zCOverride for `copy.copy()` that does not copy this sentinel object.r   r   r   r   r   __copy__*   s   zNoValue.__copy__N)__name__
__module____qualname____doc__r   r   r   r   r   r   r   r      s
    r   returnc                 C   s   t | }|dur|n| } tjdk rt| trt| tr| j} zt	
| W S  tyJ   t| trIt| drIz	t	
| jW  Y S  tyH   Y  w  w )zReturns the signature for a function or class.

  This mostly calls inspect.signature, but handles generics and some builtin
  types better.

  Args:
    fn_or_cls: Function or class callable.
  N)   	   __call__)typing_extensions
get_originsysversion_info
isinstancetype
issubclassr   __init__inspect	signature
ValueErrorhasattrr   )	fn_or_clsoriginr   r   r   _get_signature_uncached5   s"   

r+   c                 C   sJ   zt |  W S  ty   t|  Y S  ty$   t| }|t | < | Y S w )a  Returns (and maybe caches) the signature for `fn_or_cls`.

  If a signature is not available for `fn_or_cls` and `fn_or_cls` is a type,
  this function will instead try to get a signature for `fn_or_cls.__call__`.
  This behavior allows a reasonable signature to be inferred for certain builtin
  types such as `dict`.

  Args:
    fn_or_cls: The function or class to return a signature for.
  )_signature_cache	TypeErrorr+   KeyError)r)   r&   r   r   r   get_signatureS   s   
r/   c              	   C   s(   zt |  W dS  ttfy   Y dS w )a4  Returns whether `fn_or_cls` has an available signature.

  Note that this will return `True` even if a signature for `fn_or_cls` is not
  yet in the cache. The signature for `fn_or_cls` will be cached if it is
  available.

  Args:
    fn_or_cls: The function or class to check signature availability for.
  FT)r/   r'   r-   )r)   r   r   r   has_signatureh   s   

r0   cls.c                 C   s@   t | D ]}d|jv r|j  S d|jv r|j  S qtd)zEFind the first ``__init__`` or ``__new__`` method in the class's MRO.r$   __new__z#Could not find a class constructor.)r%   getmro__dict__r$   r2   RuntimeError)r1   baser   r   r   _find_class_construction_fny   s   



r7   c             	   C   sH   zt | trt| st| } tj| |dW S  ttfy#   i  Y S w )zFReturns a dictionary corresponding to the annotations for `fn_or_cls`.include_extras)	r!   r"   dataclassesis_dataclassr7   r   get_type_hintsr-   	NameError)r)   r9   r   r   r   _get_type_hints_uncached   s   r>   Fr8   r)   r9   c                C   sZ   zt | |f W S  ty   t| |d Y S  ty,   t| |d}|t | |f< | Y S w )zJReturns (and maybe caches) type hints for `fn_or_cls`, suppressing errors.r8   )_type_hints_cacher-   r>   r.   )r)   r9   hintsr   r   r   r<      s   r<   c                   @   sX  e Zd ZU dZejed< dZee	 ed< dd Z
edeeeef ef fdd	Zd
eeef dedefddZ		d$deeef de	de	deee eeef f fddZd%ddZdeeef defddZdedeeef deeef fddZedeeejf fddZedee fddZedee fd d!Zedee fd"d#Z dS )&SignatureInfoz:To store signature related information about the callable.r&   Nhas_var_keywordc                 C   sT   d | _ t| jj D ]\}}|j|jkr|| _ q|j|jkr'| jd u r'd| _qd S )NT)	_var_positional_start	enumerater&   
parametersvalueskindVAR_POSITIONALVAR_KEYWORDrB   )r   indexparamr   r   r   __post_init__   s   zSignatureInfo.__post_init__r   c              
   O   s   t | }z|j|i |j}W n ty& } ztd|  d| |d}~ww tt| D ]C\}}|j| }|j|j	krH|
|j}	|	||< |j|jkrc|
|j}
t|
D ]
\}}	|	||| < qX|j|jkrr||
|j q/|S )ax  Bind arguments and return an args dict in canonical storage format.

    Args:
      fn_or_cls: A function or a class object.
      *args: A list of positional arguments.
      **kwargs: A dict of keyword arguments.

    Returns:
      An arguments dict in canonical storage format. Please see `Buildable`
        docstring for the definition of canonical storage format.
    zCannot bind arguments to z: N)r/   bind_partial	argumentsr-   rD   listkeysrE   rG   POSITIONAL_ONLYpopnamerH   rI   update)r)   argskwargsr&   rN   erJ   rS   rK   valuerF   ir   r   r   signature_binding   s(   
zSignatureInfo.signature_bindingargumentmissingc                 C   sz   |}d}t |tr|| jv r| j| }nt |tsJ | jdur0|| jk r0t| j }|| }|r;|j|jur;|j}|S )ao  Get default value for the argument, return missing if not found.

    Args:
      argument: Specify the argument either by its name or the index for
        positional arguments.
      missing: A value to return if the argument does not have defaults.

    Returns:
      The default value for the argument if exists, return the missing object
        otherwise.
    N)	r!   strrE   intvar_positional_startrO   rF   defaultempty)r   r[   r\   rX   rK   paramsr   r   r   get_default   s   




zSignatureInfo.get_defaultFrN   include_pos_or_kw_in_argsinclude_no_valuec                 C   s  |  }t| j }g }t|D ]N\}}|j|jkr5||v r*|||  ||= n|r5|| |t	 |j|j
kr_|sB| j|v r_|j|v rT|||j  ||j= q|r_|| |t	 q| jdur~| j}||v r~|||  ||= |d7 }||v sl||fS )a(  Transform arguments in dict to *args and **kwargs.

    Args:
      arguments: An arguments dict in canonical storage format (please see
        `Buildable` docstring for the precise definition).
      include_pos_or_kw_in_args: Whether to always put positional-or-keyword
        args in the *args list as output. If set to False, such args will be
        added to **kwargs output dict if the variadic positional args list is
        empty in `arguments`.
      include_no_value: Whether to include `NO_VALUE` in the output. If set as
        True, a value is set to `NO_VALUE` if no user specific value exists and
        its default value is empty.

    Returns:
      A positional args list that can be used to build the Buildable.
      A keyword args dict that can be used to build the Buildable.
    N   )copyrO   rE   rF   rD   rG   rQ   appendrc   NO_VALUEPOSITIONAL_OR_KEYWORDr_   rS   )r   rN   rd   re   rE   positional_valuesrJ   rK   r   r   r   transform_to_args_kwargs   s4   


z&SignatureInfo.transform_to_args_kwargsc                 C   s   | j j|}|dur3|j|jkrtd|d| |j|jkr+td|d| |j|jkr3d}|du r^| js`|| j jv rJd| d}t|d| d| d	d
	| j
 d}t|dS dS )z:Raises an error if ``name`` is not a valid parameter name.Nz(Cannot access POSITIONAL_ONLY parameter z on z'Cannot access VAR_POSITIONAL parameter zVariadic arguments (e.g. *z) are not supported.zNo parameter named 'z' exists for z; valid parameter names: z, .)r&   rE   getrG   rQ   AttributeErrorrH   rI   rB   joinvalid_param_names)r   rS   r)   rK   err_msgr   r   r   validate_param_name%  s0   
z!SignatureInfo.validate_param_namekeyc                    s\    fdd}t |trt||j||j|j}n||}t |ttfs,J d| d|S )z.Replace VARARGS handle in index key if exists.c                    s   | t u r jS | S N)VARARGSr_   )xr   r   r   <lambda>D  s    z6SignatureInfo.replace_varargs_handle.<locals>.<lambda>z!Key must be an int or slice, got rm   )r!   slicestartstopstepr^   )r   rt   
replace_fnr   r   r   replace_varargs_handleB  s   

z$SignatureInfo.replace_varargs_handlerJ   c                 C   s`   |dk r|  |dd\}}|t|7 }t| jj }|t|k r.|| }|j|jkr.|jS |S )zAMap index of positional arguments to the key for `__arguments__`.r   T)	rl   lenrO   r&   rE   rF   rG   rj   rS   )r   rJ   rN   rU   _rb   rK   r   r   r   index_to_keyN  s   zSignatureInfo.index_to_keyc                 C   s   | j jS ru   )r&   rE   r   r   r   r   rE   \  s   zSignatureInfo.parametersc                 C   s   t dd | jj D S )Nc                 s   s*    | ]\}}|j |j|jfv r|V  qd S ru   )rG   rj   KEYWORD_ONLY).0rS   rK   r   r   r   	<genexpr>b  s    z2SignatureInfo.valid_param_names.<locals>.<genexpr>)tupler&   rE   itemsr   r   r   r   rq   `  s   
zSignatureInfo.valid_param_namesc                 C   s,   | j j D ]}|j|jkr|j  S qd S ru   )r&   rE   rF   rG   rI   rS   )r   rK   r   r   r   var_keyword_nameh  s
   
zSignatureInfo.var_keyword_namec                 C   s   | j S ru   )rC   r   r   r   r   r_   o  s   z"SignatureInfo.var_positional_start)FF)r   N)!r   r   r   r   r%   	Signature__annotations__rB   r   boolrL   staticmethodr   r   r^   r]   r   rZ   rc   r	   r   rl   rs   ry   r~   r   propertyr   	ParameterrE   rq   r   r_   r   r   r   r   rA      sL   
 
! 


6


rA   )#r   r:   r%   r   typingr   r   r   r   r   r   r   r	   r
   r   weakrefr   objectrv   r   ri   WeakKeyDictionaryr,   r?   r   r+   r/   r   r0   r7   r]   r>   r<   	dataclassrA   r   r   r   r   <module>   s:   0




