
    ^j                        U d 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ZddlmZmZmZmZmZmZ ddlmZ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&ddde!de!de'de
f
dZ( ed      de)de*e+e+e+e+f   fd       Z,de)de+de-fdZ.de)de+de-fdZ/ e	e.ej`                         Z1 e	e.ejd                         Z3 e	e.ejh                         Z5 e	e.ejl                         Z7 e	e.ejp                         Z9 e	e.ejt                         Z; e	e.ejx                         Z= e	e.ej|                         Z? e	e/ej                         ZA e	e/ej                         ZC e	e/ej                         ZE e	e/ej                         ZAde)de+de-fd!ZF e	eFej                         ZH e	eFej                         ZJ e	eFej                         ZL e	eFej                         ZN e	eFej                         ZP e	eFej                         ZR e	eFej                         ZT e	eFej                         ZV e	eFej                         ZX e	eFej                         ZZ e	eFej                         Z\ e	eFej                         Z^ e	eFej                         Z` e	eFej                         Zb e	eFej                         Zd e	eFej                         Zf e	eFej                         Zh e	eFej                         Zj e	eFej                         Zl e	eFej                         Zn e	eFej                         Zp e	eFej                         Zr e	eFej                         Zt e	eFej                         Zv e	eFej                         Zx e	eFej                         Zz e	eFej                         Z| e	eFej                         Z~ e	eFej                         Z e	eFej                         Z e	eFej                         Z e	eFej
                         Z e	eFej                         Z e	eFej                         Zde)de-fd"Zde)de-fd#Zde)de-fd$Zde)de-fd%Zde)de-fd&Zde)de-fd'Zde)de-fd(Zd)e!de)fd*Zddd+e!d,e'de!fd-Z	 	 	 	 	 	 dd/Z	 	 	 	 	 	 dd0Zddd)e!de!fd1Z e       Zee+   ed2<   ddd)e!de!fd3Z	 	 	 	 	 	 dd4Zddd)e!d+e!de!fd5Zddd)e!d6e!de!fd7Zddd8e!d9e!d:e!de!f
d;Zddd:e!d+e!d<e!de!f
d=Zddd8e!d9e!de!fd>Zddd:e!d+e!de!fd?Zddd)e!de!fd@Zddd)e!de!fdAZddd)e!dd.fdBZddd)e!de!fdCZddd)e!de!fdDZddd)e!de!fdEZd)e!de-fdFZddd)e!dd.fdGZi dHej                  dIej                  dJej                  dKej                  dLej                  dMej                  dNej                  dOej                  dPej                  dQej                  dRej                  dSej                  dTej                  dUej                  dVej                  dWej                  dXej                  ej                  ej                  ej                  ej                  ej                  ejT                  dYZdZe!de-fd[Zde!de!de-fd\Zddde!de!d]e'de!f
d^Zddde!de!d]e'de'de!fd_Zddde!de!d`e'd]e'de!fdaZddde!de!d`e'd]e'de'de!fdbZddde!de!de!fdcZddde!de!de!fddZdddee!dfe!de!fdgZdddee!dfe!de!fdhZdddie!ddfdjZddde!de!de!fdkZddde!de!de!fdlZ	 ddddme!dne!doe-de!f
dpZdddme!dne!de!fdqZeZdme!dddne!dre'de!f
dsZdme!dddne!dre'de!f
dtZdudvdwdxdydzd{Zee'e'f   ed|<   d}d~dddddZee'e'f   ed<   ddde!de!dre'de!f
dZddde!de!dre'de!f
dZddd)e!de*e+e-f   fdZddd)e!de!fdZ	 	 	 	 	 	 	 	 ddZej                  ej                  j                  ej                  fZe*e)df   ed<   ddde!de!de!fdZddde!de!de*e!e!f   fdZy)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.
    N)	lru_cachepartial)NoReturnTYPE_CHECKING)get_type_slotshas_slotPyMappingSlotsPyNumberSlotsPySequenceSlotsPyTypeSlots   )graph_break_hints	polyfills)handle_observed_exceptionObservedTypeErrorraise_observed_exceptionraise_type_errorunimplemented)istype   )NO_SUCH_SUBOBJVariableTrackerConstantVariable)InstructionTranslatorBase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	} 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)TracebackVariable)SetVariabler   )	variablesN)r   createget_real_python_backed_valuer   dictsr    listsr!   miscr"   setsr#   
isinstancepython_typeNotImplementedError r$   r   ExceptionVariableexc_type)r   r   left_val	right_val
left_knownright_knownr    r!   r"   r#   r$   s              r/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/torch/_dynamo/variables/object_protocol.pyvt_identity_comparer6   .   sm    u}&&t,,002H224I/J>1Kk 9$ ##D)	
 "((/	
 [ &&u-- )#'! ,=NO  &&u--U%6%6%88#**511 9  	tY0015)556MM/&&u--  s   4E* *	E65E6txr   vw	op_symbolc           
      h    t        | d| d|j                          d|j                          d       y )Nz unsupported operand type(s) for z: '' and '')r   python_type_name)r7   r8   r9   r:   s       r5   binop_type_errorr?   j   s=     

