
    ЦiR                    J   S r SSKJr  SSKJr  SSKJrJrJrJ	r	  SSK
Jr  SSKJr  0 SS_SS	_S
S_SS_SS SS4S SS4S SS4S SS4S SS4S SS4S SS4/_S S! S S4/_S"S#_S$S%_S&S'_S(S(_S)S)_S*S*_S+S+_S,S,_S-S-_S.S._S/S/_S0S1S2S3S4SS5.Er/ S6Qr " S7 S8\5      rS<S: jrS; rg9)=a  
Rust code printer

The `RustCodePrinter` converts SymPy expressions into Rust expressions.

A complete code generator, which uses `rust_code` extensively, can be found
in `sympy.utilities.codegen`. The `codegen` module can be used to generate
complete source code files.

    )annotations)Any)SRationalFloatLambdaequal_valued)CodePrinterfloorceilingceilAbsabssignsignumPowc                    [        US5      $ )Nr	   baseexps     R/var/www/html/ai-image-ml/venv/lib/python3.13/site-packages/sympy/printing/rust.py<lambda>r   I   s    |C4    recip   c                    [        US5      $ )Ng      ?r	   r   s     r   r   r   J   s    |C5r   sqrtc                    [        US5      $ )Ng      r	   r   s     r   r   r   K   s    |C6r   zsqrt().recipc                     U[        SS5      :H  $ )N      )r   r   s     r   r   r   L   s    shq!n4r   cbrtc                    [        U S5      $ )Nr   r	   r   s     r   r   r   M   s    |D!4r   exp2r#   c                    UR                   $ N
is_integerr   s     r   r   r   N   s    s~~r   powir"   c                $    UR                   (       + $ r(   r)   r   s     r   r   r   O   s    3>>1r   powfr   c                    g)NT )r   s    r   r   r   P   s    r   loglnMaxmaxMinminsincostanasinacosatanatan2sinhcoshtanhasinhacoshatanh)r>   r?   r@   rA   rB   r   )4abstractalignofasbecomeboxbreakconstcontinuecratedoelseenumexternfalsefinalfnforifimplinletloopmacromatchmodmovemutoffsetofoverrideprivprocpubpurerefreturnSelfselfsizeofstaticstructsupertraittruetypetypeofunsafeunsizedusevirtualwherewhileyieldc            	      z  ^  \ rS rSr% SrSrSr\" \R                  40 S0 S\
" 5       S.D6r	S\S	'   0 4S
 jrS rS rS rS rS rS rS rS rS rS rS-U 4S jjrS-U 4S jjrS rS rS rS rS 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$S-S# jr%S$ r&S% r'S& r(S' r)S( r*U 4S) jr+S* r,S+ r-S,r.U =r/$ ).RustCodePrinter   z>A printer to convert SymPy expressions to strings of Rust code
