o
    f                 	   @  sd  U d Z ddlmZ ddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlmZmZ ddlmZmZ ddlmZ ddlmZ ddlmZmZmZ dd	lmZ dd
lmZ ddlmZ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- ddlm.Z. ddl/m0Z0m1Z1m2Z2m3Z3 ddl4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z; ddl<m=Z= ddl>m?Z?m@Z@ ddlAmBZBmCZCmDZD ddlEmFZFmGZGmHZH ddlImJZJ ddlKmLZL ddlmMZM ddlNmOZOmPZPmQZQmRZRmSZS ddlTmUZUmVZV ddlWmXZXmYZY ddlOmZZZm[Z[m\Z\m]Z]m^Z^m_Z_m`Z`maZambZb ddlPmcZcmdZdmeZemfZfmgZgmhZhmiZimjZjmkZkmlZlmmZmmnZn ddlompZp ddlqmrZrmsZs dd ltmuZu dd!lvmwZwmxZxmyZymzZz dd"l{m|Z| dd#l}m~Z~ dd$lSmZmZ dd%lmZ e rdd&lmZmZ dd'lmZ dd(lmZ dd)lmZ dd*lmZ dd+l}mZ e	jd,kZee5ed-f Ze+ejefeef Ze*d.ed/Ze+ecej ecef ecee f Ze?Ze"e!ege2j0f Zee
jgZd0ed1< ee
jejjgZd0ed2< ee
jejjgZd0ed3< ee
jejjgZd0ed4< ee
j#ejjejj(gZd0ed5< dd<d=ZddCdDZddHdIZddPdQZddRdd[d\Ze#e)e! eDf ZddadbZe+e#ee!f df ZG dcdd ddZddgdhZG didj djZdkdl dmdl dndl dodl dpdl dqdl drdl dsdl dtZduedv< ddydzZdd|d}ZdddZdddZdddZdddZdddZG dd de8ZdddddddddZG dd dZdddZG dd dZG dd dZdS )z-Convert python types to pydantic-core schema.    )annotationsN)	ExitStackcontextmanager)copydeepcopy)Enum)partial)	Parameter_ParameterKind	signature)chain)
attrgetter)FunctionType
LambdaType
MethodType)TYPE_CHECKINGAnyCallableDictFinal
ForwardRefIterableIteratorMappingTypeTypeVarUnioncastoverload)warn)
CoreSchemaPydanticUndefinedcore_schemato_jsonable_python)	AnnotatedLiteralTypeAliasType	TypedDictget_args
get_originis_typeddict   )AliasGenerator)GetCoreSchemaHandlerGetJsonSchemaHandler)
ConfigDictJsonDictJsonEncoder)PydanticSchemaGenerationErrorPydanticUndefinedAnnotationPydanticUserError)JsonSchemaValue)version_short)PydanticDeprecatedSince20   )_core_utils_decorators_discriminated_union_known_annotated_metadata_typing_extra)ConfigWrapperConfigWrapperStack)CoreMetadataHandlerbuild_metadata_dict)	CoreSchemaOrFieldcollect_invalid_schemasdefine_expected_missing_refsget_refget_type_refis_function_with_inner_schema%is_list_like_schema_with_items_schemasimplify_schema_referencesvalidate_core_schema)	DecoratorDecoratorInfosFieldSerializerDecoratorInfoFieldValidatorDecoratorInfoModelSerializerDecoratorInfoModelValidatorDecoratorInfoRootValidatorDecoratorInfoValidatorDecoratorInfoget_attribute_from_basesinspect_field_serializerinspect_model_serializerinspect_validator)extract_docstrings_from_cls)collect_dataclass_fieldsget_type_hints_infer_globalns)PydanticRecursiveRef)get_standard_typevars_maphas_instance_in_typerecursively_defined_type_refsreplace_types)MockCoreSchema)CallbackGetCoreSchemaHandler)is_finalvaris_self_type)lenient_issubclass)ComputedFieldInfo	FieldInfo	BaseModel)Discriminator)FieldValidatorModes)StandardDataclass)GetJsonSchemaFunction)      {   FieldDecoratorInfoType)boundz
list[type]TUPLE_TYPES
LIST_TYPES	SET_TYPESFROZEN_SET_TYPES
DICT_TYPESinfoFieldDecoratorInfofieldstrreturnboolc                 C  s,   d| j v rdS | j D ]	}||kr dS q
dS )zCheck if field name is in validator fields.

    Args:
        info: The field info.
        field: The field name to check.

    Returns:
        `True` if field name is in validator fields, `False` otherwise.
    *TF)fields)rv   rx   v_field_name r   [/var/www/NoticeGen/venv/lib/python3.10/site-packages/pydantic/_internal/_generate_schema.py)check_validator_fields_against_field_namer   s   

r   
decoratorsIterable[AnyFieldDecorator]r}   Iterable[str]Nonec                 C  sf   t |}| D ]*}d|jjv rq|jjdu rq|jjD ]}||vr/td|j d|j dddqqdS )	av  Check if the defined fields in decorators exist in `fields` param.

    It ignores the check for a decorator if the decorator has `*` as field or `check_fields=False`.

    Args:
        decorators: An iterable of decorators.
        fields: An iterable of fields name.

    Raises:
        PydanticUserError: If one of the field names does not exist in `fields` param.
    r|   Fz*Decorators defined with incorrect fields: .zO (use check_fields=False if you're inheriting from the model and intended this)zdecorator-missing-fieldcodeN)setrv   r}   check_fieldsr4   cls_refcls_var_name)r   r}   decrx   r   r   r   check_decorator_fields_exist   s   r   validator_functions+Iterable[Decorator[FieldDecoratorInfoType]]'list[Decorator[FieldDecoratorInfoType]]c                   s    fdd| D S )Nc                   s   g | ]
}t |j r|qS r   )r   rv   ).0r   rx   r   r   
<listcomp>       z8filter_field_decorator_info_by_field.<locals>.<listcomp>r   )r   rx   r   r   r   $filter_field_decorator_info_by_field   s   r   schemacore_schema.CoreSchemaeach_item_validators'list[Decorator[ValidatorDecoratorInfo]]
field_name
str | Nonec                 C  s   | d dkrt | d ||| d< | S | d dkr1| d }d ur/t| d | ||| d |< | S t| rM| dd }|d u rCt }t|||| d< | S | d dkrk| dd }|d u rat }t|||| d< | S |rvtd	| d  | S )
Ntypenullabler   tuplevariadic_item_indexitems_schemadictvalues_schemazO`@validator(..., each_item=True)` cannot be applied to fields with a schema of )apply_each_item_validatorsgetapply_validatorsrH   r"   
any_schema	TypeError)r   r   r   r   inner_schemar   r   r   r      s4   
r   )titleschema_or_fieldrB   handlerr.   clsr   r   r5   c                C  s   ddl m} ddlm} ddlm} ddlm} || }||}	d|	v r4|	d }
|		  d|
ig|	d< |d	ur=||	d
< n	d
|	vrF|j
|	d
< ||u sR||sR||rTd	n|j}|rfd|	vrft||	d< |S t||ry|jd jry|jd j|	d< |S )a  Add title and description for model-like classes' JSON schema.

    Args:
        schema_or_field: The schema data to generate a JSON schema from.
        handler: The `GetCoreSchemaHandler` instance.
        cls: The model-like class.
        title: The title to set for the model's schema, defaults to the model's name

    Returns:
        JsonSchemaValue: The updated JSON schema.
    r+   is_pydantic_dataclassrf   )	RootModelr8   )is_builtin_dataclassz$refallOfNr   descriptionroot)dataclassesr   mainrg   
root_modelr   _dataclassesr   resolve_ref_schemaclear__name____doc__inspectcleandoc
issubclassmodel_fieldsr   )r   r   r   r   r   rg   r   r   json_schemaoriginal_schemaref	docstringr   r   r   modify_model_json_schema   s*   


"r   json_encodersJsonEncoders | Nonetpr    c                 C  s   | s|S d|v r
|S |gt |d|jjdd R D ]#}| |}|du r&qtdt  dt tj	|dd|d< |  S |S )	a  Iterate over the json_encoders and add the first matching encoder to the schema.

    Args:
        json_encoders: A dictionary of types and their encoder functions.
        tp: The type to check for a matching encoder.
        schema: The schema to add the encoder to.
    serialization__mro__Nz=`json_encoders` is deprecated. See https://docs.pydantic.dev/z</concepts/serialization/#custom-serializers for alternativesjson)	when_used)