*9+S9K9K9M8NgVWVhVhVjUkklm       )maxsizeobj_typec                     t        |       S )z'Get all type slots for a type (cached).)r   rC   s    r5   _get_cached_slotsrF   v   s     (##r@   slotc                 :    t        |       \  }}}}t        ||      S )z4Check whether obj_type implements the given sq slot.rF   r   )rC   rG   	seq_slots_s       r5   type_implements_sq_slotrL   |   s"    *84Iq!QIt$$r@   c                 :    t        |       \  }}}}t        ||      S )z4Check whether obj_type implements the given mp slot.rI   )rC   rG   rK   	map_slotss       r5   type_implements_mp_slotrO      s"    *84Ay!QIt$$r@   )rG   c                 :    t        |       \  }}}}t        ||      S )z.Check whether obj_type implements the nb slot.rI   )rC   rG   rK   number_slotss       r5   type_implements_nb_slotrR      s"    -h7Aq,L$''r@   c                 V    t        |       \  }}}}t        |t        j                        S N)rF   r   r   TP_ITERrC   rK   	type_slots      r5   type_implements_tp_iterrX     s(    *84Aq!YI{2233r@   c                 V    t        |       \  }}}}t        |t        j                        S rT   )rF   r   r   TP_ITERNEXTrV   s      r5   type_implements_tp_iternextr[     s(    *84Aq!YI{6677r@   c                 V    t        |       \  }}}}t        |t        j                        S )z3Check whether obj_type implements the tp_repr slot.)rF   r   r   TP_REPRrV   s      r5   type_implements_tp_reprr^     s(    *84Aq!YI{2233r@   c                 V    t        |       \  }}}}t        |t        j                        S )z2Check whether obj_type implements the tp_str slot.)rF   r   r   TP_STRrV   s      r5   type_implements_tp_strra     s(    *84Aq!YI{1122r@   c                     t        |       S rT   )r[   rE   s    r5   pyiter_checkrc   "  s     'x00r@   c                 :    t        | t              ryt        |       S )zBImplements PySequence_Check semantics for VariableTracker objects.F)
issubclassdicttype_implements_sq_itemrE   s    r5   pysequence_checkrh   )  s     (D!"8,,r@   c                     t        |       S )z@Implements _PyIndex_Check semantics for VariableTracker objects.)type_implements_nb_indexrE   s    r5   pyindex_checkrk   1  s     $H--r@   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)rl   s    r5   maybe_get_python_typert   7  sR    
   	
4e<=@"--	
	
s    +A A keycontainer_namec                     t        |      }|t        t        t        fvrBt	        |      s&t        t        | | d|j                          g       |j                  |       }|S )u   _PyIndex_Check → nb_index path used by list/tuple/range/str/bytes subscript.

    ref: https://github.com/python/cpython/blob/v3.13.3/Include/internal/pycore_abstract.h (_PyIndex_Check)
    z) indices must be integers or slices, not args)	rt   intboolslicerj   r   	TypeErrorr>   nb_index_impl)r7   ru   rv   key_types       r5   validate_sequence_indexr   F  sj     %S)HT5))'1$%&&OPSPdPdPfOgh #Jr@   r   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())rt   type_implements_mp_length	mp_lengthtype_implements_sq_lengthr   r>   r7   rl   Ts      r5   vt_mapping_sizer   ]  sf     	c"A #}}R   # 4 4 677HIJR?3+?+?+A*B-PQr@   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.
    )rt   r   	sq_lengthr   r   s      r5   generic_lenr   k  s2     	c"A #}}R  2s##r@   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                         }|dk  rt        t$        | dg        |j                  |dkD        S # t        $ r+}t        t        |      | t        |      g       Y d}~d}~ww xY w# 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   rx   N)SymNodeVariabler   z__len__() should return >= 0T)constantr   is_python_constantr%   r{   as_python_constant	Exceptionr   typestrrt   type_implements_nb_bool	bool_implr   tensorr   r+   as_proxy
ValueErrorr   r   )	r7   rl   r   erC   resultlengthr   
length_vals	            r5   generic_boolr   z  sB    +
	A*#**40F0F0H+IJJ %S)Hx(r"M&R%+fo."))"foo.?!.CDD..0
>$B&D%E '&&zA~66+  	A$T!WbAx@@	A,  &!"%& #""4((s0   (C+ -A D" .<D" +	D4!DD"D98D9_repr_runningc                 2   t        |      }t        |      rt        |      }|t        v rCt        dt
        dt        j                  di}t        j                  |j                  |d            S t        j                  |       	 |j                  |       }t        j                  |       t        |      }t        |t              st!        | d|j"                   d       |S t!        | d|j%                          d       y# t        j                  |       w xY w)	zMirrors PyObject_Repr with Py_ReprEnter/Py_ReprLeave cycle detection.

    https://github.com/python/cpython/blob/v3.13.3/Objects/object.c#L745-L778

    Resolution order: tp_repr -> TypeError if the result is not str.
    z[...]z{...}z...z#__repr__ returned non-string (type )zobject of type 'z' has no reprN)rt   r^   idr   listrf   collectionsdequer   r%   getadd	repr_impldiscardre   r   r   __name__r>   )r7   rl   rC   obj_idsentinelr   result_types          r5   generic_reprr     s     %S)Hx(C]"gtWk6G6GQH#**8<<%+HII&!	*]]2&F!!&)+F3+s+5k6J6J5K1M R+C,@,@,B+C=QR !!&)s   C? ?Dc                 H   t        |      t        u r|S t        |      }t        |      r7t        |      j                  t
        j                  ur|j	                  |       }nt        | |      }t        |      }t        |t              st        | d|j                   d       |S )zMirrors PyObject_Str semantics in Dynamo.

    https://github.com/python/cpython/blob/v3.13.3/Objects/object.c#L781-L829

    Resolution order: str identity check -> tp_str (str_impl) -> tp_repr fallback.
    z"__str__ returned non-string (type r   )
