a
    h                     @  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$ZVd%d&d'd(d)ZiG d*d+ d+e7ZjG d,d- d-Zkd.d/d0d1d2ZlG d3d4 d4ZmG d5d6 d6ZnG d7d8 d8ZoG d9d: d:eCZpG d;d< d<Zqd=d>d?d@dAZredBdCdDZsedEdFdDZtedGdHdDZuedIdJdDZvedKdLdDZwedKdMdDZxedKdNdDZyd%dOdPdQdRdSdTZzd%dUdPdQdVdWdXZ{dUdPdQdYdZd[Z|d%d\dPdQd]d^d_Z}dUdPdQdYd`daZ~dOdPdQdYdbdcZdqdedfd%dgd/dhdid>dQdj	dkdlZd%dmdndodpZdS )rz^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>   0pydantic.functional_serializers.model_serializerrG   z3pydantic.deprecated.class_validators.root_validatorz.pydantic.functional_validators.field_validatorz.pydantic.deprecated.class_validators.validatorz*pydantic.functional_serializers.serializerrH   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)rL    rO   I/var/www/html/assistant/venv/lib/python3.9/site-packages/pydantic/mypy.pypluginm   s    rQ   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
  ZS )rN   zThe Pydantic mypy plugin.r*   NoneoptionsrM   c                   s&   t || _| j | _t | d S N)PydanticPluginConfigplugin_configto_data_plugin_datasuper__init__)selfrT   	__class__rO   rP   r[      s    
zPydanticPlugin.__init__rK   z(Callable[[ClassDefContext], None] | None)fullnamerM   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_   symrO   rO   rP   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_   rO   rO   rP   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_callbackrj   rO   rO   rP   get_method_hook   s    
zPydanticPlugin.get_method_hookr/   dict[str, Any]ctxrM   c                 C  s   | j S )zjReturn all plugin config data.

        Used by mypy to determine if cache needs to be discarded.
        )rY   )r\   rq   rO   rO   rP   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transformerrO   rO   rP   re      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)rW   debug_dataclass_transformrt   infoZdeclared_metaclassgetattrtyperx   )r\   rq   Zinfo_metaclassrO   rO   rP   ri      s    
z8PydanticPlugin._pydantic_model_metaclass_marker_callback)__name__
__module____qualname____doc__r[   rg   rk   rn   rr   re   ri   __classcell__rO   rO   r]   rP   rN   |   s   	rN   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 )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_aliasesry   boolr   r   r   ry   r*   rR   rS   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toolrF   Fz/Configuration value must be a boolean for key: )fallback)config_file
parse_tomlget	__slots__ra   r   
ValueErrorsetattrr   read
getbooleanCONFIGFILE_KEY)r\   rT   Ztoml_configconfigkeyZsettingrW   rO   rO   rP   r[      s    




zPydanticPluginConfig.__init__ro   rM   c                   s    fdd j D S )z/Returns a dict of config names to their values.c                   s   i | ]}|t  |qS rO   )r{   ).0r   r\   rO   rP   
<dictcomp>       z0PydanticPluginConfig.to_data.<locals>.<dictcomp>)r   r   rO   r   rP   rX      s    zPydanticPluginConfig.to_dataN)r}   r~   r   r   r   __annotations__r[   rX   rO   rO   rO   rP   rV      s   

rV   r-   r;   rp   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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|   ra   r=   itemr8   Zret_typer9   r^   r}   error_unexpected_behaviorrv   contextZdefault_return_typemetadatar   METADATA_KEYrc   rd   error_from_attributesname)rq   Zctx_typeZ
model_typedetailZpydantic_metadatar   rO   rO   rP   rm      s&    

rm   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.rK   z
str | Noner   bool | NoneintType | Noner(   
r   alias	is_frozenhas_dynamic_aliashas_defaultstrictlinecolumnr|   rz   c                 C  s@   || _ || _|| _|| _|| _|| _|| _|| _|	| _|
| _	d S rU   r   )r\   r   r   r   r   r   r   r   r   r|   rz   rO   rO   rP   r[      s    zPydanticModelField.__init__r0   r   )	current_infotypedmodel_strictforce_optional	use_aliasrv   force_typevars_invariantis_root_model_rootrM   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   r7   r<   explicitr   r   r   r   r
   )r\   r   r   r   r   r   rv   r   r   r   r   r   rO   rO   rP   to_argument  s    