getattr	__class__r   r   warningsr   r6   r7   r"   $plain_serializer_function_ser_schema)r   r   r   baseencoderr   r   r   ,_add_custom_serialization_from_json_encoders   s   
$
r   c                   @  s6   e Zd ZdZdddZedddZedddZdS )TypesNamespaceStackzA stack of types namespaces.types_namespaceTypesNamespacec                 C  s   |g| _ d S N_types_namespace_stack)selfr   r   r   r   __init__#  s   zTypesNamespaceStack.__init__rz   c                 C  s
   | j d S Nr   r   r   r   r   r   tail&  s   
zTypesNamespaceStack.tailfor_type	type[Any]c                 c  sJ    i t || jpi }| j| zd V  W | j  d S | j  w r   )r=   get_cls_types_namespacer   r   appendpop)r   r   r   r   r   r   push*  s   zTypesNamespaceStack.pushN)r   r   )rz   r   )r   r   )	r   
__module____qualname__r   r   propertyr   r   r   r   r   r   r   r      s    
r   abc                 C  s   | dur| S |S )aB  Return the first argument if it is not None, otherwise return the second argument.

    Use case: serialization_alias (argument a) and alias (argument b) are both defined, and serialization_alias is ''.
    This function will return serialization_alias, which is the first argument, even though it is an empty string.
    Nr   )r   r   r   r   r   _get_first_non_null4  s   r   c                   @  sb  e Zd ZdZdZ	ddddZedddZedddZ	edddZ
edddZeddd Zdd"d#Zdd'd(Zdd+d,Zdd-d.Zdd/d0Zdd1d2Zdd4d5Zd d9d:ZG d;d< d<eZdd=d>Zdd?d@ZddDdEZ	FdddIdJZddMdNZe	dddSdTZddUdVZddYdZZdd[d\Z e!d	d`daZ"e!d
dcdaZ"dddedaZ"ddfdgZ#ddidjZ$ddkdlZ%ddmdnZ&ddpdqZ'dFdrddzd{Z(dd}d~Z)dddZ*edddZ+edddZ,edddZ-dddZ.dddZ/dddZ0dddZ1dddZ2dddZ3e4j5dfdddZ6dddZ7dddZ8dddZ9dddZ:dddZ;d ddZ<d!ddZ=dddZ>d"ddZ?d#ddńZ@d$ddɄZAd%ddЄZBd&ddӄZCd'ddׄZDddل fd(dd߄ZEd)ddZFd)ddZGd*ddZH	ddd+ddZId,ddZJdS (-  GenerateSchemaz\Generate core schema for a Pydantic model, dataclass and types like `str`, `datetime`, ... .)_config_wrapper_stackr   _typevars_mapfield_name_stackmodel_type_stackdefsNconfig_wrapperr>   r   dict[str, Any] | Nonetypevars_mapdict[Any, Any] | Nonerz   r   c                 C  s6   t || _t|| _|| _t | _t | _t	 | _
d S r   )r?   r   r   r   r   _FieldNameStackr   _ModelTypeStackr   _Definitionsr   )r   r   r   r   r   r   r   r   I  s   

zGenerateSchema.__init__config_wrapper_stackr?   types_namespace_stackr   r   r   r   r   c                 C  s4   |  | }||_||_||_||_t |_||_|S r   )__new__r   r   r   r   r   r   r   )r   r   r   r   r   r   objr   r   r   __from_parentW  s   
	zGenerateSchema.__from_parentc                 C     | j jS r   )r   r   r   r   r   r   _config_wrapperi     zGenerateSchema._config_wrapperc                 C  r   r   )r   r   r   r   r   r   _types_namespacem  r   zGenerateSchema._types_namespacec                 C  s(   | j jpt}|| j| j| j| j| jS r   )	r   schema_generatorr   _GenerateSchema__from_parentr   r   r   r   r   )r   r   r   r   r   _current_generate_schemaq  s   z'GenerateSchema._current_generate_schemar{   c                 C  r   r   )r   arbitrary_types_allowedr   r   r   r   _arbitrary_types|  r   zGenerateSchema._arbitrary_typesr    c                 C  s   t  S )zGenerate a CoreSchema for `str`)r"   
str_schemar   r   r   r   r    r   zGenerateSchema.str_schemar   r   
items_typec                 C     t | |S r   )r"   list_schemagenerate_schemar   r   r  r   r   r   _list_schema     zGenerateSchema._list_schema	keys_typevalues_typec                 C  s   t | || |S r   )r"   dict_schemar  )r   r   r  r  r   r   r   _dict_schema  s   zGenerateSchema._dict_schemac                 C  r	  r   )r"   
set_schemar  r  r   r   r   _set_schema  r  zGenerateSchema._set_schemac                 C  r	  r   )r"   frozenset_schemar  r  r   r   r   _frozenset_schema  r  z GenerateSchema._frozenset_schemac                 C  s,   t |tst|dt t S t|S )Na   is not a Python type (it may be an instance of an object), Pydantic will allow any object with no validation since we cannot even enforce that the input is an instance of the given type. To get rid of this error wrap the type with `pydantic.SkipValidation`.)
isinstancer   r   UserWarningr"   r   is_instance_schema)r   r   r   r   r   _arbitrary_type_schema  s   

z%GenerateSchema._arbitrary_type_schemar   c                 C  s   t d|d)N,Unable to generate pydantic-core schema for a  . Set `arbitrary_types_allowed=True` in the model_config to ignore this error or implement `__get_pydantic_core_schema__` on your type to fully support it.

If you got this error by calling handler(<some type>) within `__get_pydantic_core_schema__` then you likely need to call `handler.generate_schema(<some type>)` since we do not call `__get_pydantic_core_schema__` on `<some type>` otherwise to avoid infinite recursion.)r2   r   r   r   r   r   _unknown_type_schema  s   
z#GenerateSchema._unknown_type_schemar   discriminatorstr | Discriminator | Nonec                 C  s@   |d u r|S zt ||W S  t jy   t || | Y S w r   )r;   apply_discriminatorMissingDefinitionForUnionRefset_discriminator_in_metadata)r   r   r  r   r   r   _apply_discriminator_to_union  s   z,GenerateSchema._apply_discriminator_to_unionc                   @  s   e Zd ZdS )zGenerateSchema.CollectedInvalidN)r   r   r   r   r   r   r   CollectedInvalid  s    r$  c                 C  s8   |  |}t|}t|r|  t|}t|}|S r   )collect_definitionsrI   rC   r$  r;   apply_discriminatorsrJ   r   r   r   r   r   clean_schema  s   

zGenerateSchema.clean_schemac                 C  sP   t d|dd }|r|| jj|< d|v rt|d }t|t| jj S )Nr   r   )	r   r   r   definitionsr"   definition_reference_schemadefinitions_schemalistvalues)r   r   r   r   r   r   r%    s   z"GenerateSchema.collect_definitionsmetadata_schemajs_functionCallable[..., Any]c                 C  s0   t |j}|dg }||vr|| d S d S )Npydantic_js_functions)r@   metadata
setdefaultr   )r   r.  r/  r2  r1  r   r   r   _add_js_function  s
   
zGenerateSchema._add_js_functionTfrom_dunder_get_core_schemar   c                 C  sv   d}|r|  ||}|dur|}|du r| |}t||}|dur1t|| jj}|r1| || t| jj	||}|S )a  Generate core schema.

        Args:
            obj: The object to generate core schema for.
            from_dunder_get_core_schema: Whether to generate schema from either the
                `__get_pydantic_core_schema__` function or `__pydantic_core_schema__` property.

        Returns:
            The generated core schema.

        Raises:
            PydanticUndefinedAnnotation:
                If it is not possible to evaluate forward reference.
            PydanticSchemaGenerationError:
                If it is not possible to generate pydantic-core schema.
            TypeError:
                - If `alias_generator` returns a disallowed type (must be str, AliasPath or AliasChoices).
                - If V1 style validator with `each_item=True` applied on a wrong field.
            PydanticUserError:
                - If `typing.TypedDict` is used instead of `typing_extensions.TypedDict` on Python < 3.12.
                - If `__modify_schema__` method is used instead of `__get_pydantic_json_schema__`.
        N)
_generate_schema_from_property_generate_schema_inner!_extract_get_pydantic_json_schemaresolve_original_schemar   r)  r4  r   r   r   )r   r   r5  r   from_propertymetadata_js_functionr.  r   r   r   r    s   

zGenerateSchema.generate_schemar   type[BaseModel]c                   sf  j |\}}|dur|W  d   S |j}|j  j}tt j  j	  j
 h | |  t|jdd}||}||}ttt||dgd}	 j }
