o
    Y۷i:                     @  s~   d Z ddlmZ ddlZddlZddlZddlmZmZm	Z	 e
 Zd&ddZd'ddZ				d(d)ddZ		d*d+d$d%ZdS ),zUtilities for creating high-performance keyword argument wrapper functions.

This module provides tools for wrapping positional-only callables with
keyword argument support using code generation techniques.
    )annotationsN)AnyCallableIterablenames	list[str]arg_typestrreturnNonec                 C  s   t t| t | krtd|  d|  | D ]9}t|ts.t| dt|j d|t	
|r@td|  d|d| sQtd|  d|dqd	S )
a  Validate that argument names are valid Python identifiers and unique.

    Parameters
    ----------
    names
        List of argument names to validate.
    arg_type
        Description of the argument type (e.g., "Argument", "Keyword-only argument").

    z
Duplicate z names found in: z name must be a string, got z: zInvalid z name: z; is a Python keyword and cannot be used as a parameter namez! is not a valid Python identifierN)lenset
ValueErrorlower
isinstancer	   	TypeErrortype__name__keyword	iskeywordisidentifier)r   r   name r   R/home/ubuntu/vllm_env/lib/python3.10/site-packages/tvm_ffi/utils/kwargs_wrapper.py_validate_argument_names"   s"   

r   	arg_namesarg_defaultstuplekwonly_nameskwonly_defaultsdict[str, Any]reserved_namesset[str]c                 C  s   t | d t|tstdt|j t|t| kr+tdt| dt|  dt |d t|}|D ]}||vrFtd| d| q6t| }||@ }|rXtd	| ||B }	|	|@ }
|
rjtd
|
 ddS )a  Validate all input arguments for make_kwargs_wrapper.

    Parameters
    ----------
    arg_names
        List of positional argument names.
    arg_defaults
        Tuple of default values for positional arguments.
    kwonly_names
        List of keyword-only argument names.
    kwonly_defaults
        Dictionary of default values for keyword-only arguments.
    reserved_names
        Set of reserved internal names that cannot be used as argument names.

    Argumentz"arg_defaults must be a tuple, got zarg_defaults has z values but only z positional argumentszKeyword-only argumentzDefault provided for 'z ' which is not in kwonly_names: z6Arguments cannot be both positional and keyword-only: z-Argument names conflict with internal names: z/. Please avoid using names starting with "__i_"N)	r   r   r   r   r   r   r   r   r   )r   r   r   r   r!   kwonly_names_setkeyarg_names_setoverlapall_user_names	conflictsr   r   r   _validate_wrapper_argsA   s8   



r*   r   target_funcr   list[str] | Nonedict[str, Any] | None	prototypeCallable | Nonec                   sn  |du rg }|du ri }d}dd | h}t ||||| |r/tt|t| d |ni }g g i d fdd}	|D ]}
|
|v rR|	|
||
  qD|
 |
 qD|rd |D ]}
|
|v rt|	|
||
  qf|
 |
 qfd}d}d| d| d| d}|| t i}i }t||| |d }|durtj	||dd |S )a  Create a wrapper with kwargs support for a function that only accepts positional arguments.

    This function dynamically generates a wrapper using code generation to minimize overhead.

    Parameters
    ----------
    target_func
        The underlying function to be called by the wrapper. This function must only
        accept positional arguments.
    arg_names
        A list of ALL positional argument names in order. These define the positional
        parameters that the wrapper will accept. Must not overlap with kwonly_names.
    arg_defaults
        A tuple of default values for positional arguments, right-aligned to arg_names
        (matching Python's __defaults__ behavior). The length of this tuple determines
        how many trailing arguments have defaults.
        Example: (10, 20) with arg_names=['a', 'b', 'c', 'd'] means c=10, d=20.
        Empty tuple () means no defaults.
    kwonly_names
        A list of keyword-only argument names. These arguments can only be passed by name,
        not positionally, and appear after a '*' separator in the signature. Can include both
        required and optional keyword-only arguments. Must not overlap with arg_names.
        Example: ['debug', 'timeout'] creates wrapper(..., *, debug, timeout).
    kwonly_defaults
        Optional dictionary of default values for keyword-only arguments (matching Python's
        __kwdefaults__ behavior). Keys must be a subset of kwonly_names. Keyword-only
        arguments not in this dict are required.
        Example: {'timeout': 30} with kwonly_names=['debug', 'timeout'] means 'debug'
        is required and 'timeout' is optional.
    prototype
        Optional prototype function to copy metadata (__name__, __doc__, __module__,
        __qualname__, __annotations__) from. If None, no metadata is copied.

    Returns
    -------
        A dynamically generated wrapper function with the specified signature

    Notes
    -----
    The generated wrapper will directly embed default values for None and bool types
    and use a MISSING sentinel object to distinguish between explicitly
    passed arguments and those that should use default values for other types to ensure
    the generated code does not contain unexpected str repr.

    N__i_target_func__i_MISSING__i_arg_defaultsr   r	   default_valuer   r
   r   c                   s   |du r |  d  |  dS t|tu r0|rdnd} |  d|   |  dS  |  d  || <    d|  d|  d d	|  	 dS )
