a
    Of                     @  s  d Z ddlmZ ddlZddlmZ ddlmZmZm	Z	 ddl
mZ ddlmZmZ ddlmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/ dd	l0m1Z1 dd
l2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9 ddl:m;Z; ddl<m=Z= ddl>m?Z? ddl@mAZA ddlBmCZC ddlDmEZE ddlFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQ ddlRmSZS ddlTmUZU ddlVmWZX ddlYmZZZ ddl[m\Z\ zddlFm]Z] W n  e^y   ddlFmOZ] Y n0 dZ_dZ`dZadZbdZcdZddZed Zfd!Zgh d"Zhe\eXZieid#kr8d$nd%Zjd&ZWd'd(d)d*d+ZkG d,d- d-e7ZlG d.d/ d/Zmd0d1d2d3d4ZnG d5d6 d6ZoG d7d8 d8ZpG d9d: d:ZqG d;d< d<Zred=d>d?Zsed@dAd?ZtedBdCd?ZuedDdEd?ZvedFdGd?ZwedFdHd?ZxedFdId?Zyd'dJdKdLdMdNdOZzd'dPdKdLdQdRdSZ{dPdKdLdTdUdVZ|d'dWdKdLdXdYdZZ}dPdKdLdTd[d\Z~dJdKdLdTd]d^ZdJdKdLdTd_d`Zdodbdcd'ddd1dedfdgdLdh	didjZd'dkdldmdnZdS )pz^This module includes classes and functions designed specifically for use with the mypy plugin.    )annotationsN)ConfigParser)AnyCallableIterator)	ErrorCode)expand_typeexpand_type_by_instance) 	ARG_NAMEDARG_NAMED_OPTARG_OPTARG_POS	ARG_STAR2	INVARIANTMDEFArgumentAssignmentStmtBlockCallExprClassDefContext	DecoratorDictExprEllipsisExpr
ExpressionFuncDefIfStmtJsonDict
MemberExprNameExprPassStmtPlaceholderNodeRefExpr	StatementStrExprSymbolTableNodeTempNode	TypeAliasTypeInfoVar)Options)CheckerPluginInterfaceClassDefContextFunctionContextMethodContextPluginReportConfigContextSemanticAnalyzerPluginInterface)dataclasses)deserialize_and_fixup_type)set_callable_name)make_wildcard_trigger)state)map_type_from_supertype)AnyTypeCallableTypeInstanceNoneType
OverloadedType	TypeOfAnyTypeTypeTypeVarType	UnionTypeget_proper_type)fill_typevars)get_unique_redefinition_name)__version__)_fields)parse_mypy_version)
TypeVarDef)r@   pydantic-mypyzpydantic-mypy-metadatazpydantic.main.BaseModelz#pydantic_settings.main.BaseSettingszpydantic.root_model.RootModelz5pydantic._internal._model_construction.ModelMetaclasszpydantic.fields.Fieldzpydantic.dataclasses.dataclass.pydantic.functional_validators.model_validator>   z.pydantic.functional_validators.field_validatorz0pydantic.functional_serializers.model_serializerz*pydantic.functional_serializers.serializerrJ   z3pydantic.deprecated.class_validators.root_validatorz.pydantic.deprecated.class_validators.validator)r   i  builtins__builtins__   strztype[Plugin])versionreturnc                 C  s   t S )a!  `version` is the mypy version string.

    We might want to use this to print a warning if the mypy version being used is
    newer, or especially older, than we expect (or need).

    Args:
        version: The mypy version string.

    Return:
        The Pydantic mypy plugin type.
    )PydanticPlugin)rO    rR   F/var/www/ai-form-bot/venv/lib/python3.9/site-packages/pydantic/mypy.pyplugins   s    rT   c                      s   e Zd ZdZddd fddZddd	d
