U
    ZÊ¹jûR  ã                4   @  sr  d Z ddlmZ ddlmZ ddlmZmZmZm	Z	 ddl
mZ ddlmZ ddd	d
dd„ ddfdd„ ddfdd„ ddfdd„ ddfdd„ ddfdd„ ddfdd„ ddfgdd„ ddfgdd d!d"d#d$d%d&d'd(d)d*d+d,d-d.dd/œZd0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcg4ZG ddde„ deeƒZdkdgdh„Zdidj„ ZdfS )la  
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ÚceilÚabsÚsignumc                 C  s
   t |dƒS )Néÿÿÿÿr   ©ÚbaseÚexp© r   úR/var/www/html/bwave/python/venv/lib/python3.8/site-packages/sympy/printing/rust.pyÚ<lambda>I   ó    r   Zrecipé   c                 C  s
   t |dƒS )Ng      à?r   r   r   r   r   r   J   r   Úsqrtc                 C  s
   t |dƒS )Ng      à¿r   r   r   r   r   r   K   r   zsqrt().recipc                 C  s   |t ddƒkS )Né   é   )r   r   r   r   r   r   L   r   Zcbrtc                 C  s
   t | dƒS )Nr   r   r   r   r   r   r   M   r   Zexp2r   c                 C  s   |j S ©N©Ú
is_integerr   r   r   r   r   N   r   Zpowir   c                 C  s   |j  S r   r   r   r   r   r   r   O   r   Zpowfc                 C  s   dS )NTr   )r   r   r   r   r   P   r   r   ÚlnÚmaxÚminÚsinÚcosÚtanÚasinÚacosÚatanÚatan2ÚsinhÚcoshÚtanhÚasinhÚacoshÚatanh)r   ZceilingZAbsÚsignÚPowr   ÚlogZMaxZMinr!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r   ZabstractZalignofÚasZbecomeÚboxÚbreakÚconstÚcontinueZcrateÚdoÚelseÚenumZexternÚfalseÚfinalÚfnÚforÚifÚimplÚinZletÚloopÚmacroÚmatchÚmodÚmoveZmutZoffsetofÚoverrideZprivÚprocZpubZpureÚrefÚreturnÚSelfÚselfZsizeofZstaticÚstructÚsuperZtraitÚtrueÚtypeZtypeofÚunsafeZunsizedZuseZvirtualÚwhereÚwhileÚyieldc                      st  e Zd ZU dZdZdZeejfdi de	ƒ dœŽZde
d< i fd	d
„Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ ZdN‡ fd d!„	ZdO‡ fd"d#„	Zd$d%„ Zd&d'„ Zd(d)„ Zd*d+„ Zd,d-„ ZdPd.d/„ZdQd0d1„ZdRd2d3„ZdSd4d5„Z dTd6d7„Z!dUd8d9„Z"dVd:d;„Z#dWd<d=„Z$d>d?„ Z%d@dA„ Z&dBdC„ Z'dDdE„ Z(dFdG„ Z)‡ fdHdI„Z*dJdK„ Z+dLdM„ Z,‡  Z-S )XÚRustCodePrinterz>A printer to convert SymPy expressions to strings of Rust codeZ
_rust_codeÚRusté   T)Ú	precisionÚuser_functionsÚcontractÚdereferencezdict[str, Any]Ú_default_settingsc                 C  sN   t  | |¡ ttƒ| _| di ¡}| j |¡ t| dg ¡ƒ| _ttƒ| _d S )NrW   rY   )	r
   Ú__init__ÚdictÚknown_functionsÚgetÚupdateÚsetÚ_dereferenceÚreserved_words)rJ   ÚsettingsZ	userfuncsr   r   r   r[   ç   s    
zRustCodePrinter.__init__c                 C  s   |d S )Né   r   )rJ   Úpr   r   r   Ú_rate_index_positionï   s    z$RustCodePrinter._rate_index_positionc                 C  s   d| S )Nz%s;r   )rJ   Z
codestringr   r   r   Ú_get_statementò   s    zRustCodePrinter._get_statementc                 C  s   d| S )Nz// %sr   )rJ   Útextr   r   r   Ú_get_commentõ   s    zRustCodePrinter._get_commentc                 C  s   d||f S )Nzconst %s: f64 = %s;r   )rJ   ÚnameÚvaluer   r   r   Ú_declare_number_constø   s    z%RustCodePrinter._declare_number_constc                 C  s
   |   |¡S r   )Úindent_code)rJ   Úlinesr   r   r   Ú_format_codeû   s    zRustCodePrinter._format_codec                   s    |j \}‰ ‡ fdd„t|ƒD ƒS )Nc                 3  s$   | ]}t ˆ ƒD ]}||fV  qqd S r   )Úrange)Ú.0ÚiÚj©Úcolsr   r   Ú	<genexpr>   s     
  z;RustCodePrinter._traverse_matrix_indices.<locals>.<genexpr>)Úshaperp   )rJ   ÚmatÚrowsr   rt   r   Ú_traverse_matrix_indicesþ   s    