zPydanticModelField.to_argumentF)r   rv   r   r   rM   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}|rt |trt|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)ra   r|   r>   copy_modifiedr   Zvariancerz   	self_typer4   strict_optional_setrT   strict_optionalrA   r9   argsr   idis_root_modelr	   r?   )r\   r   rv   r   r   Zmodified_typeZfilled_with_typevarsargZexpanded_typeZ	root_typeZexpanded_root_typerO   rO   rP   r   2  s,    



$zPydanticModelField.expand_typer)   )r   rv   r   r   rM   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   rv   r   r   r   rO   rO   rP   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   rO   rO   rP   r   n  s    
zPydanticModelField.serialize)rz   datarv   rM   c                 C  s,   |  }t|d|}| f ||d|S )ABased on mypy.plugins.dataclasses.DataclassAttribute.deserialize.r|   )r|   rz   )copyr1   pop)rt   rz   r   rv   typrO   rO   rP   deserialize}  s    zPydanticModelField.deserializerR   )sub_typerv   rM   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|   r4   r   rT   r   r6   rz   )r\   r   rv   rO   rO   rP   expand_typevar_from_subtype  s    
z.PydanticModelField.expand_typevar_from_subtypeN)FF)F)r}   r~   r   r   r[   r   r   r   r   classmethodr   r   rO   rO   rO   rP   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 )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   rO   rO   rP   r[     s    zPydanticModelClassVar.__init__r   )r   rM   c                 C  s   |  }| f i |S )r   )r   )rt   r   rO   rO   rP   r     s    z!PydanticModelClassVar.deserializer   c                 C  s
   d| j iS )r   r   r   r   rO   rO   rP   r     s    zPydanticModelClassVar.serializeN)r}   r~   r   r   r[   r   r   r   rO   rO   rO   rP   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 )Vrs   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.
    >   validate_by_namefrozenextrapopulate_by_namealias_generatorr   validate_by_aliasr   zset[str]tracked_config_fieldsr   zExpression | Statementr0   rV   rR   )rt   ru   rv   rW   rM   c                 C  s   || _ || _|| _|| _d S rU   )_clsZ_reason_apirW   )r\   rt   ru   rv   rW   rO   rO   rP   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 rO   r   r   r   fieldrO   rO   rP   r     r   z6PydanticModelTransformer.transform.<locals>.<dictcomp>c                 S  s   i | ]}|j | qS rO   r   )r   Z	class_varrO   rO   rP   r     r   )fields
class_varsr   )r   rz   r   collect_configcollect_fields_and_class_varsr|   rc   BASESETTINGS_FULLNAMEadd_initializeradd_model_construct_method
set_frozenr   r   adjust_decorator_signaturesget_values_dictr   r   )r\   rz   Zis_a_root_modelr   r   r   r   is_settingsrO   rO   rP   rw     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)	arg_namesra   r$   value)r   ir   Z	first_decrO   rP   	<genexpr>  s   zGPydanticModelTransformer.adjust_decorator_signatures.<locals>.<genexpr>TN)r   rz   namesvaluesra   rb   r   Zoriginal_decoratorsr   calleer   r_   (IMPLICIT_CLASSMETHOD_DECORATOR_FULLNAMESMODEL_VALIDATOR_FULLNAMEany	enumerater   funcis_class)r\   rf   rO   r   rP   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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s| jjrt| 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bodyra   r   r   lvaluesr   r   rvaluer   zipr   r   r   r$   r   r   failhas_alias_generatorr   r   rW   r   error_required_dynamic_aliasesrz   mror   r   add_plugin_dependencyr3   r_   
setdefault)r\   rt   r   Zhas_config_kwargsZhas_config_from_namespacer   exprZconfig_datastmtlhsarg_namer   Zkey_exprZ
value_exprZsubstmtrz   r   rO   rO   rP   r     s~    

z'PydanticModelTransformer.collect_configzJtuple[list[PydanticModelField] | None, list[PydanticModelClassVar] | None])r   r   rM   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 ]}| |||}|du r q |jd }t|ts:J t|tr~|rf|jdkrft| 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   reversedrz   r
  r   r   r   r  r3   r_   r   r   r   r   r   r   rb   ra   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   rt   Zfound_fieldsZfound_class_varsrz   r   r   r   sym_nodeZcurrent_field_namesZcurrent_class_vars_namesr  Zmaybe_fieldr  rO   rO   rP   r   P  sH    


z6PydanticModelTransformer.collect_fields_and_class_varsr   zIterator[AssignmentStmt])r  rM   c                 c  sJ   |j D ]}|js| |E d H  q|jd urF|jjsF| |jE d H  d S rU   )r  Zis_unreachabler  Z	else_body)r\   r  r  rO   rO   rP   ,_get_assignment_statements_from_if_statement  s
    
