
    9jx,              	          d Z ddlmZ ddlmZ ddlmZmZmZm	Z	m
Z
 ddlmZ ddlmZmZmZmZmZ ddlmZ d	d
lmZmZ d	dlmZ erddlmZ dededdfdZ ed      dedeeeeef   fd       Z dede!fdZ"dede!fdZ#dede!fdZ$dede!fdZ%dede!fdZ&dede!fdZ'dedefdZ(	 	 	 	 	 	 d(d Z)	 	 	 	 	 	 d(d!Z*dddedefd"Z+ddded#edefd$Z,dddedefd%Z-dddedefd&Z.y'))a3  
Dynamo implementations of CPython's PyObject_* default slot algorithms.

Analogous to CPython's Objects/object.c, this module holds the general
dispatch machinery that is independent of any specific type.
Per-type hook implementations (bool_impl, richcompare_impl, etc.)
live in their respective VT files.
    )	lru_cache)TYPE_CHECKING)get_type_slotshas_slotPyMappingSlotsPyNumberSlotsPySequenceSlots   )graph_break_hints)handle_observed_exceptionObservedTypeErrorraise_observed_exceptionraise_type_errorunimplemented)istype   )NO_SUCH_SUBOBJVariableTrackerConstantVariable)InstructionTranslatorleftrightreturnzVariableTracker | Nonec                    | |u rt        j                  d      S | j                         }|j                         }|t        u}|t        u}|r0|r.||u rt        j                  d      S t        j                  d      S ||k7  rt        j                  d      S ddlm} ddlm} ddlm	} t        | |||f      rt        j                  d      S 	 | j                         |j                         urt        j                  d      S 	 ddlm}	 t        | |	j                         rCt        ||	j                         r-| j"                  |j"                  urt        j                  d      S y	# t        $ r Y kw xY w)
zTry to determine Python identity (left is right) at trace time.

    Returns ConstantVariable(True/False) if determinable, else None.
    Mirrors the logic in BuiltinVariable's handle_is handler.
    TFr   )ConstDictVariable)ListVariable)SetVariabler
   )	variablesN)r   createget_real_python_backed_valuer   dictsr   listsr   setsr   
isinstancepython_typeNotImplementedError r   r   ExceptionVariableexc_type)
r   r   left_val	right_val
left_knownright_knownr   r   r   r   s
             g/media/conek/DATA/Code/OCR/venv/lib/python3.12/site-packages/torch/_dynamo/variables/object_protocol.pyvt_identity_comparer0   &   sb    u}&&t,,002H224I/J>1Kk 9$ ##D)	
 "((/	
 [ &&u-- )#!$*L+FG&&u--U%6%6%88#**511 9  	tY0015)556MM/&&u--  s   4E# #	E/.E/   )maxsizeobj_typec                     t        |       S )z'Get all type slots for a type (cached).)r   )r3   s    r/   _get_cached_slotsr5   _   s     (##    c                 V    t        |       \  }}}}t        |t        j                        S )z>Check whether obj_type implements __len__ as sequence protocol)r5   r   r	   	SQ_LENGTH)r3   	seq_slots_s      r/   type_implements_sq_lengthr;   e   s(    *84Iq!QI8899r6   c                 V    t        |       \  }}}}t        |t        j                        S )z=Check whether obj_type implements __len__ as mapping protocol)r5   r   r   	MP_LENGTH)r3   r:   	map_slotss      r/   type_implements_mp_lengthr?   k   s(    *84Ay!QI~7788r6   c                 V    t        |       \  }}}}t        |t        j                        S )zRCheck whether obj_type implements the nb_bool slot (i.e. has __bool__ or __len__).)r5   r   r   NB_BOOLr3   r:   number_slotss      r/   type_implements_nb_boolrD   q   s(    -h7Aq,L-"7"788r6   c                 V    t        |       \  }}}}t        |t        j                        S )z2Check whether obj_type implements the nb_int slot.)r5   r   r   NB_INTrB   s      r/   type_implements_nb_intrG   w   s(    -h7Aq,L-"6"677r6   c                 V    t        |       \  }}}}t        |t        j                        S )z4Check whether obj_type implements the nb_index slot.)r5   r   r   NB_INDEXrB   s      r/   type_implements_nb_indexrJ   }   (    -h7Aq,L-"8"899r6   c                 V    t        |       \  }}}}t        |t        j                        S )z4Check whether obj_type implements the nb_float slot.)r5   r   r   NB_FLOATrB   s      r/   type_implements_nb_floatrN      rK   r6   objc                     	 | j                         S # t        $ r% t        d|  ddg t        j                         Y y w xY w)NzUnsupported python_type() callz! does not implement python_type()zhThis VariableTracker does not implement python_type(), which is required for object protocol operations.)gb_typecontextexplanationhints)r&   r'   r   r   
DYNAMO_BUG)rO   s    r/   maybe_get_python_typerV      sR    
   	
4e<=@"--	
	
