a
    “˜ëj’î  ã                   @  sª  d Z ddlmZ ddlZddlmZ ddlmZ ddlm	Z	m
Z
 ddl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/m0Z0m1Z1m2Z2 dd
l3m4Z4 ddl5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z< ddl=m>Z> ddl?m@Z@ ddlAmBZB ddlCmDZD ddlEmFZF ddlGmHZH ddlmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPmQZQmRZR ddlSmTZT ddlUmVZV ddlWmXZY ddlZm[Z[ ddl\m]Z] dZ^dZ_dZ`dZadZbdZcdZddZed Zfd!Zgh d"£Zhehd#h Zie]eYƒZjd$Zkd%ZXd&d'd(œd)d*„ZlG d+d,„ d,e:ƒZmG d-d.„ d.ƒZnd/d0d1œd2d3„ZoG d4d5„ d5ƒZpG d6d7„ d7ƒZqG d8d9„ d9ƒZrG d:d;„ d;eFƒZsG d<d=„ d=ƒZtd>d?d@œdAdB„ZuedCdDdEƒZvedFdGdEƒZwedHdIdEƒZxedJdKdEƒZyedLdMdEƒZzedLdNdEƒZ{edLdOdEƒZ|d&dPdQdRdSœdTdU„Z}d&dVdQdRdWœdXdY„Z~dVdQdRdZœd[d\„Zd&d]dQdRd^œd_d`„Z€dVdQdRdZœdadb„Z�dPdQdRdZœdcdd„Z‚drdfdgd&dhd0didjd?dRdkœ	dldm„Zƒd&dndoœdpdq„Z„dS )sz^This module includes classes and functions designed specifically for use with the mypy plugin.é    )ÚannotationsN)ÚIterator)ÚConfigParser)ÚAnyÚCallable)Ú	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ÚDynamicClassDefContextÚMethodContextÚPluginÚReportConfigContextÚSemanticAnalyzerPluginInterface)Údeserialize_and_fixup_type)Úset_callable_name)Úmake_wildcard_trigger)Ústate)ÚTypeTranslator)Úmap_type_from_supertype)
ÚAnyTypeÚCallableTypeÚInstanceÚNoneTypeÚTypeÚ	TypeOfAnyÚTypeTypeÚTypeVarTypeÚ	UnionTypeÚget_proper_type)Úfill_typevars)Úget_unique_redefinition_name)Ú__version__)Ú_fields)Úparse_mypy_versionúpydantic-mypyzpydantic-mypy-metadatazpydantic.main.BaseModelzpydantic.main.create_modelz#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_serializers.serializerz3pydantic.deprecated.class_validators.root_validatorz.pydantic.deprecated.class_validators.validatorú0pydantic.functional_serializers.model_serializerrH   z.pydantic.functional_validators.field_validatorrI   Ú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)rM   © rP   úL/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/pydantic/mypy.pyÚpluginq   s    rR   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‡  ZS )!rO   zThe Pydantic mypy plugin.r*   ÚNone©ÚoptionsrN   c                   s&   t |ƒ| _| j ¡ | _tƒ  |¡ d S ©N)ÚPydanticPluginConfigÚplugin_configÚto_dataÚ_plugin_dataÚsuperÚ__init__)ÚselfrU   ©Ú	__class__rP   rQ   r\   ƒ   s    
zPydanticPlugin.__init__rL   z(Callable[[ClassDefContext], None] | None)ÚfullnamerN   c                 C  s0   |   |¡}|r,t|jtƒr,|j t¡r,| jS dS )zUpdate Pydantic model class.N)Úlookup_fully_qualifiedÚ
isinstanceÚnoder(   Úhas_baseÚBASEMODEL_FULLNAMEÚ$_pydantic_model_class_maker_callback)r]   r`   ÚsymrP   rP   rQ   Úget_base_class_hookˆ   s
    
z"PydanticPlugin.get_base_class_hookc                 C  s   |t kr| jS dS )z,Update Pydantic `ModelMetaclass` definition.N)ÚMODEL_METACLASS_FULLNAMEÚ)_pydantic_model_metaclass_marker_callback©r]   r`   rP   rP   rQ   Úget_metaclass_hook‘   s    z!PydanticPlugin.get_metaclass_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_callbackrk   rP   rP   rQ   Úget_method_hook—   s    
zPydanticPlugin.get_method_hookz/Callable[[DynamicClassDefContext], None] | Nonec                 C  s   |t kr| jS dS )zARecognize `create_model()` calls as dynamic BaseModel subclasses.N)ÚCREATE_MODEL_FULLNAMEÚ_pydantic_create_model_callbackrk   rP   rP   rQ   Úget_dynamic_class_hook�   s    z%PydanticPlugin.get_dynamic_class_hookr0   údict[str, Any]©ÚctxrN   c                 C  s   | j S )zjReturn all plugin config data.

        Used by mypy to determine if cache needs to be discarded.
        )rZ   )r]   ru   rP   rP   rQ   Úreport_config_data£   s    z!PydanticPlugin.report_config_datar,   c                 C  s"   t |j|j|j| jƒ}| ¡  d S rV   )ÚPydanticModelTransformerÚclsÚreasonÚapirX   Ú	transform)r]   ru   ZtransformerrP   rP   rQ   rf   ª   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 )zÓReset 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)rX   Údebug_dataclass_transformrx   ÚinfoZdeclared_metaclassÚgetattrÚtyper|   )r]   ru   Zinfo_metaclassrP   rP   rQ   rj   ®   s    