rt   r   ra   r   str_implr   r   re   r   r   )r7   rl   rC   r   r   s        r5   generic_strr     s     S!S(
$S)Hx(Io&>&>>b!b#&'/Kk3'01E1E0FaH	
 Mr@   c                    t        |      }t        |      r|j                  | |      S t        |      rYt        |      }t	        |      r|j                  |       }t        | ||      S t        | |j                   d|j                          t        |t              r|j                  | |      S t        | d|j                   d       y)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).
    Branch 2 fires for types with only sq_item (e.g. deque).
    Branch 3 delegates to mp_subscript_impl for type objects (__class_getitem__).
    z indices must be integers, not r=   z' object is not subscriptableN)rt   type_implements_mp_subscriptmp_subscript_implrg   rj   r~   vt_sequence_getitemr   r   re   r   )r7   rl   ru   rC   r   s        r5   
vt_getitemr     s    $ %S)H#H-$$R-- x((-#H-##B'C&r344  !!@ARAR@ST	
 (D!$$R--R1X..//LMNr@   indexc                    t        |      }t        |      rt        |t              rg|j	                         }t        |t
              rG|dk  rBt        |      r7|j                  |       }t        j                  ||j	                         z         }|j                  | |      S t        |      rt        | d|j                          d       t        | d|j                          d       y)uM  CPython's PySequence_GetItem — always sq_item, never mp_subscript.

    ref: https://github.com/python/cpython/blob/v3.13.3/Objects/abstract.c#L1874-L1902

    Called by PyObject_GetItem branch 2, reversed() fallback, and the old
    iteration protocol.  Wraps negative indices via sq_length before
    dispatching to sq_item.
    r   r=   ' is not a sequencez"' object does not support indexingN)rt   rg   r+   r   r   rz   r   r   r%   sq_item_implr   r   r>   )r7   rl   r   rC   	index_valr   s         r5   r   r     s     %S)Hx(e-.002I)S)i!m,X6 ]]2.F,33!F$=$=$??E E**#H-q!5!5!7 88KLMR1S11344VWXr@   sioc                    t        |      }t        |      rt        |t              rg|j	                         }t        |t
              rG|dk  rBt        |      r7|j                  |       }t        j                  ||j	                         z         }|j                  | ||      S t        |      rt        | d|j                          d       t        | d|j                          d       y )Nr   r=   r   )' object does not support item assignment)rt   type_implements_sq_ass_itemr+   r   r   rz   r   r   r%   sq_ass_item_impl type_implements_mp_ass_subscriptr   r>   )r7   r   r   r   s_typer   r   s          r5   vt_sequence_setitemr   1  s     #1%F"6*a)*,,.I)S)i!m,V4[[_F(//	F<U<U<W0WXA!!"a++'/q!3!3!5 66IJK
a""$%%NOr@   valuec                 N   t        |      }t        |      r|j                  | ||      S t        |      rSt        |      }t	        |      r|j                  |       }t        | |||      S t        | d|j                          d       t        | d|j                          d       y )Nz%sequence index must be integer, not 'r=   r   )	rt   r   mp_ass_subscript_implr   rk   r~   r   r   r>   )r7   r   ru   r   o_typer   s         r5   generic_setitemr   K  s     #1%F'/&&r366"6*(-"##B'C&r1c59978L8L8N7OqQ	
 