d}|ddkr|jd |u snJ |jd	 tu swJ |jdd	 D ]D}t|d
i dd}|durt|trttj|dddj}t|}|tt fvrt!dj"|ddd }|t#ur$|} nq~j%&| j'&| j(|j)r*d|d  }|d }t+||
d}t,j-||t|dddt|dd|||	d}nOt,j. fdd|/ D  fdd| D ||j0d}t1| j2 d}t3|t4 }|dur5|}t+||
d}t,j-||t|dddt|dd|||	d}5| j6 }t+||
d}|j j7|< t,8|W  d   W  d   W  d   S 1 sw   Y  W d   n1 sw   Y  W d   dS W d   dS 1 sw   Y  dS )z%Generate schema for a Pydantic model.NF)checkr   r   js_functionsextra_fields_behaviorallowr   r   __annotations____pydantic_extra__T)is_argumentis_classzEThe type annotation for `__pydantic_extra__` must be `Dict[str, ...]`requiredr8   r   r   inner__pydantic_custom_init____pydantic_post_init__)custom_initr   	post_initconfigr   r2  c                   s    i | ]\}}| || qS r   )_generate_md_field_schemar   kvr   r   r   r   
<dictcomp>O  s     z0GenerateSchema._model_schema.<locals>.<dictcomp>c                      g | ]	} | jqS r   _computed_field_schemafield_serializersr   drS  r   r   r   P      z0GenerateSchema._model_schema.<locals>.<listcomp>)computed_fieldsextras_schema
model_nameouter)9r   get_schema_or_refr   __pydantic_decorators__r\  r   r   field_validatorsr-  rX  
validatorskeysr>   model_configcore_config_get_model_title_from_configrA   r   r   model_validatorsr   r   objectr   r  ry   r=   eval_type_backport_make_forward_refr  r)   r   r   r2    _get_args_resolving_forward_refsr   r  r   r   r   r  __pydantic_root_model___common_field_schemaapply_model_validatorsr"   model_schemamodel_fields_schemaitemsr   r   root_validatorsrD   r]   _apply_model_serializersmodel_serializersr)  r*  )r   r   	model_refmaybe_schemar}   r\  r   rf  r   r2  rh  r]  candidate_clsextras_annotationr   extra_items_type
root_fieldr   rp  fields_schemanew_inner_schemar   r   rS  r   _model_schema  s   





	


4//$zGenerateSchema._model_schemamodel#type[BaseModel | StandardDataclass]ConfigWrapper | Noner   c                 C  sR   |du rdS |j r|j S |j}|r'|| }t|ts%td| d|j |S dS )zfGet the title of a model if `model_title_generator` or `title` are set in the config, else return NoneNzmodel_title_generator  must return str, not )r   model_title_generatorr  ry   r   r   )r  r   r  r   r   r   r   rg  m  s   
z+GenerateSchema._get_model_title_from_configc                   sB   ddd |d dkr| j j fd	d
|d D  |d }|S )zuUnpack all 'definitions' schemas into `GenerateSchema.defs.definitions`
        and return the inner schema.
        sr    rz   ry   c                 S  s   | d S )Nr   r   )r  r   r   r   rE     s   z1GenerateSchema._unpack_refs_defs.<locals>.get_refr   r)  c                   s   i | ]} ||qS r   r   )r   r  rE   r   r   rT        z4GenerateSchema._unpack_refs_defs.<locals>.<dictcomp>r   N)r  r    rz   ry   )r   r)  updater'  r   r  r   _unpack_refs_defs  s
   
 z GenerateSchema._unpack_refs_defssourcecore_schema.CoreSchema | Nonec                 C  s|  t |r	| j }| j|\}}|dur|W  d   S W d   n1 s)w   Y  ||u r5d}nd}t|dd }dur\tt|j	dkrP||}nC||t
| j| |d}n7t|dd }durvt|tsv|dd|krv|}nt|d	d }	durtd
t tdd |	 D }ndS | |}t|r|d dd}
|
r|
|d< nt|}
|
r|| jj|
< t|
S |S )a0  Try to generate schema from either the `__get_pydantic_core_schema__` function or
        `__pydantic_core_schema__` property.

        Note: `__get_pydantic_core_schema__` takes priority so it can
        decide whether to use a `__pydantic_core_schema__` attribute, or generate a fresh schema.
        Nunpackzto-def__get_pydantic_core_schema__r8   )ref_mode__pydantic_core_schema__r   __get_validators__zc`__get_validators__` is deprecated and will be removed, use `__get_pydantic_core_schema__` instead.c                 S  s   g | ]}t |qS r   r"   "with_info_plain_validator_functionr   rR  r   r   r   r     r  zAGenerateSchema._generate_schema_from_property.<locals>.<listcomp>r   r   )rb   r   r   r   r`  r   lenr   r   
parametersr`   r7  r  r_   r   r7   r"   chain_schemar  rG   r   rE   r)  r*  )r   r   r  _rw  r  
get_schemar   existing_schemarc  r   r   r   r   r6    sP   



z-GenerateSchema._generate_schema_from_propertyc              
   C  sl   z
t j|| jd}W n ty } zt||d }~ww t|tr+t|jd| | j	r4t
|| j	}|S )N)globalnsz%Unable to evaluate forward reference )r=   rj  r  	NameErrorr3   from_name_errorr  r   __forward_arg__r   r^   )r   r   er   r   r   _resolve_forward_ref  s   
z#GenerateSchema._resolve_forward_refrH  Literal[True]tuple[Any, ...]c                 C     d S r   r   )r   r   rH  r   r   r   rl       z/GenerateSchema._get_args_resolving_forward_refstuple[Any, ...] | Nonec                 C  r  r   r   r  r   r   r   rl    r  Fc                   s>   t |}|rt fdd|D }|S |rtd| d|S )Nc                   s$   g | ]}t |tr |n|qS r   )r  r   r  )r   r   r   r   r   r     s   $ zCGenerateSchema._get_args_resolving_forward_refs.<locals>.<listcomp>z	Expected z+ to have generic parameters but it had none)r(   r   r   )r   r   rH  argsr   r   r   rl    s   c                 C  s   |  |}|s	tS |d S )Nr   )rl  r   )r   r   r  r   r   r   _get_first_arg_or_any  s   
z$GenerateSchema._get_first_arg_or_anytuple[Any, Any]c                 C  sJ   |  |}|sttfS t|dk rt|}td| d|d |d fS )Nr+   z Expected two type arguments for z, got 1r   r8   )rl  r   r  r)   r   )r   r   r  originr   r   r   _get_first_two_args_or_any  s   
z)GenerateSchema._get_first_two_args_or_anyc                 C  s   t |tr
| |S t |tr|S t |trt|}t |tr'| | |S ddlm	} t
||rM| j| | |W  d    S 1 sHw   Y  t |trYtj|jdS | |S )Nr+   rf   )
schema_ref)r  _AnnotatedType_annotated_schemar   ry   r   r  r  r   rg   rc   r   r   r~  rZ   r"   r*  type_ref
match_type)r   r   rg   r   r   r   r7    s    





 

z%GenerateSchema._generate_schema_innerc                 C  s  |t u r|  S |tu rt S |tu rt S |tu r t S |t	u r(t
 S |tu s0|tu r4t S |du s=|tju rAt S |tv rJ| |S |tv rW| || |S |tv rd| || |S |tv rq| || |S |tv r| j|g| |R  S t|tr| |S |t u r| ! S t"|rt# S t$|r| %|S t&|r| '|dS t(|r| )|dS t*|r| +|j,S |t-j.kr| /|S |t0j1j2u s|t3j2u r| 4 S t|t3j5r| 6|S t7|r|t8u rt S | +| |S t|t9t:t;t<fr| =|S t>?|r&t@|tAr&ddlBmC} ||| jDjES tF|r2| G|dS | H|d}|durG|\}}| I||S tJ|}|durV| K||S | jLr_| M|S | N|S )a  Main mapping of types to schemas.

        The general structure is a series of if statements starting with the simple cases
        (non-generic primitive types) and then handling generics and other more complex cases.

        Each case either generates a schema directly, calls into a public user-overridable method
        (like `GenerateSchema.tuple_variable_schema`) or calls into a private method that handles some
        boilerplate before calling into the user-facing method (e.g. `GenerateSchema._tuple_schema`).

        The idea is that we'll evolve this into adding more and more user facing methods over time
        as they get requested and we figure out what the right API for them is.
        Nr8   )get_enum_core_schemar   )Ory   r  bytesr"   bytes_schemaint
