§
    5P„jø9  ã                  ó"  — U d Z ddlmZ ddlZddlZddlmZ ddlmZm	Z	m
Z
mZmZ ddl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 ddlmZ  ddl!m"Z" erdd	lm#Z# g d
¢Z$dZ%dZ&de'd<    ed¦  «        Z( ed¦  «        Z) ede*¬¦  «        Z+ G d„ de"¦  «        Z,d/d„Z-ed0d„¦   «         Z.ed1d„¦   «         Z.	 d2d3d!„Z.ed0d"„¦   «         Z/ed1d#„¦   «         Z/	 d2d3d$„Z/e.Z0	 d4d(„Ze	 d2dd)œd5d+„¦   «         Z1ed6d,„¦   «         Z1	 d2dd)œd7d.„Z1dS )8a�  Integration with :mod:`attrs`.

This module implements PyTree integration with :mod:`attrs` by providing :func:`field`,
:func:`define`, :func:`frozen`, and :func:`register_node` functions. The :func:`field` and
:func:`define` functions wrap the corresponding :mod:`attrs` functions with an additional
``pytree_node`` parameter for controlling which fields are tree children versus metadata.
The :func:`register_node` function allows registering existing :mod:`attrs` classes as pytree nodes.

The PyTree integration allows attrs classes to be flattened and unflattened recursively. The fields
are stored in a special attribute named ``__optree_attrs_fields__`` in the attrs class.

>>> import optree
... from optree.integrations import attrs
...
>>> @attrs.define(namespace='my_module')
... class Point:
...     x: float
...     y: float
...     z: float = 0.0
...
>>> point = Point(2.0, 6.0, 3.0)
>>> point
Point(x=2.0, y=6.0, z=3.0)
>>> # Flatten without specifying the namespace
>>> optree.tree_flatten(point)  # `Point`s are leaf nodes
([Point(x=2.0, y=6.0, z=3.0)], PyTreeSpec(*))
>>> # Flatten with the namespace
>>> optree.tree_flatten(point, namespace='my_module')
([2.0, 6.0, 3.0], PyTreeSpec(CustomTreeNode(Point[()], [*, *, *]), namespace='my_module'))
>>> treespec = optree.tree_structure(point, namespace='my_module')
>>> point == optree.tree_unflatten(treespec, [2.0, 6.0, 3.0])
True