a""$%%NOr@   c                    t        |      }t        |      rat        |t              r>|j	                         }|dk  r)t        |      r|j                  |       }t        | ||      }|j                  | |d       S t        |      rt        | d|j                          d       t        | d|j                          d       y )Nr   r=   r   z'' object does not support item deletion)rt   r   r+   r   r   r   r   vt_addr   r   r   r>   )r7   r   r   r   idxr   s         r5   sequence_delitemr   c  s     #1%F"6*a)*&&(CQw,V4[[_Fr1f-A!!"a..'/q!3!3!5 66IJK
a""$%%LMr@   c                 J   t        |      }t        |      r|j                  | |d       S t        |      }t        |      r|j	                  |       }t        | ||      S t        |      rt        | d|j                                 t        | d|j                          d       y )Nz$sequence index must be integer, not r=   z ' does not support item deletion)	rt   r   r   rk   r~   r   r   r   r>   )r7   r   ru   r   r   	key_values         r5   generic_delitemr   |  s     #1%F'/&&r355$S)HX%%b)	Ay11	$V	,6s7K7K7M6NO	
 R1Q//122RSTr@   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   rx   NzLint() argument must be a string, a bytes-like object or a real number, not 'r=   )r   r   r   r+   r   rz   r%   rt   type_implements_nb_intnb_int_implrj   r~   r   bytes	bytearrayr   r   r   r>   r7   rl   r   rC   r   s        r5   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   rx   Nz9float() argument must be a string or a real number, not 'r=   )r   r   r   r+   r   floatr%   rt   type_implements_nb_floatnb_float_implrj   r~   r   r   r   r   r   r>   r   s        r5   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c                     t        |      }t        |      st        | d|j                          d       |j	                  |       S )a7  
    Implements PyIter_Next / tp_iternext semantics for VariableTracker objects.

    Calls obj.tp_iternext_impl(tx) if the object is an iterator, otherwise raises
    TypeError. StopIteration propagation is left to the caller (mirrors
    CPython's iternext contract where NULL return signals exhaustion).
    zexpected an iterator, got 'r=   )rt   r[   r   r>   tp_iternext_implr   s      r5   generic_iternextr     sF     	c"A&q):3;O;O;Q:RRSTU##r@   c                     t        |      }t        |      r|j                  |       S t        | d|j	                          d       y)zMirrors PyNumber_Negative.

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

    Algorithm:
    1. If type has nb_negative slot, call obj.nb_negative_impl(tx)
    2. Otherwise, raise TypeError
    zbad operand type for unary -: 'r=   N)rt   type_implements_nb_negativenb_negative_implr   r>   r7   rl   rC   s      r5   generic_negr     H     %S)H"8,##B''

)#*>*>*@)ACr@   c                     t        |      }t        |      r|j                  |       S t        | d|j	                          d       y)zMirrors PyNumber_Positive.

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

    Algorithm:
    1. If type has nb_positive slot, call obj.nb_positive_impl(tx)
    2. Otherwise, raise TypeError
    zbad operand type for unary +: 'r=   N)rt   type_implements_nb_positivenb_positive_implr   r>   r   s      r5   generic_posr     r   r@   c                     t        |      }t        |      r|j                  |       S t        | d|j	                          d       y)zMirrors PyNumber_Absolute.

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

    Algorithm:
    1. If type has nb_absolute slot, call obj.nb_absolute_impl(tx)
    2. Otherwise, raise TypeError
    zbad operand type for abs(): 'r=   N)rt   type_implements_nb_absolutenb_absolute_implr   r>   r   s      r5   generic_absr   %  sH     %S)H"8,##B''

'(<(<(>'?qAr@   c                 H    t        |       }t        |      xs t        |      S )zOCheck if the object supports iteration (i.e. has tp_iter or sequence protocol).)rt   rX   rh   )rl   r   s     r5   vt_is_iterabler   ;  s"    c"A"1%<)9!)<<r@   c                    t        |      }t        |      rG|j                  |       }t        |      }t        |      st	        | d|j                          d       |S t        |      r8ddlm}  |t        j                  j                        j                  | |gi       S t	        | d|j                          d       y)z
    Implements PyObject_GetIter semantics for VariableTracker objects.
    Routes to obj.tp_iter_impl(tx), the tp_iter slot on the object's type.
    z&iter() returned non-iterator of type 'r=   r   )UserFunctionVariablez' object is not iterableN)rt   rX   tp_iter_implrc   r   r>   rh   	functionsr   r   builtinssequence_iteratorcall_function)r7   rl   r   resres_Tr   s         r5   generic_getiterr   A  s      	c"Aq!r"%c*E"89M9M9O8PPQR 
	!	3#I$6$6$H$HIWWr
 	
 	q!5!5!7 88PQRr@   	nb_lshiftnb_inplace_lshiftnb_inplace_rshift	nb_rshiftnb_ornb_inplace_ornb_subtractnb_inplace_subtractnb_addnb_inplace_addnb_multiplynb_inplace_multiplynb_andnb_inplace_andnb_xornb_inplace_xornb_floor_divide)nb_inplace_floor_dividenb_true_dividenb_inplace_true_dividenb_remaindernb_inplace_remainder	nb_divmodr   c                 ,    | j                  t              S rT   )is_constant_matchNotImplemented)r   s    r5   is_nb_not_implementedr    s    ##N33r@   c                 r    	 t        | j                         |j                               S # t        $ r Y yw xY w)z?Check if w's underlying Python type is a proper subtype of v's.F)re   r,   r-   )r9   r8   s     r5   is_python_subtyper    s2    !--/1==?;; s   '* 	66op_slotc                    | d}t         |   }t        |      }t        |      }t        ||      rt        t	        |      |d      nd}t        ||      rt        t	        |      |d      nd}	||	u rd}	|@|	&t        ||      r |	|| |d      }
t        |
      s|
S d}	 ||| |d      }
t        |
      s|
S |	 |	|| |d      }
t        |
      s|
S t        j                  t              S )u/  CPython's binary_op1: try v's slot, then w's slot with subclass priority.

    Each VT that participates provides a ``<op_slot>_impl(self, tx, other,
    reverse)`` method. ``reverse=False`` means "self is left operand" (forward,
    e.g. ``__or__``), ``reverse=True`` means "self is right operand" (reverse,
    e.g. ``__ror__``). For built-in types the flag is ignored because their
    slots check both operands symmetrically.

    CPython splits the check into two steps: ``Py_TYPE(v)->tp_as_number !=
    NULL`` (does the type have a number-protocol struct), then read the
    slot pointer (which may itself be NULL).  We collapse both into a
    single :func:`type_implements_nb_slot` query — its bit is set only
    when the specific slot is non-NULL, which already implies
    ``tp_as_number`` is non-NULL.  Treating a missing slot as "no impl"
    is what keeps the base ``VariableTracker.nb_*_impl`` graph-break
    out of the path for types that genuinely lack the slot in C.

    https://github.com/python/cpython/blob/3.13/Objects/abstract.c#L926-L977
    _implNTF)