dZddd	ddZddd	ddZddd	ddZddd	ddZ	dddddZ
dddddZdddd d!Zd"d#dd$d%Z  ZS )&rQ   zThe Pydantic mypy plugin.r*   NoneoptionsrP   c                   s&   t || _| j | _t | d S N)PydanticPluginConfigplugin_configto_data_plugin_datasuper__init__)selfrW   	__class__rR   rS   r^      s    
zPydanticPlugin.__init__rN   z(Callable[[ClassDefContext], bool] | None)fullnamerP   c                 C  s:   |  |}|r6t|jtr6tdd |jjD r6| jS dS )zUpdate Pydantic model class.c                 s  s   | ]}|j tkV  qd S rX   )rb   BASEMODEL_FULLNAME.0baserR   rR   rS   	<genexpr>       z5PydanticPlugin.get_base_class_hook.<locals>.<genexpr>N)lookup_fully_qualified
isinstancenoder(   anymro$_pydantic_model_class_maker_callbackr_   rb   symrR   rR   rS   get_base_class_hook   s
    
z"PydanticPlugin.get_base_class_hookz(Callable[[ClassDefContext], None] | Nonec                 C  s   |t kr| jS dS )z,Update Pydantic `ModelMetaclass` definition.N)MODEL_METACLASS_FULLNAME)_pydantic_model_metaclass_marker_callbackr_   rb   rR   rR   rS   get_metaclass_hook   s    z!PydanticPlugin.get_metaclass_hookz(Callable[[FunctionContext], Type] | Nonec                 C  s"   |  |}|r|jtkr| jS dS )z/Adjust the return type of the `Field` function.N)ri   rb   FIELD_FULLNAME_pydantic_field_callbackro   rR   rR   rS   get_function_hook   s    
z PydanticPlugin.get_function_hookz&Callable[[MethodContext], Type] | Nonec                 C  s   | drtS dS )z-Adjust return type of `from_orm` method call.z	.from_ormN)endswithfrom_attributes_callbackrt   rR   rR   rS   get_method_hook   s    
zPydanticPlugin.get_method_hookc                 C  s   |t krtdk rtjS dS )zMark pydantic.dataclasses as dataclass.

        Mypy version 1.1.1 added support for `@dataclass_transform` decorator.
        )   r|   N)DATACLASS_FULLNAMEMYPY_VERSION_TUPLEr2   Zdataclass_class_maker_callbackrt   rR   rR   rS   get_class_decorator_hook   s    z'PydanticPlugin.get_class_decorator_hookr0   dict[str, Any]ctxrP   c                 C  s   | j S )zjReturn all plugin config data.

        Used by mypy to determine if cache needs to be discarded.
        )r\   )r_   r   rR   rR   rS   report_config_data   s    z!PydanticPlugin.report_config_datar,   boolc                 C  s   t |j|j|j| j}| S rX   )PydanticModelTransformerclsreasonapirZ   	transform)r_   r   ZtransformerrR   rR   rS   rn      s    z3PydanticPlugin._pydantic_model_class_maker_callbackc                 C  s<   | j jrdS |jjj}|s"J dt|jddr8d|j_dS )zReset dataclass_transform_spec attribute of ModelMetaclass.

        Let the plugin handle it. This behavior can be disabled
        if 'debug_dataclass_transform' is set to True', for testing purposes.
        Nz-callback not passed from 'get_metaclass_hook'dataclass_transform_spec)rZ   debug_dataclass_transformr   infoZdeclared_metaclassgetattrtyper   )r_   r   Zinfo_metaclassrR   rR   rS   rs      s    
z8PydanticPlugin._pydantic_model_metaclass_marker_callbackr-   r=   c           	        s  |j  |jd dksJ d|jd dks2J d|jd }|jd }|r`|r`t|j|j  S |r|jd d }|d }t|ts|S nt|r|jd d }t|t	r|j
d }t|tr|j}t|dd}|rtd	d
 |D rt fdd
|D |_|S  S )ao  Extract the type of the `default` argument from the Field function, and use it as the return type.

        In particular:
        * Check whether the default and default_factory argument is specified.
        * Output an error if both are specified.
        * Retrieve the type of the argument which is specified, and use it as return type for the function.
        r   defaultz0"default" is no longer first argument in Field()r|   default_factoryz9"default_factory" is no longer second argument in Field()argsNc                 s  s   | ]}t |tV  qd S rX   )rj   r@   )re   argrR   rR   rS   rg      rh   z:PydanticPlugin._pydantic_field_callback.<locals>.<genexpr>c                 3  s   | ]
} V  qd S rX   rR   )re   _Zdefault_any_typerR   rS   rg      rh   )default_return_typeZcallee_arg_namesr   +error_default_and_default_factory_specifiedr   context	arg_typesrj   r   r<   itemsr9   ret_typer   alltuple)	r_   r   Zdefault_argsZdefault_factory_argsZdefault_typeZdefault_argZdefault_factory_typer   r   rR   r   rS   rw      s2    