z8PydanticPlugin._pydantic_model_metaclass_marker_callbackr-   c           	      C  s  t }t|jj|jjƒD ]`\}}|dkrt|tƒr|jdurt|jtƒrP|jj	}qt|jt
ƒrt|jjtƒr|jjjj	}q|j |¡}|du s˜t|jtƒs¼|j t ¡}|du s¸t|jtƒs¼dS |j}t|ƒ}t|tƒsØJ ‚|j |j||jj¡}|j|_|j |jtt|ƒ¡ dS )zFMake variables assigned from `create_model()` usable as types by mypy.Ú__base__N)re   ÚzipÚcallÚ	arg_namesÚargsrb   r"   rc   r(   r`   r)   r€   r:   rz   Zlookup_fully_qualified_or_nonerB   Zbasic_new_typeinfoÚnameÚlineZmetaclass_typeZadd_symbol_table_noder%   r   )	r]   ru   Zbase_fullnameÚarg_nameZarg_exprZbase_symZ	base_infoZbase_instancer~   rP   rP   rQ   rq   »   s$    
z.PydanticPlugin._pydantic_create_model_callback)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r\   rh   rl   ro   rr   rv   rf   rj   rq   Ú__classcell__rP   rP   r^   rQ   rO   €   s   	rO   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 )rW   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}   ÚboolrŽ   r�   r�   r}   r*   rS   rT   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| ||ƒ qŠd S )NZtoolrG   Fz/Configuration value must be a boolean for key: )Úfallback)Úconfig_fileÚ
parse_tomlÚgetÚ	__slots__rb   r‘   Ú
ValueErrorÚsetattrr   ÚreadÚ
getbooleanÚCONFIGFILE_KEY)r]   rU   Ztoml_configÚconfigÚkeyZsettingrX   rP   rP   rQ   r\   í   s    




zPydanticPluginConfig.__init__rs   ©rN   c                   s   ‡ fdd„ˆ j D ƒS )z/Returns a dict of config names to their values.c                   s   i | ]}|t ˆ |ƒ“qS rP   )r   )Ú.0r�   ©r]   rP   rQ   Ú
<dictcomp>  ó    z0PydanticPluginConfig.to_data.<locals>.<dictcomp>)r–   r    rP   r    rQ   rY      s    zPydanticPluginConfig.to_dataN)r‰   rŠ   r‹   rŒ   r–   Ú__annotations__r\   rY   rP   rP   rP   rQ   rW   ×   s   

rW   r.   r<   rt   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 |j  t¡sž| jS | di ¡ d¡}|durÌt|j j| j
| jƒ | jS )z1Raise an error if from_attributes is not enabled.z
ctx.type: z
 (of type ú)Nrœ   Úfrom_attributesT)r€   rb   r>   Úitemr9   Zret_typer:   r_   r‰   Úerror_unexpected_behaviorrz   ÚcontextZdefault_return_typeÚmetadatar•   ÚMETADATA_KEYrd   re   Úerror_from_attributesr†   )ru   Zctx_typeZ
model_typeÚdetailZpydantic_metadatar¥   rP   rP   rQ   rn     s&    