NB_SLOT_MAPPINGrt   rR   getattrr   r  r  r   r%   r  )r7   r8   r9   r  	impl_attrnb_slot_bitv_typew_typev_slotw_slotr   s              r5   
binary_op1r!    s   2 )5!I!'*K"1%F"1%F #6;7 	QD)  #6;7 	QD)   "3Aq"9 Ar1d+F(0F2q%($V,M2q$'$V,M"">22r@   c                 T    t        | |||      }t        |      rt        | |||       |S )zCPython's binary_op: binary_op1 + TypeError fallback.
    https://github.com/python/cpython/blob/3.13/Objects/abstract.c#L997-L1020
    )r!  r  r?   )r7   r8   r9   r  r:   r   s         r5   	binary_opr#    s/     Aq'*FV$Q9-Mr@   iop_slotc                     t        |      }t        |t        |         r1| d}t        t	        |      |      } ||| |      }t        |      s|S t        | |||      S )Nr  )rt   rR   r  r  r   r  r!  )	r7   r8   r9   r$  r  r  r  rG   r   s	            r5   binary_iop1r&    sd     #1%Fvx'@Aj&	tAw	*aQ$V,Mb!Q((r@   c                 V    t        | ||||      }t        |      rt        | |||       |S )zCPython's binary_iop: try inplace slot, fallback to binary_op1.

    Combines binary_iop1 + TypeError fallback from binary_iop.
    https://github.com/python/cpython/blob/3.13/Objects/abstract.c#L1229-L1270 (binary_iop1, binary_iop)
    )r&  r  r?   )r7   r8   r9   r$  r  r:   r   s          r5   
binary_iopr(    s1     Q8W5FV$Q9-Mr@   c                     t        | ||d      }t        |      s|S t        |      }t        |      r|j	                  | |      S t        | ||d       y)zHImplements addition via nb_add / nb_inplace_add with binary_op dispatch.r  +N)r!  r  rt   type_implements_sq_concatsq_concat_implr?   )r7   r8   r9   r   r   s        r5   r   r   *  sT     Aq(+F (a A #A&&RAs#r@   c                     t        | ||dd      }t        |      rSt        |      }t        |      r|j	                  | |      S t        |      r|j                  | |      S t        | ||d       |S )zIImplements in-place addition via nb_inplace_add with binary_iop dispatch.r  r  z+=)r&  r  rt   !type_implements_sq_inplace_concatsq_inplace_concat_implr+  r,  r?   )r7   r8   r9   r   rC   s        r5   vt_inplace_addr0  ;  sr     Q#3X>FV$(+,X6++B22&x0##B**RAt,Mr@   seqnc                     t        |      }t        |      st        | d|j                          d       |j	                  |       }t        | |       |j                  | |      S )zMirrors CPython's sequence_repeat helper.

    Validates that ``n`` is index-like, converts it to an int, and dispatches
    to ``seq.sq_repeat_impl(tx, count)``.

    https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1156-L1174
    ,can't multiply sequence by non-int of type 'r=   )rt   rj   r   r>   r~   validate_sequence_repeat_countsq_repeat_implr7   r1  r2  n_typecounts        r5   sequence_repeatr:  Z  se     #1%F#F+:1;M;M;O:PPQR	
 OOBE"2u-b%((r@   c                     t        |      }t        |      st        | d|j                          d       |j	                  |       }t        | |       |j                  | |      S )zsequence_repeat using sq_inplace_repeat.

    The validation step is identical to ``sequence_repeat``; only the
    target slot differs.
    r4  r=   )rt   rj   r   r>   r~   r5  sq_inplace_repeat_implr7  s        r5   sequence_inplace_repeatr=  q  se     #1%F#F+:1;M;M;O:PPQR	
 OOBE"2u-%%b%00r@   r9  c                     |j                         }|t        j                   dz
  k  s|t        j                  kD  rt        t        | dg       y y )Nr   z,cannot fit 'int' into an index-sized integerrx   )r   sysrB   r   OverflowError)r7   r9  r2  s      r5   r5  r5    sH     	  "ACKK<!q3;; @A	
  /r@   c                 $   t        | ||d      }t        |      s|S t        |      }t        |      }t        |      rt	        | ||      S t        |      rt	        | ||      S t        | d|j                          d|j                          d       y)zMirrors CPython's PyNumber_Multiply.

    Try nb_multiply via binary_op1; on NotImplemented fall back to sq_repeat
    on either operand.  TypeError if no path works.

    https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1176-L1193
    r  $unsupported operand type(s) for *: 'r<   r=   N)r!  r  rt   type_implements_sq_repeatr:  r   r>   r7   r8   r9   r   r  r  s         r5   generic_multiplyrE    s     Aq-0F ("1%F"1%F (r1a(( (r1a((
 !););)=(>a	Ar@   c                 V   t        | ||dd      }t        |      s|S t        |      }t        |      }t        |      rt	        | ||      S t        |      rt        | ||      S t        |      rt        | ||      S t        | d|j                          d|j                          d       y)a  Mirrors CPython's PyNumber_InPlaceMultiply.

    Try nb_inplace_multiply / nb_multiply via binary_iop1; on NotImplemented
    fall back to sq_inplace_repeat (preferred), then sq_repeat.

    https://github.com/python/cpython/blob/v3.13.0/Objects/abstract.c#L1330-L1357
    r  r  z%unsupported operand type(s) for *=: 'r<   r=   N)	r&  r  rt   !type_implements_sq_inplace_repeatr=  rC  r:  r   r>   rD  s         r5   generic_inplace_multiplyrH    s     Q#8-HF ("1%F"1%F(0&r1a00 (r1a(( !(r1a((
 !););)=(>a	Ar@   selfotherreversec                    t        |      }t        |t        j                        r|j	                  | ||      S t        |      rt        | ||      S t        | d|j                          d|j                          d       y)z@``self.__mul__(other)`` / ``self.__rmul__(other)`` slot wrapper.)rK  rB  r<   r=   N)	rt   rR   r
   NB_MULTIPLYnb_multiply_implrC  r:  r   r>   )r7   rI  rJ  rK  	self_types        r5   slot_wrapper_mulrP    s     &d+Iy-*C*CD$$R$@@ + r4//