z'PydanticPlugin._pydantic_field_callback)__name__
__module____qualname____doc__r^   rq   ru   rx   r{   r   r   rn   rs   rw   __classcell__rR   rR   r`   rS   rQ      s   		rQ   c                   @  sT   e Zd ZU dZdZded< ded< ded< ded< dd	d
ddZddddZdS )rY   a  A Pydantic mypy plugin config holder.

    Attributes:
        init_forbid_extra: Whether to add a `**kwargs` at the end of the generated `__init__` signature.
        init_typed: Whether to annotate fields in the generated `__init__`.
        warn_required_dynamic_aliases: Whether to raise required dynamic aliases error.
        debug_dataclass_transform: Whether to not reset `dataclass_transform_spec` attribute
            of `ModelMetaclass` for testing purposes.
    )init_forbid_extra
init_typedwarn_required_dynamic_aliasesr   r   r   r   r   r   r*   rU   rV   c                 C  s   |j d u rd S t|j }|d urr|di di }| jD ]4}||d}t|tsbtd| t| || q:n:t }|	|j  | jD ] }|j
t|dd}t| || qd S )NZtoolrI   Fz/Configuration value must be a boolean for key: )fallback)config_file
parse_tomlget	__slots__rj   r   
ValueErrorsetattrr   read
getbooleanCONFIGFILE_KEY)r_   rW   Ztoml_configconfigkeyZsettingrZ   rR   rR   rS   r^     s    




zPydanticPluginConfig.__init__r   rP   c                   s    fdd j D S )z/Returns a dict of config names to their values.c                   s   i | ]}|t  |qS rR   )r   )re   r   r_   rR   rS   
<dictcomp>#  rh   z0PydanticPluginConfig.to_data.<locals>.<dictcomp>)r   r   rR   r   rS   r[   !  s    zPydanticPluginConfig.to_dataN)r   r   r   r   r   __annotations__r^   r[   rR   rR   rR   rS   rY      s   

rY   r.   r=   r   c                 C  s   | j }t|tr|j}t|tr4t|jtr4|j}n<t|trD|}n,d| d|jj d}t	|| j
| j | jS |j jt}|du r| jS |di d}|durt|j j| j
| j | jS )z1Raise an error if from_attributes is not enabled.z
ctx.type: 
 (of type )Nr   from_attributesT)r   rj   r?   itemr9   r   r:   ra   r   error_unexpected_behaviorr   r   r   metadatar   METADATA_KEYerror_from_attributesname)r   Zctx_typeZ
model_typedetailZpydantic_metadatar   rR   rR   rS   rz   &  s"    

rz   c                	   @  s   e Zd ZdZdddddddddd	d
ZddddddddddZd$dddddddZd%ddddddddZddddZe	dddd dddZ
dddd d!d"Zd#S )&PydanticModelFieldz5Based on mypy.plugins.dataclasses.DataclassAttribute.rN   z
str | Noner   intType | Noner(   r   aliashas_dynamic_aliashas_defaultlinecolumnr   r   c	           	      C  s4   || _ || _|| _|| _|| _|| _|| _|| _d S rX   r   )	r_   r   r   r   r   r   r   r   r   rR   rR   rS   r^   @  s    zPydanticModelField.__init__r1   r   )current_infotypedforce_optional	use_aliasr   force_typevars_invariantrP   c           	      C  sH   |  ||||}|r | ||nttj}t||d|s<| jr@tntdS )zABased on mypy.plugins.dataclasses.DataclassAttribute.to_argument.N)variabletype_annotationZinitializerkind)	to_varr   r8   r>   explicitr   r   r   r
   )	r_   r   r   r   r   r   r   r   r   rR   rR   rS   to_argumentT  s    
zPydanticModelField.to_argumentF)r   r   r   rP   c                 C  s   |r&t | jtr&| j }t|_|| _| jdurt| jdddurt	|j
jN t|}|rz|jD ]}t |trdt|_qdt| j| jjj|iW  d   S 1 s0    Y  | jS )zABased on mypy.plugins.dataclasses.DataclassAttribute.expand_type.N	self_type)rj   r   r@   Zcopy_modifiedr   Zvariancer   r   r6   strict_optional_setrW   strict_optionalrC   r   r   r   id)r_   r   r   r   Zmodified_typeZfilled_with_typevarsr   rR   rR   rS   r   g  s    


4zPydanticModelField.expand_typer)   )r   r   r   r   rP   c                 C  s0   |r| j dur| j }n| j}t|| |||S )z<Based on mypy.plugins.dataclasses.DataclassAttribute.to_var.N)r   r   r)   r   )r_   r   r   r   r   r   rR   rR   rS   r     s    zPydanticModelField.to_varr   r   c                 C  s0   | j s
J | j| j| j| j| j| j| j  dS )?Based on mypy.plugins.dataclasses.DataclassAttribute.serialize.)r   r   r   r   r   r   r   )r   r   r   r   r   r   r   	serializer   rR   rR   rS   r     s    
zPydanticModelField.serialize)r   datar   rP   c                 C  s,   |  }t|d|}| f ||d|S )ABased on mypy.plugins.dataclasses.DataclassAttribute.deserialize.r   )r   r   )copyr3   pop)r   r   r   r   typrR   rR   rS   deserialize  s    zPydanticModelField.deserializerU   )sub_typer   rP   c                 C  sN   | j durJt|jj" t| j || j| _ W d   n1 s@0    Y  dS )zxExpands type vars in the context of a subtype when an attribute is inherited
        from a generic super type.
        N)r   r6   r   rW   r   r7   r   )r_   r   r   rR   rR   rS   expand_typevar_from_subtype  s    
z.PydanticModelField.expand_typevar_from_subtypeN)F)F)r   r   r   r   r^   r   r   r   r   classmethodr   r   rR   rR   rR   rS   r   =  s    " r   c                   @  s:   e Zd ZdZdd Zedd dddZddd	d
ZdS )PydanticModelClassVarzBased on mypy.plugins.dataclasses.DataclassAttribute.

    ClassVars are ignored by subclasses.

    Attributes:
        name: the ClassVar name
    c                 C  s
   || _ d S rX   r   )r_   r   rR   rR   rS   r^     s    zPydanticModelClassVar.__init__r   )r   rP   c                 C  s   |  }| f i |S )r   )r   )r   r   rR   rR   rS   r     s    z!PydanticModelClassVar.deserializer   c                 C  s
   d| j iS )r   r   r   r   rR   rR   rS   r     s    zPydanticModelClassVar.serializeN)r   r   r   r   r^   r   r   r   rR   rR   rR   rS   r     s
   r   c                	   @  s|  e Zd ZU dZh dZded< ddddd	d
ddZddddZd	dddZddddZ	ddddddZ
dddddZddd d!d"Zd#dd$d%d&d'd(Zd)d*d+d,d-d.d/Zd0dddd	d1d2d3Zd0ddd	d4d5d6Zd0ddd	d7d8d9ZdPd*d;dd<d=d>d?Zed#ddd@dAZed#dBddCdDZdQd0ddddddEdFdGdHZd0dddIdJdKZed0dddLdMdNZdOS )Rr   zTransform the BaseModel subclass according to the plugin settings.

    Attributes:
        tracked_config_fields: A set of field configs that the plugin has to track their value.
    >   populate_by_nameextrafrozenr   alias_generatorzset[str]tracked_config_fieldsr   zExpression | Statementr1   rY   rU   )r   r   r   rZ   rP   c                 C  s   || _ || _|| _|| _d S rX   )_clsZ_reason_apirZ   )r_   r   r   r   rZ   rR   rR   rS   r^     s    z!PydanticModelTransformer.__init__r   r   c                 C  s   | j j}tdd |jdd D }|  }| ||\}}|du sL|du rPdS |D ]}|jdu rT dS qTtdd |jdd D }| |||| |s| ||| | j	|| j
|jdu d |   d	d
 |D dd
 |D | d|jt< dS )a  Configures the BaseModel subclass according to the plugin settings.

        In particular:

        * determines the model config and fields,
        * adds a fields-aware signature for the initializer and construct methods
        * freezes the class if frozen = True
        * stores the fields, config, and if the class is settings in the mypy metadata for access by subclasses
        c                 s  s   | ]}t |jv V  qd S rX   )ROOT_MODEL_FULLNAMErb   rd   rR   rR   rS   rg     rh   z5PydanticModelTransformer.transform.<locals>.<genexpr>NFc                 s  s   | ]}|j tkV  qd S rX   )rb   BASESETTINGS_FULLNAMErd   rR   rR   rS   rg     rh   T)r   c                 S  s   i | ]}|j | qS rR   r   r   re   fieldrR   rR   rS   r     rh   z6PydanticModelTransformer.transform.<locals>.<dictcomp>c                 S  s   i | ]}|j | qS rR   r   )re   Z	class_varrR   rR   rS   r     rh   )fields
class_varsr   )r   r   rl   rm   collect_configcollect_fields_and_class_varsr   add_initializeradd_model_construct_method
set_frozenr   r   adjust_decorator_signaturesget_values_dictr   r   )r_   r   is_root_modelr   r   r   r   is_settingsrR   rR   rS   r     s(    

z"PydanticModelTransformer.transformc                   s   | j jj D ]t\}}t|jtr|jjd  t trt j	t
r j	jtv r j	jtkrxt fddt jD sd|jj_qdS )a  When we decorate a function `f` with `pydantic.validator(...)`, `pydantic.field_validator`
        or `pydantic.serializer(...)`, mypy sees `f` as a regular method taking a `self` instance,
        even though pydantic internally wraps `f` with `classmethod` if necessary.

        Teach mypy this by marking any function whose outermost decorator is a `validator()`,
        `field_validator()` or `serializer()` call as a `classmethod`.
        r   c                 3  s4   | ],\}} j | d ko*t|to*|jdkV  qdS )modeafterN)	arg_namesrj   r$   value)re   ir   Z	first_decrR   rS   rg     s   zGPydanticModelTransformer.adjust_decorator_signatures.<locals>.<genexpr>TN)r   r   namesr   rj   rk   r   Zoriginal_decoratorsr   calleer   rb   DECORATOR_FULLNAMESMODEL_VALIDATOR_FULLNAMErl   	enumerater   funcis_class)r_   r   rp   rR   r  rS   r   
  s     


z4PydanticModelTransformer.adjust_decorator_signaturesModelConfigDatac              	   C  sL  | j }t }d}d}|j D ]&\}}| ||}|rd}|| qd}|jjD ]V}t|t	t
fshqRt|t	r"|jd }	t|	trR|	jdkrqRt|jtrt|jj|jjD ](\}
}|
du rq|| j|
|dd qnBt|jtr|jjD ]*\}}t|ts
q|| |j| qnjt|t
r|jdkr<qR|jjD ]F}t|t	sXqD|jd }	t|	tsrqD|| |	j|j qD|r| jd|  qd}qR|s|r|r|jr|js| jjrt| j| |jjd	d D ]R}t|j vrq| j!t"|j# |j t d
  D ]\}}|$|| q,q|S )zhCollects the values of the config attributes that are used by the plugin, accounting for parent classes.FTNr   model_config)	lax_extraZConfigzYSpecifying config in two places is ambiguous, use either Config attribute or class kwargsr|   r   )%r   r	  keywordsr   get_config_updateupdatedefsbodyrj   r   r   lvaluesr   r   rvaluer   zipr   r   r   r$   r   r   failhas_alias_generatorr   rZ   r   error_required_dynamic_aliasesr   rm   r   r   add_plugin_dependencyr5   rb   
setdefault)r_   r   r   Zhas_config_kwargsZhas_config_from_namespacer   exprZconfig_datastmtlhsarg_namer   Zkey_exprZ
value_exprZsubstmtr   r   rR   rR   rS   r   %  sz    

z'PydanticModelTransformer.collect_configzJtuple[list[PydanticModelField] | None, list[PydanticModelClassVar] | None])r
  r   rP   c                 C  s  | j }i }i }t|jjdd D ]}t|jvr2q"| jt|j	 |jt d 
 D ]d\}}t||| j}	|	|j| j |	||< |jj|}
|
rV|
jrVt|
jtsV| jd|
j qV|jt d 
 D ]\}}t|||< qq"t }t }| |jD ]}| |||}t|tr`|jd }|rH|jdkrHt| j| n||j |||j< n,t|tr |jd }||j |||j< q t| t| fS )zACollects the fields for the model, accounting for parent classes.r|   r   r   z7BaseModel field may only be overridden by another fieldr   r   root)r   reversedr   rm   r   r   r   r  r5   rb   r   r   r   r   r  r   rk   rj   r)   r  r   set%_get_assignment_statements_from_blockr  $collect_field_or_class_var_from_stmtr  r    error_extra_fields_on_root_modeladdlistvalues)r_   r
  r   r   Zfound_fieldsZfound_class_varsr   r   r   r   sym_nodeZcurrent_field_namesZcurrent_class_vars_namesr  Zmaybe_fieldr  rR   rR   rS   r   q  sD    