s    +A A txr   c                     t        |      }t        |      r|j                  |       S t        |      rt	        | |j                          d       t	        | d|j                          d       y )Nz is not a mappingzobject of type z has no len())rV   r?   	mp_lengthr;   r   python_type_namerW   rO   Ts      r/   vt_mapping_sizer]      sf     	c"A #}}R   # 4 4 677HIJR?3+?+?+A*B-PQr6   c                 h    t        |      }t        |      r|j                  |       S t        | |      S )z
    Implements PyObject_Size/PyObject_Length semantics for VariableTracker objects.
    Dispatches to sq_length (sequences) or mp_length (mappings) depending on the VT type.
    )rV   r;   	sq_lengthr]   r[   s      r/   generic_lenr`      s2     	c"A #}}R  2s##r6   c                    ddl m} |j                         r) |j                  t	        |j                                     S t        |      }t        |      r|j                  |       }||S 	 t        | |      }ddl
m} t        ||      r#|j                  | |j                         dkD        S  |j                  |j                         dkD        S # t        $ r t        |        Y nw xY w |j                  d      S )u   Mirrors PyObject_IsTrue.

    https://github.com/python/cpython/blob/c09ccd9c429/Objects/object.c#L2135-L2158

    Resolution order: constants → nb_bool → mp_length/sq_length → truthy.
    r   r   )SymNodeVariabler   T)constantr   is_python_constantr    boolas_python_constantrV   rD   	bool_implr`   tensorrb   r%   as_proxyr   r   )rW   rO   r   r3   resultlengthrb   s          r/   generic_boolrl      s     +
&&&tC,B,B,D'EFF$S)Hx(r"M&R%+fo."))"foo.?!.CDD&&&v'@'@'BQ'FGG &!"%& #""4((s   ,A C -"C C'&C'keyc                 &    |j                  | |      S )u  CPython's PyObject_GetItem — dispatch to the type's mp_subscript/sq_item.

    PyObject_GetItem: https://github.com/python/cpython/blob/62a6e898e01/Objects/abstract.c#L155-L206

    CPython checks three branches in order:
      1. tp_as_mapping->mp_subscript  (L161-166)
      2. tp_as_sequence->sq_item      (L168-181) — only if key passes _PyIndex_Check
      3. PyType_Check(o)              (L183-203) — type[int] → GenericAlias/__class_getitem__

    Branch 1 is the common path (list, tuple, dict, range all have mp_subscript).
    TODO(follow-up): use has_slot(map_slots, PyMappingSlots.MP_SUBSCRIPT) to gate
    Branch 1 and has_slot(seq_slots, PySequenceSlots.SQ_ITEM) to gate Branch 2,
    matching CPython's dispatch order.
    TODO(follow-up): Branch 2 (sq_item) for C extension types that only have
    tp_as_sequence (e.g. deque — Modules/_collectionsmodule.c:1888).
    Branch 3 is handled by TypingVariable.mp_subscript_impl for typing module types
    and by BuiltinVariable for builtin types like list[int].

    Types that work via constant fold fallback (no dedicated mp_subscript_impl):
    TODO(follow-up): str (unicode_subscript, Objects/unicodeobject.c:13809)
    TODO(follow-up): bytes (bytes_subscript, Objects/bytesobject.c)
    )mp_subscript_impl)rW   rO   rm   s      r/   
vt_getitemrp      s    6   S))r6   c                    ddl m} |j                         rGt        |j	                         t
              r) |j                  t        |j	                                     S t        |      }t        |      r|j                  |       S t        |      r|j                  |       S |j                         rSt        |j	                         t        t        t        f      r*	  |j                  t        |j	                                     S t#        | d|j%                          d       y# t        $ r&}t!        t        | t        |      g       Y d}~Id}~ww xY w)u   Mirrors PyNumber_Long (int(x) dispatch).

    https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1520-L1632

    Resolution: nb_int → nb_index → str/bytes/bytearray parsing → TypeError.
    r   r   argsNzLint() argument must be a string, a bytes-like object or a real number, not '')rc   r   rd   r%   rf   intr    rV   rG   nb_int_implrJ   nb_index_implstrbytes	bytearray
ValueErrorr   r   rZ   rW   rO   r   r3   es        r/   generic_intr~      s&    +
 Js/E/E/G$M&&&s3+A+A+C'DEE$S)Hh'r"")  $$ J 3y"9%	D*#**3s/E/E/G+HII 
""%"6"6"8!9	<  	D$Z3q6(CC	Ds   (D# #	E,EEc                    ddl m} |j                         rGt        |j	                         t
              r) |j                  t        |j	                                     S t        |      }t        |      r|j                  |       S t        |      r|j                  |       S |j                         rNt        |j	                         t        t        f      r*	  |j                  t        |j	                                     S t!        | d|j#                          d       y# t        $ r&}t        t        | t        |      g       Y d}~Id}~ww xY w)u   Mirrors PyNumber_Float (float(x) dispatch).

    https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1635-L1692

    Resolution: nb_float → nb_index → str parsing → TypeError.
    r   r   rr   Nz9float() argument must be a string or a real number, not 'rt   )rc   r   rd   r%   rf   floatr    rV   rN   nb_float_implrJ   rw   rx   ry   r{   r   r   rZ   r|   s        r/   generic_floatr     s$    +
 Js/E/E/G$O&&&uS-C-C-E'FGG$S)H)  $$  )  $$ Js/E/E/G#u$V	D*#**51G1G1I+JKK 
$$&'q	*  	D$Z3q6(CC	Ds   (D 	E'EEN)rW   r   rO   r   r   r   )/__doc__	functoolsr   typingr   torch._C._dynamor   r   r   r   r	   r(   r   excr   r   r   r   r   utilsr   baser   r   rc   r   symbolic_convertr   r0   typetupleru   r5   re   r;   r?   rD   rG   rJ   rN   rV   r]   r`   rl   rp   r~   r    r6   r/   <module>r      s        !   1 & 86
66 6r 3$ $sCc/A)B $ $
: : :9 9 99d 9t 98T 8d 8:t : ::t : :
 
4 
RR&7RR$$&7$$), )? ) )@**	* 
* 	*<%+ %/ %o %P$- $O $ $r6   