
    3j`                    
   S SK Jr  S SKrS SKrS SKrS SKrS SKrS SKrS SKJ	r	J
r
  \
(       a  S SKrS SKJr  SSKJr  SSKJrJrJrJrJrJr  SSKJr  SS	KJr  SS
KJrJr  SSKJrJ r   \RB                  " \"5      r#\RH                  SS j5       r%\RH                  SS j5       r&\RN                   " S S5      5       r(SS jr)SS jr*SS jr+      SS jr,                SS jr-        SS jr.      SS jr/g)     )annotationsN)AnyTYPE_CHECKING)Callable   )InstructionTranslatorBase)create_copycreate_dup_topcreate_instructioncreate_swapInstruction	unique_id)	PyCodegen)unimplemented)GraphCompileReasonStackLocalsMetadata)NullVariableUnknownVariablec                    [         R                  S:  d   eSS jn [        R                  " U 5       Vs/ s H  oR                  PM     nn[        U5      S-
  USSS2   R                  S5      -
  nUR                  S5      nX#U $ s  snf )	zNGet the bytecode instructions that precede BUILD_LIST in a list comprehension.      c                 B    [        S5       V s/ s H  o PM     sn $ s  sn f Nr   rangeis    a/home/wildlama/miniconda3/lib/python3.13/site-packages/torch/_dynamo/comprehension_graph_break.pyfn._get_comprehension_bytecode_prefix.<locals>.fn*        8$8a8$$$   r   NLOAD_FAST_AND_CLEAR
BUILD_LISTreturnz	list[int])sysversion_infodisget_instructionsopnamelenindex)r    instinsts	start_idxend_idxs        r   "_get_comprehension_bytecode_prefixr4   $   s     w&&&% &)%9%9"%=>%=T[[%=E>E
Qtt!2!23H!IIIkk,'G7## ?s   Bc                     [         R                  S:  d   eSS jn SS jnSS jnSS jnSS jnU" U 5      nU" U5      nU" U5      nU" U5      nUS   US   S	.US   US   S	.US   US   S	.US   / S	.S
.$ )a  Discover bytecode patterns for comprehension result handling.

Analyzes sample functions to extract the opcode sequences that appear
after END_FOR for each result disposition (stored, discarded, returned, consumed).

Returns patterns with:
    - pre_store_ops: opcodes between END_FOR and first STORE_FAST
    - post_store_op: first opcode after all STORE_FASTs (for disambiguation)
r   c                 D    [        S5       V s/ s H  o PM     nn U$ s  sn f r   r   )r   results     r   	fn_stored5_get_comprehension_result_patterns.<locals>.fn_storedB   s$    "1X&X!X& 's   c                 B    [        S5       V s/ s H  o PM       n gs  sn f r   r   r   s    r   fn_discarded8_get_comprehension_result_patterns.<locals>.fn_discardedF   s     !HHqH 	r#   c                 B    [        S5       V s/ s H  o PM     sn $ s  sn f r   r   r   s    r   fn_returned7_get_comprehension_result_patterns.<locals>.fn_returnedJ   r"   r#   c                 T    [        [        S5       V s/ s H  o PM     sn 5      $ s  sn f r   )sumr   r   s    r   fn_consumed7_get_comprehension_result_patterns.<locals>.fn_consumedM   s#    uQx(x!Ax())(s   %c                   [        [        R                  " U R                  5      5      S   S   n/ nSn[        R                  " U 5       H}  nU(       a  UR
                  (       a    OdUR                  nU(       d  M2  UR                  U:X  d  MD  U=(       d    [        UR
                  5      nUR                  UR                  5        M     X"R                  S5      S-   S nSn/ nU[        U5      :  a9  Xg   S:w  a1  UR                  Xg   5        US-  nU[        U5      :  a
  Xg   S:w  a  M1  U[        U5      :  a&  Xg   S:X  a  US-  nU[        U5      :  a
  Xg   S:X  a  M  X[        U5      :  a  Xg   4$ S4$ )zCExtract (pre_store_ops, post_store_op) from comprehension bytecode.r   FEND_FORNr   
STORE_FAST)listr+   findlinestarts__code__r,   starts_line	positionslinenoboolappendr-   r/   r.   )	r    target_liner1   startedinstrposopsidxpre_store_opss	            r   extract_pattern;_get_comprehension_result_patterns.<locals>.extract_patternP   sL   3--bkk:;A>qA))"-E5,,//Csszz[0!<T%*;*;%<U\\* . KK	*Q.01CHn\!9  *1HC CHn\!9 CHn\!91HC CHn\!9 C.chBBdBB    r   r   )rU   post_store_op)stored	discardedreturnedconsumedr'   )r(   int)r    zCallable[..., Any]r(   ztuple[list[str], str | None])r)   r*   )	r8   r;   r>   rB   rV   rZ   r[   r\   r]   s	            r   "_get_comprehension_result_patternsr_   5   s     w&&&%*C4 Y'F-I{+H{+H %+1Iq	J'0|iPQlS&.qkHQKP&.qkBG	 rX   c                  V    \ rS rSr% SrS\S'   S\S'   S\S'   S	\S
'   S	\S'   S	\S'   Srg)ComprehensionAnalysisw   a  Metadata about a comprehension's bytecode structure.

Attributes:
    end_ip: Instruction pointer after all comprehension bytecode
    result_var: Name of result variable, or None if result stays on stack
    result_on_stack: True if result stays on stack (discarded, returned, or in expression)
    iterator_vars: Variables from LOAD_FAST_AND_CLEAR (need restoration)
    walrus_vars: Variables assigned via walrus operator (:=) inside comprehension
    captured_vars: Variables read from outer scope via LOAD_FAST inside comprehension
r^   end_ipz
str | None
result_varrM   result_on_stack	list[str]iterator_varswalrus_varscaptured_vars N)__name__
__module____qualname____firstlineno____doc____annotations____static_attributes__rj   rX   r   ra   ra   w   s,    	 KrX   ra   c                    [         R                  S:  d   eU R                  c   eU R                  S-
  n[        5       nU R                  U[        U5      -
  U  Vs/ s H  o3R                  PM     nnXB:H  $ s  snf )zDetect if we're at the start of a list/dict comprehension in 3.12+.

In Python 3.12+, comprehensions are inlined with a bytecode pattern that
precedes BUILD_LIST/BUILD_MAP.
r   r   )r)   r*   instruction_pointerr4   instructionsr.   r-   )txippatternr0   prefixs        r   _is_comprehension_startry      s}     w&&&!!---			!	#B02G&(oob3w<6G"&MN&Mdkk&MFN Os   A7c                @   [         R                  S:  d   eU R                  c   eSn[        U R                  [	        U R
                  5      5       HJ  nU R
                  U   nUR                  S:X  a  US-  nM)  UR                  S:X  d  M;  US-  nUS:X  d  MH  Us  $    g)zPFind the instruction pointer of the outermost END_FOR for current comprehension.r   r   FOR_ITERr   rE   r$   )r)   r*   rs   r   r.   rt   r-   )ru   nesting_depth	search_ipr0   s       r   _find_comprehension_end_for_ipr~      s    w&&&!!---M2113r3GH	y);;*$QM[[I%QM!   I rX   c           	       ^ ^^^ [         R                  S:  d   eT R                  c   e[        5       mT R                  S-
  n/ n/ n/ n[	        5       nUS-
  nUS:  a`  T R
                  U   nUR                  S:X  a"  UR                  SUR                  5        US-  nOUR                  S;   a  US-  nOOUS:  a  M`  UR                  U5        [        T 5      nUS:X  a  [        SS	S
