o
    =n0j                     @  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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/m0Z0 dd
l1m2Z2 ddl3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9 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lFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZP ddlQmRZR ddlSmTZT ddlUmVZW ddlXmYZY ddlZm[Z[ dZ\dZ]dZ^dZ_dZ`dZadZbdZcd Zdh d!Zeeed"h Zfe[eWZgd#Zhd$ZVdxd)d*ZiG d+d, d,e7ZjG d-d. d.Zkdyd2d3ZlG d4d5 d5ZmG d6d7 d7ZnG d8d9 d9ZoG d:d; d;eCZpG d<d= d=ZqdzdAdBZredCdDdEZsedFdGdEZtedHdIdEZuedJdKdEZvedLdMdEZwedLdNdEZxedLdOdEZyd{dVdWZzd|dZd[Z{d}d\d]Z|d~d`daZ}d}dbdcZ~ddddeZ			fdddrdsZddvdwZdS )z^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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_settings.main.BaseSettingszpydantic.root_model.RootModelz5pydantic._internal._model_construction.ModelMetaclasszpydantic.fields.Fieldzpydantic.dataclasses.dataclass.pydantic.functional_validators.model_validator>   rG   z*pydantic.functional_serializers.serializer0pydantic.functional_serializers.model_serializerz3pydantic.deprecated.class_validators.root_validatorz.pydantic.deprecated.class_validators.validatorz.pydantic.functional_validators.field_validatorrH   builtins   versionstrreturntype[Plugin]c                 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)rK    rP   T/home/wildlama/miniconda3/envs/lam_a2e/lib/python3.10/site-packages/pydantic/mypy.pypluginm   s   rR   c                      s^   e Zd ZdZd fddZdddZdddZdddZdddZd ddZ	d ddZ
  ZS )!rO   zThe Pydantic mypy plugin.optionsr*   rM   Nonec                   s&   t || _| j | _t | d S N)PydanticPluginConfigplugin_configto_data_plugin_datasuper__init__)selfrS   	__class__rP   rQ   r[      s   
zPydanticPlugin.__init__fullnamerL   (Callable[[ClassDefContext], None] | Nonec                 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_hook&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_hookctxr/   dict[str, Any]c                 C  s   | j S )zjReturn all plugin config data.

        Used by mypy to determine if cache needs to be discarded.
        )rY   )r\   rq   rP   rP   rQ   report_config_data   s   z!PydanticPlugin.report_config_datar,   c                 C  s"   t |j|j|j| j}|  d S rU   )PydanticModelTransformerclsreasonapirW   	transform)r\   rq   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rd|j_dS 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)rW   debug_dataclass_transformru   infoZdeclared_metaclassgetattrtypery   )r\   rq   Zinfo_metaclassrP   rP   rQ   rj      s   