z6PydanticModelTransformer.collect_fields_and_class_varsr   zIterator[AssignmentStmt])r  rP   c                 c  sJ   |j D ]}|js| |E d H  q|jd urF|jjsF| |jE d H  d S rX   )r  Zis_unreachabler   Z	else_body)r_   r  r  rR   rR   rS   ,_get_assignment_statements_from_if_statement  s
    
zEPydanticModelTransformer._get_assignment_statements_from_if_statementr   )blockrP   c                 c  s<   |j D ]0}t|tr|V  qt|tr| |E d H  qd S rX   )r  rj   r   r   r'  )r_   r(  r  rR   rR   rS   r     s
    


z>PydanticModelTransformer._get_assignment_statements_from_blockr   z dict[str, PydanticModelClassVar]z1PydanticModelField | PydanticModelClassVar | None)r  r
  r   rP   c              
   C  s,  | j }|jd }t|tr0t|jr0|jdkr4dS |jst|jt	rxt|jj
t	rxt|jj
j
trx|jj
j
jtv rxdS |j|v rdS t| j| dS |jd }t|tsdS t|jr|jdkrdS |jj|j}|du rdS |j}t|trdS t|tr| jd| dS t|ts&dS |jr8t|jS t|j}t|trj|jjdkrj| jd| | |}	|jdu r|jr|jr| jj|jdd}
|
r|
|_n| jd	| t t!j"|_| #|\}}|r|j$s| j%j&rt'| j| | (||j|}t)|j||	||j*|j+||jd
S )a^  Get pydantic model field from statement.

        Args:
            stmt: The statement.
            model_config: Configuration settings for the model.
            class_vars: ClassVars already known to be defined on the model.

        Returns:
            A pydantic model field if it could find the field in statement. Otherwise, `None`.
        r   r
  NzFType aliases inside BaseModel definitions are not supported at runtimezdataclasses.InitVarz%InitVar is not supported in BaseModelT)is_finalzGNeed type argument for Final[...] with non-literal default in BaseModel)r   r   r   r   r   r   r   r   ),r   r  rj   r   rF   Zis_valid_field_namer   Z