.. versionadded:: 0.20.0
é    )ÚannotationsN)ÚMappingProxyType)ÚTYPE_CHECKINGÚAnyÚCallableÚTypeVarÚoverload)ÚNOTHINGÚ	AttributeÚFactoryÚasdictÚastupleÚ	cmp_usingÚ
convertersÚevolveÚ
exceptionsÚfieldsÚfields_dictÚfiltersÚhasÚresolve_typesÚsettersÚvalidateÚ
validators)Ú
make_class)ÚGetAttrEntry)ÚClassVar)Ú
AttrsEntryÚfieldÚdefineÚfrozenÚmutabler   Úregister_noder
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   Ú__optree_attrs_fields__TÚboolÚ_PYTREE_NODE_DEFAULTÚ_TÚ_UÚ_TypeT)Úboundc                  ó”   — e Zd ZU dZdZded<   ded<   edd	„¦   «         Zedd
„¦   «         Zedd„¦   «         Z	edd„¦   «         Z
dd„ZdS )r   z%A path entry class for attrs classes.© zClassVar[tuple[()]]Ú	__slots__z	str | intÚentryÚreturnútuple[str, ...]c               óH   — t          d„ | j        j        D ¦   «         ¦  «        S )zGet all field names.c              3  ó$   K  — | ]}|j         V — Œd S ©N)Úname©Ú.0Úas     ú^/root/disk_3tb/conda_envs/Huy-visual/lib/python3.11/site-packages/optree/integrations/attrs.pyú	<genexpr>z$AttrsEntry.fields.<locals>.<genexpr>‹   s$   è è € Ð?Ð? �Q”VÐ?Ð?Ð?Ð?Ð?Ð?ó    ©ÚtupleÚtypeÚ__attrs_attrs__©Úselfs    r8   r   zAttrsEntry.fieldsˆ   s&   € õ Ð?Ð? T¤YÔ%>Ð?Ñ?Ô?Ñ?Ô?Ð?r:   c               óH   — t          d„ | j        j        D ¦   «         ¦  «        S )zGet the init field names.c              3  ó2   K  — | ]}|j         ¯	|j        V — Œd S r3   )Úinitr4   r5   s     r8   r9   z)AttrsEntry.init_fields.<locals>.<genexpr>�   s+   è è € ÐIÐI À!Ä&ÐI�Q”VÐIÐIÐIÐIÐIÐIr:   r;   r?   s    r8   Úinit_fieldszAttrsEntry.init_fields�   s&   € õ ÐIÐI T¤YÔ%>ÐIÑIÔIÑIÔIÐIr:   Ústrc               óh   — t          | j        t          ¦  «        r| j        | j                 S | j        S )zGet the field name.)Ú
isinstancer.   ÚintrD   r?   s    r8   r   zAttrsEntry.field’   s0   € õ �d”j¥#Ñ&Ô&ð 	0ØÔ# D¤JÔ/Ð/ØŒzÐr:   c               ó   — | j         S )zGet the attribute name.)r   r?   s    r8   r4   zAttrsEntry.name™   s   € ð ŒzÐr:   c               ó@   — | j         j        › d| j        ›d| j        ›d�S )z)Get the representation of the path entry.z(field=z, type=ú))Ú	__class__Ú__name__r   r=   r?   s    r8   Ú__repr__zAttrsEntry.__repr__ž   s*   € à”.Ô)ÐUÐU°$´*ÐUÐUÀtÄyÐUÐUÐUÐUr:   N)r/   r0   )r/   rE   )rM   Ú
__module__Ú__qualname__Ú__doc__r-   Ú__annotations__Úpropertyr   rD   r   r4   rN   r,   r:   r8   r   r   �   sÙ   € € € € € € Ø/Ð/à%'€IÐ'Ð'Ð'Ñ'àÐÐÑàð@ð @ð @ñ „Xð@ð ðJð Jð Jñ „XðJð ðð ð ñ „Xðð ðð ð ñ „XððVð Vð Vð Vð Vð Vr:   r   Úkwargsr   r/   c                 óF  — |                       dd¦  «        }t          |                       dd¦  «        pi ¦  «        }|€|                     dt          ¦  «        }||d<   |                      dd¦  «        }|s|rt	          dt
          › d�¦  «        ‚t          j        dd|i| ¤ŽS )	aë  Field factory for :func:`define`.

    This factory function is used to define the fields in an attrs class. It is similar to
    :func:`attrs.field`, but with an additional ``pytree_node`` parameter. If ``pytree_node`` is
    :data:`True` (default), the field will be considered a child node in the PyTree structure which
    can be recursively flattened and unflattened. Otherwise, the field will be considered as PyTree
    metadata.

    Setting ``pytree_node`` in the field factory is equivalent to setting a key ``'pytree_node'`` in
    ``metadata``. The ``pytree_node`` value can be accessed using ``field.metadata['pytree_node']``.
    If ``pytree_node`` is :data:`None`, the value ``metadata.get('pytree_node', True)`` will be
    used.

    .. note::
        If a field is considered a child node, it must be included in the argument list of the
        :meth:`__init__` method, i.e., passes ``init=True`` in the field factory.

    Args:
        pytree_node (bool or None, optional): Whether the field is a PyTree node.
        **kwargs (optional): Optional keyword arguments passed to :func:`attrs.field`.

    Returns:
        The field defined using the provided arguments with ``metadata['pytree_node']`` set.

    .. versionadded:: 0.20.0
    Úpytree_nodeNÚmetadatarC   TzN`pytree_node=True` is not allowed for non-init fields. Please explicitly set `ú'.field(init=False, pytree_node=False)`.r,   )ÚpopÚdictÚgetr&   Ú	TypeErrorrM   Úattrsr   )rT   rV   rW   rC   s       r8   r   r   £   sÇ   € ð6 —*’*˜]¨DÑ1Ô1€KÝ�F—J’J˜z¨4Ñ0Ô0Ð6°BÑ7Ô7€HØÐØ—l’l =Õ2FÑGÔGˆØ)€Hˆ]Ñà�:Š:�f˜dÑ#Ô#€DØð 