_rust_codeRust   T)	precisionuser_functionscontractdereferencezdict[str, Any]_default_settingsc                   [         R                  " X5        [        [        5      U l        UR	                  S0 5      nU R                  R                  U5        [        UR	                  S/ 5      5      U l        [        [        5      U l        g )Nr~   r   )	r   __init__dictknown_functionsgetupdateset_dereferencereserved_words)rg   settings	userfuncss      r   r   RustCodePrinter.__init__   sg    T,#O4LL!126	##I.]B ?@!.1r   c                    US-  $ )N   r/   )rg   ps     r   _rate_index_position$RustCodePrinter._rate_index_position   s    s
r   c                    SU-  $ )Nz%s;r/   )rg   
codestrings     r   _get_statementRustCodePrinter._get_statement   s    z!!r   c                    SU-  $ )Nz// %sr/   )rg   texts     r   _get_commentRustCodePrinter._get_comment   s    ~r   c                    SU< SU< S3$ )Nzconst z: f64 = ;r/   )rg   namevalues      r   _declare_number_const%RustCodePrinter._declare_number_const   s    (,e44r   c                $    U R                  U5      $ r(   )indent_code)rg   liness     r   _format_codeRustCodePrinter._format_code   s    &&r   c                L   ^ UR                   u  nmU4S j[        U5       5       $ )Nc              3  P   >#    U  H  n[        T5        H  o!U4v   M
     M     g 7fr(   )range).0ijcolss      r   	<genexpr>;RustCodePrinter._traverse_matrix_indices.<locals>.<genexpr>   s     A1U4[A[s   #&)shaper   )rg   matrowsr   s      @r   _traverse_matrix_indices(RustCodePrinter._traverse_matrix_indices   s    YY
dAdAAr   c           
         / n/ nSnU Hp  nUR                  UU R                  U5      U R                  UR                  5      U R                  UR                  S-   5      S.-  5        UR                  S5        Mr     X#4$ )Nz#for %(var)s in %(start)s..%(end)s {r"   )varstartend})append_printlowerupper)rg   indices
open_linesclose_lines	loopstartr   s         r   _get_loop_opening_ending(RustCodePrinter._get_loop_opening_ending  s    
9	Ai{{1~QWW-{{177Q;/+1 1 2 s#  &&r   c                    [        UR                  5      S:  a  SU R                  U5      -   S-   $ UR                  (       a  U R                  USS9$ U R                  U5      $ )Nr"   ()T)_type)lenargsr   	is_numberrg   exprs     r   _print_caller_var!RustCodePrinter._print_caller_var  sV    tyy>A T**S00^^;;t4;00;;t$$r   c                  ^  UR                   R                  T R                  ;   GaF  T R                  UR                   R                     nSnSn[        U[        5      (       a  UnO"U H  u  pSnU" UR
                  6 (       d  M    O   Ub  US:X  a_  ST R                  UR
                  S   5      U[        UR
                  5      S:  a  T R                  UR
                  SS S5      OSS.-  nU$ US:X  a&  S	T R                  UR
                  S   5      US
.-  nU$ US:X  a&  S	T R                  UR
                  S   5      US
.-  nU$ SUT R                  UR
                  S5      S.-  nU$ g[        US5      (       aG  [        UR                  [        5      (       a(  T R                  UR                  " UR
                  6 5      $ UR                   R                  T R                  ;   aw  T R                  UR                   R                     u  pxT R                  U5      (       a;  [        U 4S jU 5       5      (       a   T R                  UR!                  U5      5      $ ggT R#                  U5      $ )a  
basic function for printing `Function`

Function Style :

1. args[0].func(args[1:]), method with arguments
2. args[0].func(), method without arguments
3. args[1].func(), method without arguments (e.g. (e, x) => x.exp())
4. func(args), function with arguments
Nr"   z%(var)s.%(method)s(%(args)s)r   ,  )r   methodr   r   z%(var)s.%(method)s())r   r   r#   z%(func)s(%(args)s))funcr   _imp_c              3  F   >#    U  H  nTR                  U5      v   M     g 7fr(   )
_can_print)r   frg   s     r   r   2RustCodePrinter._print_Function.<locals>.<genexpr>M  s     0Y[1C1C[   !)r   __name__r   
isinstancestrr   r   r   	stringifyhasattrr   r   r   _rewriteable_functionsr   allrewrite_print_not_supported)	rg   r   	cond_funcr   stylecondrettarget_frequired_fss	   `        r   _print_FunctionRustCodePrinter._print_Function  sB    99!5!55,,TYY-?-?@IDE)S)) )2%DTYY'' *3 A:8#55diilC"&GJ499~XYGYtyy}d C_a< C( 
 aZ0#55diilC"&4 C 
 aZ0#55diilC"&4 C 
	 / $ $tyy$ ?2 C 
-  . T7##
4::v(F(F;;tzz499566YY4#>#>>$($?$?		@R@R$S!Hx((S0Y[0Y-Y-Y{{4<<#9:: .Z( ,,T22r   c                   UR                   R                  (       a[  UR                  R                  (       d@  [        U5      " [	        UR                   5      UR                  5      nU R                  U5      $ U R                  U5      $ r(   )r   r*   r   rn   r   r   r   r   s     r   
_print_PowRustCodePrinter._print_PowR  sX    99(;(;:eDII.9D;;t$$##D))r   c                >   > [         TU ]  U5      nU(       a  US-   $ U$ )N_f64)rk   _print_Floatrg   r   r   r   	__class__s       r   r   RustCodePrinter._print_FloatX  s$    g"4(<Jr   c                >   > [         TU ]  U5      nU(       a  US-   $ U$ )N_i32)rk   _print_Integerr   s       r   r   RustCodePrinter._print_Integer_  s$    g$T*<Jr   c                `    [        UR                  5      [        UR                  5      p2SX#4-  $ )Nz%d_f64/%d.0)intr   q)rg   r   r   r   s       r   _print_RationalRustCodePrinter._print_Rationalf  s&    466{CK1v%%r   c                    U R                  UR                  5      nU R                  UR                  5      nUR                  nSR	                  X$U5      $ )Nz{} {} {})r   lhsrhsrel_opformat)rg   r   lhs_coderhs_codeops        r   _print_Relational!RustCodePrinter._print_Relationalj  sB    ;;txx(;;txx([[  x88r   c                R   UR                   n[        R                  n[        R                  n[	        [        UR                  5      5       H  nX1R                  U   U-  -  nXBU   -  nM      U R                  UR                  R                  5      < SU R                  U5      < S3$ )N[])r   r   ZeroOnereversedr   rankr   r   r   label)rg   r   dimselemoffsetr   s         r   _print_IndexedRustCodePrinter._print_Indexedp  s}    zzvv%		*+ALLOF**D1gF ,  ;;tyy7T9JKKr   c                .    UR                   R                  $ r(   )r  r   r   s     r   
_print_IdxRustCodePrinter._print_Idxz  s    zzr   c                    UR                   $ r(   )r   r   s     r   _print_DummyRustCodePrinter._print_Dummy}  s    yyr   c                    g)NEr/   rg   r   r   s      r   _print_Exp1RustCodePrinter._print_Exp1  s    r   c                    g)NPIr/   r  s      r   	_print_PiRustCodePrinter._print_Pi  s    r   c                    g)NINFINITYr/   r  s      r   _print_InfinityRustCodePrinter._print_Infinity  s    r   c                    g)NNEG_INFINITYr/   r  s      r   _print_NegativeInfinity'RustCodePrinter._print_NegativeInfinity  s    r   c                    g)Nrm   r/   r  s      r   _print_BooleanTrue"RustCodePrinter._print_BooleanTrue  s    r   c                    g)NrP   r/   r  s      r   _print_BooleanFalse#RustCodePrinter._print_BooleanFalse  s    r   c                4    [        U5      R                  5       $ r(   )r   r   r  s      r   _print_boolRustCodePrinter._print_bool  s    4y  r   c                    g)NNANr/   r  s      r   
_print_NaNRustCodePrinter._print_NaN  s    r   c                \   UR                   S   R                  S:w  a  [        S5      e/ n[        UR                   5       H  u  nu  pEUS:X  a$  UR	                  SU R                  U5      -  5        OOU[        UR                   5      S-
  :X  a  US:X  a  US==   S-  ss'   OUS==   SU R                  U5      -  -  ss'   U R                  U5      nUR	                  U5        UR	                  S	5        M     U R                  S
   (       a  SR                  U5      $ SR                  U5      $ )Nr   TzAll Piecewise expressions must contain an (expr, True) statement to be used as a default condition. Without one, the generated expression may not evaluate to anything under some condition.r   z	if (%s) {r"   z else {z else if (%s) {r   inline 
)	r   r   
ValueError	enumerater   r   r   	_settingsjoin)rg   r   r   r   eccode0s          r   _print_Piecewise RustCodePrinter._print_Piecewise  s   99R=%  / 0 0
 "499-IAvAv[4;;q>9:c$))nq((Q$Yb	Y&	b	.Q??	KKNELLLL . >>(#88E?"99U##r   c                L    SSK Jn  U R                  UR                  USS95      $ )Nr   )	PiecewiseF)deep)sympy.functionsrE  r   r   )rg   r   rE  s      r   
_print_ITERustCodePrinter._print_ITE  s!    -{{4<<	<>??r   c                v   ^  UR                   S:X  a  SSR                  U 4S jU 5       5      -  $ [        S5      e)Nr"   z[%s]r   c              3  F   >#    U  H  nTR                  U5      v   M     g 7fr(   )r   )r   arg   s     r   r   4RustCodePrinter._print_MatrixBase.<locals>.<genexpr>  s     %@adkk!nnar   zLFull Matrix Support in Rust need Crates (https://crates.io/keywords/matrix).)r   r>  r;  )rg   As   ` r   _print_MatrixBase!RustCodePrinter._print_MatrixBase  s4    66Q;DII%@a%@@@@kllr   c                $    U R                  U5      $ r(   )r   )rg   r   s     r   _print_SparseRepMatrix&RustCodePrinter._print_SparseRepMatrix  s    ((--r   c                    UR                   < SUR                  UR                  UR                   R                  S   -  -   < S3$ )Nr  r"   r  )parentr   r   r   r   s     r   _print_MatrixElement$RustCodePrinter._print_MatrixElement  s9    ;;66DFF4;;+<+<Q+?$??A 	Ar   c                N   > [         TU ]  U5      nXR                  ;   a  SU-  $ U$ )Nz(*%s))rk   _print_Symbolr   )rg   r   r   r   s      r   rY  RustCodePrinter._print_Symbol  s-    w$T*$$$T>!Kr   c                T   SSK Jn  UR                  nUR                  nU R                  S   (       a=  UR                  U5      (       d  UR                  U5      (       a  U R                  XC5      $ U R                  U5      nU R                  U5      nU R                  U< SU< 35      $ )Nr   )IndexedBaser   z = )	sympy.tensor.indexedr\  r   r   r=  has_doprint_loopsr   r   )rg   r   r\  r   r   r  r  s          r   _print_Assignment!RustCodePrinter._print_Assignment  s    4hhhh>>*%377;+?+?$$ &&s00{{3'H{{3'H&&Hh'GHHr   c                   [        U[        5      (       a1  U R                  UR                  S5      5      nSR	                  U5      $ SnSnSnU Vs/ s H  ofR                  S5      PM     nnU Vs/ s H+  n[        [        [        UR                  U5      5      5      PM-     nnU Vs/ s H+  n[        [        [        UR                  U5      5      5      PM-     nn/ n	Sn
[        U5       HE  u  pUS;   a  U	R                  U5        M  XU   -  n
U	R                  X:-  < U< 35        XU   -  n
MG     U	$ s  snf s  snf s  snf )	z0Accepts a string of code or a list of code linesTr   z    ){r   z{
z(
)r   r   z 	r   )r   r:  )r   r   r   
splitlinesr>  lstripr   anymapendswith
startswithr<  r   )rg   code
code_linestab	inc_token	dec_tokenlineincreasedecreaseprettylevelns               r   r   RustCodePrinter.indent_code  s3    dC  ))$//$*?@J77:&&,		046U#6IMOSS	:;<O!%(!% S)<=>!% 	 (  GAz!d#a[ EMMCIt45a[ E '  7O(s   D712D<)2E)r   r   r   )F)0r   
__module____qualname____firstlineno____doc__printmethodlanguager   r   r   r   __annotations__r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r   r$  r(  r+  r.  r1  r5  rB  rH  rO  rR  rV  rY  r`  r   __static_attributes____classcell__)r   s   @r   rx   rx      s    HKH(,[-J-J )u	O )~  !# 2"5'B'	%63p*&9L!$6@m.AI r   rx   Nc                6    [        U5      R                  X5      $ )a
  Converts an expr to a string of Rust code

Parameters
==========

expr : Expr
    A SymPy expression to be converted.
assign_to : optional
    When given, the argument is used as the name of the variable to which
    the expression is assigned. Can be a string, ``Symbol``,
    ``MatrixSymbol``, or ``Indexed`` type. This is helpful in case of
    line-wrapping, or for expressions that generate multi-line statements.
precision : integer, optional
    The precision for numbers such as pi [default=15].
user_functions : dict, optional
    A dictionary where the keys are string representations of either
    ``FunctionClass`` or ``UndefinedFunction`` instances and the values
    are their desired C string representations. Alternatively, the
    dictionary value can be a list of tuples i.e. [(argument_test,
    cfunction_string)].  See below for examples.
dereference : iterable, optional
    An iterable of symbols that should be dereferenced in the printed code
    expression. These would be values passed by address to the function.
    For example, if ``dereference=[a]``, the resulting code would print
    ``(*a)`` instead of ``a``.
human : bool, optional
    If True, the result is a single string that may contain some constant
    declarations for the number symbols. If False, the same information is
    returned in a tuple of (symbols_to_declare, not_supported_functions,
    code_text). [default=True].
contract: bool, optional
    If True, ``Indexed`` instances are assumed to obey tensor contraction
    rules and the corresponding nested loops over indices are generated.
    Setting contract=False will not generate loops, instead the user is
    responsible to provide values for the indices in the code.
    [default=True].

Examples
========

>>> from sympy import rust_code, symbols, Rational, sin, ceiling, Abs, Function
>>> x, tau = symbols("x, tau")
>>> rust_code((2*tau)**Rational(7, 2))
'8*1.4142135623731*tau.powf(7_f64/2.0)'
>>> rust_code(sin(x), assign_to="s")
's = x.sin();'

Simple custom printing can be defined for certain types by passing a
dictionary of {"type" : "function"} to the ``user_functions`` kwarg.
Alternatively, the dictionary value can be a list of tuples i.e.
[(argument_test, cfunction_string)].

>>> custom_functions = {
...   "ceiling": "CEIL",
...   "Abs": [(lambda x: not x.is_integer, "fabs", 4),
...           (lambda x: x.is_integer, "ABS", 4)],
...   "func": "f"
... }
>>> func = Function('func')
>>> rust_code(func(Abs(x) + ceiling(x)), user_functions=custom_functions)
'(fabs(x) + x.CEIL()).f()'

``Piecewise`` expressions are converted into conditionals. If an
``assign_to`` variable is provided an if statement is created, otherwise
the ternary operator is used. Note that if the ``Piecewise`` lacks a
default term, represented by ``(expr, True)`` then an error will be thrown.
This is to prevent generating an expression that may not evaluate to
anything.

>>> from sympy import Piecewise
>>> expr = Piecewise((x + 1, x > 0), (x, True))
>>> print(rust_code(expr, tau))
tau = if (x > 0) {
    x + 1
} else {
    x
};

Support for loops is provided through ``Indexed`` types. With
``contract=True`` these expressions will be turned into loops, whereas
``contract=False`` will just print the assignment expression that should be
looped over:

>>> from sympy import Eq, IndexedBase, Idx
>>> len_y = 5
>>> y = IndexedBase('y', shape=(len_y,))
>>> t = IndexedBase('t', shape=(len_y,))
>>> Dy = IndexedBase('Dy', shape=(len_y-1,))
>>> i = Idx('i', len_y-1)
>>> e=Eq(Dy[i], (y[i+1]-y[i])/(t[i+1]-t[i]))
>>> rust_code(e.rhs, assign_to=e.lhs, contract=False)
'Dy[i] = (y[i + 1] - y[i])/(t[i + 1] - t[i]);'

Matrices are also supported, but a ``MatrixSymbol`` of the same dimensions
must be provided to ``assign_to``. Note that any expression that can be
generated normally can also exist inside a Matrix:

>>> from sympy import Matrix, MatrixSymbol
>>> mat = Matrix([x**2, Piecewise((x + 1, x > 0), (x, True)), sin(x)])
>>> A = MatrixSymbol('A', 3, 1)
>>> print(rust_code(mat, A))
A = [x.powi(2), if (x > 0) {
    x + 1
} else {
    x
}, x.sin()];
)rx   doprint)r   	assign_tor   s      r   	rust_coder    s    Z 8$,,T==r   c                .    [        [        U 40 UD65        g)z3Prints Rust representation of the given expression.N)printr  )r   r   s     r   print_rust_coder  i  s    	)D
%H
%&r   r(   )ry  
__future__r   typingr   
sympy.corer   r   r   r   sympy.core.numbersr
   sympy.printing.codeprinterr   r   r   rx   r  r  r/   r   r   <module>r     s  	B #  1 1 + 2$2 W2 v2 
52 H2  
4gqA5vqA6J4fa@4fa@-vq9161=?!2. 
ua()/20 
412< 
5=2> 
5?2B 
5C2D 
5E2F 
5G2H FI2J FK2L FM2N WO2V FW2X c2X3l[k [|m>`'r   