!!#$GE,B,B,D+EQ	Hr@   c                     t        |      }t        |t        j                        r|j	                  | |      S t        |      rt        | ||      S t        | ||      S )u  ``self.__imul__(other)`` slot wrapper.

    When neither ``nb_inplace_multiply`` nor ``sq_inplace_repeat`` is
    installed, the slotdef machinery doesn't generate ``__imul__`` at all
    — but the operator-level fallback in ``slot_nb_inplace_multiply``
    (typeobject.c) does try the non-inplace slot.  We mirror that here so
    method lookups don't graph-break on (e.g.) tuple, even though tuple
    has no ``__imul__`` attribute in standard CPython.
    )rt   rR   r
   NB_INPLACE_MULTIPLYnb_inplace_multiply_implrG  r=  rP  )r7   rI  rJ  rO  s       r5   slot_wrapper_imulrT    sW     &d+Iy-*K*KL,,R77(3&r477Be,,r@   opc                 h   |dk(  rLt        | |      }|%|j                         rt        j                  d      S t        j                  t              S |dk(  rD| j                  ||d      }t        |      r|S t        j                  |j                                S t        j                  t              S )a   object's tp_richcompare.

    https://github.com/python/cpython/blob/e76aa128fe/Objects/typeobject.c#L6263-L6305
    - __eq__: identity check, else NotImplemented
    - __ne__: delegates to tp_richcompare(self, other, Py_EQ) and inverts
    - ordering
    __eq__T__ne__)r6   r   r   r%   r  richcompare_implis_richcompare_not_implemented)rI  r7   rJ  rU  identity	eq_results         r5   object_richcomparer]  Z  s     
X~&tU3H$?$?$A#**400&&~66	x ))"eX>	))4&&9+G+G+I'IJJ&&~66r@   c                    | j                         r|j                         st        j                  t              S | j	                         }|j	                         }	  t        t        |      |      ||      }t        j                        S # t        $ r/}t        t        |t        |j                               Y d}~Hd}~ww xY w)z=Constant-fold comparison for types with as_python_constant().rx   N)r   r   r%   r  r   r  r   r}   r   r   ry   )rI  r7   rJ  rU  self_val	other_valr   r   s           r5    python_constant_richcompare_implra  x  s     ""$E,D,D,F&&~66&&(H((*IC,h,XyA ""6**  C BT!&&\BBCs   B 	C%B??C__gt____lt____ge____le__rW  rX  )rc  rb  re  rd  rW  rX  _REFLECTED_OP<z<=z==z!=>z>=)rc  re  rW  rX  rb  rd  _OP_STRc           
         t         |   }	 |j                         }	 |j                         }d}|4|2||ur.t        ||      r"d}|j	                  | ||      }t        |      s|S |j	                  | ||      }t        |      s|S |s |j	                  | ||      }t        |      s|S |dv rct        ||      }	|	+|dk(  r$t        j                  |	j                                S |	S t        dd| d| d| d	d
g t        j                         yt        | dt        |    d|j                          d|j                          d       y# t        $ r d}Y :w xY w# t        $ r d}Y ;w xY w)au  Dynamo's do_richcompare.

    https://github.com/python/cpython/blob/e76aa128fe/Objects/object.c#L994-L1039

    Implements the 4-step algorithm directly using richcompare_impl slots.
    Graph breaks inside user comparison methods propagate to COMPARE_OP
    (which runs eagerly) because UDOV.richcompare_impl disables nested
    graph breaks on the resolved funcvar.
    NFTrW  rX  rX  z*richcompare identity fallback undeterminedzgeneric_richcompare(, r   z9Cannot determine object identity for comparison fallback.rn   r=   z&' not supported between instances of 'r<   )rf  r,   r-   re   rY  rZ  r6   r   r%   r   r   r   SUPPORTABLEr   ri  r>   )