�Kð 
ÝðXÝ&.ðXð Xð Xñ
ô 
ð 	
õ
 Œ;Ð3Ð3 Ð3¨FÐ3Ð3Ð3r:   Ú	namespacerE   úCallable[[_TypeT], _TypeT]c                ó   — d S r3   r,   ©r^   rT   s     r8   r    r    Î   ó	   € ð
 "% r:   Úclsc              ó   — d S r3   r,   ©rc   r^   rT   s      r8   r    r    Ö   ó	   € ð ˆSr:   ú_TypeT | Noneú#_TypeT | Callable[[_TypeT], _TypeT]c              óÀ   ‡‡— | €	d
ˆˆfd„}|S t          j        | ¦  «        st          dt          › d| ›d�¦  «        ‚t	          j        | fi ‰¤Ž} t          | ‰¬	¦  «        S )a6  Attrs class decorator with PyTree integration.

    This is a wrapper around :func:`attrs.define` that also registers the class as a pytree node.

    Args:
        cls (type or None, optional): The class to decorate. If :data:`None`, return a decorator.
        namespace (str): The registry namespace used for the PyTree registration.
        **kwargs (optional): Optional keyword arguments passed to :func:`attrs.define`.

    Returns:
        type or callable: The decorated class with PyTree integration or decorator function.

    .. versionadded:: 0.20.0
    Nrc   r)   r/   c                ó"   •— t          | fd‰i‰¤ŽS )Nr^   )r    )rc   rT   r^   s    €€r8   Ú	decoratorzdefine.<locals>.decorator÷   s   ø€ Ý˜#Ð=Ð=¨Ð=°fÐ=Ð=Ð=r:   ú@z-.define() can only be used with classes, not ú.©r^   ©rc   r)   r/   r)   )ÚinspectÚisclassr\   rM   r]   r    r#   )rc   r^   rT   rk   s    `` r8   r    r    à   s–   øø€ ð* €{ð	>ð 	>ð 	>ð 	>ð 	>ð 	>ð 	>ð ÐåŒ?˜3ÑÔð ]ÝÐ[�HÐ[Ð[ÐSVÐ[Ð[Ð[Ñ\Ô\Ð\å
Œ,�sÐ
%Ð
%˜fÐ
%Ð
%€CÝ˜¨	Ð2Ñ2Ô2Ð2r:   c                ó   — d S r3   r,   ra   s     r8   r!   r!     rb   r:   c              ó   — d S r3   r,   re   s      r8   r!   r!     rf   r:   c              óx   — |                      dd¦  «         |                      dd¦  «         t          | fd|i|¤ŽS )a)  Frozen attrs class decorator with PyTree integration.

    This is a convenience wrapper around :func:`define` with ``frozen=True``.

    Args:
        cls (type or None, optional): The class to decorate. If :data:`None`, return a decorator.
        namespace (str): The registry namespace used for the PyTree registration.
        **kwargs (optional): Optional keyword arguments passed to :func:`attrs.define`.

    Returns:
        type or callable: The decorated class with PyTree integration or decorator function.

    .. versionadded:: 0.20.0
    r!   TÚ