/ S9  [        U 4S j[        X5       5       5      n	[        U	S-   U5       GHE  n
T R
                  U
   nUR                  S:X  as  UR                  S:X  ac  U
S-   U:  aZ  T R
                  U
S-      nUR                  S:X  a8  UR                  nX;  a'  X;  a"  UR                  U5        UR!                  U5        UR                  S:X  a  UR!                  UR                  5        M  UR                  R#                  S5      (       d  M  [%        UR                  [&        5      (       a  UR                  OUR                  4nU H"  nX;  d  M
  X;  d  M  UR                  U5        M$     GMH     / mUS-   nU[)        T R
                  5      :  a  T R
                  U   R                  S:w  ae  TR                  T R
                  U   R                  5        US-  nU[)        T R
                  5      :  a  T R
                  U   R                  S:w  a  Me  UnU[)        T R
                  5      :  aZ  T R
                  U   R                  S:X  a=  US-  nU[)        T R
                  5      :  a  T R
                  U   R                  S:X  a  M=  U[)        T R
                  5      :  a  T R
                  U   R                  OSmSUUU4S jjnSnU" S5      (       a  T R
                  U   R                  nSnOVU" S5      (       a  SnSnTS   S   (       a  US-   OUnO0U" S5      (       d  TTS   S   :X  a  SnSnO[        SST ST 3S/ S9  [+        UUWUUUS9$ )zDAnalyze comprehension bytecode to determine result handling pattern.r   Nr   r   r%   )SWAPGET_ITERr$   z)Comprehension analysis failed: No END_FOR z=Could not find END_FOR instruction in comprehension bytecode.)gb_typecontextexplanationhintsc              3  f   >#    U  H&  nTR                   U   R                  S :X  d  M"  Uv   M(     g7f)r{   N)rt   r-   ).0r   ru   s     r   	<genexpr>)_analyze_comprehension.<locals>.<genexpr>   s1      ,A??1$$
2 	
,s   !1	1COPYrF   	LOAD_FASTc                ^   > TU    nTUS   :H  =(       a    TUS   :H  =(       d
    US   (       + $ )NrU   rY   rj   )namepatpatternsrY   rU   s     r   matches'_analyze_comprehension.<locals>.matches	  s=    tnO 44 
S11M_9M5M	
rX   rZ   Fr[   rY   r\   r]   rU   Tz)Comprehension analysis failed: No matcheszpre_store_ops=z, post_store_op=z8Comprehension does not match any known bytecode pattern.)rc   rd   re   rg   rh   ri   )r   strr(   rM   )r)   r*   rs   r_   setrt   r-   insertargvalupdater~   r   nextr   argrN   add
startswith
isinstancetupler.   ra   )ru   start_iprg   rh   ri   defined_insideiter_scan_ipr0   
end_for_ipfor_iter_ipbody_ip	next_instvar_name	var_namesscan_ipstore_fast_ipr   rd   re   r   rY   rU   s   `                  @@@r   _analyze_comprehensionr      s   w&&&!!---13H%%)H!MK!M"uN a<L
!
|,;;//  DKK0AL[[00AL !
 -(/3JR?W		
  x, K q*5w' ;;& TXX]w{Z7O!4I</$++0X5P&&x0"&&x0 ;;,&t{{+ [[##K00)$++u==DKK>  &1h6S!((2 &+ 64  "M1nG#boo&&OOG$++|;R__W5<<=1	 	#boo&&OOG$++|;
 M 	#boo&&OOG$++|;1 	#boo&&OOG$++|;
 ,3S5I+I ''t 
 
 "Jx__]3::
			
!)+!6!G'A+W			*1Eo1V V
?$]O3CM?SR		
 !'## rX   c           	        [         R                  S:  d   eU R                  c   eU R                  S-
  n[        U 5      nS[	        UR
                  5      -   n[        SU R                  5       /5      n[        R                  S5        U R                  R                  U UUS9n[        U5       Vs/ s H9  n[        U R                  [	        U R                  5      U-
  U-      [        5      PM;     nnU R!                  U5        US   n	[#        U R                  R$                  5      n
['        S U 5       5      n[	        U R                  5      [	        U	R(                  5      -
  nU
R+                  / [-        X-   S-   5      QU
R/                  S5      PU
R1                  5       P5        [3        [        U5      5       Ha  nU
R+                  [5        S	5      5        X   (       a!  U
R+                  U
R7                  5       5        MG  U
R+                  [9        S
SS9/5        Mc     U
R+                  [9        S5      /5        [;        U UUUUUU	5      u  pU
R+                  / [-        US	-   5      QU
R/                  S5      PU
R1                  5       P[9        SSS9P[-        US	-   5      QU
R/                  S5      PU
R1                  5       P[9        SSS9P5        U R=                  U/U/U
5        US:  a  US-   S-   nU
R+                  / [-        U5      QU
R/                  S5      PU
R1                  5       P[?        5       PU
R/                  U* 5      PU
R/                  S5      P[9        SS	S9P[9        S5      P[9        S5      P5        UR@                  URB                  (       a  URB                  /O/ -   n0 nU H`  n[E        5       U RF                  U'   UU	RH                  ;   a  U	RH                  U   UU'   M>  [	        U	RH                  5      U	RH                  U'   Mb     US	-   nUR@                  (       Ga3  U
R+                  / [-        U5      QU
R/                  S5      PU
R1                  5       P5        [K        UR@                  5       H  u  nnU
R+                  / [-        S	5      QU
R/                  US-   5      PU
R1                  5       P5        UU;   a=  U
R+                  / [-        S	5      QU
R/                  UU   5      P[9        S5      P5        M  U
R+                  [9        S
SS9/5        M     U
R+                  [9        S5      U
R/                  S5      U
R1                  5       /5        URL                  (       a  U RO                  [E        5       5        OURB                  (       a  U
R+                  / [-        U5      QU
R/                  S5      PU
R1                  5       P5        URB                  U;   a9  U
R+                  U
R/                  UURB                     5      [9        S5      /5        OMU
R+                  / [5        S	5      Q[9        S
SS9P[9        S5      P5        OU
R+                  [9        S5      /5        U R                  RQ                  U
RS                  5       5        U RT                  URV                     nU R                  RQ                  U RY                  UU5      5        SU l        gs  snf )zHandle list/dict comprehension graph break.

Builds a synthetic function wrapping the comprehension bytecode,
calls it via codegen_call_resume, then chains into the resume
function for the post-comprehension code.
r   Nr   comprehension_graph_breakzcomprehension triggered compile)reason
stack_popsr   c              3  6   #    U  H  o(       a  M  S v   M     g7f)r   Nrj   )r   ms     r   r   4_handle_comprehension_graph_break.<locals>.<genexpr>U  s     A#7aq#7s   
	   LIST_APPENDr   POP_TOPr&   BUILD_SLICEDELETE_SUBSCRSTORE_SUBSCR)-r)   r*   rs   r   r.   rg   r   frame_summarylogdebugoutputcompile_subgraphr   r   stackr   popnr   root_txrA   stack_null_idxesextend_outputr	   create_load_constcreate_binary_subscrreversedr   pop_nullr   _build_comprehension_fncodegen_call_resumer
   rh   rd   r   symbolic_localslocals_names	enumeratere   pushadd_output_instructionsr,   rt   rc   create_call_resume_at)ru   r0   r   analysisr   r   all_stack_locals_metadatar   stack_pops_null_maskmetacgnonnull_countlive_stack_depthnew_codefn_nameframe_values_posvars_to_passexisting_varsr   fv_depthj
walrus_varresume_insts                          r   !_handle_comprehension_graph_breakr   -  s    w&&&!!---%%)H%b)HS//00J ;b>N>N>P=QRFII/0 !#		 : :
 !; ! z""A 	288CMJ6:;\J"  
 GGJ$Q'D	299$$	%B A#7AAM 288}s4+@+@'AA 	
)6:;	
   #	
 ##%		
 eJ'(
Q("R[[]+0AFGH ) (345
 0
H 		
)A-.		
  #		
 ##%		
 |3			

 )A-.		
   #		
 ##%		
 |3		
  H:y"5
 q+a/!3
-.$$Q' '')
   $$m^4 $$T* #=a8 #?3 #9-	
& ''!)!4!4		"L %'M '6'88$t(((&*&7&7&AM(#*-d.?.?*@Dh' !  !#H 
X&$$Q' '')	
 'x';';<MAz ^((Q/ ++- ]*  $Q,,]:-FG +>:   "4]"J!KL' =* 	"9-$$Q''')		
 
!"			
X&$$Q' '')	
 -/((x7J7J)KL&~6  ^&}!< 'y1 	,Y789 II%%b&9&9&;< //(//2KII%%
  .GH "Bs   0A [ c                  ^ ^^^^^^^^^^^^ SSK Jn  SSKJn  SSKJmJm  [        U 4S jUR                   5       5      n	SS/[        U	5      -   [        T5       V
s/ s H  n
SU
 3PM
     sn
-   m[        [        [        T R                  R                  =(       d    / 5      [        T R                  R                  =(       d    / 5      -   5      5      mT R                  b  T R                  OT R                  R                   m[#        S	T R                  R$                   S
T 35      mTR&                  TR(                  -   TR*                  (       a  TR*                  /O/ -   TR,                  -   mSUUUUUUUUUUUUU 4S jjnU" T R                  U5      u  pU" U5        T R.                  R1                  TUT R2                  5        UT4$ s  sn
f )ar  Build a synthetic function wrapping comprehension bytecode.

Uses the same calling convention as resume functions created by
create_resume / ContinueExecutionCache.generate: the first two args
are __nested_resume_fns and __nested_frame_values (ignored here),
followed by stack items and live locals.

Returns (code, name) where name is the global name for the function.
r   )transform_code_object)	skip_code)
CO_VARARGSCO_VARKEYWORDSc              3  R   >#    U  H  oTR                  5       ;  d  M  Uv   M     g 7fN)cell_and_freevars)r   kru   s     r   r   *_build_comprehension_fn.<locals>.<genexpr>#  s#     U 11b>R>R>T5TQQ 1s   '	'__nested_resume_fns__nested_frame_values___stack__comprehension__at_c           	     ^  > TUS'   [         R                  S:  a  TUS'   TUS'   SUS'   TUS'   [        T5      US'   S	US
'   S	US'   [        TT Vs/ s H  o"T;  d  M
  UPM     sn-   5      US'   US   T	T
-  ) -  US'   / nT(       a"  UR	                  [        S[        T5      S95        UR	                  [        SS	S95        TS-
  n[        T5       HJ  nTU   (       a  UR	                  [        S5      5        M)  UR	                  [        SSU 3S95        US-  nML     [        TTTR                  5      n/ nTR                  (       dN  TR                  (       a$  UR	                  [        STR                  S95        OUR	                  [        SS S95        TR                  (       a[  TR                   H  nUR	                  [        SUS95        M     UR	                  [        SS[        TR                  5      -   S95        UR	                  [        S5      5        X6-   U-   U S S & g s  snf )Nco_name)r      co_qualnameco_firstlinenorj   co_cellvarsco_freevarsco_argcountr   co_posonlyargcountco_kwonlyargcountco_varnamesco_flagsCOPY_FREE_VARSr   RESUMEr   	PUSH_NULLr   r   )r   
LOAD_CONSTBUILD_TUPLERETURN_VALUE)r)   r*   r.   r   rN   r   r   _copy_comprehension_bytecoderc   re   rd   rh   )rt   code_optionsvrx   	nonnull_ir   
comp_instsepiloguer   r   r   r   argscomprehension_body_varsr   freevarsrL   r   r   r   r   ru   s            r   r   '_build_comprehension_fn.<locals>.update8  s.   ")Yw&*1L')/%&&(]#&.]#&)$i]#-.)*,-()&+6H6!4-A6HH'
]# $0
#;'?
 $
Z  %'MM,-=3x=QR(q9: "A%	z"A#A&0=>&{Xi[;QR Q	 # 2"hP
 ')''""&{8;N;NO  2< MN$00 2;x PQ 1OO"!C 4 455 	*>:; -8Qa Is   	H*
H*
)rt   list[Instruction]r  zdict[str, Any]r(   None)bytecode_transformationr   
eval_framer   resume_executionr   r   r   r   rG   r   sortedf_coder   r   rL   r   r   r   rg   rh   rd   ri   r   install_resume_function_global	f_globals)ru   r   r   r   r   r   r   r   r   argnamesr   r   r   _r   r   r  r  r   r  rL   s   ``````        @@@@@@@r   r   r   
  s   $ ?%<
 U 1 1UUH	 78
x.	#(#7
8#7aXaS>#7
8	9 	 tBII))/R04		8M8M8SQS3TTUH ))/RYYRYY5M5MF*299+<+<*=T&JKG 	


	$,$7$7H R	A 
 
 	! ;9 ;9 ;9z (		6:KHh II,,WhMWi 9s   Gc                .   0 n/ n[        X5       HD  nU R                  U   n[        R                  " U5      nSUl        XsU'   UR	                  U5        MF     U H7  nUR
                  c  M  UR
                  U;   d  M$  X7R
                     Ul        M9     U$ )z@Copy comprehension bytecode instructions, updating jump targets.N)r   rt   copyexn_tab_entryrN   target)ru   r   rc   inst_mapcopied_instsrv   original_instcopied_insts           r   r   r   ~  s     02H&(LH%+ii.$(!"-K( & $)k.@.@H.L!)*<*<!=K $ rX   c                &   [         R                  S:  a  UR                  S:X  d  g[        U 5      (       d  g[	        S U R
                   5       5      =(       a    U R                  (       + =(       aj    U R                  (       + =(       aR    U R                  (       + =(       a:    U R                  (       + =(       a"    U R                  R                  R                  SL nU(       a  U R                  b  U R                  5       nU(       aH  U R                  S:X  a8  U R                  5       nUR!                  U 5      (       a  [#        X5        gX0l        ['        U 5      nUS:  d   eU R(                  R+                  U5        U =R                  S-  sl        g)z
Handle comprehension start for Python 3.12+ BUILD_LIST/BUILD_MAP with argval 0.
Returns True if a graph break was triggered and the caller should return early.
r   r   Fc              3  @   #    U  H  oR                  5       v   M     g 7fr   )can_restore)r   bs     r   r   8maybe_setup_comprehension_speculation.<locals>.<genexpr>  s     4^MMOO^s   NTr   )r)   r*   r   ry   allblock_stack	one_grapherror_on_graph_breakis_tracing_resume_prologueactive_generic_context_managersr   current_tracerparent#_can_speculate_comprehension_nested_comprehension_depth	speculatefailedr   current_speculationr~   _comprehension_end_for_ipsr   )ru   r0   can_speculatespeculationr   s        r   %maybe_setup_comprehension_speculationr2    sC    'DKK1,<"2&& 	4R^^44 	4	4'''	4 ---	4 222		4
 II$$++t3  .>>@00A5llnb!!-b7!,/3J??!!%%j1q rX   )r(   rf   )r(   zdict[str, dict[str, Any]])ru   r   r(   rM   )ru   r   r(   r^   )ru   r   r(   ra   )ru   r   r0   r   r(   r  )ru   r   r   ra   r   r^   r   r^   r   z
list[bool]r   r^   r   r   r(   ztuple[types.CodeType, str])ru   r   r   r^   rc   r^   r(   r
  )ru   r   r0   r   r(   rM   )0
__future__r   r  dataclassesr+   	functoolsloggingr)   typingr   r   typescollections.abcr   symbolic_convertr   r  r	   r
   r   r   r   r   codegenr   excr   output_graphr   r   variables.miscr   r   	getLoggerrk   r   cacher4   r_   	dataclassra   ry   r~   r   r   r   r   r2  rj   rX   r   <module>rB     su   "   
   
 % (;    A 9 ! $ $  > >B   (""|~Z"!Z")4Z"	Z"zq!q#q q 	q
 %q q q  qh!-0:=*#!#)4#	#rX   