z(RustCodePrinter._traverse_matrix_indicesc              
   C  sX   g }g }d}|D ]>}|  ||  |¡|  |j¡|  |jd ¡dœ ¡ |  d¡ q||fS )Nz#for %(var)s in %(start)s..%(end)s {r   )ÚvarÚstartÚendÚ})ÚappendÚ_printÚlowerÚupper)rJ   ÚindicesZ
open_linesZclose_linesZ	loopstartrr   r   r   r   Ú_get_loop_opening_ending  s    
ý
z(RustCodePrinter._get_loop_opening_endingc                 C  sB   t |jƒdkr d|  |¡ d S |jr4| j|dd�S |  |¡S d S )Nr   ú(ú)T)Ú_type)ÚlenÚargsr€   Z	is_number©rJ   Úexprr   r   r   Ú_print_caller_var  s
    z!RustCodePrinter._print_caller_varc           	        s   |j jˆ jk�rˆ j|j j }d}d}t|tƒr6|}n|D ]\}}}||jŽ r: qTq:|dk	�rœ|dkr¨dˆ  |jd ¡|t|jƒdkrœˆ  |jdd… d¡nddœ }n`|dkrÌd	ˆ  |jd ¡|d
œ }n<|dkrðd	ˆ  |jd ¡|d
œ }nd|ˆ  |jd¡dœ }|S nŽt	|dƒ�r:t|j
tƒ�r:ˆ  |j
|jŽ ¡S |j jˆ jk�r’ˆ j|j j \}}ˆ  |¡�rœt‡ fdd„|D ƒƒ�rœˆ  | |¡¡S n
ˆ  |¡S dS )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  s   | ]}ˆ   |¡V  qd S r   )Ú
_can_print)rq   Úf©rJ   r   r   rv   M  s     z2RustCodePrinter._print_Function.<locals>.<genexpr>)r�   Ú__name__r]   Ú
isinstanceÚstrr‰   rŒ   rˆ   Ú	stringifyÚhasattrr‘   r   r€   Z_rewriteable_functionsr’   ÚallÚrewriteÚ_print_not_supported)	rJ   r‹   Z	cond_funcr�   ÚstyleÚcondÚretZtarget_fZrequired_fsr   r”   r   Ú_print_Function  sL    


&ý
þ
þ
þ$zRustCodePrinter._print_Functionc                 C  s:   |j jr0|jjs0t|ƒt|j ƒ|jƒ}|  |¡S |  |¡S r   )r   r   r   rN   r   r€   r    rŠ   r   r   r   Ú
_print_PowR  s    
zRustCodePrinter._print_PowFc                   s    t ƒ  |¡}|r|d S |S d S )NZ_f64)rL   Ú_print_Float©rJ   r‹   r‡   rŸ   ©Ú	__class__r   r   r¢   X  s    zRustCodePrinter._print_Floatc                   s    t ƒ  |¡}|r|d S |S d S )NZ_i32)rL   Ú_print_Integerr£   r¤   r   r   r¦   _  s    zRustCodePrinter._print_Integerc                 C  s"   t |jƒt |jƒ }}d||f S )Nz%d_f64/%d.0)Úintre   Úq)rJ   r‹   re   r¨   r   r   r   Ú_print_Rationalf  s    zRustCodePrinter._print_Rationalc                 C  s,   |   |j¡}|   |j¡}|j}d |||¡S )Nz{} {} {})r€   ÚlhsÚrhsZrel_opÚformat)rJ   r‹   Úlhs_codeÚrhs_codeÚopr   r   r   Ú_print_Relationalj  s    z!RustCodePrinter._print_Relationalc                 C  s`   |j }tj}tj}tt|jƒƒD ]"}||j| | 7 }||| 9 }q d|  |j	j
¡|  |¡f S )Nú%s[%s])rw   r   ZZeroZOneÚreversedrp   Zrankrƒ   r€   r   Úlabel)rJ   r‹   ZdimsÚelemÚoffsetrr   r   r   r   Ú_print_Indexedp  s    zRustCodePrinter._print_Indexedc                 C  s   |j jS r   )r³   rj   rŠ   r   r   r   Ú
_print_Idxz  s    zRustCodePrinter._print_Idxc                 C  s   |j S r   )rj   rŠ   r   r   r   Ú_print_Dummy}  s    zRustCodePrinter._print_Dummyc                 C  s   dS )NÚEr   ©rJ   r‹   r‡   r   r   r   Ú_print_Exp1€  s    zRustCodePrinter._print_Exp1c                 C  s   dS )NZPIr   rº   r   r   r   Ú	_print_Piƒ  s    zRustCodePrinter._print_Pic                 C  s   dS )NÚINFINITYr   rº   r   r   r   Ú_print_Infinity†  s    zRustCodePrinter._print_Infinityc                 C  s   dS )NZNEG_INFINITYr   rº   r   r   r   Ú_print_NegativeInfinity‰  s    z'RustCodePrinter._print_NegativeInfinityc                 C  s   dS )NrM   r   rº   r   r   r   Ú_print_BooleanTrueŒ  s    z"RustCodePrinter._print_BooleanTruec                 C  s   dS )Nr9   r   rº   r   r   r   Ú_print_BooleanFalse�  s    z#RustCodePrinter._print_BooleanFalsec                 C  s   t |ƒ ¡ S r   )r—   r�   rº   r   r   r   Ú_print_bool’  s    zRustCodePrinter._print_boolc                 C  s   dS )NZNANr   rº   r   r   r   Ú
_print_NaN•  s    zRustCodePrinter._print_NaNc                 C  sØ   |j d jdkrtdƒ‚g }t|j ƒD ]Ž\}\}}|dkrP| d|  |¡ ¡ nF|t|j ƒd kr||dkr||d  d7  < n|d  d|  |¡ 7  < |  |¡}| |¡ | d	¡ q&| jd
 rÊd |¡S d |¡S d S )Nr   Tz¼All 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)rJ   r‹   rn   rr   ÚeÚcZcode0r   r   r   Ú_print_Piecewise˜  s    