on_setattrNr^   )Ú
setdefaultr    re   s      r8   r!   r!     sK   € ð* ×Ò�h Ñ%Ô%Ð%Ø
×Ò�l DÑ)Ô)Ð)Ý�#Ð5Ð5 Ð5¨fÐ5Ð5Ð5r:   r4   r]   r=   c              ó@   — t          | |fi |¤Ž}t          ||¬¦  «        S )a^  Create a new attrs class and register it as a pytree node.

    This is a wrapper around :func:`attrs.make_class` that also registers the class as a pytree
    node.

    Args:
        name (str): The name for the new class.
        attrs: A list of names or a dictionary of mappings of names to :func:`attrs.field` calls.
        namespace (str): The registry namespace used for the PyTree registration.
        **kwargs (optional): Optional keyword arguments passed to :func:`attrs.make_class`.

    Returns:
        type: A new attrs class registered as a pytree node.

    .. versionadded:: 0.20.0
    rn   )Ú_attrs_make_classr#   )r4   r]   r^   rT   rc   s        r8   r   r   3  s.   € õ0 ˜D %Ð
2Ð
2¨6Ð
2Ð
2€CÝ˜¨	Ð2Ñ2Ô2Ð2r:   rn   ú
str | Nonec              ó   — d S r3   r,   ©rc   r^   s     r8   r#   r#   O  s	   € ð "% r:   c              ó   — d S r3   r,   r{   s     r8   r#   r#   X  s	   € ð ˆSr:   ú_TypeT | str | Nonec              óð  ‡ ‡‡‡‡— ddl m} ‰ |u st          ‰ t          ¦  «        r+‰�t	          d¦  «        ‚‰ dk    rt	          d¦  «        ‚d‰ cŠ Š‰€t	          d¦  «        ‚‰ €d*ˆfd„}|S t          j        ‰ ¦  «        st          d‰ ›d�¦  «        ‚t          j	        ‰ ¦  «        st          ‰ ›d�¦  «        ‚t          ‰ j        v rt          d‰ j        › d�¦  «        ‚‰|ur(t          ‰t          ¦  «        st          d‰›d�¦  «        ‚‰dk    r|Št          t          ‰ dd¦  «        dd¦  «        s-t          j        d‰ j        ›dt          › d�t           d¬¦  «         i }i Št          j        ‰ ¦  «        D ]e}|j                             dt(          ¦  «        r2|j        s t          d|j        ›dt          › d�¦  «        ‚|||j        <   ŒT|j        r
|‰|j        <   Œft/          |¦  «        Št/          d„ |                     ¦   «         D ¦   «         ¦  «        Št3          |¦  «        }t3          ‰¦  «        }t5          ‰ t          ||f¦  «         d+ˆˆfd"„}d,ˆˆ fd'„}	dd(l m}
  |
‰ ||	t8          ‰¬)¦  «         ‰ S )-a3  Register an existing attrs class as a pytree node.

    This function takes an existing :func:`attrs.define`-decorated class and registers it as a
    pytree node. It can be used as a direct function call or as a decorator.

    Fields with ``metadata['pytree_node']`` set to :data:`True` (or not set, defaulting to
    :data:`True`) are treated as children, while init fields with ``metadata['pytree_node']`` set
    to :data:`False` are treated as metadata.

    Usage::

        # Direct function call
        register_node(Point, namespace='my-namespace')

        # As a decorator
        @register_node(namespace='my-namespace')
        @attrs.define
        class Point:
            x: float
            y: float

    Args:
        cls (type, optional): An existing attrs-decorated class. If :data:`None`, return a
            decorator.
        namespace (str): The registry namespace used for the PyTree registration.

    Returns:
        type or callable: The same class, now registered as a pytree node, or a decorator function.

    .. versionadded:: 0.20.0
    r   )Ú__GLOBAL_NAMESPACENz?Cannot specify `namespace` when the first argument is a string.Ú z(The namespace cannot be an empty string.z<Must specify `namespace` when the first argument is a class.rc   r)   r/   c               ó&   •— t          | ‰¬¦  «        S )Nrn   )r#   r{   s    €r8   rk   z register_node.<locals>.decorator•  s   ø€ Ý  °	Ð:Ñ:Ô:Ð:r:   zExpected a class, got rm   z! is not an attrs-decorated class.zCannot register z! as a pytree node more than once.z$The namespace must be a string, got Ú__attrs_props__Ú