rn   c                   @  s¶   e Zd ZdZddddddddddd	œ
d
d„Zddddddddddœ	dd„Zd%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.rL   z
str | Noner‘   úbool | NoneÚintúType | Noner(   ©
r†   ÚaliasÚ	is_frozenÚhas_dynamic_aliasÚhas_defaultÚstrictr‡   Úcolumnr€   r~   c                 C  s@   || _ || _|| _|| _|| _|| _|| _|| _|	| _|
| _	d S rV   r±   )r]   r†   r²   r³   r´   rµ   r¶   r‡   r·   r€   r~   rP   rP   rQ   r\   "  s    zPydanticModelField.__init__r1   r   )	Úcurrent_infoÚtypedÚmodel_strictÚforce_optionalÚ	use_aliasrz   Úforce_typevars_invariantÚis_root_model_rootrN   c	                 C  sn   |   ||||¡}	| jdu r|n| j}
|s,|
r>| j||dd�}n
ttjƒ}t|	|d|rXtn|sb| jrft	nt
d�S )zABased on mypy.plugins.dataclasses.DataclassAttribute.to_argument.NT)Úinclude_root_type)ÚvariableÚtype_annotationZinitializerÚkind)Úto_varr¶   r   r8   r=   Úexplicitr   r   rµ   r   r
   )r]   r¸   r¹   rº   r»   r¼   rz   r½   r¾   rÀ   r¶   rÁ   rP   rP   rQ   Úto_argument:  s    
ÿúzPydanticModelField.to_argumentF)r¸   rz   r½   r¿   rN   c                 C  s  |r&t | jtƒr&| j ¡ }t|_|| _| jdu�r| jjdu�rt 	|j
j¡�´ t|ƒ}t |tƒsfJ ‚|r†|jD ]}t |tƒrpt|_qpt| j| jjj|iƒ}|rðt |tƒrðt|jƒrð|jd j}	|	du rÚ|W  d  ƒ S t|	|ƒ}
t||
gƒ}|W  d  ƒ S 1 �s
0    Y  | jS )zABased on mypy.plugins.dataclasses.DataclassAttribute.expand_type.NÚroot)rb   r€   r?   Úcopy_modifiedr   Zvariancer~   Ú	self_typer5   Ústrict_optional_setrU   Ústrict_optionalrB   r:   r…   r   ÚidÚis_root_modelr	   r@   )r]   r¸   rz   r½   r¿   Zmodified_typeZfilled_with_typevarsÚargZexpanded_typeZ	root_typeZexpanded_root_typerP   rP   rQ   r   W  s,    



$zPydanticModelField.expand_typer)   )r¸   rz   r¼   r½   rN   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¸   rz   r¼   r½   r†   rP   rP   rQ   rÃ   „  s    zPydanticModelField.to_varr   rž   c              
   C  s8   | j s
J ‚| j| 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´   rµ   r¶   r‡   r·   Ú	serializer    rP   rP   rQ   rÏ   “  s    
÷zPydanticModelField.serialize)r~   Údatarz   rN   c                 C  s,   |  ¡ }t| d¡|ƒ}| f ||dœ|¤ŽS )úABased on mypy.plugins.dataclasses.DataclassAttribute.deserialize.r€   )r€   r~   )Úcopyr2   Úpop)rx   r~   rÐ   rz   ÚtyprP   rP   rQ   Údeserialize¢  s    zPydanticModelField.deserializerS   )Úsub_typerz   rN   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€   r5   rÉ   rU   rÊ   r7   r~   )r]   rÖ   rz   rP   rP   rQ   Úexpand_typevar_from_subtype©  s    
z.PydanticModelField.expand_typevar_from_subtypeN)FF)F)r‰   rŠ   r‹   rŒ   r\   rÅ   r   rÃ   rÏ   ÚclassmethodrÕ   r×   rP   rP   rP   rQ   r­     s    !  û2 û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 )ÚPydanticModelClassVarz•Based on mypy.plugins.dataclasses.DataclassAttribute.

    ClassVars are ignored by subclasses.

    Attributes:
        name: the ClassVar name
    c                 C  s
   || _ d S rV   ©r†   )r]   r†   rP   rP   rQ   r\   »  s    zPydanticModelClassVar.__init__r   )rÐ   rN   c                 C  s   |  ¡ }| f i |¤ŽS )rÑ   )rÒ   )rx   rÐ   rP   rP   rQ   rÕ   ¾  s    z!PydanticModelClassVar.deserializerž   c                 C  s
   d| j iS )rÎ   r†   rÚ   r    rP   rP   rQ   rÏ   Ä  s    ÿzPydanticModelClassVar.serializeN)r‰   rŠ   r‹   rŒ   r\   rØ   rÕ   rÏ   rP   rP   rP   rQ   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d	d1œd4d5„Zd0ddd	d6œd7d8„ZdTd*d:dd;d<œd=d>„Zed#ddœd?d@„ƒZed#dAdœdBdC„ƒZed#dDdœdEdF„ƒZed#ddœdGdH„ƒZdUd0ddddddddIdJœ	dKdL„Zd0dddMœdNdO„Zed0dddPœdQdR„ƒZdSS )Vrw   z¸Transform 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.
    >   ÚextraÚvalidate_by_aliasÚpopulate_by_nameÚalias_generatorÚvalidate_by_namer¥   Úfrozenr¶   zset[str]Útracked_config_fieldsr   zExpression | Statementr1   rW   rS   )rx   ry   rz   rX   rN   c                 C  s   || _ || _|| _|| _d S rV   )Ú_clsZ_reasonÚ_apirX   )r]   rx   ry   rz   rX   rP   rP   rQ   r\   Ý  s    z!PydanticModelTransformer.__init__r‘   rž   c                 C  sÎ   | j j}t|ƒ}|  ¡ }|  ||¡\}}|du s8|du r<dS |D ]}|jdu r@ dS q@| t¡}|  ||||¡ |  	||||¡ | 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
        NFT)rà   c                 S  s   i | ]}|j | ¡ “qS rP   ©r†   rÏ   ©rŸ   ÚfieldrP   rP   rQ   r¡     r¢   z6PydanticModelTransformer.transform.<locals>.<dictcomp>c                 S  s   i | ]}|j | ¡ “qS rP   rä   )rŸ   Z	class_varrP   rP   rQ   r¡     r¢   )ÚfieldsÚ