int_schemafloatfloat_schemar{   bool_schemar   ri  r   r=   NoneTypenone_schemarq   _tuple_schemarr   r  r  rs   r  rt   r  ru   r  r  r  r&   _type_alias_type_schemar   _type_schemais_callable_typecallable_schemais_literal_type_literal_schemar*   _typed_dict_schemais_namedtuple_namedtuple_schemais_new_typer  __supertype__rePattern_pattern_schemacollectionsabcHashabletyping_hashable_schemar   _unsubstituted_typevar_schemara   r   r   r   r   r   _callable_schemar   isclassr   r   _std_types_schemar  r   config_dictis_dataclass_dataclass_schema0_get_prepare_pydantic_annotations_for_known_type_apply_annotationsr)   _match_generic_typer  r  r  )r   r   r  ressource_typer   r  r   r   r   r    s   















zGenerateSchema.match_typer  c                 C  s  t |tr
| |S t|r| ||S t|r | ||S | ||}|d ur,|S t	|r6| 
|S |tv r?| |S |tv rL| || |S |tv rY| || |S |tv rf| || |S |tv rv| j|g| |R  S t|r| ||S |tjtfv r| |S |tjtjjhv r|  |S |tj!tjj!tj"tjj"hv r| #|S |t$j%tj%fv r| &|S | j'r| (|S | )|S r   )*r  r&   r  r=   r  r  r  r  r6  origin_is_union_union_schemarq   r  rr   r  r  rs   r  rt   r  ru   r  r  r*   r  r  r   r   _subclass_schemaSequencer  r  _sequence_schemar   	Generator_iterable_schemar  r  r  r  r  r  )r   r   r  r:  r   r   r   r  m  sD   












z"GenerateSchema._match_generic_typerG  namery   
field_infore   r   rL   core_schema.TypedDictFieldc                C  sD   |  |||}tj|d | sdn||d |d |d |d dS )zAPrepare a TypedDictField to represent a model or typeddict field.r   Fserialization_excludevalidation_aliasserialization_aliasr2  )rH  r  r  r  r2  )rn  r"   typed_dict_fieldis_required)r   r  r  r   rH  common_fieldr   r   r   _generate_td_field_schema  s   	z(GenerateSchema._generate_td_field_schemacore_schema.ModelFieldc                 C  s<   |  |||}tj|d |d |d |d |d |d dS )z0Prepare a ModelField to represent a model field.r   r  r  r  frozenr2  r  r  r  r  r2  )rn  r"   model_fieldr   r  r  r   r  r   r   r   rO    s   z(GenerateSchema._generate_md_field_schemacore_schema.DataclassFieldc                 C  sV   |  |||}tj||d |j|jpd|jrdnd|d |d |d |d |d d	
S )
zJPrepare a DataclassField to represent the parameter/field, of a dataclass.r   NFr  r  r  r  r2  )init	init_onlykw_onlyr  r  r  r  r2  )rn  r"   dataclass_fieldr  init_varr  r  r   r   r   _generate_dc_field_schema  s   z(GenerateSchema._generate_dc_field_schemaalias_generator%Callable[[str], str] | AliasGeneratorr   c                 C  s  |j du s|j dks|jdu s|jdu s|jdu rd\}}}t| tr,| |\}}}nt| trE| |}t|tsEt	d|  d|j
 |j du sO|j dkrRd|_ |j dkrft|||_t|||_||_|jdu rn||_|jdu ryt|||_|jdu rt|||_dS dS dS )a  Apply an alias_generator to aliases on a FieldInfo instance if appropriate.

        Args:
            alias_generator: A callable that takes a string and returns a string, or an AliasGenerator instance.
            field_info: The FieldInfo instance to which the alias_generator is (maybe) applied.
            field_name: The name of the field from which to generate the alias.
        Nr8   NNNalias_generator r  )alias_priorityaliasr  r  r  r,   generate_aliasesr   ry   r   r   r   )r  r  r   r  r  r  r   r   r   $_apply_alias_generator_to_field_info  s4   












z3GenerateSchema._apply_alias_generator_to_field_infocomputed_field_inford   computed_field_namec                 C  s   |j du s|j dks|jdu rUd\}}}t| tr"| |\}}}nt| tr;| |}t|ts;td|  d|j |j du sE|j dkrHd|_ |j dkrWt	|||_dS dS dS )a  Apply an alias_generator to alias on a ComputedFieldInfo instance if appropriate.

        Args:
            alias_generator: A callable that takes a string and returns a string, or an AliasGenerator instance.
            computed_field_info: The ComputedFieldInfo instance to which the alias_generator is (maybe) applied.
            computed_field_name: The name of the computed field from which to generate the alias.
        Nr8   r  r  r  )
r  r  r  r,   r  r   ry   r   r   r   )r  r  r  r  r  r  r   r   r   -_apply_alias_generator_to_computed_field_info  s    







z<GenerateSchema._apply_alias_generator_to_computed_field_infoFieldInfo | ComputedFieldInfoc                 C  sZ   |j p| j }|du rdS |jdu r+|||}t|ts&td| d|j ||_dS dS )ae  Apply a field_title_generator on a FieldInfo or ComputedFieldInfo instance if appropriate
        Args:
            config_wrapper: The config of the model
            field_info: The FieldInfo or ComputedField instance to which the title_generator is (maybe) applied.
            field_name: The name of the field from which to generate the title.
        Nzfield_title_generator r  )field_title_generatorr   r  ry   r   r   )r   r  r   r  r   r   r   r   *_apply_field_title_generator_to_field_info/  s   




z9GenerateSchema._apply_field_title_generator_to_field_info_CommonFieldc                   s  ddl m}m} ddlm} tjttfrlj	}j
r/|pi  }|dd j
 D  tj|}|jurlt|tsl||}	|	j_|	j D ]\}
}|
jvrb|
jvrbt|
| qNg |	jj_jj}}dfd	d
}j| jd urj|||d}n||}W d    n1 sw   Y  t|j |}t|rd_dd |D   fdd|D }t| |}t |t|||}t |t|j! ||}" st#|}$|t|j% |}&j'| j(j)t*j+pj+dkpd t,j-d}dd | D }j.}t/t0||gd}j'j1}|d ur92|| t3j4||frHj45 }nj4}t6|j7rSdnd |j8j9|dS )Nr+   )AliasChoices	AliasPathre   c                 S  s   i | ]\}}|j |qS r   )r   rP  r   r   r   rT  Q      z7GenerateSchema._common_field_schema.<locals>.<dictcomp>r   r    rz   c                   s    |  j} | S r   )r#  r  r   )r  r   r   r   set_discriminatorf  s   z>GenerateSchema._common_field_schema.<locals>.set_discriminator)transform_inner_schemaTc                 S  s   g | ]
}|j jd u r|qS T)rv   	each_itemr  r   r   r   r   z  r   z7GenerateSchema._common_field_schema.<locals>.<listcomp>c                   s   g | ]}| vr|qS r   r   r  )r   r   r   r   {  r   )r   r   
deprecatedexamplesc                 S  s   i | ]\}}|d ur||qS r   r   rP  r   r   r   rT    s    js_annotation_functionsr  r   r    rz   r    ):r  r  r  r}   re   r\   
annotationr   ry   r  r   r   r  rr  r=   eval_type_lenientrZ   from_annotation_attributes_setmetadata_lookupsetattrr2  r   r   r  r  r   rc  r-  $_validators_require_validate_defaultvalidate_defaultr   r   rb  r  wrap_default_apply_field_serializersrX  r  r   r   r   r{   r  r#   r  json_schema_extrarA   get_json_schema_update_funcr  r  r  r  convert_to_aliases_common_fieldexcluder  r  )r   r  r  r   r  r  re   r   	evaluatednew_field_inforQ  rR  r  r   r	  r   this_field_validatorsjson_schema_updatesr  r2  r  r  r   )r   r  r   r   rn  E  s   




z#GenerateSchema._common_field_schema
union_typec           
      C  s   | j |dd}g }d}|D ]}|du s|tju rd}q|| | qt|dkr/|d }n'g }|D ]}|di tj}	|	durK|||	f q3|| q3t	
|}|r]t	|}|S )zGenerate schema for a Union.TrG  FNr8   r   r2  )rl  r=   r  r   r  r  r   r9   TAGGED_UNION_TAG_KEYr"   union_schemanullable_schema)
r   r&  r  choicesr   argr  choices_with_tagschoicetagr   r   r   r    s&   