z8PydanticPlugin._pydantic_model_metaclass_marker_callbackrS   r*   rM   rT   )r_   rL   rM   r`   )r_   rL   rM   rm   )rq   r/   rM   rr   )rq   r,   rM   rT   )__name__
__module____qualname____doc__r[   rh   rl   rp   rs   rf   rj   __classcell__rP   rP   r]   rQ   rO   |   s    

	


rO   c                   @  sJ   e Zd ZU dZdZded< ded< ded< ded< dddZdddZdS )rV   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_aliasesrz   boolr   r   r   rz   rS   r*   rM   rT   c                 C  s   |j d u rd S t|j }|d ur:|di di }| jD ]}||d}t|ts1td| t| || qd S t }|	|j  | jD ]}|j
t|dd}t| || qFd S )NtoolrF   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\   rS   Ztoml_configconfigkeyZsettingrW   rP   rP   rQ   r[      s"   




zPydanticPluginConfig.__init__rr   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   rX         zPydanticPluginConfig.to_dataNr~   rM   rr   )r   r   r   r   r   __annotations__r[   rX   rP   rP   rP   rQ   rV      s   
 

rV   rq   r-   r;   c                 C  s   | j }t|tr|j}t|trt|jtr|j}nt|tr"|}nd| d|jj d}t	|| j
| j | jS |j jt}|du rF| jS |j tsO| jS |di d}|durft|j j| j
| j | jS )z1Raise an error if from_attributes is not enabled.z
ctx.type: 
 (of type )Nr   from_attributesT)r}   rb   r=   itemr8   Zret_typer9   r^   r   error_unexpected_behaviorrw   contextZdefault_return_typemetadatar   METADATA_KEYrd   re   error_from_attributesname)rq   Zctx_typeZ
model_typedetailZpydantic_metadatar   rP   rP   rQ   ro      s&   

ro   c                   @  sd   e Zd ZdZd4ddZd5d d!Z	"	"d6d7d$d%Z	"d8d9d'd(Zd:d*d+Ze	d;d-d.Z
d<d1d2Zd3S )=PydanticModelFieldz5Based on mypy.plugins.dataclasses.DataclassAttribute.r   rL   alias
str | None	is_frozenr   has_dynamic_aliashas_defaultstrictbool | Nonelineintcolumnr}   Type | Noner{   r(   c                 C  s@   || _ || _|| _|| _|| _|| _|| _|| _|	| _|
| _	d S rU   )
r   r   r   r   r   r   r   r   r}   r{   )r\   r   r   r   r   r   r   r   r   r}   r{   rP   rP   rQ   r[      s   
zPydanticModelField.__init__current_infotypedmodel_strictforce_optional	use_aliasrw   r0   force_typevars_invariantis_root_model_rootrM   r   c	                 C  sv   |  ||||}	| jdu r|n| j}
|s|
r| j||dd}nttj}t|	|d|r.tdS |s3| jr7t	dS t
dS )zABased on mypy.plugins.dataclasses.DataclassAttribute.to_argument.NT)include_root_type)variabletype_annotationZinitializerkind)to_varr   r   r7   r<   explicitr   r   r   r   r
   )r\   r   r   r   r   r   rw   r   r   r   r   r   rP   rP   rQ   to_argument  s    
zPydanticModelField.to_argumentFr   c                 C  s  |rt | jtr| j }t|_|| _| jdur| jjdurt	|j
jZ t|}t |ts1J |rA|jD ]
}t |tr@t|_q6t| j| jjj|i}|rvt |trvt|jrv|jd j}	|	du rk|W  d   S t|	|}
t||
g}|W  d   S 1 sw   Y  | jS )zABased on mypy.plugins.dataclasses.DataclassAttribute.expand_type.Nroot)rb   r}   r>   copy_modifiedr   Zvariancer{   	self_typer4   strict_optional_setrS   strict_optionalrA   r9   argsr   idis_root_modelr	   r?   )r\   r   rw   r   r   Zmodified_typeZfilled_with_typevarsargZexpanded_typeZ	root_typeZexpanded_root_typerP   rP   rQ   r   2  s2   



 zPydanticModelField.expand_typer)   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   rw   r   r   r   rP   rP   rQ   r   _  s   zPydanticModelField.to_varr   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   n  s   
zPydanticModelField.serializedatac                 C  s,   |  }t|d|}| d||d|S )ABased on mypy.plugins.dataclasses.DataclassAttribute.deserialize.r}   )r}   r{   NrP   )copyr1   pop)ru   r{   r   rw   typrP   rP   rQ   deserialize}  s   zPydanticModelField.deserializesub_typerT   c                 C  sT   | j dur(t|jj t| j || j| _ W d   dS 1 s!w   Y  dS dS )zxExpands type vars in the context of a subtype when an attribute is inherited
        from a generic super type.
        N)r}   r4   r   rS   r   r6   r{   )r\   r   rw   rP   rP   rQ   expand_typevar_from_subtype  s
   
"z.PydanticModelField.expand_typevar_from_subtypeN)r   rL   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   rw   r0   r   r   r   r   rM   r   )FF)
r   r(   rw   r0   r   r   r   r   rM   r   F)
r   r(   rw   r0   r   r   r   r   rM   r)   rM   r   )r{   r(   r   r   rw   r0   rM   r   )r   r(   rw   r0   rM   rT   )r   r   r   r   r[   r   r   r   r   classmethodr   r   rP   rP   rP   rQ   r      s    

!2
r   c                   @  s0   e Zd ZdZdd ZedddZ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 rU   r   )r\   r   rP   rP   rQ   r[     s   
zPydanticModelClassVar.__init__r   r   rM   c                 C  s   |  }| di |S )r   NrP   )r   )ru   r   rP   rP   rQ   r     s   z!PydanticModelClassVar.deserializec                 C  s
   d| j iS )r   r   r   r   rP   rP   rQ   r     s   zPydanticModelClassVar.serializeN)r   r   rM   r   r   )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ZdaddZdbddZdcddZ	ddddZ
ded!d"Zdfd%d&Zdgd+d,Zdhd4d5Zdid:d;Zdid<d=Zdjd?d@ZdkdldFdGZedmdHdIZedndKdLZedodNdOZedmdPdQZ	AdkdpdXdYZdqdZd[Zedrd]d^Zd_S )srt   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.
    >   frozenalias_generatorpopulate_by_nameextrar   r   validate_by_aliasvalidate_by_namezset[str]tracked_config_fieldsru   r   rv   Expression | Statementrw   r0   rW   rV   rM   rT   c                 C  s   || _ || _|| _|| _d S rU   )_cls_reason_apirW   )r\   ru   rv   rw   rW   rP   rP   rQ   r[     s   
z!PydanticModelTransformer.__init__r   c                 C  s   | j j}t|}|  }| ||\}}|du s|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     i | ]}|j | qS rP   r   r   r   fieldrP   rP   rQ   r     r   z6PydanticModelTransformer.transform.<locals>.<dictcomp>c                 S  r   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   rx     s(   


z"PydanticModelTransformer.transformc                   s   | j jj D ]8}t|jtr?|jjd  t tr?t j	t
r? j	jtv r? j	jtkr:t 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  s6    | ]\}} j | d kot|to|jdkV  qdS )modeafterN)	arg_namesrb   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  s&  | j }t }d}d}|j D ]\}}| ||}|r"d}|| qd}|jjD ]}t|t	t
fs3q)t|t	r|jd }	t|	trG|	jdkrHq)t|jtrmt|jj|jjD ]\}
}|
du r`qW|| j|
|dd qWnNt|jtr|jjD ]\}}t|tsqw|| |j| qwn.t|t
r|jdkrq)|jjD ]}t|t	sq|jd }	t|	tsq|| |	j|j q|r| jd|  nd}q)|s|r|r|jr|js|js| jjrt| j| |jjd	d D ]&}t |j!vrq| 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 kwargs   r   )&r   r  keywordsitemsget_config_updateupdatedefsbodyrb   r   r   lvaluesr   r   rvaluer   zipr   r   r   r$   r   r   failhas_alias_generatorr   r   rW   r   error_required_dynamic_aliasesr{   mror   r   add_plugin_dependencyr3   r_   
setdefault)r\   ru   r   Zhas_config_kwargsZhas_config_from_namespacer   exprZconfig_datastmtlhsarg_namer   Zkey_exprZ
value_exprZsubstmtr{   r   rP   rP   rQ   r     s   









z'PydanticModelTransformer.collect_configr  r   Jtuple[list[PydanticModelField] | None, list[PydanticModelClassVar] | None]c                 C  s  | j }i }i }t|jjdd D ]b}t|jvrq| jt|j	 |jt d 
 D ]2\}}t||| j}	|	|j| j |	||< |jj|}