z RustCodePrinter._print_Piecewisec                 C  s    ddl m} |  |j|dd�¡S )Nr   )Ú	PiecewiseF)Údeep)Zsympy.functionsrÎ   r€   r›   )rJ   r‹   rÎ   r   r   r   Ú
_print_ITE³  s    zRustCodePrinter._print_ITEc                   s2   |j dkr&dd ‡ fdd„|D ƒ¡ S tdƒ‚d S )Nr   z[%s]r�   c                 3  s   | ]}ˆ   |¡V  qd S r   )r€   )rq   Úar”   r   r   rv   ¹  s     z4RustCodePrinter._print_MatrixBase.<locals>.<genexpr>zLFull Matrix Support in Rust need Crates (https://crates.io/keywords/matrix).)ru   rÊ   rÇ   )rJ   ÚAr   r”   r   Ú_print_MatrixBase·  s    
z!RustCodePrinter._print_MatrixBasec                 C  s
   |   |¡S r   )rœ   )rJ   rx   r   r   r   Ú_print_SparseRepMatrix½  s    z&RustCodePrinter._print_SparseRepMatrixc                 C  s"   d|j |j|j|j jd   f S )Nr±   r   )Úparentrs   rr   rw   rŠ   r   r   r   Ú_print_MatrixElementÁ  s    ÿz$RustCodePrinter._print_MatrixElementc                   s&   t ƒ  |¡}|| jkrd| S |S d S )Nz(*%s))rL   Ú_print_Symbolra   )rJ   r‹   rj   r¤   r   r   r×   Å  s    