zGenerateSchema._union_schemac              	   C  s   | j |b\}}|d ur|W  d    S t|p|}|j}t|}| j|% t|| j	}t
||}| |}|d dksCJ ||d< W d    n1 sQw   Y  || j j|< t|W  d    S 1 skw   Y  d S )Nr   r)  r   )r   r`  r)   	__value__r[   r   r   r=   r  r  r^   r  r)  r"   r*  )r   r   r   rw  r  r  r   r   r   r   r   r    s"   


$z&GenerateSchema._type_alias_type_schemaliteral_typec                 C  s&   t |}|sJ d| t|S )zGenerate schema for a Literal.z(literal "expected" cannot be empty, obj=)r=   all_literal_valuesr"   literal_schema)r   r0  expectedr   r   r   r    s   

zGenerateSchema._literal_schematyped_dict_clsc                   s(  ddl m} j|| j|[\}}|dur,|W  d   W  d   S t|}|dur6|}tsEt|j	dkrEt
dddzt|d}W n tyW   d}Y nw j| j| j|}j|j}	i }
t| jjrt|d	d
}nd}t|jd	d D ]\\}}t||}||	v }t|tjkrd	}j|d	dd }nt|tjkrd}j|d	dd }| |}|dur|j!du r||v r|| |_!"j|| j#|| |d|
|< q$|t%|}t&t't(||dg|d}t)j*|
 fdd j+, D |||d}-| j., }t/| j0, d}|jj1|< t)2|W  d   W  d   W  d   W  d   S 1 sTw   Y  W d   n	1 sdw   Y  W d   n1 stw   Y  W d   dS W d   dS 1 sw   Y  dS )a  Generate schema for a TypedDict.

        It is not possible to track required/optional keys in TypedDict without __required_keys__
        since TypedDict.__new__ erases the base classes (it replaces them with just `dict`)
        and thus we can track usage of total=True/False
        __required_keys__ was added in Python 3.9
        (https://github.com/miss-islington/cpython/blob/1e9939657dd1f8eb9f596f77c1084d2d351172fc/Doc/library/typing.rst?plain=1#L1546-L1548)
        however it is buggy
        (https://github.com/python/typing_extensions/blob/ac52ac5f2cb0e00e7988bae1e2a1b8257ac88d6d/src/typing_extensions.py#L657-L666).

        On 3.11 but < 3.12 TypedDict does not preserve inheritance information.

        Hence to avoid creating validators that do not do what users expect we only
        support typing.TypedDict on Python >= 3.12 or typing_extension.TypedDict on all versions
        r+   r  Nr  zXPlease use `typing_extensions.TypedDict` instead of `typing.TypedDict` on Python < 3.12.ztyped-dict-versionr   __pydantic_config__T)use_inspect)localnsinclude_extrasrG  r   Fr>  )r@  r4  c                   rU  r   rV  rY  rS  r   r   r   C  r[  z5GenerateSchema._typed_dict_schema.<locals>.<listcomp>)r\  r   r2  rN  all)3r}   re   r   r   r   r`  r[   _SUPPORTS_TYPEDDICTr   r   r4   rS   AttributeErrorr   r   r   rf  r  __required_keys__rL   builduse_attribute_docstringsrW   rY   r  rr  r^   r)   r=   Requiredrl  NotRequiredr  r   r  r  rg  r>   rA   r   r   r"   typed_dict_schemar\  r-  rt  ru  ro  rh  r)  r*  )r   r4  r  re   typed_dict_refrw  r   rN  rf  required_keysr}   field_docstringsr   r  rH  r  r   r2  	td_schemar   r   rS  r   r    s    





2Tz!GenerateSchema._typed_dict_schemanamedtuple_clsc              	     s"  j   j j\}}|dur$|W  d   W  d   S t |dur.| t djd}|s@dd  jD }rMfdd| D }t	j
 fdd| D tdd	d
}t	j| |dW  d   W  d   S 1 szw   Y  W d   dS 1 sw   Y  dS )z!Generate schema for a NamedTuple.NT)r8  r7  c                 S  s   i | ]}|t qS r   )r   )r   rQ  r   r   r   rT  b      z5GenerateSchema._namedtuple_schema.<locals>.<dictcomp>c                   s   i | ]
\}}|t | qS r   r^   r   r   r  r   r   r   rT  e  s    
c              	     s,   g | ]\}}j || j|tjd qS ))default)_generate_parameter_schema_field_defaultsr   r	   emptyrI  )rF  r   r   r   r   k  s    z5GenerateSchema._namedtuple_schema.<locals>.<listcomp>)js_prefer_positional_arguments)r2  )r   )r   r   r   r`  r[   rY   r  _fieldsrr  r"   arguments_schemarA   call_schema)r   rF  r  namedtuple_refrw  r   rQ  r   )rF  r   r   r   r  Q  s4   
	Rz!GenerateSchema._namedtuple_schemar  r   rK  modeJLiteral['positional_only', 'positional_or_keyword', 'keyword_only'] | Nonecore_schema.ArgumentsParameterc                 C  s  ddl m} |tju r||}n|||}|jdus J d|j|j}}| j	| | 
||}	W d   n1 s>w   Y  | sLt||	}	t||	}
|durZ||
d< |jdurf|j|
d< |
S | jj}t|tr}|jdur}|||
d< |
S t|tr|||
d< |
S )zXPrepare a ArgumentsParameter to represent a field in a namedtuple or function signature.r+   r  Nz<field.annotation should not be None when generating a schemarT  r  )r}   re   r	   rN  r  from_annotated_attributer  r2  r   r   r  r  r  r"   arguments_parameterr  r   r  r  r,   r   )r   r  r  rK  rT  re   rx   r  r   r   parameter_schemar  r   r   r   rL  u  s0   




z)GenerateSchema._generate_parameter_schema
tuple_typec                   s   t | |}r|rtfdd|D }|s-|tv r(tjt gddS tg S |d tu rJt|dkrFtj 	|d gddS t
dt|dkr[|d d	kr[tg S t fd
d|D S )zIGenerate schema for a Tuple, e.g. `tuple[int, str]` or `tuple[int, ...]`.c                 3  s    | ]}t | V  qd S r   rH  r   paramrJ  r   r   	<genexpr>  s    z/GenerateSchema._tuple_schema.<locals>.<genexpr>r   )r   r   r+   z&Variable tuples can only have one typer8   r   c                   s   g | ]}  |qS r   )r  r[  r   r   r   r     r  z0GenerateSchema._tuple_schema.<locals>.<listcomp>)r[   rl  r   rq   r"   tuple_schemar   Ellipsisr  r  
ValueError)r   rZ  paramsr   )r   r   r   r    s   


zGenerateSchema._tuple_schemac                 C  s   t jt tdddS )Nis_typezInput should be a typecustom_error_typecustom_error_message)r"   custom_error_schemar  r   r   r   r   r   r    s
   zGenerateSchema._type_schemac                   s&    j |dd}t fdd|D S )z*Generate schema for `Type[Union[X, ...]]`.TrG  c                      g | ]
}  tj| qS r   r  r  r   )r   r  r   r   r   r     r   z<GenerateSchema._union_is_subclass_schema.<locals>.<listcomp>)rl  r"   r(  )r   r&  r  r   r   r   _union_is_subclass_schema  s   z(GenerateSchema._union_is_subclass_schematype_c                   s     |}|tkr  S t|tjr>|jr*tt	|jr$ 
|jS t|jS |jr:t fdd|jD S   S tt	|rJ 
|S t|S )z-Generate schema for a Type, e.g. `Type[int]`.c                   rg  r   rh  )r   cr   r   r   r     r   z3GenerateSchema._subclass_schema.<locals>.<listcomp>)r  r   r  r  r  r   	__bound__r=   r  r)   ri  r"   is_subclass_schema__constraints__r(  )r   rj  
type_paramr   r   r   r    s    


zGenerateSchema._subclass_schemasequence_typec           	      C  s   ddl m} | |}| |}t|}tjtjdd}|t	kr2ddl
m} t|t||g}tj||dd}tj|||dS )	z5Generate schema for a Sequence, e.g. `Sequence[int]`.r8   )serialize_sequence_via_listr  )cls_repr)sequence_validatorT)r   info_arg)r   python_schemar   )r  rq  r  r  r"   r
  r  r  r  r   _validatorsrs  r  no_info_wrap_validator_function#wrap_serializer_function_ser_schemajson_or_python_schema)	r   rp  rq  	item_typeitem_type_schemar
  ru  rs  r   r   r   r   r    s    


zGenerateSchema._sequence_schemacore_schema.GeneratorSchemac                 C  s   |  |}t| |S )z$Generate a schema for an `Iterable`.)r  r"   generator_schemar  )r   rj  rz  r   r   r   r    s   
zGenerateSchema._iterable_schemapattern_typec                 C  s   ddl m} tdd gd}tjtddt d}|tjks$|t	jkr-tj
|j||d	S | j|d
dd }|tu rCtj
|j||d	S |tu rPtj
|j||d	S td|d)Nr8   )rv  c                 S  s
   dddS )Nstringregex)r   formatr   )_1_2r   r   r   <lambda>     
 z0GenerateSchema._pattern_schema.<locals>.<lambda>r?  patternr   )r   return_schema)r   r2  TrG  r   r  r   )r  rv  rA   r"   r   r   r  r  r  r   no_info_plain_validator_functionpattern_either_validatorrl  ry   pattern_str_validatorr  pattern_bytes_validatorr2   )r   r~  rv  r2  serr\  r   r   r   r    s0   zGenerateSchema._pattern_schemac                 C  s   t jt tjjdddS )Nis_hashablezInput should be hashablerc  )r"   rf  r  r  r  r  r   r   r   r   r    s
   zGenerateSchema._hashable_schema	dataclasstype[StandardDataclass]type[StandardDataclass] | Nonec                   s  j |u j|\\}}|dur&|W  d   W  d   S t|}|dur0|}t *}|jD ]}t|rH|	j
| q8d}t|jD ]}t|rft|dd}|	j| qPj|}	jddlm}
 |
|rt|j}|r| D ]	}||j qnt|j|d}jjjdkr| D ]\}}|jdu rtd| d	d
dq|jdpt | t! fdd| D dd d}t"|d}t"|d}t#j$|j%| fdd j& D |d}t'| j( d} j) }t*||d}+|t,|}t-t.t/||dgd}t#j0||||dd t1|D ||	|d}2| j3 }t*||d}|jj4|< t#5|W  d   W  d   W  d   S 1 sbw   Y  J d1 sow   Y  W d   dS 1 sw   Y  dS )z Generate schema for a dataclass.Nr5  r+   r   rJ  rB  FzField zd has `init=False` and dataclass has config setting `extra="allow"`. This combination is not allowed.z dataclass-init-false-extra-allowr   ra  c                 3  s"    | ]\}} || V  qd S r   )r  rP  rS  r   r   r]  T  s     z3GenerateSchema._dataclass_schema.<locals>.<genexpr>c                 S  s   |  dduS )Nr  Fr   )r   r   r   r   r  U  s    z2GenerateSchema._dataclass_schema.<locals>.<lambda>)key__post_init__	__slots__c                   rU  r   rV  rY  rS  r   r   r   ]  r[  z4GenerateSchema._dataclass_schema.<locals>.<listcomp>)r\  collect_init_onlyrI  r>  r?  c                 S  s   g | ]}|j qS r   )r  )r   rx   r   r   r   r   s  rG  )rM  r   r}   slotsrN  r2  r_  Unreachable)6r   r   r   r`  r[   r   r   r   r  enter_contextr   reversedr   r   r   rf  r  r   r   __pydantic_fields__r-  apply_typevars_mapr  rX   r   extrarr  r  r4   __dict__r   rL   r=  sortedhasattrr"   dataclass_args_schemar   r\  r   rs  rh  ro  rg  r>   rA   r   r   dataclass_schemar}   rt  ru  r)  r*  )r   r  r  dataclass_refrw  r   dataclass_bases_stackdataclass_baserN  rf  r   r}   rx   r   r  has_post_init	has_slotsargs_schemar   rh  r   r2  	dc_schemar   r   rS  r   r    s    











Y8z GenerateSchema._dataclass_schemafunctioncore_schema.CallSchemac                 C  s&  t |}tj|| jd}tjdtjdtjdi}g }d}d}|j	 D ]J\}}	|	j
|ju r3ttt}
n|| }
||	j}|durP| ||
|	j|}|| q"|	jtjkr\| |
}q"|	jtjksgJ |	j| |
}q"d}| j}|jr|d}|dur| |}tjtj||||jd||dS )	zsGenerate schema for a Callable.

        TODO support functional validators once we support them in Config
        )r   positional_onlypositional_or_keywordkeyword_onlyNrz   )var_args_schemavar_kwargs_schemapopulate_by_name)r  )r   r=   get_function_type_hintsr  r	   POSITIONAL_ONLYPOSITIONAL_OR_KEYWORDKEYWORD_ONLYr  rr  r  rN  r  r   r   r   kindrL  rK  r   VAR_POSITIONALr  VAR_KEYWORDr   validate_returnr"   rR  rQ  r  )r   r  sig