class_varsrœ   )râ   r~   rÌ   Úcollect_configÚcollect_fields_and_class_varsr€   rd   ÚBASESETTINGS_FULLNAMEÚadd_initializerÚadd_model_construct_methodÚ
set_frozenrã   rà   Úadjust_decorator_signaturesÚget_values_dictr©   rª   )r]   r~   Zis_a_root_modelrœ   rç   rè   ræ   Úis_settingsrP   rP   rQ   r{   ê  s&    


ýz"PydanticModelTransformer.transformc                   s„   | j jj ¡ D ]p}t|jtƒr|jjd ‰ tˆ tƒrtˆ j	t
ƒrˆ j	jtv rˆ j	jtkrtt‡ 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)r„   rb   r$   Úvalue)rŸ   ÚirÍ   ©Z	first_decrP   rQ   Ú	<genexpr>   s   ÿzGPydanticModelTransformer.adjust_decorator_signatures.<locals>.<genexpr>TN)râ   r~   ÚnamesÚvaluesrb   rc   r   Zoriginal_decoratorsr   Úcalleer   r`   Ú(IMPLICIT_CLASSMETHOD_DECORATOR_FULLNAMESÚMODEL_VALIDATOR_FULLNAMEÚanyÚ	enumerater…   ÚfuncÚis_class)r]   rg   rP   rö   rQ   rï     s     ÿ
þ
ý
úþùz4PydanticModelTransformer.adjust_decorator_signaturesÚModelConfigDatac              	   C  sT  | 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r”qRt|jtƒrÞt|jj|jjƒD ](\}
}|
du rÄq²| | j|
|dd�¡ q²nBt|jtƒ�rŒ|jjD ]*\}}t|tƒ�s
qô| |  |j|¡¡ qônjt|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|¡  �q¬d}qR|�s¸|�rì|�rì|j�rì|j�sì|j�sì| jj�rìt| j|ƒ |jjd	d… D ]R}t |j!v�r�qü| j "t#|j$ƒ¡ |j!t  d
  ¡ D ]\}}| %||¡ �q4�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 kwargsé   rœ   )&râ   r  ÚkeywordsÚitemsÚget_config_updateÚupdateÚdefsÚbodyrb   r   r   Úlvaluesr   r†   Úrvaluer   r‚   r„   r…   r   r$   rô   rã   ÚfailÚhas_alias_generatorrß   rÝ   rX   r�   Úerror_required_dynamic_aliasesr~   Úmrorª   r©   Úadd_plugin_dependencyr4   r`   Ú
setdefault)r]   rx   rœ   Zhas_config_kwargsZhas_config_from_namespacer†   ÚexprZconfig_dataÚstmtÚlhsrˆ   rÍ   Zkey_exprZ
value_exprZsubstmtr~   rô   rP   rP   rQ   ré   )  s~    