zEPydanticModelTransformer._get_assignment_statements_from_if_statementr   )blockrM   c                 c  s<   |j D ]0}t|tr|V  qt|tr| |E d H  qd S rU   )r  ra   r   r   r  )r\   r  r  rO   rO   rP   r    s
    


z>PydanticModelTransformer._get_assignment_statements_from_blockr   z dict[str, PydanticModelClassVar]z1PydanticModelField | PydanticModelClassVar | None)r  r   r   rM   c                 C  sd  | 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#|_|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|   rz   )/r   r  ra   r   rD   Zis_valid_field_namer   Z
new_syntaxr  r   r   r_   DECORATOR_FULLNAMESerror_untyped_fieldsr   rz   r   r   rb   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   rt   r  rf   rb   Z	node_typer   r   r   r   r   r   Z	init_typerO   rO   rP   r    s    
 
	









z=PydanticModelTransformer.collect_field_or_class_var_from_stmtr%   rK   r   r   )rf   r   r   rM   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__rJ   z(Unsupported signature for "__set__" in ""zUnsupported "__set__" in ")r|   Zimplicitr@   ra   r9   r   rb   r   Zget_containing_type_infor6   r7   r<   Zunannotatedr8   	arg_kindsr   r	   	arg_typesr   r  r   )	r\   rf   r   r   defaulttsetterZ
super_infoZsetter_typerO   rO   rP   r#  +  s.    


z8PydanticModelTransformer._infer_dataclass_attr_init_typezlist[PydanticModelField])r   r   r   r   rM   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sJ d|
jv rr|
jd j}t|tsJ |durr|jdurr|j}t|tsJ t|jD ]|\}}|du s|ds|dsq| j|j| }|durR|dkrR|ttj}t||}|	 t!||dt" q| #||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   rz   r   plugin_generatedrW   r   r   r   r   r   r   r  get_field_argumentsr   r`   r   rb   ra   r(   r   r|   r8   r   r   
startswithZ	anal_typer'  acceptChangeExplicitTypeOfAnyr<   Zfrom_omitted_genericsr)   appendr   r   should_init_forbid_extrar7   r   r   
add_methodr:   )r\   r   r   r   r   r   r   r   r+  r   Zbase_settings_nodeZbase_settings_init_node	func_typeZarg_idxr  Zanalyzed_variable_typer   varrO   rO   rP   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 s0    Y  | ||std}	|t|	ttjdt |r||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   r+  r   r   r   r.  Zmodel_construct)r   r/  is_classmethod)r   
named_typeBUILTINS_NAMEr?   r:   r   r)   r   r4   r   rT   r   r1  r   r   r6  r5  r7   r<   r   r   r7  r   rA   rz   )
r\   r   r   r   r   Zset_strZoptional_set_strZfields_set_argumentr   r9  rO   rO   rP   r     s2    $$	
z3PydanticModelTransformer.add_model_construct_method)r   rv   r   rM   c           
   	   C  s   | j j}|D ]}|j|j}|dur|j}t|trD|p>|j|_	qt|t