type_hintsmode_lookuparguments_listr  r  r  pr  parameter_mode
arg_schemar  r   return_hintr   r   r   r    sJ   

zGenerateSchema._callable_schematypevartyping.TypeVarc                 C  s   t |tjsJ |j}|j}z| }W n ty%   t|dd d u}Y nw |d ut|dk | dkr8t	d|r@| 
|jS |rJ| tj| S |r`| 
|}tjdd t d|d< |S t S )	N__default__r   r8   zZPydantic does not support mixing more than one of TypeVar bounds, constraints and defaultsc                 S     || S r   r   )xhr   r   r   r        z>GenerateSchema._unsubstituted_typevar_schema.<locals>.<lambda>r  r   )r  r  r   rl  rn  has_defaultr;  r   r  NotImplementedErrorr  r  r  r   r"   rx  r   )r   r  rp   constraintstypevar_has_defaultr   r   r   r   r    s.   

z,GenerateSchema._unsubstituted_typevar_schemarZ  Decorator[ComputedFieldInfo]rX  2dict[str, Decorator[FieldSerializerDecoratorInfo]]core_schema.ComputedFieldc           	   
     s  zt  j jj| j}W n ty } zt||d }~ww |t	u r*t
dddt|| j}tj j|d _| |}| j|t|  jdd}| jj}|d ur^| j| j jd | | j j j d fdd}t|gd}tj j| jj|dS )NzComputed field is missing return type annotation or specifying `return_type` to the `@computed_field` decorator (e.g. `@computed_field(return_type=int|str)`)zmodel-field-missing-annotationr   )return_typeTcomputed_field)r  r  r  r   rB   r   r.   rz   r5   c                   s   || }d|d<  j j}|d ur||d<  j j}|d ur ||d<  j js* j jdkr.d|d<  j j}|d ur<t||d<  j j}|d urIt|| |S )NTreadOnlyr   r   r  r  r  )rv   r   r   r  r  r#   r  add_json_schema_extra)r   r   r   r   r   r  r  rZ  r   r   set_computed_field_metadata  s"   
zJGenerateSchema._computed_field_schema.<locals>.set_computed_field_metadatar  )r  r  r2  )r   rB   r   r.   rz   r5   )r:   get_function_return_typefuncrv   r  r  r  r3   r  r!   r4   r^   r   r   replacer  r  r   r-  r   r   r  r  r  rA   r"   r  r  )	r   rZ  rX  r  r  return_type_schemar  r  r2  r   r  r   rW    s<   

z%GenerateSchema._computed_field_schemaannotated_typec                 C  sL   ddl m} | j|dd^}}| ||}|D ]}t||r#t||}q|S )zdGenerate schema for an Annotated type, e.g. `Annotated[int, Field(...)]` or `Annotated[int, Gt(0)]`.r+   r  TrG  )r}   re   rl  r  r  r  )r   r  re   r  r   r   r  r   r   r   r    s   


z GenerateSchema._annotated_schemar   tuple[Any, list[Any]] | Nonec                 C  s\   ddl m} zt| W n
 ty   Y d S w |D ]}|||| jj}|d ur+|  S qd S )Nr8   )PREPARE_METHODS)r  r  hashr   r   r  )r   r   r   r  genr  r   r   r   r  &  s   z?GenerateSchema._get_prepare_pydantic_annotations_for_known_typec                 C  s   | S r   r   )r  r   r   r   r  =  s    zGenerateSchema.<lambda>r  	list[Any]r
  "Callable[[CoreSchema], CoreSchema]c                   s   t t|} t|}|dur|\}g }d	 fdd}t| }|D ]}|du r0q) |||}q)|}	|rLt|	j}
|
	dg 
| t jj|	S )
a  Apply arguments from `Annotated` or from `FieldInfo` to a schema.

        This gets called by `GenerateSchema._annotated_schema` but differs from it in that it does
        not expect `source_type` to be an `Annotated` object, it expects it to be  the first argument of that
        (in other words, `GenerateSchema._annotated_schema` just unpacks `Annotated`, this process it).
        Nr   r   rz   r    c                   s`     | }|d u r | }n|}t| |}|d ur,t| jj}|d ur, || |S r   )r6  r7  r8  r9  r   r)  r4  )r   r:  r   r;  r.  r   r  r
  r   r   inner_handlerL  s   