new_syntaxr  r   r  rb   r  error_untyped_fieldsr   r   r  r   rk   r!   r'   r  r)   Zis_classvarr   rB   r   r:   get_has_defaultr)  Zis_inferredZanalyze_simple_literal_typer8   r>   Z
from_errorget_alias_infor   rZ   r   r  _infer_dataclass_attr_init_typer   r   r   )r_   r  r
  r   r   r  rp   rk   Z	node_typer   r   r   r   Z	init_typerR   rR   rS   r!    s    
 
	






z=PydanticModelTransformer.collect_field_or_class_var_from_stmtr%   rN   r   r   )rp   r   r   rP   c           	      C  s   |j }|jr|S t|j }t|ts(|S |j d}|rt|jtr|j d}|sXJ |j rttt	|j |j |}n
t
tjS t|tr|jtttgkrt|jd |S | jd|j j d| n| jd|j j d| |S )zvInfer __init__ argument type for an attribute.

        In particular, possibly use the signature of __set__.
        __set__rM   z(Unsupported signature for "__set__" in ""zUnsupported "__set__" in ")r   ZimplicitrB   rj   r:   r   rk   r   Zget_containing_type_infor7   r8   r>   Zunannotatedr9   	arg_kindsr   r	   r   r   r  r   )	r_   rp   r   r   r   tsetterZ
super_infoZsetter_typerR   rR   rS   r-  =  s.    


z8PydanticModelTransformer._infer_dataclass_attr_init_typezlist[PydanticModelField])r   r   r   r   rP   c                 C  sr  d| j jjv r"| j jjd js"dS | jj}|jdu}t|joB|j }| j	|||||dd}|rt
dkr|d jtkrztnt|d _|r&| jtj}	d|	jv r&|	jd j}
|
dur&|
jdur&|
j}t|jD ]N\}}|ds|dsq| j|j| }t||}|t||dt q| ||sVtd	}|t|ttjdt  t!| j| j d|t" d
 dS )zAdds a fields-aware `__init__` method to the class.

        The added `__init__` will be annotated with types vs. all `Any` depending on the plugin settings.
        r^   NT)r   requires_dynamic_aliasesr   r   r   )r|   r   r|   r   __r   kwargs)r   return_type)#r   r   r  plugin_generatedrZ   r   r   r   r  get_field_argumentsr~   r   r
   r   r   r   ri   r   rk   r   r  r   