þÿþýýüz'PydanticModelTransformer.collect_configzJtuple[list[PydanticModelField] | None, list[PydanticModelClassVar] | None])r  rÌ   rN   c                 C  sÀ  | j }i }i }t|jjdd… ƒD ]È}t|jvr2q"| j t|j	ƒ¡ |jt d  
¡ D ]h\}}t ||| j¡}	|	 |j| j¡ |	||< |jj |¡}
|
rV|
jrVt|
jttfƒsV| j d|
j¡ qV|jt d  
¡ D ]\}}t |¡||< qÒq"tƒ }tƒ }|  |j¡D ]¢}|  |||¡}|du �r$�q|jd }t|tƒ�s>J ‚t|tƒ�r‚|�rj|jdk�rjt| j|ƒ n| |j¡ |||j< n"t|tƒ�r| |j¡ |||j< �qt|  ¡ ƒt|  ¡ ƒfS )	zACollects the fields for the model, accounting for parent classes.r  éÿÿÿÿrç   z7BaseModel field may only be overridden by another fieldrè   Nr   rÆ   )!râ   Úreversedr~   r  rª   r©   rã   r  r4   r`   r  r­   rÕ   r×   rø   r•   rc   rb   r)   r!   r  rÙ   ÚsetÚ%_get_assignment_statements_from_blockr	  Ú$collect_field_or_class_var_from_stmtr  r   r†   Ú error_extra_fields_on_root_modelÚaddÚlistrù   )r]   r  rÌ   rx   Zfound_fieldsZfound_class_varsr~   r†   rÐ   ræ   Úsym_nodeZcurrent_field_namesZcurrent_class_vars_namesr  Zmaybe_fieldr  rP   rP   rQ   rê   u  sH    
þ

z6PydanticModelTransformer.collect_fields_and_class_varsr   zIterator[AssignmentStmt])r  rN   c                 c  sJ   |j D ]}|js|  |¡E d H  q|jd urF|jjsF|  |j¡E d H  d S rV   )r
  Zis_unreachabler  Z	else_body)r]   r  r
  rP   rP   rQ   Ú,_get_assignment_statements_from_if_statement¹  s
    
zEPydanticModelTransformer._get_assignment_statements_from_if_statementr   )ÚblockrN   c                 c  s<   |j D ]0}t|tƒr|V  qt|tƒr|  |¡E d H  qd S rV   )r
  rb   r   r   r  )r]   r   r  rP   rP   rQ   r  À  s
    


z>PydanticModelTransformer._get_assignment_statements_from_blockr   z dict[str, PydanticModelClassVar]z1PydanticModelField | PydanticModelClassVar | None)r  r  rè   rN   c                 C  sd  | j }|jd }t|tƒr0t |j¡r0|jdkr4dS |js–t|jt	ƒrxt|jj
t	ƒrxt|jj
j
tƒrx|jj
j
jtv rxdS |j|v r†dS t| j|ƒ dS |jd }t|tƒs®dS t |j¡rÄ|jdkrÈdS |jj |j¡}|du rädS |j}t|tƒrød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#ƒ|_|j�rì|	�rìt|jƒS |  $|¡\}}|�r&|j%�s&|j&�s&| j'j(�r&t)| 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~   )/râ   r  rb   r   rE   Zis_valid_field_namer†   Z
new_syntaxr  r   rú   r`   ÚDECORATOR_FULLNAMESÚerror_untyped_fieldsrã   r~   rø   r•   rc   r!   r'   r  r)   Zis_classvarrÙ   rA   r€   r:   Úget_has_defaultÚ
get_strictr!  Zis_inferredZanalyze_simple_literal_typer8   r=   Z
from_errorÚget_alias_inforß   rÝ   rX   r�   r  Úis_field_frozenÚ_infer_dataclass_attr_init_typer­   r‡   r·   )r]   r  r  rè   rx   r  rg   rc   Z	node_typerµ   r¶   rÔ   r²   r´   r³   Z	init_typerP   rP   rQ   r  Ç  s¤    
 
ÿþýü	



þ

þ

þ
ÿþþý
öz=PydanticModelTransformer.collect_field_or_class_var_from_stmtr%   rL   r   r°   )rg   r†   r¨   rN   c           	      C  sâ   |j }|jr|S t|j ƒ}t|tƒs(|S |j  d¡}|rÞt|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r¨t|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__rK   z(Unsupported signature for "__set__" in "ú"zUnsupported "__set__" in ")r€   ZimplicitrA   rb   r:   r•   rc   r   Zget_containing_type_infor7   r8   r=   Zunannotatedr9   Ú	arg_kindsr   r	   Ú	arg_typesrã   r  r†   )	r]   rg   r†   r¨   ÚdefaultÚtÚsetterZ
super_infoZsetter_typerP   rP   rQ   r(  P  s.    


ýz8PydanticModelTransformer._infer_dataclass_attr_init_typezlist[PydanticModelField])rç   rœ   rñ   rÌ   rN   c              
   C  s¾  d| j jjv r"| j jjd js"dS | jj}t|jƒ}|jp>|j	 oJ|j