|
r]|
jr]t|
jts]| jd|
j q+|jt d 
 D ]\}}t|||< qgqt }t }| |jD ]I}| |||}|du rq|jd }t|tsJ t|tr|r|jdkrt| j| q||j |||j< qt|tr||j |||j< qt| 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  r3   r_   r  r   r   r   r   r   rc   rb   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   ru   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   P  sN   




z6PydanticModelTransformer.collect_fields_and_class_varsr  r   Iterator[AssignmentStmt]c                 c  sT    |j D ]}|js| |E d H  q|jd ur&|jjs(| |jE d H  d S d S d S rU   )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_statementblockr   c                 c  s>    |j D ]}t|tr|V  qt|tr| |E d H  qd S rU   )r  rb   r   r   r%  )r\   r&  r  rP   rP   rQ   r    s   


z>PydanticModelTransformer._get_assignment_statements_from_blockr   r    dict[str, PydanticModelClassVar]1PydanticModelField | PydanticModelClassVar | Nonec                 C  sN  | j }|jd }t|trt|jr|jdkrdS |jsKt|jt	r<t|jj
t	r<t|jj
j
tr<|jj
j
jtv r<dS |j|v rCdS t| j| dS |jd }t|tsWdS t|jrb|jdkrddS |jj|j}|du rrdS |j}t|tr|dS t|tr| jd| dS t|tsdS |jrt|jS t|j}t|tr|jjdkr| jd| | |}	| |}
|jdu r|jr|jr| jj |jdd}|r||_n| jd	| t!t"j#|_|jr|	rt|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   rD   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   r@   r}   r9   get_has_default
get_strictr)  Zis_inferredZanalyze_simple_literal_typer7   r<   Z
from_errorget_alias_infor   r   rW   r   r  is_field_frozen_infer_dataclass_attr_init_typer   r   r   )r\   r  r  r   ru   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_stmtrg   r%   r   rL   r   r   r   c           	      C  s   |j }|jr|S t|j }t|ts|S |j d}|rpt|jtrc|j d}|s,J |j r:tt	|j |j |}nt
tjS t|trT|jtttgkrTt|jd |S | jd|j j d| |S | jd|j j d| |S )zvInfer __init__ argument type for an attribute.

        In particular, possibly use the signature of __set__.
        __set__rJ   z(Unsupported signature for "__set__" in ""zUnsupported "__set__" in ")r}   Zimplicitr@   rb   r9   r   rc   r   Zget_containing_type_infor6   r7   r<   Zunannotatedr8   	arg_kindsr   r	   	arg_typesr   r  r   )	r\   rg   r   r   defaulttsetterZ
super_infoZsetter_typerP   rP   rQ   r0  +  s0   


z8PydanticModelTransformer._infer_dataclass_attr_init_typer   list[PydanticModelField]r   r   c              
   C  s  d| j jjv r| j jjd jsdS | jj}t|j}|jp|j	 o%|j