startswithZ	anal_typer   r)   appendr   should_init_forbid_extrar8   r>   r   r   
add_methodr;   )r_   r   r   r   r   r   r   r3  r   Zbase_settings_nodeZbase_settings_init_node	func_typeZarg_idxr  Zanalyzed_variable_typer   varrR   rR   rS   r   c  s>    
	
z(PydanticModelTransformer.add_initializer)r   r   r   rP   c           	      C  s   | j t d| j t dg}t|t g}ttd||dt}t	| j j
j$ | j|ddd|d}W d   n1 s0    Y  | ||std}|t|ttjdt |g| }t| j | jd	|t| jjdd
 dS )zAdds a fully typed `model_construct` classmethod to the class.

        Similar to the fields-aware __init__ method, but always uses the field names (not aliases),
        and does not treat settings fields as optional.
        z.setz.strZ_fields_setNTF)r   r3  r   r   r5  Zmodel_construct)r   r6  is_classmethod)r   
named_typeBUILTINS_NAMErA   r;   r   r)   r   r6   r   rW   r   r8  r;  r:  r8   r>   r   r   r<  r   rC   r   )	r_   r   r   r   Zset_strZoptional_set_strZfields_set_argumentr   r>  rR   rR   rS   r     s&    $
$

z3PydanticModelTransformer.add_model_construct_method)r   r   r   rP   c           
   	   C  s   | j j}|D ]}|j|j}|dur|j}t|tr>||_qt|t	r\| j
js\| j
  qzt|}W n ty   t|}Y n0 d| d|j d}	t|	| j
| j  q|j||dd}||_||_|jd |j |_tt||j|j< qdS )zMarks all fields as properties so that attempts to set them trigger mypy errors.

        This is the same approach used by the attrs and dataclasses plugins.
        Nzsym_node.node: r   r   F)r   .)r   r   r  r   r   rk   rj   r)   Zis_propertyr!   r   Zfinal_iterationZdeferrN   	TypeErrorreprra   r   r   rb   	_fullnamer%   r   )
r_   r   r   r   r   r   r&  r>  Zvar_strr   rR   rR   rS   r     s(    
z#PydanticModelTransformer.set_frozenFr   ModelConfigData | None)r   r   r  rP   c                 C  s   || j vrdS |dkrbt|tr,|jdk}n,t|trB|jdk}n|sTt|| j| dS t|dS |dkrd}t|t	r|j
dkrd}t|d	S t|t	r|j
d
v rtf i ||j
dkiS t|| j| dS )zDetermines the config update due to a single kwarg in the ConfigDict definition.

        Warns if a tracked config attribute is set to a value the plugin doesn't know how to interpret (e.g., an int)
        Nr   Zforbid)forbid_extrar   Tbuiltins.NoneF)r  )builtins.Truezbuiltins.FalserI  )r   rj   r$   r   r   r   error_invalid_config_valuer   r	  r   rb   )r_   r   r   r  rG  r  rR   rR   rS   r    s(    


	

z*PydanticModelTransformer.get_config_updatec                 C  s   | j }t|trdS t|trt|jtr|jjtkrt|j	|j
D ]H\}}|du s\|dkrj|jtu  S |dkrDt|to|jdk   S qDdS t|t S )zUReturns a boolean indicating whether the field defined in `stmt` is a required field.FNr   r   rH  )r  rj   r&   r   r  r"   rb   rv   r  r   r   ra   r   r   )r  r  r   r   rR   rR   rS   r+    s    
"z(PydanticModelTransformer.get_has_defaultztuple[str | None, bool]c                 C  s   | j }t|trdS t|tr6t|jtr6|jjtks:dS t|j	D ]:\}}|dkrVqD|j
| }t|trx|jdf  S  dS qDdS )a  Returns a pair (alias, has_dynamic_alias), extracted from the declaration of the field defined in `stmt`.

        `has_dynamic_alias` is True if and only if an alias is provided, but not as a string literal.
        If `has_dynamic_alias` is True, `alias` will be None.
        )NFr   F)NT)r  rj   r&   r   r  r"   rb   rv   r  r   r   r$   r   )r  r  r   r  r   rR   rR   rS   r,    s$    