z8GenerateSchema._apply_annotations.<locals>.inner_handler pydantic_js_annotation_functionsr   r   rz   r    )r,  r<   expand_grouped_metadatar  r   r`   _get_wrapped_inner_schemar@   r2  r3  extendr   r   r   )r   r  r   r
  r  r  r  get_inner_schemar  r   r2  r   r  r   r  9  s$   

z!GenerateSchema._apply_annotationsr2  c           
      C  sX  ddl m} t||r%|jD ]}| ||}q|jd ur#| ||j}|S |d dkrA|dt	 }| ||}|r?||d< |S |}|dd }|d urk|
 }|dt|  }|| jjv rf| jj| S ||d< n1|d dkr|d	 }|| jjv r| jj| 
 }|dt|  }|| jjv r| jj| S ||d< t||
 }	|	d ur|	S |S )
Nr+   r  r   r   r   r   r  definition-refr  )r}   re   r  r2  _apply_single_annotationr  r#  r   r"   r   r   reprr   r)  r<   apply_known_metadata)
r   r   r2  re   field_metadatarI  r   r   new_refmaybe_updated_schemar   r   r   r  h  sB   



z'GenerateSchema._apply_single_annotationc                 C  s   ddl m} t||rI|jD ]}| ||}qi }|jr!|j|d< |jr)|j|d< |jr3t|j|d< |j	}|s:|rIt
|jdg t|| |S )Nr+   r  r   r   r  r  )r}   re   r  r2  $_apply_single_annotation_json_schemar   r   r  r#   r  r@   r3  r   r  )r   r   r2  re   r  json_schema_updater  r   r   r   r    s"   



z3GenerateSchema._apply_single_annotation_json_schemar  r-   r  list[GetJsonSchemaFunction]r`   c                   s4   t  dd p	dd d
 fdd	}t|S )Nr  c                 S  r  r   r   )r  r   r   r   r   r    r  z:GenerateSchema._get_wrapped_inner_schema.<locals>.<lambda>r  r   rz   r   c                   sB   | } | }| }t |}|d ur| |S r   )r  r  r8  r   )r  r   r;  r  r  metadata_get_schemar  r   r   r   new_handler  s   


z=GenerateSchema._get_wrapped_inner_schema.<locals>.new_handler)r  r   rz   r   )r   r`   )r   r  r  r  r  r   r  r   r    s
   

z(GenerateSchema._get_wrapped_inner_schemaserializers-list[Decorator[FieldSerializerDecoratorInfo]]r  c              
   C  s2  |rt |}|d dkr|d }| |||d< |S td|dd}|dur-t|}|d }t|j|j	j
|d\}}zt|j|j	j| j}	W n ty\ }
 zt|
|
d}
~
ww |	tu rdd}n| |	}|j	j
d	krtj|j||||j	jd
|d< |S |j	j
dksJ tj|j||||j	jd
|d< |S )z$Apply field serializers to a schema.r   r)  r   zstr|Noner   Nr   r  wrap)is_field_serializerrt  r  r   r   plain)r   r  r  r   r   r"   r*  rT   r  rv   rT  r:   r  r  r  r  r3   r  r!   r  rx  r   r   )r   r   r  r  r   r   
serializerr  rt  r  r  r  r   r   r   r    sT   




z'GenerateSchema._apply_field_serializers1Iterable[Decorator[ModelSerializerDecoratorInfo]]c           
   
   C  s   | dd}|ret|d }t|j|jj}zt|j|jj| j	}W n t
y5 } zt||d}~ww |tu r=d}n| |}|jjdkrUtj|j|||jjd}	ntj|j|||jjd}	|	|d< |rk||d< |S )z$Apply model serializers to a schema.r   Nr   r  )rt  r  r   r   )r   r,  rU   r  rv   rT  r:   r  r  r  r  r3   r  r!   r  r"   rx  r   r   )
r   r   r  r   r  rt  r  r  r  
ser_schemar   r   r   rt    s@   
z'GenerateSchema._apply_model_serializersr   )r   r>   r   r   r   r   rz   r   )r   r?   r   r   r   r   r   r   r   r   rz   r   )rz   r>   )rz   r   )rz   r   )rz   r{   )rz   r    )r   r   r  r   rz   r    )r   r   r  r   r  r   rz   r    )r   r   rz   r    r  )r   r    r  r  rz   r    r  )r.  r    r/  r0  rz   r   r  )r   r   r5  r{   rz   r   )r   r<  rz   r   )r  r  r   r  rz   r   )r   r   r  r   rz   r  )r   r   rz   r   )r   r   rH  r  rz   r  )r   r   rz   r  )F)r   r   rH  r{   rz   r  )r   r   rz   r  )r   r   rz   r   )r   r   r  r   rz   r    )
r  ry   r  re   r   rL   rH  r{   rz   r  )r  ry   r  re   r   rL   rz   r  )r  ry   r  re   r   rL   rz   r  )r  r  r  re   r   ry   rz   r   )r  r  r  rd   r  ry   )r   r>   r  r   r   ry   rz   r   )r  ry   r  re   r   rL   rz   r  )r&  r   rz   r   )r0  r   rz   r    )r4  r   r  r   rz   r   )rF  r   r  r   rz   r   )
r  ry   r  r   rK  r   rT  rU  rz   rV  )rZ  r   rz   r   )rz   r   )rj  r   rz   r   )rp  r   rz   r   )rj  r   rz   r|  )r~  r   rz   r   )r  r  r  r  rz   r   )r  r0  rz   r  )r  r  rz   r   )rZ  r  rX  r  rz   r  )r  r   rz   r   )r   r   r   r  rz   r  )r  r   r   r  r
  r  rz   r    )r   r   r2  r   rz   r   )r  r-   r  r   r  r  rz   r`   )r   r   r  r  r  r{   rz   r   )r   r   r  r  rz   r   )Kr   r   r   r   r  r   classmethodr  r   r   r  r  r  r  r  r  r  r  r  r  r#  	Exceptionr$  r(  r%  r4  r  r~  staticmethodrg  r  r6  r  r   rl  r  r  r7  r  r  r  rO  r  r  r  r  rn  r  r  r  r  r  r	   rN  rL  r  r  ri  r  r  r  r  r  r  r  r  rW  r  r  r  r  r  r  r  rt  r   r   r   r   r   =  s    







	/a=	V21*i
l(#j5B/*7r   c                 C     t | |S r   )r"   !no_info_before_validator_functionfr   r  r   r   r   r  #      r  c                 C  r  r   )r"    no_info_after_validator_functionr  r   r   r   r  $  r  c                 C  s
   t | S r   )r"   r  )r  r  r  r   r   r   r  %  r  c                 C  r  r   )r"   rw  r  r   r   r   r  &  r  c                 C     t j| ||dS N)r   )r"   #with_info_before_validator_functionr  r   r   r   r   r   r  '      c                 C  r  r  )r"   "with_info_after_validator_functionr
  r   r   r   r  *  r  c                 C  s   t j| |dS r  r  )r  r  r   r   r   r   r  -  s    c                 C  r  r  )r"   !with_info_wrap_validator_functionr
  r   r   r   r  0  r  ))beforeno-info)afterr  )r  r  )r  r  )r  	with-info)r  r  )r  r  )r  r  zMapping[tuple[FieldValidatorModes, Literal['no-info', 'with-info']], Callable[[Callable[..., Any], core_schema.CoreSchema, str | None], core_schema.CoreSchema]]_VALIDATOR_F_MATCHrc  Iterable[Decorator[RootValidatorDecoratorInfo]] | Iterable[Decorator[ValidatorDecoratorInfo]] | Iterable[Decorator[FieldValidatorDecoratorInfo]]c                 C  sD   |D ]}t |j|jj}|rdnd}t|jj|f |j| |} q| S )a  Apply validators to a schema.

    Args:
        schema: The schema to apply validators on.
        validators: An iterable of validators.
        field_name: The name of the field if validators are being applied to a model field.

    Returns:
        The updated schema.
    r  r  )rV   r  rv   rT  r  )r   rc  r   	validatorrt  val_typer   r   r   r   6  s
   r   +Iterable[Decorator[ValidatorDecoratorInfo]]c                 C  s   | D ]	}|j jr dS qdS )a?  In v1, if any of the validators for a field had `always=True`, the default value would be validated.

    This serves as an auxiliary function for re-implementing that logic, by looping over a provided
    collection of (v1-style) ValidatorDecoratorInfo's and checking if any of them have `always=True`.

    We should be able to drop this function and the associated logic calling it once we drop support
    for v1-style validator decorators. (Or we can extend it and keep it if we add something equivalent
    to the v1-validator `always` kwarg to `field_validator`.)
    TF)rv   always)rc  r  r   r   r   r  O  s
   