du}t|jo-|j }| j|||||||dd}	|r| jtj}
t|
tsLJ d|
jv r|
jd j}t|ts^J |dur|jdur|j}t|tsqJ t|jD ];\}}|du s|ds|dsqv| j|j| }|dur|dkr|ttj}t||}|	 t!||dt" qv| #||st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[   NFT)r   r   requires_dynamic_aliasesr   r   r   r   ___Z_cli_settings_sourcekwargs)r   return_type))r   r{   r   plugin_generatedrW   r   r   r   r   r   r   r  get_field_argumentsr   ra   r   rc   rb   r(   r   r}   r8   r   r   
startswithZ	anal_typer4  acceptChangeExplicitTypeOfAnyr<   Zfrom_omitted_genericsr)   appendr   r   should_init_forbid_extrar7   r   r   
add_methodr:   )r\   r   r   r   r   r   r   r   r9  r   Zbase_settings_nodeZbase_settings_init_node	func_typeZarg_idxr  Zanalyzed_variable_typer   varrP   rP   rQ   r   Q  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 sEw   Y  | ||satd}	|t|	ttjdt |rh||g n|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   r   r9  r   r   r   r<  Zmodel_construct)r   r=  is_classmethod)r   
named_typeBUILTINS_NAMEr?   r:   r   r)   r   r4   r   rS   r   r?  r   r   rD  rC  r7   r<   r   r   rE  r   rA   r{   )
r\   r   r   r   r   Zset_strZoptional_set_strZfields_set_argumentr   rG  rP   rP   rQ   r     s4   $


z3PydanticModelTransformer.add_model_construct_methodr   c           
   	   C  s   | j j}|D ]r}|j|j}|durX|j}t|tr"|p|j|_	qt|t
r1| jjs1| j  qzt|}W n tyD   t|}Y nw 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   rc   rb   r)   r   Zis_propertyr!   r   Zfinal_iterationZdeferrL   	TypeErrorreprr^   r   r   r_   	_fullnamer%   r   )
r\   r   rw   r   r{   r   r#  rG  Zvar_strr   rP   rP   rQ   r     s,   
z#PydanticModelTransformer.set_frozenFr   r   r  ModelConfigData | Nonec                 C  s   || j vrdS |dkr1t|tr|jdk}nt|tr!|jdk}n|s*t|| j| dS t|dS |dkrHd}t|t	rC|j
dkrCd}t|d	S t|t	r^|j
d
v r^td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.Truebuiltins.FalserR  rP   )r   rb   r$   r   r   r   error_invalid_config_valuer   r  r   r_   )r\   r   r   r  rP  r  rP   rP   rQ   r	    s(   


	

z*PydanticModelTransformer.get_config_updatec                 C  s   | j }t|tr
dS t|trIt|jtrI|jjtkrIt|j	|j
D ]$\}}|du s.|dkr5|jtu  S |dkrFt|toB|jdk   S q"dS t|t S )zUReturns a boolean indicating whether the field defined in `stmt` is a required field.FNr5  default_factoryrQ  )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r<t|jtr<|jjtkr<t|j|j	D ] \}}|dkr$qt|t
r9|jdkr1 dS |jdkr9 dS  dS dS )zEReturns a the `strict` value of a field if defined, otherwise `None`.r   rR  TrS  FN)r  rb   r   r   r"   r_   rV  r  r   r   r   rW  rP   rP   rQ   r-    s   "


