NL idZddlmZddlmZmZddlmZmZm Z m Z m Z m Z m Z mZmZmZmZmZddlmZmZmZmZmZmZmZmZmZmZmZmZm Z m!Z!ddl"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/m0Z0m1Z1m2Z2m3Z3m4Z4ddl5m6Z6ddl7m8Z8dd l9m:Z:m;Z;dd lZ>m?Z?m@Z@mAZAmBZBmCZCdd lDmEZEmFZFdd lGmHZHmIZImJZJmKZKdd lLmMZMmNZNmOZOddlPmQZQddlRmSZSddlTmUZUddlVmWZWddlXmYZYegdfZZ d8dZ[ d9dZ\ d:dZ]d;dZ^ ddZb d? d@dZcGddZdGdd edZeGd!d"edZfGd#d$edZgdAd%ZhGd&d'edZiGd(d)edZjGd*d+ejZkGd,d-ejZlGd.d/ejZmGd0d1edZnGd2d3edZoGd4d5edZpGd6d7edZqy)BzHelpers for generating for loops and comprehensions. We special case certain kinds for loops such as "for x in range(...)" for better efficiency. Each for loop generator class below deals one such special case. ) annotations)CallableClassVar) ARG_POSCallExprDictionaryComprehension Expression GeneratorExprLvalue MemberExprNameExprRefExprSetExpr TupleExpr TypeAlias) ERR_NEVER BasicBlockBranchIntegerIntOp LoadAddressLoadErrorValueLoadMem MethodCallRaiseStandardErrorRegisterTupleGetTupleSetValue) RInstanceRTupleRTypebool_rprimitivec_pyssize_t_rprimitiveint_rprimitiveis_dict_rprimitiveis_fixed_width_rtypeis_immutable_rprimitiveis_list_rprimitiveis_sequence_rprimitiveis_short_int_rprimitiveis_str_rprimitiveis_tuple_rprimitiveobject_pointer_rprimitiveobject_rprimitivepointer_rprimitiveshort_int_rprimitive) IRBuilder)GENERATOR_HELPER_NAME)AssignmentTargetAssignmentTargetTuple)dict_check_size_opdict_item_iter_opdict_key_iter_opdict_next_item_opdict_next_key_opdict_next_value_opdict_value_iter_op)no_err_occurred_oppropagate_if_error_op)aiter_opanext_opiter_opnext_op)list_append_oplist_get_item_unsafe_opnew_list_set_item_op)stop_async_iteration_op)CFunctionDescription) set_add_op)str_get_item_unsafe_op)tuple_get_item_unsafe_opNc lt}t}t} t} || n| } t||||| ||} |j|| t} |j| | j |j || j ||j|| j|j| | j| |j|)|j | ||j| |j | y)aGenerate IR for a loop. Args: index: the loop index Lvalue expr: the expression to iterate over body_insts: a function that generates the body of the loop else_insts: a function that generates the else block instructions N)is_async) rmake_for_loop_generatorpush_loop_stackgoto_and_activate gen_conditionactivate_block begin_bodygen_stepgoto add_cleanuppop_loop_stack)builderindexexpr body_insts else_instsrLline body_block step_block else_block exit_blocknormal_loop_exitfor_gencondition_blocks _/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/mypyc/irbuild/for_helpers.pyfor_loop_helperreVs$JJJJ&0%;z%j*:D8G J 3 lO o.  :& L j)  LL! () z*  Z  :&ct|jsJ|j|}t}t}t} t} t |||| |d} | j ||d|j || |j| | j|j|| j||j| j|j|| j|j| | j| |j!|j| y)a}Generate IR for a sequence iteration. This function only works for sequence type. Compared to for_loop_helper, it would feed iteration index to body_insts. Args: index: the loop index Lvalue expr: the expression to iterate over body_insts: a function that generates the body of the loop. It needs a index as parameter. FreverseN)r*typeget_sequence_typer ForSequenceinitrNrOrPrQrRread index_targetrSrTrUrV) rWrXrYexpr_regrZr\ target_typer]r^r`rcrbs rdfor_loop_helper_with_indexrrs& "(-- 00 0++D1KJJJ lO'5*j$NG LL;L6 J 3 o.  :& w||G0012 j)  LL!  #  :&rfc$tjdk(rtjdk(rtjddk(rj jd}t |rj jd}jj|jd}||jdfd }tjdjd||jSy)a$Generate a new tuple or list from a simple generator expression. Currently we only optimize for simplest generator expression, which means that there is no condition list in the generator and only one original sequence with one index is allowed. e.g. (1) tuple(f(x) for x in a_list/a_tuple/a_str/a_bytes) (2) list(f(x) for x in a_list/a_tuple/a_str/a_bytes) (3) [f(x) for x in a_list/a_tuple/a_str/a_bytes] RTuple as an original sequence is not supported yet. Args: empty_op_llbuilder: A function that can generate an empty sequence op when passed in length. See `new_list_op_with_length` and `new_tuple_op_with_length` for detailed implementation. set_item_op: A primitive that can modify an arbitrary position of a sequence. The op should have three arguments: - Self - Target position - New Value See `new_list_set_item_op` and `new_tuple_set_item_op` for detailed implementation. rT use_pyssize_tc|jj}j||gjyN)accept left_exprcall_cr\) item_indexerWgen set_item_op target_ops rdset_itemz.set_items0NN3==1{Y A,FQrfN)r|rreturnNone) len sequencesindices condlists node_typer*ryrW builtin_lenr\rr) rWr~empty_op_llbuilderrrtypesequencelengthrrs `` ` @rd*sequence_from_generator_preallocate_helperrs: 3==Q3s{{#3q#8SqAQ=RVW=W!!#--"23 !% (~~cmmA&67H__00388SW0XF*6388.gen_inner_stmtss9 NN3== )^gll8.Da-H#((Srfrr))raise_error_if_contains_unreachable_namesnonerrWnew_list_op_with_lengthrE maybe_spill new_list_opr\listziprrrrLcomprehension_helperrn)rWr~val loop_paramsrrs`` @rdtranslate_list_comprehensionrs0#>||~ 5 "??BB(  C   ""7#6#6r388#DEHs3;; s}}cllSTKT+I << !!rfctd|jDr7ttjd|j}|j |yy)zRaise a runtime error and return True if generator contains unreachable names. False is returned if the generator can be safely transformed without crashing. (It may still be unreachable!) c3\K|]$}t|txr|jdu&ywrx) isinstancer node).0ss rd z.s' K!:a " 5qvv~ 5 Ks*,z+mypyc internal error: should be unreachableTF)anyrr RUNTIME_ERRORr\add)rWr~errors rdrrsG Ks{{ KK"  , , 9 HH   E rfcvtrjSjjgjt t jjjj}dfd }t||jjS)Ncjj}jtj |gj yrx)ryrzrrHrnr\)r}rWr~set_opss rdrz4translate_set_comprehension..gen_inner_stmts*s9 NN3== )Z',,w*?)CSXXNrfr) rrr new_set_opr\rrrrrrLrrn)rWr~rrrs`` @rdtranslate_set_comprehensionr#s0#>||~!!'"4"4R"BCGs3;; s}}cllSTKO+I <<  rfcJdfd  dfd |y)aHelper function for list comprehensions. Args: loop_params: a list of (index, expr, [conditions]) tuples defining nested loops: - "index" is the Lvalue indexing that loop; - "expr" is the expression for the object to be iterated over; - "conditions" is a list of conditions, evaluated in order with short-circuiting, that must all be true for the loop body to be executed gen_inner_stmts: function to generate the IR for the body of the innermost loop c Ld\}}}t||fdd|y)zGenerate IR for a loop. Given a list of (index, expression, [conditions]) tuples, generate IR for the nested loops the list defines. rcddSNrt)conds loop_contentsrsrdz;comprehension_helper..handle_loop..NsM%QR9rfN)rLr\)re)rrXrYrLrrWr\rs` @rd handle_loopz)comprehension_helper..handle_loopCs4 (31~$tUH    9  rfc<|D]}j|}tt}}j|||j|jdj |j j||r|Sy)aaGenerate the body of the loop. Args: conds: a list of conditions to be evaluated (in order, with short circuiting) to gate the body of the loop remaining_loop_params: the parameters for any further nested loops; if it's empty we'll instead evaluate the "gen_inner_stmts" function N)ryradd_bool_branchrQnonlocal_control gen_continuer\rO) rremaining_loop_paramscondcond_val cont_block rest_blockrWrrs rdrz+comprehension_helper..loop_contentsTs 2D~~d+H%/\:< J  # #Hj* E  " ": .  $ $R ( 5 5gtyy I  % %j 1 2 !45 5  rfN)r7list[tuple[Lvalue, Expression, list[Expression], bool]]rr)rlist[Expression]rrrrr)rWrrr\rrs` ``@@rdrr2s1" "V < rfcz|jdk(xs+t|jtxr|jdk(S)Nzbuiltins.rangezsix.moves.xrange)fullnamerrr)rYs rd is_range_refrus9 )) 0 dii + 0 MM/ /rf ForGeneratorc|rW|j|}t||||||} |j|} |j| } | j || | S|j |} t | rH|j|}|j|} t||||||}|j || d|St| rF|j|}|j|} t||||||}|j || |St|trt|jtrt!|jr|t#|j$dks8t#|j$dk(rK|j'|j$d,t)|j*t,hk(rt#|j$dk(r*t/d}|j|j$d}n<|j|j$d}|j|j$d}t#|j$dk(rQ|j'|j$d}|J|dk(r,|j1d|j$dj2nd}t5||||||}|j ||||S|jj6d k(rt#|j$dk(r|j*t,gk(rxt|t8rht#|j:dk(rP|j:d}|j:d}t=||||||}|j |||j$d|S|jj6d k(rt#|j$dk\rt)|j*t,hk(rst|t8rct#|j:t#|j$k(r8t?||||||}|j |j:|j$|S|jj6d k(rt#|j$dk(r|j*t,gk(r|t |j |j$drU|j|j$d}|j|} t||||||}|j || d |St|trnt|jt@rS|j$sF|j |jjB}t|r|jjDd vr|j|jjB}d}|jjDdk(r,|j|jjB} t}np|jjDdk(r,|jG|jjB} tH}n+|jK|jjB} tL}|||||||}|j || |Sd}t|tNrddl(m)}|||}||}||j|}|jT}t|tVr0|jXj[t\rt_||||||}nta||||||}|j|} |j| } |j || |S)zReturn helper object for generating a for loop over an iterable. If "nested" is True, this is a nested iterator such as "e" in "enumerate(e)". FrhNrtrzrange() step can't be zerozbuiltins.enumeratez builtins.zipzbuiltins.reversedT)keysvaluesitemsrr)precompute_set_literal)1ryForAsyncIterable_analyze_iterable_item_type type_to_rtypermrr*rkrlr&get_dict_key_typeForDictionaryKeysrrcalleerrrargs extract_intset arg_kindsrrrr\ForRangerrr ForEnumerateForZipr rYnameget_dict_value_typeForDictionaryValuesget_dict_item_typeForDictionaryItemsrmypyc.irbuild.expressionrrjr class_ir has_methodr3ForNativeGenerator ForIterable) rWrXrYr] loop_exitr\rLnestedrp async_obj item_type item_rtypertyprqfor_listfor_dict start_regend_regstep for_rangelvalue1lvalue2 for_enumeratefor_zipr for_dict_type for_dict_geniterable_expr_regr set_literalitfor_objs rdrMrM}s >>$'$WeZDRXY 77= **95 x,   T "Dd#>>$'//5 wz9dFS h U ;$>>$'//5 $WeZDRXY h ,$!jg&F  %DII!# Na'G,?,? ! ,M,YDNN#y0 499~"#*1: !..16#NN499Q<8 !..16499~"**499Q<8'''19MM"> ! @Q@QR %YfUI NN9gt 4  KK $8 8DII!#7)+5),EKK A%kk!nGkk!nG(%YPTV\]M   w1 >  KK N 2DII!#DNN#y05),EKK C N2WeZD&QG LLdii 0N KK $7 7DII!#7)+&w'8'81'FG~~diil3H!33D9K"7E:y$PVWH MM(KM >O$!jj&IRVR[R[!!$++"2"23 e $)9)9=X)X~~dkk&6&67H7;M{{6)%77 8H8HI 1 !!X-%99$++:J:JK 3 %889I9IJ 2 (%YPTV\]L   h 4 &*$ C,Wd;  " +  #NN40   B"i R[[%;%;A helper to get collection length, used by several subclasses.Tru)rWrrnr\)rrYs rdload_lenzForGenerator.load_lenOsD||##// LL  dDII . 0  rfN)rWr2rXr r]rrrr\intrboolrrrr)r`rrrr)rYzValue | AssignmentTargetrr) __name__ __module__ __qualname____doc__rrrUrPrRrSrr rrfrdrrss7''' '  '  '' '2*KE>6 rfc@eZdZdZd dZd dZd dZd dZd dZd dZ y) rzIGenerate IR for a for loop over an arbitrary iterable (the general case).cyNTrrs rdrzForIterable.need_cleanupYrfc|j}|jt|g|j}|j ||j ||_||_yrx)rWrrAr\r iter_targetrqrrprqrWiter_regs rdrmzForIterable.init]sP,,''(TYYGH%"..x8&rfc4|j}|j}|jt|j |j |g||_|jt|j |j|jtjyrx) rWr\r{rBrnrnext_regrrrr]IS_ERRORrrWr\s rdrPzForIterable.gen_conditiongsg ,,yywd>N>NPT1U0VX\]  F4==$..$//6??[\rfc|j}|j}|j|j|j|}|j |j |j||yrxrWr\coercerrqassignget_assignment_targetrXrrWr\rs rdrRzForIterable.begin_bodyqS,,yy>>$--1A1A4Hw44TZZ@(DQrfcyrxrrs rdrSzForIterable.gen_step{ rfcZ|jjtg|jyrxrWr{r=r\rs rdrzForIterable.gen_cleanups .DII>rfNrrprrqr"rrr rrrrrrmrPrRrSrrrfrdrrVs%S']R ?rfrc@eZdZdZd dZd dZd dZd dZd dZd dZ y) rz3Generate IR for a for loop over a native generator.cyrrrs rdrzForNativeGenerator.need_cleanuprrfcV|j}|j||_||_yrx)rWrrrq)rrprqrWs rdrmzForNativeGenerator.inits(,,"..x8&rfc ||j}|j}tt|_|j t td}|j|j|||j tt|j}|j}t|j|jt|||||g|}t|_|j ||_|j t%|j"|j&|j(t$j*y)NT) undefines)rWr\rr/ return_valuerrr#rr. none_objectrrnrr3r error_kindrrrr]r)rrWr\errptrnn helper_calls rdrPz ForNativeGenerator.gen_conditions,,yy$%67kk.):dKLt((#t4kk+&?ARARST  " LL)) *,ABBPRTWCXZ^ "+  K0  F4==$..$//6??[\rfc|j}|j}|j|j|j|}|j |j |j||yrxr!r%s rdrRzForNativeGenerator.begin_bodyr&rfcyrxrrs rdrSzForNativeGenerator.gen_stepr(rfcp|jjt|jg|jyrx)rWrr>r2r\rs rdrzForNativeGenerator.gen_cleanups( !!"7$:K:K9LdiiXrfNrr+rr,rrfrdrrs&='].R Yrfrc0eZdZdZddZddZddZddZy) rz"Generate IR for an async for loop.c|j}|jt|g|j}|j ||j ||_||_tt|_ yrx) rWr{r?r\rrrqrr#stop_regrs rdrmzForAsyncIterable.initsZ ,,>>(XJ BH%"..x8& 1 rfc2ddlmm}jjdfd }dfd }dfd }|||fd|fgdj t jjjt jy)Nr) emit_awaittransform_try_exceptcjtttj}jt tj |dS)NT)borrow)rrr0rFsrcrrj)addrrWr\s rd except_matchz4ForAsyncIterable.gen_condition..except_matchsC;;{+=?V?Z?Z\`abD;;w'>'C'CTRVWX Xrfcjtjjg}|_j j jdyNr)r{r@rnrrr#r>false) awaitablerWr@r\rs rdtry_bodyz0ForAsyncIterable.gen_condition..try_bodysRx',,t?O?O2P1QSWXI&w 4@DM NN4=='--/2 >rfc\jjjyrx)r#r>true)rWr\rsrd except_bodyz3ForAsyncIterable.gen_condition..except_bodys NN4==',,.$ ?rf)rrr) mypyc.irbuild.statementr@rArWr\rrr>rr]BOOL)rrArFrKrNrWr@r\s` @@@rdrPzForAsyncIterable.gen_conditions M,,yy Y ? ?  @  X,!5t[ IJDRV   F4==$..$//6;;WXrfc|j}|j}|j|j|j|}|j |j |j||yrxr!r%s rdrRzForAsyncIterable.begin_bodyr&rfcyrxrrs rdrSzForAsyncIterable.gen_stepr(rfNr+r)rrrrrmrPrRrSrrfrdrrs, 2 YDR rfrcBt|jr|jt||g|St |jr|j t ||g|St|jr|j t||g|S|j|d|gd|S)z.Emit a potentially unsafe index into a target. __getitem__N) r)rjrrDr-r{rJr,rIgen_method_call)rWtargetrXr\s rd unsafe_indexrWs &++&##$;fe_dSS V[[ )~~6NN 6;; '~~4vuotLL&&v}ugtTRRrfc<eZdZUdZded<d dZd dZd dZd dZy) rlzoGenerate optimized IR for a for loop over a sequence. Supports iterating in both forward and reverse. zValue | AssignmentTarget | None length_regcDt|jsJ||j}||_|j ||_t |jr0|j |j|j |_nd|_|stdt}n_|j|j|j}n|j|j }|jj|d}|j||_||_y)Nrrt)r*rjrWrir expr_targetr(r rYrr$rnint_submaybe_spill_assignablerorq)rrprqrirW index_reglen_vals rdrmzForSequence.inits%hmm4>h>4,, #..x8 "8== 1%11$--@P@P2QRDO#DO&q*@AI*!,,t7--(8(89//;I#::9E&rfc\|j}|j}|jro|j|j |j |t dd|}t}|j|||j|j||j|j|j}n|j |j|}|j|j |j ||d|}|j||j|jy)Nrz>=<)rWr\ri binary_oprnrorrrrrQrYr r[r])rrWr\ comparison second_checklen_regs rdrPzForSequence.gen_condition1s,,yy << !** T..5wqz4J&>$"3"3hZK"..x8rfcH|j}|j}|jj|j|j |j ||j |j |g||_|jt|jd|}|j|j |||jt|jd|}|jt||j|jtjy)zIGet next key/value pair, set new offset, and check if we should continue.rtrN)rWr\r{rmrnrrs next_tuplerrr#rr]rrP)rrWr\ new_offsetshould_continues rdrPz!ForDictionaryCommon.gen_conditions,,yy,,--    \\$**D 17<<@R@RTX3Y Z  [[$//1d!CD t)):t<!++ht4&HI F?DOOT^^V[[YZrfc|j}|j}|jt|j |j ||j |j |g|y)zCheck that dictionary didn't change size during iteration. Raise RuntimeError if it is not the case to match CPython behavior. N)rWr\r{r6rnr[rtrs rdrSzForDictionaryCommon.gen_stepsP ,,yy  \\$**D 17<< 43P Q  rfcZ|jjtg|jyrxr*rs rdrzForDictionaryCommon.gen_cleanups .DII>rfNrr+r) rrrrrjrrmrPrSrrrfrdrlrlgs/ 1000 9["  ?rfrlc eZdZdZeZeZddZy)rz:Generate optimized IR for a for loop over dictionary keys.c|j}|j}|jt|jd|}|j |j |j|j||j||yNr rWr\rrrwr#r$rXr"rq)rrWr\keys rdrRzForDictionaryKeys.begin_bodysh,,yykk(4??At<=  ) )$** 5 NN3 0 0$ 7  rfNr) rrrrr:rmr8rnrRrrfrdrrsD#L#L  rfrc eZdZdZeZeZddZy)rz?  ) )$** 5 NN5$"2"2D 9  rfNr) rrrrr;rmr<rnrRrrfrdrrsF%L%L  rfrc eZdZdZeZeZddZy)rz;Generate optimized IR for a for loop over dictionary items.cV|j}|j}|jt|jd|}|jt|jd|}t |j tsJ|j |j||j jd|}|j||j jd|}|j|j}t |trkt|jdk7r|jd||j!|jd|||j!|jd||y|jt#||g|}|j!|||y)Nrrrrtz'Expected a pair for dict item iteration)rWr\rrrwrrqr!r"typesr$rXr5rrrr#r)rrWr\rrrVrvalues rdrRzForDictionaryItems.begin_bodysK,,yykk(4??At<= HT__a>?$**F3ET5E5EE3nnS$"2"2"8"8";TBud&6&6&<&F NN664 0rfNr) rrrrr9rmr7rnrRrrfrdrrsE$L$L1rfrc(eZdZdZddZddZddZy)rz;Generate optimized IR for a for loop over an integer range.cb|j}||_||_||_|j ||_t |jrt |jrt}n(t|jr |j}nt}t|}|j||d|j||_|j|j |_|j|j"|j%|j|j&|j&yrH)rWrrrr end_targetr+rjr1r'r%rr#r]r^r$rXrornr\)rrrrrW index_typer^s rdrmz ForRange.inits,,"  !--g6 "9>> 27Nw||7\ 4J !',, / J'JZ( y)R0 77 B9@9V9VW[WaWa9bt((',,t~~tyy*QSWS\S\]rfc8|j}|j}|jdkDrdnd}|j|j |j ||j |j |||}|j||j|jy)Nrra>) rWr\rrbrnr^rrr]r)rrWr\cmprcs rdrPzForRange.gen_condition sz,,yyYY]c&& LL . T__d0SUXZ^   DOOT^^LrfcP|j}|j}t|jjrtt|j jrU|j t|j|j|t|jtj|}nA|j|j|j|t|jd|}|j|j|||j|j ||y)N+)rWr\r+rrjrint_opr1rnr^rrrADDrbr#rorrWr\new_vals rdrSzForRange.gen_steps,,yy #4>>#6#6 7>499UY  / LL&$[_  rfc8|jjyrx)rrPrs rdrPzForEnumerate.gen_condition[s ##%rfcl|jj|jjyrx)rrRrrs rdrRzForEnumerate.begin_body_s" !!#   "rfcl|jj|jjyrx)rrSrrs rdrSzForEnumerate.gen_stepcs" !  rfcl|jj|jjyrx)rrrrs rdrzForEnumerate.gen_cleanupgs" ""$ !!#rfNr)rr rr rYr rrrr,rrfrdrrHs#S  &#!$rfrc@eZdZdZd dZd dZd dZd dZd dZd dZ y) rz?Generate IR for a for loop of form `for x, ... in zip(a, ...)`.cyrrrs rdrzForZip.need_cleanuporprfc t|t|k(sJtt|dz Dcgc] }tc}|jgz|_g|_t |||jD]Q\}}}t|j||||j|jd}|j j|Sycc}w)NrtTr) rrangerr] cond_blocksgensrrMrWrr\append)rindexesexprs_rXrY next_blockr~s rdrmz ForZip.initts7|s5z)))38G q8H2IJQJLJdooM^^(* '*7E4;K;K'L " #E4) eT:t~~tyyY]C II  S !  "KsC ct|jD]Y\}}|j|t|jdz ks2|jj |j |[yr) enumeraterrPrrWrQr)rir~s rdrPzForZip.gen_conditions^ * AFAs    3tyy>A%% ++D,<,mypyc.primitives.generic_opsr?r@rArBmypyc.primitives.list_opsrCrDrEmypyc.primitives.misc_opsrFmypyc.primitives.registryrGmypyc.primitives.set_opsrHmypyc.primitives.str_opsrImypyc.primitives.tuple_opsrJrrerrrrrrrrrMrrrrrWrlrlrrrrrrrrrfrdrs#%     (,7IOMMcc=:/;? 2t8 ;' ;' ;' ;' ;'  ;'  ;' ;' ;'|.' .' .' .' .' ( .'  .' .'b- - -6-& -  -`"4 D ( !@ @H@(@  @  @F\ \ \ \ \  \  \\ \\~7 7 t.?,.?b6Y6Yr= |= @ SU5,U5pG?,G?T + & - &1,1<69|69r]]4!$<!$H$\$rf