r  0Iterable[Decorator[ModelValidatorDecoratorInfo]]rT   Literal['inner', 'outer', 'all']c                 C  s   |  dd}|D ]o}|dkr|jjdkrq|dkr |jjdkr qt|j|jj}|jjdkrB|r9tj|j| d} qtj|j| d} q|jjdkr\|rStj|j| d} qtj	|j| d} q|jjdksdJ |rotj
|j| d} qtj|j| d} q|r~|| d< | S )	a  Apply model validators to a schema.

    If mode == 'inner', only "before" validators are applied
    If mode == 'outer', validators other than "before" are applied
    If mode == 'all', all validators are applied

    Args:
        schema: The schema to apply validators on.
        validators: An iterable of validators.
        mode: The validator mode.

    Returns:
        The updated schema.
    r   NrI  r  r_  r  )r  r   r  )r   rv   rT  rV   r  r"   r  rw  r	  r  r  r  )r   rc  rT  r   r  rt  r   r   r   ro  _  s,   ro  r  re   c                 C  s<   | j rtj|| j | jdS | jturtj|| j| jdS |S )a  Wrap schema with default schema if default value or `default_factory` are available.

    Args:
        field_info: The field info object.
        schema: The schema to apply default on.

    Returns:
        Updated schema by default value or `default_factory`.
    )default_factoryr  )rK  r  )r  r"   with_default_schemar  rK  r!   )r  r   r   r   r   r    s   



r  GetJsonSchemaFunction | Nonec                 C  s   t | dd}t| dr;ddlm} |duo |jj|t |ddfv}|s;t | dd}td|r3d	| d
nd dddt| drQt| tt	t
df sQt| j|S |du rWdS |S )z`Extract `__get_pydantic_json_schema__` from a type, handling the deprecated `__modify_schema__`.__get_pydantic_json_schema__N__modify_schema__r   rf   __func__r   zjThe `__modify_schema__` method is not supported in Pydantic v2. Use `__get_pydantic_json_schema__` insteadz in class ``r  r   zcustom-json-schemar   
__origin__placeholder)r   r  pydanticrg   r  r  r4   r  r   r$   r  r8  r!  )r   r   js_modify_functionrg   has_custom_v2_modify_js_funccls_namer   r   r   r8    s*   
 r8  r  r  3JsonDict | typing.Callable[[JsonDict], None] | Nonerk   c                   s   d	 fdd}|S )
Ncore_schema_or_fieldrB   r   r.   rz   r5   c                   s   i || }t |  |S r   )r  )r(  r   r   r  r  r   r   json_schema_update_func  s   
z<get_json_schema_update_func.<locals>.json_schema_update_func)r(  rB   r   r.   rz   r5   r   )r  r  r*  r   r)  r   r    s   r  r   c                 C  s4   t |tr| t| d S t|r||  d S d S r   )r  r   r  r#   callable)r   r  r   r   r   r    s
   
r  c                   @  s>   e Zd ZU ded< ded< ded< ded< ded	< d
ed< dS )r  r   r   4str | list[str | int] | list[list[str | int]] | Noner  r   r  bool | Noner  r  zdict[str, Any]r2  N)r   r   r   rC  r   r   r   r   r    s   
 r  )r  r  r  r  r2  r  r,  r  r  r-  r  r2  c                C  s   | |||||dS )Nr   r  r  r  r  r2  r   r.  r   r   r   r     s   
r   c                   @  s(   e Zd ZdZdddZedd	d
ZdS )r   z*Keeps track of references and definitions.rz   r   c                 C  s   t  | _i | _d S r   )r   seenr)  r   r   r   r   r     s   
z_Definitions.__init__r   r   3Iterator[tuple[str, None] | tuple[str, CoreSchema]]c              	   c  sj    t |}|| jv s|| jv r|t|fV  dS | j| z|dfV  W | j| dS | j| w )ao  Get a definition for `tp` if one exists.

        If a definition exists, a tuple of `(ref_string, CoreSchema)` is returned.
        If no definition exists yet, a tuple of `(ref_string, None)` is returned.

        Note that the returned `CoreSchema` will always be a `DefinitionReferenceSchema`,
        not the actual definition itself.

        This should be called for any type that can be identified by reference.
        This includes any recursive types.

        At present the following types can be named/recursive:

        - BaseModel
        - Dataclasses
        - TypedDict
        - TypeAliasType
        N)rF   r/  r)  r"   r*  adddiscard)r   r   r   r   r   r   r`    s   z_Definitions.get_schema_or_refNrz   r   )r   r   rz   r0  )r   r   r   r   r   r   r`  r   r   r   r   r     s
    
r   r)  dict[str, CoreSchema]CoreSchema | Nonec                 C  s4   | d dkr| | d d S | d dkr| d S | S )Nr   r  r  r)  r   r  )r   r)  r   r   r   r9  	  s
   r9  c                   @  2   e Zd ZdZdddZedd	d
ZdddZdS )r   _stackrz   r   c                 C  
   g | _ d S r   r7  r   r   r   r   r   (	     
z_FieldNameStack.__init__r   ry   Iterator[None]c                 c  "    | j | d V  | j   d S r   r8  r   r   )r   r   r   r   r   r   +	     z_FieldNameStack.pushr   c                 C     | j r| j d S d S r   r7  r   r   r   r   r   1	     
z_FieldNameStack.getNr3  )r   ry   rz   r;  )rz   r   r   r   r   r  r   r   r   r   r   r   r   r   r   %	      
r   c                   @  r6  )r   r7  rz   r   c                 C  r9  r   r7  r   r   r   r   r   ;	  r:  z_ModelTypeStack.__init__type_objr   r;  c                 c  r<  r   r=  )r   rC  r   r   r   r   >	  r>  z_ModelTypeStack.pushtype | Nonec                 C  r?  r   r7  r   r   r   r   r   D	  r@  z_ModelTypeStack.getNr3  )rC  r   rz   r;  )rz   rD  rA  r   r   r   r   r   8	  rB  r   )rv   rw   rx   ry   rz   r{   )r   r   r}   r   rz   r   )r   r   rx   ry   rz   r   )r   r   r   r   r   r   rz   r   )
r   rB   r   r.   r   r   r   r   rz   r5   )r   r   r   r   r   r    rz   r    )r   r   r   r   rz   r   )r   r   rc  r  r   r   rz   r   )rc  r  rz   r{   )r   r   rc  r  rT  r  rz   r   )r  re   r   r   rz   r   )r   r   r   r    rz   r  )r  r5   r  r'  rz   rk   )r   r5   r  r'  )r   r   r  r,  r  r   r  r-  r  r-  r2  r   rz   r  )r   r    r)  r4  rz   r5  )r   
__future__r   _annotationscollections.abcr  r   r   r  sysr  r   
contextlibr   r   r   r   enumr   	functoolsr   r	   r
   r   	itertoolsr   operatorr   typesr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   pydantic_corer    r!   r"   r#   typing_extensionsr$   r%   r&   r'   r(   r)   r*   aliasesr,   annotated_handlersr-   r.   rN  r/   r0   r1   errorsr2   r3   r4   r   r5   versionr6   r7   r  r9   r:   r;   r<   r=   _configr>   r?   _core_metadatar@   rA   rB   rC   rD   rE   rF   rG   rH   rI   rJ   rK   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rU   rV   _docs_extractionrW   rP  rX   rY   _forward_refrZ   	_genericsr[   r\   r]   r^   _mock_val_serr_   _schema_generation_sharedr`   ra   rb   _utilsrc   r}   rd   re   r   rg   rh   rc  ri   r   rj   rk   version_infor:  r   r  r  rw   ro   AnyFieldDecoratorModifyCoreSchemaWrapHandlerGetCoreSchemaFunctionr   Tuplerq   rC  r,  Listr  MutableSequencerr   r   Set
MutableSetrs   	frozenset	FrozenSetrt   r   MutableMappingru   r   r   r   r   r   JsonEncodersr   ry   r   r   r   r   r  r   r  ro  r  r8  r  r  r  r   r   r9  r   r   r   r   r   r   <module>   s    @$,8




*+
"
	             s




/


	
'	