r7   r8   r9   rU  	reflectedr  r  checked_reverser   r[  s
             r5   generic_richcomparerp    s    b!I O 	& vv&##B95-f5M Ar*F)&1 ##B95-f5M 
!!&q!,X~'..83N3N3P/PQQO@*1#Rs"RD:S2%112		
 	} ""$%WQ-?-?-A,B!E	
]    s"   E E EEE('E(c                     |dvrt        d|       t        ||      }|(|j                         rt        j                  |dk(        S t        | |||      S )a  Dynamo's PyObject_RichCompareBool for eq/ne.

    https://github.com/python/cpython/blob/e76aa128fe/Objects/object.c#L1046-L1080

    Like generic_richcompare, but with an identity shortcut first: if v
    and w are the same Python object, eq is True and ne is False. This
    matters for NaN (nan is nan -> True, but nan == nan -> False). Used by
    container comparisons (list_richcompare, tuplerichcompare) which call
    PyObject_RichCompareBool per element in CPython.
    rk  z2generic_richcompare_bool only supports eq/ne, got rW  )AssertionErrorr6   r   r   r%   rp  )r7   r8   r9   rU  r[  s        r5   generic_richcompare_boolrs    se      
%%QRTQUVWW"1a(H ; ; =&&rX~66r1a,,r@   c                 $    |j                  |       S )zInternal API: compute hash as (value, is_fake).

    Dispatches to the VT's hash_impl.  Called by generic_hash (which wraps
    the result in a VT), container hash_impls (which propagate is_fake),
    and HashableTracker (which just needs the int).
    )	hash_impl)r7   rl   s     r5   generic_hash_implrv    s     ==r@   c                     ddl m}m}m} t	        | |      \  }}|r |||j
                        S  |j                  |      S )a$  User-facing API: mirrors PyObject_Hash, returns a VariableTracker.

    https://github.com/python/cpython/blob/e76aa128fe/Objects/object.c#L1101-L1115

    Wraps the result in ConstantVariable or FakeIdVariable depending on
    whether the hash depends on a sourceless object's identity.
    r   )r   FakeIdVariableFakeValueKind)kind)r   r   rx  ry  rv  HASHr%   )r7   rl   r   rx  ry  his_fakes          r5   generic_hashr~  
  sE     JI"2s+JAwam&8&899"""1%%r@   c                     t        |      }t        |      r|j                  | |      S t        | |      }t	        j
                  | t        j                        j                  | ||gi       S )z
    Implements PySequence_Contains semantics for VariableTracker objects.

    If the object has sq_contains (i.e., __contains__), calls obj.sq_contains(tx, item).
    Otherwise falls back to iterating over obj and comparing each element.
    )	rt   type_implements_sq_containssq_containsr   r   buildr   impl_CONTAINS_OP_fallbackr   )r7   rl   itemr   its        r5   generic_containsr    se     	c"A"1%r4(( R%$$	33

-T2J
+	,r@   .(_CONSTANT_FOLD_SUBCLASSCHECK_METACLASSESderivedclsc                    |j                         }|j                         }|t        u s|t        u r7t        dd| d| dddgt        j                  t        j
                         t        |      }|t        u r 	 t        j                  t        ||            S t        j                   h}t"        j$                  d
k  r|j'                  t(        j*                         ||v r+t)        j,                  |      }t/        j0                  | |      }ddlm}	 t7        ||	      rg|j8                  D ]C  }
t;        | ||
      }t7        |t              s!|j<                  s.t        j                  d      c S  t        j                  d      S t7        |t              r9t        t        |      t>              r 	 t        j                  t        ||            S t7        |t              stA        | d       |jC                  | d|gi       }tE        | |      S # t        $ r0}t        t        | t        |j                               Y d	}~d	}~ww xY w# t        $ r/}t        t        | t        |j                               Y d	}~d	}~ww xY w)zMirrors CPython's PyObject_IsSubclass / object_issubclass.

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

    This only attempts to replicate object_issubclass, otherwise we delegate to cpython
    z'issubclass() with unsupported argumentszissubclass(rl  r   z:Arguments to issubclass() must be backed by python values.z#Make sure your arguments are types.rn   rx   N)      r   )TupleVariableTFzBissubclass() arg 2 must be a class, a tuple of classes, or a union__subclasscheck__)#r&   r   r   r   
USER_ERRORrm  rt   r   r   r%   re   r}   r   r   ry   types	UnionTyper?  version_infor   typing_UnionGenericAliasget_argsr   r  r(   r  r+   itemsgeneric_issubclassr   r  r   call_methodr   )r7   r  r  
derived_pycls_pycls_typer   union_typesry   r  r  rr   s                r5   r  r  <  sO    557J--/F^#v'?=!'"SE3T5"-- #..			
 %S)H 4	G#**  ??#K