du}t|joZ|j ƒ}| j|||||||dd�}	|�rr| j t¡j}
t|
tƒsšJ ‚d|
jv �rr|
jd j}t|tƒsÀJ ‚|du�rr|jdu�rr|j}t|tƒsêJ ‚t|jƒD ]|\}}|du sô| d¡sô| d¡�sqô| j |j| ¡}|du�rR|dv �rR| ttjƒ¡}t||ƒ}|	  t!||dt"ƒ¡ qô|  #||¡�s¢td	ƒ}|	  t!|t$tj%ƒdt&ƒ¡ t'| j| j d|	t(ƒ d
� dS )z§Adds 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\   NFT)r¹   rº   Úrequires_dynamic_aliasesr¼   rñ   rÌ   r½   Ú__Ú_)Z_cli_settings_sourceZ_build_sourcesÚkwargs)r…   Úreturn_type))râ   r~   rø   Úplugin_generatedrX   r�   r‘   r¶   rß   rÝ   rÜ   r  Úget_field_argumentsrã   ra   rë   rc   rb   r(   r   r€   r9   rþ   r„   Ú
startswithZ	anal_typer,  ÚacceptÚChangeExplicitTypeOfAnyr=   Zfrom_omitted_genericsr)   Úappendr   r   Úshould_init_forbid_extrar8   rÄ   r   Ú
add_methodr;   )r]   rç   rœ   rñ   rÌ   r¹   rº   r¼   r0  r…   Zbase_settings_nodeZbase_settings_init_nodeÚ	func_typeZarg_idxrˆ   Zanalyzed_variable_typerÀ   ÚvarrP   rP   rQ   rì   v  sN    
øÿ
z(PydanticModelTransformer.add_initializerc           
   
   C  sþ   | j  t› d�| j  t› d�¡g¡}t|tƒ gƒ}ttd|ƒ|dtƒ}t 	| j j
j¡�. | j|dt|jƒdd||d�}W d  ƒ n1 sŠ0    Y  |  ||¡sÂtdƒ}	| t|	ttjƒdtƒ¡ |rÐ||g n|g| }t| j | jd	|t| jjƒdd
� dS )zäAdds 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¹   rº   r0  r¼   rñ   rÌ   r3  Zmodel_construct)r…   r4  Úis_classmethod)rã   Ú
named_typeÚBUILTINS_NAMEr@   r;   r   r)   r   r5   rÉ   rU   rÊ   r6  r‘   r¶   r;  r:  r8   r=   rÄ   r   r<  râ   rB   r~   )
r]   rç   rœ   rñ   rÌ   Zset_strZoptional_set_strZfields_set_argumentr…   r>  rP   rP   rQ   rí   ¯  s2    $ù$	
úz3PydanticModelTransformer.add_model_construct_method)rç   rz   rà   rN   c                 C  s¨   | j j}|D ]–}|j |j¡}|durb|j}t|tƒrD|p>|j|_	q¢t|t
ƒr¢| jjs¢| j ¡  q|j||dd�}||_||_	|jd |j |_tt|ƒ|j|j< qdS )z§Marks 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.
        NF)r¼   Ú.)râ   r~   rø   r•   r†   rc   rb   r)   r³   Zis_propertyr!   rã   Zfinal_iterationÚdeferrÃ   r`   Ú	_fullnamer%   r   )r]   rç   rz   rà   r~   ræ   r  r>  rP   rP   rQ   rî   ×  s    
z#PydanticModelTransformer.set_frozenFr   úModelConfigData | None)r†   rÍ   r  rN   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r�d}t|t	ƒr†|j
dkr†d}t|d	�S t|t	ƒr¼|j
d
v r¼tf i ||j
dki¤ŽS t|| j|ƒ dS )zÐDetermines 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.Trueúbuiltins.FalserH  )rá   rb   r$   rô   r   r†   Úerror_invalid_config_valuerã   r  r   r`   )r]   r†   rÍ   r  rF  r  rP   rP   rQ   r  ð  s(    


	

z*PydanticModelTransformer.get_config_updatec                 C  sž   | j }t|tƒrdS t|tƒr’t|jtƒr’|jjtkr’t|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-  Údefault_factoryrG  )r  rb   r&   r   rú   r"   r`   ÚFIELD_FULLNAMEr‚   r…   r„   r_   r   r   ©r  r  rÍ   r†   rP   rP   rQ   r$    s    
"z(PydanticModelTransformer.get_has_defaultr®   c                 C  s|   | j }t|tƒrxt|jtƒrx|jjtkrxt|j|j	ƒD ]@\}}|dkrHq6t|t
ƒrr|jdkrb dS |jdkrr dS  dS dS )zEReturns a the `strict` value of a field if defined, otherwise `None`.r¶   rH  TrI  FN)r  rb   r   rú   r"   r`   rL  r‚   r…   r„   r   rM  rP   rP   rQ   r%  )  s    "