added_initTzAttrs class zn does not use an attrs-generated `__init__` (for example, `init=False`). `tree_unflatten()` may fail because `z>.register_node()` reconstructs instances with `cls(**kwargs)`.é   )Ú
stacklevelrV   zPyTree node field z> must be included in `__init__()`. Or you can explicitly set `rX   c              3  ó$   K  — | ]}|j         V — Œd S r3   )Úaliasr5   s     r8   r9   z register_node.<locals>.<genexpr>¾  s$   è è € ÐGÐG¨˜QœWÐGÐGÐGÐGÐGÐGr:   Úobjr'   úCtuple[tuple[_U, ...], tuple[tuple[str, Any], ...], tuple[str, ...]]c               ó    •‡ — t          ˆ fd„‰D ¦   «         ¦  «        }t          ˆ fd„‰                     ¦   «         D ¦   «         ¦  «        }||‰fS )Nc              3  ó8   •K  — | ]}t          ‰|¦  «        V — Œd S r3   )Úgetattr)r6   r4   rˆ   s     €r8   r9   z6register_node.<locals>.flatten_func.<locals>.<genexpr>Ë  s-   øè è € ÐMÐM°�  dÑ+Ô+ÐMÐMÐMÐMÐMÐMr:   c              3  óP   •K  — | ] }|j         t          ‰|j        ¦  «        fV — Œ!d S r3   )r‡   rŒ   r4   )r6   r7   rˆ   s     €r8   r9   z6register_node.<locals>.flatten_func.<locals>.<genexpr>Ì  s6   øè è € Ð[Ð[¸Q˜!œ'¥7¨3°´Ñ#7Ô#7Ð8Ð[Ð[Ð[Ð[Ð[Ð[r:   )r<   Úvalues)rˆ   ÚchildrenrW   Úchildren_field_namesÚmetadata_fieldss   `  €€r8   Úflatten_funcz#register_node.<locals>.flatten_funcÃ  se   øø€ õ ÐMÐMÐMÐMÐ8LÐMÑMÔMÑMÔMˆÝÐ[Ð[Ð[Ð[À/×BXÒBXÑBZÔBZÐ[Ñ[Ô[Ñ[Ô[ˆØ˜Ð#7Ð7Ð7r:   rW   útuple[tuple[str, Any], ...]r�   útuple[_U, ...]c               óx   •— t          t          ‰|¦  «        ¦  «        }|                     | ¦  «          ‰di |¤ŽS )Nr,   )rZ   ÚzipÚupdate)rW   r�   rT   Úchildren_aliasesrc   s      €€r8   Úunflatten_funcz%register_node.<locals>.unflatten_funcÐ  s?   ø€ Ý•cÐ*¨HÑ5Ô5Ñ6Ô6ˆØ�Š�hÑÔÐØˆsˆ}ˆ}�Vˆ}ˆ}Ðr:   )Úregister_pytree_node)Úpath_entry_typer^   ro   )rˆ   r'   r/   r‰   )rW   r“   r�   r”   r/   r'   )Úoptree.registryr   rG   rE   Ú
ValueErrorrp   rq   r\   r]   r   Ú_FIELDSÚ__dict__rM   rŒ   ÚwarningsÚwarnÚUserWarningr   rW   r[   r&   rC   r4   r<   rŽ   r   Úsetattrrš   r   )rc   r^   ÚGLOBAL_NAMESPACErk   Úchildren_fieldsr7   Úchildren_fields_proxyÚmetadata_fields_proxyr’   r™   rš   r˜   r�   r‘   s   ``         @@@r8   r#   r#   a  sŠ  øøøøø€ ðL GÐFÐFÐFÐFÐFà
ÐÐÐ¥*¨Sµ#Ñ"6Ô"6ÐØÐ ÝÐ^Ñ_Ô_Ð_Ø�"Š9ˆ9ÝÐGÑHÔHÐHØ˜sˆˆˆYàÐÝÐWÑXÔXÐXà
€{ð	;ð 	;ð 	;ð 	;ð 	;ð 	;ð ÐåŒ?˜3ÑÔð ;ÝÐ9°Ð9Ð9Ð9Ñ:Ô:Ð:ÝŒ9�S‰>Œ>ð EÝ˜3ÐCÐCÐCÑDÔDÐDÝ�#”,ÐÐÝØN˜sœ|ÐNÐNÐNñ
ô 
ð 	
ð Ð(Ð(Ð(µ¸IÅsÑ1KÔ1KÐ(ÝÐM¸yÐMÐMÐMÑNÔNÐNØ�B‚€Ø$ˆ	Ý•7˜3Ð 1°4Ñ8Ô8¸,ÈÑMÔMð 
ÝŒðY˜3œ<ð Yð Yõ ðYð Yð Yõ Øð	
ñ 	
ô 	
ð 	
ð €OØ€OÝŒ\˜#ÑÔð 	(ð 	(ˆØŒ:�>Š>˜-Õ)=Ñ>Ô>ð 	(Ø”6ð Ýðd¨¬ð dð dÝ2:ðdð dð dñô ð ð '(ˆO˜AœFÑ#Ð#ØŒVð 	(Ø&'ˆO˜AœFÑ#øå  Ñ1Ô1ÐÝÐGÐG¨o×.DÒ.DÑ.FÔ.FÐGÑGÔGÑGÔGÐÝ,¨_Ñ=Ô=ÐÝ,¨_Ñ=Ô=ÐÝˆC•Ð0Ð2GÐHÑIÔIÐIð
8ð 
8ð 
8ð 
8ð 
8ð 
8ð 
8ðð ð ð ð ð ð ð
 5Ð4Ð4Ð4Ð4Ð4àÐØØØÝ"Øðñ ô ð ð €Jr:   )rT   r   r/   r   )r^   rE   rT   r   r/   r_   )rc   r)   r^   rE   rT   r   r/   r)   r3   )rc   rg   r^   rE   rT   r   r/   rh   )
r4   rE   r]   r   r^   rE   rT   r   r/   r=   )rc   ry   r^   ry   r/   r_   )rc   r)   r^   rE   r/   r)   )rc   r}   r^   ry   r/   rh   )2rQ   Ú
__future__r   rp   r    Útypesr   Útypingr   r   r   r   r	   r]   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rx   Úoptree.accessorsr   r   Ú__all__rž   r&   rR   r'   r(   r=   r)   r   r   r    r!   r"   r#   r,   r:   r8   ú<module>r­      s”  ðð"ð "ð "ðN #Ð "Ð "Ð "Ð "Ð "à €€€Ø €€€Ø "Ð "Ð "Ð "Ð "Ð "Ø BÐ BÐ BÐ BÐ BÐ BÐ BÐ BÐ BÐ BÐ BÐ BÐ BÐ Bà €€€ðð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð ð& 2Ð 1Ð 1Ð 1Ð 1Ð 1à )Ð )Ð )Ð )Ð )Ð )ð ð  ØÐÐÐÐÐðð ð €ð< $€Ø!Ð Ð !Ð !Ð !Ñ !ð €WˆT�]„]€Ø€WˆT�]„]€Ø	ˆ� Ð	&Ñ	&Ô	&€ðVð Vð Vð Vð V�ñ Vô Vð VðD(4ð (4ð (4ð (4ðV 
ð%ð %ð %ñ 
„ð%ð 
ðð ð ñ 
„ðð ð 3ð  3ð  3ð  3ð  3ðF 
ð%ð %ð %ñ 
„ð%ð 
ðð ð ñ 
„ðð ð6ð 6ð 6ð 6ð 6ð4 €Ø ð3ð 3ð 3ð 3ð8 
àð%ð !ð	%ð %ð %ð %ð %ñ 
„ð%ð 
ðð ð ñ 
„ðð  $ð}ð !ð	}ð }ð }ð }ð }ð }ð }ð }r:   