'!%%	
 ;v&##B- %#}%II 	5D"2w5A!-.177'..t44	5  &&u-- &$JV>%	G#**  fd#P	
 __R!4wiDF F##y  	G$YaffFF	GP  	G$YaffFF	Gs0   <H 0I 	I%I  I	J %I;;J iter_null_or_idxc                     ddl m} t        ||      s#t        |      t        u r|j                  | |      S t        | |      }| |       fS )ab  
    Mirrors _PyForIter_VirtualIteratorNext.

    When ``null_or_idx`` is a tagged int (3.15+ virtual-iter path), dispatch
    to the iterable's ``_tp_iteritem`` slot via ``tp_iteritem_impl`` and
    return ``(value, next_index)``.  Otherwise fall back to the standard
    iterator protocol (``tp_iternext``) and return ``(value, NULL)``.

    Iterator exhaustion is signaled by ``ObservedUserStopIteration``
    propagating out of the slot impl, matching the rest of Dynamo's
    iterator protocol.

    https://github.com/python/cpython/blob/f31a89bb901067dd105b00cfa90523cf7ffdbbdd/Python/ceval.c#L3733
    r   )NullVariable)r)   r  r+   rt   rz   tp_iteritem_implr   )r7   r  r  r  next_s        r5   virtual_iterator_nextr    sL    & # {L1!+.#5%%b+66R'E,.  r@   )r7   r   rl   r   r   r   )F)r7   r   rl   r   r  r   r   r   )__doc__abcr   enumr?  r  r  	functoolsr   r   r   r   torchtorch._C._dynamor   r   r	   r
   r   r   r.   r   r   excr   r   r   r   r   utilsr   baser   r   r   r   symbolic_convertr   r6   r   r?   r   tuplerz   rF   r{   rL   rO   SQ_ITEMrg   	SQ_LENGTHr   	SQ_CONCATr+  SQ_INPLACE_CONCATr.  SQ_CONTAINSr  SQ_ASS_ITEMr   	SQ_REPEATrC  SQ_INPLACE_REPEATrG  	MP_LENGTHr   MP_SUBSCRIPTr   MP_ASS_SUBSCRIPTr   rR   NB_ADDtype_implements_nb_addNB_SUBTRACTtype_implements_nb_subtractrM  type_implements_nb_multiplyNB_REMAINDERtype_implements_nb_remainderNB_POWERtype_implements_nb_powerNB_NEGATIVEr   NB_POSITIVEr   NB_ABSOLUTEr   NB_BOOLr   	NB_INVERTtype_implements_nb_invert	NB_LSHIFTtype_implements_nb_lshift	NB_RSHIFTtype_implements_nb_rshiftNB_ANDtype_implements_nb_andNB_XORtype_implements_nb_xorNB_ORtype_implements_nb_orNB_INTr   NB_FLOATr   NB_INPLACE_ADDtype_implements_nb_inplace_addNB_INPLACE_SUBTRACT#type_implements_nb_inplace_subtractrR  #type_implements_nb_inplace_multiplyNB_INPLACE_REMAINDER$type_implements_nb_inplace_remainderNB_INPLACE_POWER type_implements_nb_inplace_powerNB_INPLACE_LSHIFT!type_implements_nb_inplace_lshiftNB_INPLACE_RSHIFT!type_implements_nb_inplace_rshiftNB_INPLACE_ANDtype_implements_nb_inplace_andNB_INPLACE_XORtype_implements_nb_inplace_xorNB_INPLACE_ORtype_implements_nb_inplace_orNB_FLOOR_DIVIDEtype_implements_nb_floor_divideNB_TRUE_DIVIDEtype_implements_nb_true_divideNB_INPLACE_FLOOR_DIVIDE'type_implements_nb_inplace_floor_divideNB_INPLACE_TRUE_DIVIDE&type_implements_nb_inplace_true_divideNB_INDEXrj   NB_MATRIX_MULTIPLY"type_implements_nb_matrix_multiplyNB_INPLACE_MATRIX_MULTIPLY*type_implements_nb_inplace_matrix_multiplyrX   r[   r^   ra   rc   rh   rk   rt   r   r   r   r   setr   __annotations__r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   	NB_DIVMODr  r  r  r!  r#  r&  r(  r   r0  r:  r=  r5  rE  rH  rP  rT  rZ  r]  ra  rf  rf   ri  rp  rs  rv  r~  r  ABCMeta_C_TensorMetaEnumMetar  r  r   r@   r5   <module>r     s       
   ( *   ,   1 & <9
99 9x	#		 	 		
 	 3$ $sCc/A)B $ $
%d %# %$ %%d %# %$ % ""9@W@WX #/";";  $/";";  %,/"C"C% ! &/"="=  &/"="=  $/";";  %,/"C"C% !
 $.":":   '."="=   $+."A"A$   $.":": 
(d (# ($ ( !!8}?S?ST %-";";  &-";";   '-"<"<   ##:AWAWX %-";";  &-";";  &-";";  ""9@U@UV #-"9"9  $-"9"9  $-"9"9  !!8}?S?ST  !8}?S?ST  7m>Q>QR  !8}?S?ST "#:AWAWX !(-">">"  '.-"C"C' # '.-"C"C' # (/-"D"D( $ $+-"@"@$   %,-"A"A% ! %,-"A"A% ! ")-">">"  ")-">">"  !(-"="=!  #*-"?"?#  ")-">">"  +2-"G"G+ ' *1-"F"F* & ##:AWAWX %,-"B"B& " .5-"J"J. *
4d 4t 4
8$ 84 8
4d 4t 43T 3d 314 1D 1-t - -.D .T .
 
4 
#	  	.R#R*;RR$#$*;$$')#')*9')')T %s3x S#S*9SS@#*;<(O#(O	(O 
(O 	(OVY#Y	Y Y 	YB#  	
 4# 
 	
 0#  	2U#UU 
U 	U.'#'*9''T&#&*9&&R$#$*9$$&#*9,#*9,#*9,= =D =!S#!S*9!S!SR((88 88 ((	
 ]   ]00 =,, =<< m"" m22 =,, =<< m"" m22 m""  m22!" }44#$  -DD#22+BB!..)>>((/64/ 4d 4 _  "F3#F3F3 F3 	F3
 F3R#  	
  @)#)) ) 	)
 ) )&#  	
   ($#$$ $ 	$"#  	>)#)	) ) 	).1#1	1 1 	1*

#



 


#  	<#  	R 	#
  	
 ,-#-
- - 	-V "7 7
7#7 7 		7
 7<+
+#+ + 		+
 +( !tCH~  c3h E
#E
E
 E
 		E

 E
P-#-- - 		-
 -0	#	*9	
39	&#&*9&&$,#,*;,CT,,4 KK	HHMM> (%c	*: _$#_$_$ 
_$ 	_$D!#!! !! ?O+,	!r@   