z#PydanticModelTransformer.get_strictz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 d|jv rX|j	|j 
d¡ }n"d|jv rv|j	|j 
d¡ }ndS t|tƒrŽ|jdfS dS d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.
        )NFZvalidation_aliasr²   F)NTN)r  rb   r&   r   rú   r"   r`   rL  r„   r…   Úindexr$   rô   )r  r  rÍ   rP   rP   rQ   r&  9  s$    
ÿ
ÿ
ÿ



z'PydanticModelTransformer.get_alias_infoc                 C  s|   | j }t|tƒrdS t|tƒr6t|jtƒr6|jjtks:dS t|j	ƒD ]2\}}|dkrD|j
| }t|tƒop|jdk  S qDdS )al  Returns whether the field is frozen, extracted from the declaration of the field defined in `stmt`.

        Note that this is only whether the field was declared to be frozen in a `<field_name> = Field(frozen=True)`
        sense; this does not determine whether the field is frozen because the entire model is frozen; that is
        handled separately.
        Frà   rH  )r  rb   r&   r   rú   r"   r`   rL  rþ   r„   r…   r   )r  r  rõ   rˆ   rÍ   rP   rP   rQ   r'  W  s    
ÿ
ÿ
ÿ
z(PydanticModelTransformer.is_field_frozenúlist[Argument])	rç   r¹   rº   r¼   r0  rñ   rÌ   r½   rN   c	           
   	     s.   ˆj j‰‡ ‡‡‡‡‡‡‡‡f	dd„|D ƒ}	|	S )zÈHelper 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                   s@   g | ]8}ˆr|j s|jˆˆˆˆp"ˆˆˆjˆ ˆo6|jd kd�‘qS )rÆ   )r¹   rº   r»   r¼   rz   r½   r¾   )r´   rÅ   rã   r†   rå   ©	r½   r~   rÌ   rñ   rº   r0  r]   r¹   r¼   rP   rQ   Ú
<listcomp>€  s   
õøz@PydanticModelTransformer.get_field_arguments.<locals>.<listcomp>)râ   r~   )
r]   rç   r¹   rº   r¼   r0  rñ   rÌ   r½   Ú	argumentsrP   rP  rQ   r6  p  s
    õz,PydanticModelTransformer.get_field_arguments)rç   rœ   rN   c                 C  s4   |j 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ß   rÝ   Úis_dynamic_alias_presentr‘   r  rF  rX   rŽ   )r]   rç   rœ   rP   rP   rQ   r;  �  s    z1PydanticModelTransformer.should_init_forbid_extra)rç   r  rN   c                 C  s8   | D ]}|j r dS q|r4| D ]}|jdu r dS qdS )z‘Returns 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æ   rP   rP   rQ   rS  �  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%  r&  r'  r6  r;  rS  rP   rP   rP   rQ   rw   Ë  s:   
$LD 
&9(#! ÷  rw   c                      s8   e Zd ZdZdddœ‡ fdd„Zddd	œd
d„Z‡  ZS )r9  z<A type translator used to change type of Any's, if explicit.r¯   rS   )Útype_of_anyrN   c                   s   || _ tƒ  ¡  d S rV   )Ú_type_of_anyr[   r\   )r]   rU  r^   rP   rQ   r\   ¯  s    z ChangeExplicitTypeOfAny.__init__r8   r<   )r.  rN   c                 C  s"   |j tjkr|j| jd�S |S d S )N)rU  )rU  r=   rÄ   rÇ   rV  )r]   r.  rP   rP   rQ   Ú	visit_any³  s    z!ChangeExplicitTypeOfAny.visit_any)r‰   rŠ   r‹   rŒ   r\   rW  r�   rP   rP   r^   rQ   r9  ¬  s   r9  c                
   @  s^   e Zd ZdZddd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.Nr®   ©rF  rà   r¥   rÝ   rÜ   rß   r  r¶   c	           	      C  s4   || _ || _|| _|| _|| _|| _|| _|| _d S rV   rX  )	r]   rF  rà   r¥   rÝ   rÜ   rß   r  r¶   rP   rP   rQ   r\   ½  s    zModelConfigData.__init__rs   rž   c                 C  s   dd„ | j  ¡ D ƒS )z†Returns 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 rV   rP   )rŸ   ÚkÚvrP   rP   rQ   r¡   Ö  r¢   z3ModelConfigData.get_values_dict.<locals>.<dictcomp>)Ú__dict__r  r    rP   rP   rQ   rð   Ñ  s    zModelConfigData.get_values_dictrE  rS   )rœ   rN   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œ   rY  rZ  rP   rP   rQ   r  Ø  s    zModelConfigData.updaterL   r   )r�   rô   rN   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ô   rP   rP   rQ   r  ß  s    zModelConfigData.setdefault)NNNNNNNN)r‰   rŠ   r‹   rŒ   r\   rð   r  r  rP   rP   rP   rQ   r  º  s           ÷r  r(   r‘   )r~   rN   c                 C  s
   |   t¡S )zXReturn whether the type info is a root model subclass (or the `RootModel` class itself).)rd   ÚROOT_MODEL_FULLNAME)r~   rP   rP   rQ   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   rS   )Ú