zRustCodePrinter._print_Symbolc                 C  sl   ddl m} |j}|j}| jd rB| |¡s6| |¡rB|  ||¡S |  |¡}|  |¡}|  d||f ¡S d S )Nr   )ÚIndexedBaserX   z%s = %s)	Zsympy.tensor.indexedrØ   rª   r«   rÉ   ÚhasZ_doprint_loopsr€   rg   )rJ   r‹   rØ   rª   r«   r­   r®   r   r   r   Ú_print_AssignmentÎ  s    ÿ

z!RustCodePrinter._print_Assignmentc           
        sÂ   t |tƒr$|  | d¡¡}d |¡S d}d‰d‰ dd„ |D ƒ}‡fdd„|D ƒ}‡ fd	d„|D ƒ}g }d
}t|ƒD ]J\}}	|	dkrŽ| |	¡ qr||| 8 }| d|| |	f ¡ ||| 7 }qr|S )z0Accepts a string of code or a list of code linesTrŽ   z    )Ú{r…   z{
z(
)r~   r†   c                 S  s   g | ]}|  d ¡‘qS )z 	)Úlstrip©rq   Úliner   r   r   Ú
<listcomp>ç  s     z/RustCodePrinter.indent_code.<locals>.<listcomp>c                   s    g | ]}t tt|jˆ ƒƒƒ‘qS r   )r§   ÚanyÚmapÚendswithrÝ   )Ú	inc_tokenr   r   rß   é  s     c                   s    g | ]}t tt|jˆ ƒƒƒ‘qS r   )r§   rà   rá   Ú
startswithrÝ   )Ú	dec_tokenr   r   rß   ê  s   ÿr   )rŽ   rÆ   z%s%s)r–   r—   rm   Ú
splitlinesrÊ   rÈ   r   )
rJ   ÚcodeZ
code_linesÚtabZincreaseZdecreaseÚprettyÚlevelÚnrÞ   r   )rå   rã   r   rm   Ü  s*    


ÿ
zRustCodePrinter.indent_code)F)F)F)F)F)F)F)F)F)F).r•   Ú
__module__Ú__qualname__Ú__doc__ZprintmethodÚlanguager\   r
   rZ   r`   Ú__annotations__r[   rf   rg   ri   rl   ro   rz   r„   rŒ   r    r¡   r¢   r¦   r©   r°   r¶   r·   r¸   r»   r¼   r¾   r¿   rÀ   rÁ   rÂ   rÃ   rÍ   rÐ   rÓ   rÔ   rÖ   r×   rÚ   rm   Ú__classcell__r   r   r¤   r   rS   Û   sV   
ü8








	rS   Nc                 K  s   t |ƒ | |¡S )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()];
    )rS   Zdoprint)r‹   Z	assign_torc   r   r   r   Ú	rust_codeù  s    mrò   c                 K  s   t t| f|Žƒ dS )z3Prints Rust representation of the given expression.N)Úprintrò   )r‹   rc   r   r   r   Úprint_rust_codei  s    rô   )N)rî   Ú
__future__r   Útypingr   Z
sympy.corer   r   r   r   Zsympy.core.numbersr	   Zsympy.printing.codeprinterr
   r]   rb   rS   rò   rô   r   r   r   r   Ú<module>   s¼   !úÏlÍ6   
p