z'PydanticModelTransformer.get_alias_infolist[Argument])r   r   r   r3  r   r   rP   c                   s*   j j fdd|D }|S )zHelper function used during the construction of the `__init__` and `model_construct` method signatures.

        Returns a list of mypy Argument instances for use in the generated signatures.
        c              
     s2   g | ]*}r|j s|jp j d qS ))r   r   r   r   r   )r   r   r   r   r   r   r   r3  r_   r   r   rR   rS   
<listcomp>1  s   	
z@PydanticModelTransformer.get_field_arguments.<locals>.<listcomp>)r   r   )r_   r   r   r   r3  r   r   	argumentsrR   rL  rS   r8  #  s
    	z,PydanticModelTransformer.get_field_arguments)r   r   rP   c                 C  s.   |j s| |t|jrdS |jr&dS | jjS )a@  Indicates whether the generated `__init__` should get a `**kwargs` at the end of its signature.

        We disallow arbitrary kwargs if the extra config setting is "forbid", or if the plugin config says to,
        *unless* a required dynamic alias is present (since then we can't determine a valid signature).
        FT)r   is_dynamic_alias_presentr   r  rG  rZ   r   )r_   r   r   rR   rR   rS   r;  ?  s    z1PydanticModelTransformer.should_init_forbid_extra)r   r  rP   c                 C  s8   | D ]}|j r dS q|r4| D ]}|jdu r dS qdS )zReturns whether any fields on the model have a "dynamic alias", i.e., an alias that cannot be
        determined during static analysis.
        TNF)r   r   )r   r  r   rR   rR   rS   rO  L  s    
z1PydanticModelTransformer.is_dynamic_alias_presentN)F)F)r   r   r   r   r   r   r^   r   r   r   r   r'  r   r!  r-  r   r   r   r  staticmethodr+  r,  r8  r;  rO  rR   rR   rR   rS   r     s0   
%LA}&.#" r   c                   @  sX   e Zd ZdZdddddddddZddd	d
ZdddddZddddddZdS )r	  z(Pydantic mypy plugin model config class.Nzbool | NonerG  r   r   r   r  c                 C  s"   || _ || _|| _|| _|| _d S rX   rQ  )r_   rG  r   r   r   r  rR   rR   rS   r^   ^  s
    zModelConfigData.__init__r   r   c                 C  s   dd | j  D S )zReturns a dict of Pydantic model config names to their values.

        It includes the config if config value is not `None`.
        c                 S  s   i | ]\}}|d ur||qS rX   rR   )re   kvrR   rR   rS   r   q  rh   z3ModelConfigData.get_values_dict.<locals>.<dictcomp>)__dict__r   r   rR   rR   rS   r   l  s    zModelConfigData.get_values_dictrF  rU   )r   rP   c                 C  s2   |du rdS |   D ]\}}t| || qdS )z$Update Pydantic model config values.N)r   r   r   )r_   r   rR  rS  rR   rR   rS   r  s  s    zModelConfigData.updaterN   r   )r   r   rP   c                 C  s   t | |du rt| || dS )zFSet default value for Pydantic model config if config value is `None`.N)r   r   )r_   r   r   rR   rR   rS   r  z  s    zModelConfigData.setdefault)NNNNN)r   r   r   r   r^   r   r  r  rR   rR   rR   rS   r	  [  s        r	  zpydantic-ormzInvalid from_attributes callZPydanticzpydantic-configzInvalid config valuezpydantic-aliaszDynamic alias disallowedzpydantic-unexpectedzUnexpected behaviorzpydantic-fieldzUntyped field disallowedzInvalid Field defaultsz!Extra field on RootModel subclassr+   r   rU   )