model_namerz   r¨   rN   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)r]  rz   r¨   rP   rP   rQ   r«   ó  s    r«   r1   )r†   rz   r¨   rN   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*  r^  N)r  ÚERROR_CONFIG)r†   rz   r¨   rP   rP   rQ   rJ  ø  s    rJ  )rz   r¨   rN   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 disallowedr^  N)r  ÚERROR_ALIAS©rz   r¨   rP   rP   rQ   r  ý  s    r  z8CheckerPluginInterface | SemanticAnalyzerPluginInterface)r¬   rz   r¨   rN   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!r^  N)r  ÚERROR_UNEXPECTED)r¬   rz   r¨   ÚlinkZfull_messagerP   rP   rQ   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 disallowedr^  N)r  ÚERROR_UNTYPEDrc  rP   rP   rQ   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`r^  N)r  ÚERROR_EXTRA_FIELD_ROOT_MODELrc  rP   rP   rQ   r    s    r  Fz8SemanticAnalyzerPluginInterface | CheckerPluginInterfacer   rO  r°   zTypeVarType | None)	rz   rx   r†   r…   r4  rÈ   Útvar_defr?  rN   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 |p”t|ƒ}ttdƒ|dtƒg}|| }g g g   }}}|D ]8}|jsØJ dƒ‚| |j¡ | |jj¡ | |j¡ qÆt|||||
|�r|gndd�}t||ttƒ gƒƒ}||_ t||ƒ|_||_|jd | |_|j|_||jv �rŒt||jƒ}|j| |j|< |�rÞd|_ 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.)Ú	variablesrB  rØ   )'r~   rø   r5  rb   rc   r   r	  r
  Úremover1   r@  Znamed_generic_typer>   rB   r   r)   r   rÁ   r:  rÀ   r†   rÂ   r9   r   r    r3   r€   r   r`   rD  r‡   rC   Zis_decoratedr?  r   r   r%   r   Zdefn)rz   rx   r†   r…   r4  rÈ   ri  r?  r~   rg   Zfunction_typeÚfirstr,  r„   r+  rÍ   Ú	signaturerÿ   Zr_namerZ  ÚdecrP   rP   rQ   r<    sZ    


ÿ

r<  zdict[str, Any] | None)r“   rN   c                 C  s’   |   d¡sdS tjdkr"ddl}n8zddl}W n* tyX   ddl}|jddd� Y dS 0 t| dƒ�}| 	|¡W  d  ƒ S 1 s„0    Y  dS )	z…Returns 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`.rK   )Ú
stacklevelÚrb)
rm   ÚsysÚversion_infoZtomllibZtomliÚImportErrorÚwarningsÚwarnÚopenÚload)r“   Ztoml_rv  ÚrfrP   rP   rQ   r”   r  s    


r”   )NNF)…rŒ   Ú
__future__r   rs  Úcollections.abcr   Úconfigparserr   Útypingr   r   Z
mypy.typesZmypyZ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.plugins.commonr2   Zmypy.semanalr3   Zmypy.server.triggerr4   Z
mypy.stater5   Zmypy.type_visitorr6   Zmypy.typeopsr7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   Zmypy.typevarsrB   Z	mypy.utilrC   Zmypy.versionrD   Zmypy_versionZpydantic._internalrE   Zpydantic.versionrF   r›   rª   re   rp   rë   r\  ri   rL  ZDATACLASS_FULLNAMErü   r"  rû   ZMYPY_VERSION_TUPLErA  rR   rO   rW   rn   r­   rÙ   rw   r9  r  rÌ   r`  ra  rb  re  rg  ZERROR_FIELD_DEFAULTSrh  r«   rJ  r  r§   r#  r  r<  r”   rP   rP   rP   rQ   Ú<module>   s�   ˆ"$	0
W.      f+   ø X