zAAdd a parameter with a default value to arg_parts and call_parts.Nz=NoneTrueFalse=z["z"] if z is z else )appendr   bool)r   r3   default_value_str_INTERNAL_DEFAULTS_DICT_INTERNAL_MISSING	arg_parts
call_partsruntime_defaultsr   r   _add_param_with_default   s   z4make_kwargs_wrapper.<locals>._add_param_with_default*z, z
def wrapper(z):
    return (z)
wrapperr   )updated)r   r	   r3   r   r
   r   )
r*   dictzipr   r7   joinMISSINGexec	functoolsupdate_wrapper)r+   r   r   r   r   r.   _INTERNAL_TARGET_FUNC_INTERNAL_NAMESarg_defaults_dictr@   r   arg_list	call_listcode_strexec_globals	namespacenew_funcr   r:   r   make_kwargs_wrapper   s\   6
" 




rU   	signatureinspect.Signatureexclude_arg_namesIterable[str] | Nonec                 C  s  |durt |nt  }g }g }g }i }d}	|j D ]b\}
}|
|v r#q|jtjjkr.td|jtjjkr9td|jtjj	tjj
fv rd||
 |jtjjurYd}	||j q|	rctd|
 dq|jtjjkr|||
 |jtjjur||j||
< qt|}t| |||||S )a  Create a wrapper with kwargs support for a function that only accepts positional arguments.

    This is a convenience function that extracts parameter information from a signature
    object and calls make_kwargs_wrapper with the appropriate arguments. Supports both
    required and optional keyword-only arguments.

    Parameters
    ----------
    target_func
        The underlying function to be called by the wrapper.
    signature
        An inspect.Signature object describing the desired wrapper signature.
    prototype
        Optional prototype function to copy metadata (__name__, __doc__, __module__,
        __qualname__, __annotations__) from. If None, no metadata is copied.
    exclude_arg_names
        Optional iterable of argument names to ignore when extracting parameters from the signature.
        These arguments will not be included in the generated wrapper. If a name in this iterable
        does not exist in the signature, it is silently ignored.

    Returns
    -------
        A dynamically generated wrapper function with the specified signature.

    Raises
    ------
    ValueError
        If the signature contains *args or **kwargs.

    NFz)*args not supported in wrapper generationz,**kwargs not supported in wrapper generationTzRequired positional parameter 'z(' cannot follow parameters with defaults)r   
parametersitemskindinspect	ParameterVAR_POSITIONALr   VAR_KEYWORDPOSITIONAL_ONLYPOSITIONAL_OR_KEYWORDr7   defaultemptyKEYWORD_ONLYr   rU   )r+   rV   r.   rX   skip_setr   arg_defaults_listr   r   has_seen_positional_default
param_nameparamr   r   r   r   "make_kwargs_wrapper_from_signature!  sP   %



rk   )r   r   r   r	   r
   r   )r   r   r   r   r   r   r   r    r!   r"   r
   r   )r   NNN)r+   r   r   r   r   r   r   r,   r   r-   r.   r/   r
   r   )NN)
r+   r   rV   rW   r.   r/   rX   rY   r
   r   )__doc__
__future__r   rJ   r]   r   typingr   r   r   objectrH   r   r*   rU   rk   r   r   r   r   <module>   s$   

C $