model_namer   r   rP   c                 C  s   |j d|  d|td dS )zCEmits an error when the model does not have `from_attributes=True`.r/  z$" does not have from_attributes=TruecodeN)r  	ERROR_ORM)rU  r   r   rR   rR   rS   r     s    r   r1   )r   r   r   rP   c                 C  s   |j d|  d|td dS )z0Emits an error when the config value is invalid.zInvalid value for "Config.r/  rV  N)r  ERROR_CONFIG)r   r   r   rR   rR   rS   rJ    s    rJ  )r   r   rP   c                 C  s   | j d|td dS )znEmits required dynamic aliases error.

    This will be called when `warn_required_dynamic_aliases=True`.
    z#Required dynamic aliases disallowedrV  N)r  ERROR_ALIASr   r   rR   rR   rS   r    s    r  z8CheckerPluginInterface | SemanticAnalyzerPluginInterface)r   r   r   rP   c                 C  s4   d}d|  d}|d| d7 }|j ||td dS )z Emits unexpected behavior error.z6https://github.com/pydantic/pydantic/issues/new/choosez7The pydantic mypy plugin ran into unexpected behavior: 
z&Please consider reporting this bug at z so we can try to fix it!rV  N)r  ERROR_UNEXPECTED)r   r   r   linkZfull_messagerR   rR   rS   r     s    r   c                 C  s   | j d|td dS )z;Emits an error when there is an untyped field in the model.zUntyped fields disallowedrV  N)r  ERROR_UNTYPEDr[  rR   rR   rS   r*    s    r*  c                 C  s   | j d|td dS )z]Emits an error when there is more than just a root field defined for a subclass of RootModel.z2Only `root` is allowed as a field of a `RootModel`rV  N)r  ERROR_EXTRA_FIELD_ROOT_MODELr[  rR   rR   rS   r"    s    r"  c                 C  s   | j d|td dS )zNEmits an error when `Field` has both `default` and `default_factory` together.z>Field default and default_factory cannot be specified togetherrV  N)r  ERROR_FIELD_DEFAULTSr[  rR   rR   rS   r     s    r   Fz8SemanticAnalyzerPluginInterface | CheckerPluginInterfacer   rK  r   zTypeVarDef | Noner   )	r   r   r   r   r6  r   tvar_defr?  rP   c                 C  s
  |j }||jv r<|j| }	|	jr<t|	jtr<|jj|	j t| t	rR| 
d}
n| dg }
|r|pptt|}ttd|dtdg}n |pt|}ttd|dtg}|| }g g g   }}}|D ]8}|jsJ d||j ||jj ||j qt|||||
}|r|g|_t||tt g}||_ t|||_||_|jd | |_|j|_||jv rt ||j}|j| |j|< |rd|_!t||j}||_ |j|_d|_"t#|t$dg|}|j|_t%t&|}	n
t%t&|}	d|	_|	|j|< |j'jj| dS )	zhVery closely related to `mypy.plugins.common.add_method_to_class`, with a few pydantic-specific changes.zbuiltins.functionr   NTZ__pydantic_self__z"All arguments must be fully typed.rB  r   )(r   r  r7  rj   rk   r   r  r  remover1   r@  Znamed_generic_typer?   rC   r   r)   r   r   r:  r   r   r   r9   	variablesr   r    r4   r   r  rb   rE  r   rD   Zis_decoratedr?  r   r   r%   r   Zdefn)r   r   r   r   r6  r   rb  r?  r   rp   Zfunction_typefirstr   r   r0  r   	signaturer  Zr_namerS  decrR   rR   rS   r<    sZ    




r<  zdict[str, Any] | None)r   rP   c                 C  s   |  dsdS tjdkr"ddl}n4zddl}W n& tyT   ddl}|d Y dS 0 t| d}|	|W  d   S 1 s0    Y  dS )zReturns a dict of config keys to values.

    It reads configs from toml file and returns `None` if the file is not a toml file.
    z.tomlN)      r   zJNo TOML parser installed, cannot read configuration from `pyproject.toml`.rb)
ry   sysversion_infotomllibtomliImportErrorwarningswarnopenload)r   Ztoml_rp  rfrR   rR   rS   r     s    



r   )NNF)r   
__future__r   rk  configparserr   typingr   r   r   Zmypy.errorcodesr   Zmypy.expandtyper   r	   Z
mypy.nodesr
   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)   Zmypy.optionsr*   Zmypy.pluginr+   r,   r-   r.   r/   r0   r1   Zmypy.pluginsr2   Zmypy.plugins.commonr3   Zmypy.semanalr4   Zmypy.server.triggerr5   Z
mypy.stater6   Zmypy.typeopsr7   Z
mypy.typesr8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   Zmypy.typevarsrC   Z	mypy.utilrD   Zmypy.versionrE   Zmypy_versionZpydantic._internalrF   Zpydantic.versionrG   rH   ro  r   r   rc   r   r   rr   rv   r}   r  r  r~   rA  rT   rQ   rY   rz   r   r   r   r	  rX  rY  rZ  r]  r_  ra  r`  r   rJ  r  r   r*  r"  r   r<  r   rR   rR   rR   rS   <module>   s   "$	4
v.s     %    X