rb| jjsb| 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   rz   r   r   r   rb   ra   r)   r   Zis_propertyr!   r   Zfinal_iterationdeferrK   	TypeErrorreprr^   r   r   r_   	_fullnamer%   r   )
r\   r   rv   r   rz   r   r  r9  Zvar_strr   rO   rO   rP   r     s(    
z#PydanticModelTransformer.set_frozenFr   ModelConfigData | None)r   r   r   rM   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.Truebuiltins.FalserE  )r   ra   r$   r   r   r   error_invalid_config_valuer   r   r   r_   )r\   r   r   r   rC  r  rO   rO   rP   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(  default_factoryrD  )r  ra   r&   r   r   r"   r_   FIELD_FULLNAMEr  r   r   r^   r   r   r  r  r   r   rO   rO   rP   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   rE  TrF  FN)r  ra   r   r   r"   r_   rI  r  r   r   r   rJ  rO   rO   rP   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  ra   r&   r   r   r"   r_   rI  r   r   indexr$   r   )r  r  r   rO   rO   rP   r!    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   rE  )r  ra   r&   r   r   r"   r_   rI  r   r   r   r   )r  r  r   r  r   rO   rO   rP   r"  5  s    



z(PydanticModelTransformer.is_field_frozenlist[Argument])	r   r   r   r   r+  r   r   r   rM   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 | ]8}r|j s|jp"j o6|jd kdqS )r   )r   r   r   r   rv   r   r   )r   r   r   r   r   	r   rz   r   r   r   r+  r\   r   r   rO   rP   
<listcomp>^  s   
z@PydanticModelTransformer.get_field_arguments.<locals>.<listcomp>)r   rz   )
r\   r   r   r   r   r+  r   r   r   	argumentsrO   rM  rP   r1  N  s
    z,PydanticModelTransformer.get_field_arguments)r   r   rM   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  rC  rW   r   )r\   r   r   rO   rO   rP   r6  n  s    z1PydanticModelTransformer.should_init_forbid_extra)r   r  rM   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   rO   rO   rP   rP  {  s    
z1PydanticModelTransformer.is_dynamic_alias_presentN)F)F)r}   r~   r   r   r   r   r[   rw   r   r   r   r  r  r  r#  r   r   r   r   staticmethodr  r   r!  r"  r1  r6  rP  rO   rO   rO   rP   rs     s:   
$LD 
&6(#!   rs   c                      s8   e Zd ZdZddd fddZddd	d
dZ  ZS )r4  z<A type translator used to change type of Any's, if explicit.r   rR   )type_of_anyrM   c                   s   || _ t   d S rU   )_type_of_anyrZ   r[   )r\   rR  r]   rO   rP   r[     s    z ChangeExplicitTypeOfAny.__init__r7   r;   )r)  rM   c                 C  s"   |j tjkr|j| jdS |S d S )N)rR  )rR  r<   r   r   rS  )r\   r)  rO   rO   rP   	visit_any  s    z!ChangeExplicitTypeOfAny.visit_any)r}   r~   r   r   r[   rT  r   rO   rO   r]   rP   r4    s   r4  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   rC  r   r   r   r   r   r  r   c	           	      C  s4   || _ || _|| _|| _|| _|| _|| _|| _d S rU   rU  )	r\   rC  r   r   r   r   r   r  r   rO   rO   rP   r[     s    zModelConfigData.__init__ro   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 rU   rO   )r   kvrO   rO   rP   r     r   z3ModelConfigData.get_values_dict.<locals>.<dictcomp>)__dict__r   r   rO   rO   rP   r     s    zModelConfigData.get_values_dictrB  rR   )r   rM   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   rV  rW  rO   rO   rP   r    s    zModelConfigData.updaterK   r   )r   r   rM   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   rO   rO   rP   r    s    zModelConfigData.setdefault)NNNNNNNN)r}   r~   r   r   r[   r   r  r  rO   rO   rO   rP   r     s           r   r(   r   )rz   rM   c                 C  s
   |  tS )zXReturn whether the type info is a root model subclass (or the `RootModel` class itself).)rc   ROOT_MODEL_FULLNAME)rz   rO   rO   rP   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   rR   )
model_namerv   r   rM   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)rZ  rv   r   rO   rO   rP   r     s    r   r0   )r   rv   r   rM   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   rv   r   rO   rO   rP   rG    s    rG  )rv   r   rM   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rv   r   rO   rO   rP   r	    s    r	  z8CheckerPluginInterface | SemanticAnalyzerPluginInterface)r   rv   r   rM   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   rv   r   linkZfull_messagerO   rO   rP   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_UNTYPEDr`  rO   rO   rP   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_MODELr`  rO   rO   rP   r    s    r  Fz8SemanticAnalyzerPluginInterface | CheckerPluginInterfacer   rL  r   zTypeVarType | None)	rv   rt   r   r   r/  r   tvar_defr:  rM   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.r=  r   )(rz   r   r0  ra   rb   r   r  r  remover0   r;  Znamed_generic_typer=   rA   r   r)   r   r   r5  r   r   r   r8   	variablesr   r    r2   r|   r   r_   rA  r   rB   Zis_decoratedr:  r   r   r%   r   Zdefn)rv   rt   r   r   r/  r   rf  r:  rz   rf   Zfunction_typefirstr'  r   r&  r   	signaturer   Zr_namerW  decrO   rO   rP   r7    sZ    




r7  zdict[str, Any] | None)r   rM   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)
rl   sysversion_infoZtomllibZtomliImportErrorwarningswarnopenload)r   Ztoml_rr  rfrO   rO   rP   r   P  s    



r   )NNF)r   
__future__r   ro  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   rd   r   rY  rh   rI  ZDATACLASS_FULLNAMEr   r  r   ZMYPY_VERSION_TUPLEr<  rQ   rN   rV   rm   r   r   rs   r4  r   r   r]  r^  r_  rb  rd  ZERROR_FIELD_DEFAULTSre  r   rG  r	  r   r  r  r7  r   rO   rO   rO   rP   <module>   s   " 0
6.      i+    X