z#PydanticModelTransformer.get_stricttuple[str | None, bool]c                 C  s   | j }t|tr
dS t|trt|jtr|jjtksdS d|jv r,|j	|j
d }nd|jv r;|j	|j
d }ndS t|trG|jdf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)NT)r  rb   r&   r   r   r"   r_   rV  r   r   indexr$   r   )r  r  r   rP   rP   rQ   r.    s"   





z'PydanticModelTransformer.get_alias_infoc                 C  s|   | j }t|tr
dS t|trt|jtr|jjtksdS t|j	D ]\}}|dkr;|j
| }t|to8|jdk  S q"d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   rR  )r  rb   r&   r   r   r"   r_   rV  r   r   r   r   )r  r  r   r  r   rP   rP   rQ   r/  5  s   


z(PydanticModelTransformer.is_field_frozenr   r   r   r9  r   list[Argument]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                   s@   g | ]}r	|j s|jpj o|jd kdqS )r   )r   r   r   r   rw   r   r   )r   r   r   r   r   	r   r{   r   r   r   r9  r\   r   r   rP   rQ   
<listcomp>^  s"    z@PydanticModelTransformer.get_field_arguments.<locals>.<listcomp>)r   r{   )
r\   r   r   r   r   r9  r   r   r   	argumentsrP   r[  rQ   r?  N  s
   z,PydanticModelTransformer.get_field_argumentsc                 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  rP  rW   r   )r\   r   r   rP   rP   rQ   rD  n  s   z1PydanticModelTransformer.should_init_forbid_extrar  c                 C  s8   | D ]}|j r
 dS q|r| 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   rP   rP   rQ   r^  {  s   
z1PydanticModelTransformer.is_dynamic_alias_presentN)
ru   r   rv   r   rw   r0   rW   rV   rM   rT   )rM   r   )rM   rT   )rM   r  )r  r  r   r   rM   r  )r  r   rM   r$  )r&  r   rM   r$  )r  r   r  r  r   r'  rM   r(  )rg   r%   r   rL   r   r   rM   r   )
r   r8  r   r  r   r   r   r   rM   rT   )r   r8  rw   r0   r   r   rM   rT   r   )r   rL   r   r   r  r   rM   rO  )r  r   rM   r   )r  r   rM   r   )r  r   rM   rX  )r   r8  r   r   r   r   r   r   r9  r   r   r   r   r   r   r   rM   rZ  )r   r8  r   r  rM   r   )r   r8  r  r   rM   r   )r   r   r   r   r   r   r[   rx   r   r   r   r%  r  r  r0  r   r   r   r	  staticmethodr,  r-  r.  r/  r?  rD  r^  rP   rP   rP   rQ   rt     s<   
 


$

L
D

 


&
6
(#!
 rt   c                      s,   e Zd ZdZd fddZdddZ  ZS )rB  z<A type translator used to change type of Any's, if explicit.type_of_anyr   rM   rT   c                   s   || _ t   d S rU   )_type_of_anyrZ   r[   )r\   r`  r]   rP   rQ   r[     s   z ChangeExplicitTypeOfAny.__init__r6  r7   r;   c                 C  s   |j tjkr|j| jdS |S )N)r`  )r`  r<   r   r   ra  )r\   r6  rP   rP   rQ   	visit_any  s   z!ChangeExplicitTypeOfAny.visit_any)r`  r   rM   rT   )r6  r7   rM   r;   )r   r   r   r   r[   rb  r   rP   rP   r]   rQ   rB    s    rB  c                   @  sJ   e Zd ZdZ								ddddZdddZd ddZd!ddZdS )"r  z(Pydantic mypy plugin model config class.NrP  r   r   r   r   r   r   r  r   c	           	      C  s4   || _ || _|| _|| _|| _|| _|| _|| _d S rU   )rP  r   r   r   r   r   r  r   )	r\   rP  r   r   r   r   r   r  r   rP   rP   rQ   r[     s   
zModelConfigData.__init__rM   rr   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 rU   rP   )r   kvrP   rP   rQ   r     s    z3ModelConfigData.get_values_dict.<locals>.<dictcomp>)__dict__r  r   rP   rP   rQ   r        zModelConfigData.get_values_dictr   rO  rT   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   rc  rd  rP   rP   rQ   r
    s
   zModelConfigData.updater   rL   r   r   c                 C  s"   t | |du rt| || dS 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)rP  r   r   r   r   r   r   r   r   r   r   r   r  r   r   r   r   )r   rO  rM   rT   )r   rL   r   r   rM   rT   )r   r   r   r   r[   r   r
  r  rP   rP   rP   rQ   r    s    

r  r{   r(   r   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 subclass
model_namerw   r+   r   r   rT   c                 C     |j d|  d|td dS )zCEmits an error when the model does not have `from_attributes=True`.r2  z$" does not have from_attributes=TruecodeN)r  	ERROR_ORM)rh  rw   r   rP   rP   rQ   r        r   r   r0   c                 C  ri  )z0Emits an error when the config value is invalid.zInvalid value for "Config.r2  rj  N)r  ERROR_CONFIG)r   rw   r   rP   rP   rQ   rT    rm  rT  c                 C     | 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 disallowedrj  N)r  ERROR_ALIASrw   r   rP   rP   rQ   r    rf  r  r   8CheckerPluginInterface | SemanticAnalyzerPluginInterfacec                 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!rj  N)r  ERROR_UNEXPECTED)r   rw   r   linkZfull_messagerP   rP   rQ   r     s   r   c                 C  ro  )z;Emits an error when there is an untyped field in the model.zUntyped fields disallowedrj  N)r  ERROR_UNTYPEDrq  rP   rP   rQ   r+    r   r+  c                 C  ro  )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`rj  N)r  ERROR_EXTRA_FIELD_ROOT_MODELrq  rP   rP   rQ   r     r   r   F8SemanticAnalyzerPluginInterface | CheckerPluginInterfaceru   r   r   rZ  r=  r   r   tvar_defTypeVarType | NonerH  c                 C  s  |j }||jv r|j| }	|	jrt|	jtr|jj|	j t| t	r)| 
d}
n| dg }
|rE|p8tt|}ttd|dtdg}n|pJt|}ttd|dtg}|| }g g g }}}|D ]}|jslJ d||j ||jj ||j qct|||||
|r|gndd}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.)	variablesrK  r   )'r{   r   r>  rb   rc   r   r  r  remover0   rI  Znamed_generic_typer=   rA   r   r)   r   r   rC  r   r   r   r8   r   r    r2   r}   r  r_   rN  r   rB   Zis_decoratedrH  r   r   r%   r   Zdefn)rw   ru   r   r   r=  r   ry  rH  r{   rg   Zfunction_typefirstr4  r   r3  r   	signaturer  Zr_namerd  decrP   rP   rQ   rE    sZ   





rE  r   dict[str, Any] | Nonec                 C  s   |  dsdS tjdkrddl}nzddl}W n ty*   ddl}|d Y dS w t| d}|	|W  d   S 1 s@w   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)
rn   sysversion_infotomllibtomliImportErrorwarningswarnopenload)r   Ztoml_r  rfrP   rP   rQ   r   P  s   



$r   )rK   rL   rM   rN   )rq   r-   rM   r;   )r{   r(   rM   r   )rh  rL   rw   r+   r   r   rM   rT   )r   rL   rw   r0   r   r   rM   rT   )rw   r0   r   r   rM   rT   )r   rL   rw   rr  r   r   rM   rT   )rw   r+   r   r   rM   rT   )NNF)rw   rx  ru   r   r   rL   r   rZ  r=  r;   r   r   ry  rz  rH  r   rM   rT   )r   rL   rM   r  )r   
__future__r   r  collections.abcr   configparserr   typingr   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   Zmypy.plugins.commonr1   Zmypy.semanalr2   Zmypy.server.triggerr3   Z
mypy.stater4   Zmypy.type_visitorr5   Zmypy.typeopsr6   Z
mypy.typesr7   r8   r9   r:   r;   r<   r=   r>   r?   r@   Zmypy.typevarsrA   Z	mypy.utilrB   Zmypy.versionrC   Zmypy_versionZpydantic._internalrD   Zpydantic.versionrE   r   r   re   r   rg  ri   rV  ZDATACLASS_FULLNAMEr   r*  r   ZMYPY_VERSION_TUPLErJ  rR   rO   rV   ro   r   r   rt   rB  r  r   rl  rn  rp  rt  rv  ZERROR_FIELD_DEFAULTSrw  r   rT  r  r   r+  r   rE  r   rP   rP   rP   rQ   <module>   s    " 0

6
.      i
+





X