B
    [bS              4   @   s  d 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mZ ddlmZmZ ddlmZ ddd	d
ddddddd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/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdC*ZdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwg4ZG dxdy dyeZdd{d|Zd}d~ ZdzS )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.

    )print_functiondivision)SnumbersRationalFloatLambda)string_typesrange)CodePrinter
Assignment)
precedenceZis_nanZis_infiniteZ	is_finiteZ	is_normalZclassifyfloorZceilroundZtruncZfractabsZsignumZis_sign_positiveZis_sign_negativeZmul_addc             C   s   |t j kS )N)r   One)baseexp r   2lib/python3.7/site-packages/sympy/printing/rust.py<lambda>I   s    r   Zrecip   c             C   s
   |t jkS )N)r   Half)r   r   r   r   r   r   J   s    Zsqrtc             C   s   |t j kS )N)r   r   )r   r   r   r   r   r   K   s    zsqrt().recipc             C   s   |t ddkS )N      )r   )r   r   r   r   r   r   L   s    Zcbrtc             C   s   | t jd kS )Nr   )r   r   )r   r   r   r   r   r   M   s    Zexp2r   c             C   s   |j S )N)
is_integer)r   r   r   r   r   r   N   s    Zpowir   c             C   s   |j  S )N)r   )r   r   r   r   r   r   O   s    Zpowfc             C   s   dS )NTr   )r   r   r   r   r   P   s    r   ZlnlogZlog2Zlog10Z
to_degreesZ
to_radiansmaxminZhypotsincostanasinacosatanatan2Zsin_cosZexp_m1Zln_1psinhcoshtanhasinhacoshatanh)* r,   r,   r,   r,   r   Zceilingr,   r,   r,   ZAbsZsignr,   r,   r,   ZPowr   r   r,   r,   r,   r,   r,   ZMaxZMinr,   r   r    r!   r"   r#   r$   r%   r,   r,   r,   r&   r'   r(   r)   r*   r+   ZabstractZalignofasZbecomeZboxbreakZconstcontinueZcrateZdoelseenumZexternfalsefinalfnforifimplinZletZloopZmacromatchmodZmoveZmutZoffsetofoverrideZprivprocZpubZpurerefreturnZSelfselfZsizeofZstaticZstructsuperZtraittruetypeZtypeofZunsafeZunsizedZuseZvirtualwherewhileyieldc                   s|  e Zd ZdZdZdZdddi dde dd	dd

Z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dM fd!d"	ZdN fd#d$	Zd%d& Zd'd( Zd)d* Zd+d, ZdOd-d.ZdPd/d0ZdQd1d2ZdRd3d4ZdSd5d6ZdTd7d8ZdUd9d:ZdVd;d<Z d=d> Z!d?d@ Z"dAdB Z#dCdD Z$dEdF Z%e$ Z# Z% Z& Z' Z(Z) fdGdHZ*dIdJ Z+dKdL Z,  Z-S )WRustCodePrinterz?A printer to convert python expressions to strings of Rust codeZ
_rust_codeZRustNauto   TF_)
orderZ	full_precZ	precisionuser_functionsZhumancontractdereferenceZerror_on_reservedZreserved_word_suffixinlinec             C   sN   t | | tt| _|di }| j| t|dg | _tt| _d S )NrK   rM   )	r   __init__dictknown_functionsgetupdateset_dereferencereserved_words)r?   settingsZ	userfuncsr   r   r   rO      s    
zRustCodePrinter.__init__c             C   s   |d S )N   r   )r?   pr   r   r   _rate_index_position   s    z$RustCodePrinter._rate_index_positionc             C   s   d| S )Nz%s;r   )r?   Z
codestringr   r   r   _get_statement   s    zRustCodePrinter._get_statementc             C   s   d| S )Nz// %sr   )r?   textr   r   r   _get_comment   s    zRustCodePrinter._get_commentc             C   s   d||f S )Nzconst %s: f64 = %s;r   )r?   namevaluer   r   r   _declare_number_const   s    z%RustCodePrinter._declare_number_constc             C   s
   |  |S )N)indent_code)r?   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 )N)r
   ).0ij)colsr   r   	<genexpr>  s    z;RustCodePrinter._traverse_matrix_indices.<locals>.<genexpr>)shaper
   )r?   ZmatZrowsr   )rg   r   _traverse_matrix_indices  s    
z(RustCodePrinter._traverse_matrix_indicesc          
   C   s\   g }g }d}xF|D ]>}| || || |j| |jd d  | d qW ||fS )Nz#for %(var)s in %(start)s..%(end)s {r   )varstartend})append_printlowerupper)r?   indicesZ
open_linesZclose_linesZ	loopstartre   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argsrp   Z	is_number)r?   exprr   r   r   _print_caller_var  s
    z!RustCodePrinter._print_caller_varc             C   sJ  |j j| jkr| j|j j }d}d}t|tr6|}n x|D ]\}}}||j r<P q<W |dk	rF|dkrd| |jd |t|jdkr| |jdd dndd }n`|dkrd	| |jd |d
 }n<|dkrd	| |jd |d
 }nd|| |jdd }|S n6t	|dr<t|j
tr<| |j
|j S | |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   z, r,   )rk   methodry   r   z%(var)s.%(method)s())rk   r|   r   z%(func)s(%(args)s))funcry   _imp_)r}   __name__rQ   
isinstancestrry   r{   rx   Z	stringifyhasattrr~   r   rp   Z_print_not_supported)r?   rz   Z	cond_funcr}   Zstylecondretr   r   r   _print_Function  s<    


0zRustCodePrinter._print_Functionc             C   s:   |j jr0|jjs0t|t|j |j}| |S | |S )N)r   r   r   rB   r   rp   r   )r?   rz   r   r   r   
_print_PowR  s    
zRustCodePrinter._print_Powc                s$   t t| |}|r|d S |S d S )NZ_f64)r@   rF   _print_Float)r?   rz   rw   r   )	__class__r   r   r   X  s    zRustCodePrinter._print_Floatc                s$   t t| |}|r|d S |S d S )NZ_i32)r@   rF   _print_Integer)r?   rz   rw   r   )r   r   r   r   _  s    zRustCodePrinter._print_Integerc             C   s"   t |jt |j }}d||f S )Nz%d_f64/%d.0)intrY   q)r?   rz   rY   r   r   r   r   _print_Rationalf  s    zRustCodePrinter._print_Rationalc             C   sd   |j }tj}tj}x4tt|jD ]"}||j| | 7 }||| 9 }q"W d| |j	j
| |f S )Nz%s[%s])ri   r   ZZeror   reversedr
   Zrankrs   rp   r   label)r?   rz   Zdimselemoffsetre   r   r   r   _print_Indexedj  s    zRustCodePrinter._print_Indexedc             C   s   |j jS )N)r   r^   )r?   rz   r   r   r   
_print_Idxt  s    zRustCodePrinter._print_Idxc             C   s   |j S )N)r^   )r?   rz   r   r   r   _print_Dummyw  s    zRustCodePrinter._print_Dummyc             C   s   dS )NEr   )r?   rz   rw   r   r   r   _print_Exp1z  s    zRustCodePrinter._print_Exp1c             C   s   dS )NZPIr   )r?   rz   rw   r   r   r   	_print_Pi}  s    zRustCodePrinter._print_Pic             C   s   dS )NZINFINITYr   )r?   rz   rw   r   r   r   _print_Infinity  s    zRustCodePrinter._print_Infinityc             C   s   dS )NZNEG_INFINITYr   )r?   rz   rw   r   r   r   _print_NegativeInfinity  s    z'RustCodePrinter._print_NegativeInfinityc             C   s   dS )NrA   r   )r?   rz   rw   r   r   r   _print_BooleanTrue  s    z"RustCodePrinter._print_BooleanTruec             C   s   dS )Nr2   r   )r?   rz   rw   r   r   r   _print_BooleanFalse  s    z#RustCodePrinter._print_BooleanFalsec             C   s   t | S )N)r   rq   )r?   rz   rw   r   r   r   _print_bool  s    zRustCodePrinter._print_boolc             C   s   dS )NZNANr   )r?   rz   rw   r   r   r   
_print_NaN  s    zRustCodePrinter._print_NaNc             C   s   |j d jdkrtdg }xt|j D ]\}\}}|dkrR|d| |  nF|t|j d kr~|dkr~|d  d7  < n|d  d| | 7  < | |}|| |d	 q(W | jd
 rd|S d|S d S )NTzAll 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) {rn   rN    
)	ry   r   
ValueError	enumeratero   rp   rx   	_settingsjoin)r?   rz   rb   re   ecZcode0r   r   r   _print_Piecewise  s    



z RustCodePrinter._print_Piecewisec             C   s:   ddl m} ||jd |jd f|jd df}| |S )Nr   )	Piecewiser   r   T)Zsympy.functionsr   ry   rp   )r?   rz   r   Z
_piecewiser   r   r   
_print_ITE  s    $zRustCodePrinter._print_ITEc             C   s"   d|j |j|j|j jd   f S )Nz%s[%s]r   )parentrf   re   ri   )r?   rz   r   r   r   _print_Matrix  s    zRustCodePrinter._print_Matrixc                s2   |j dkr&dd fdd|D  S tdd S )Nr   z[%s]z, c             3   s   | ]}  |V  qd S )N)rp   )rd   a)r?   r   r   rh     s    z4RustCodePrinter._print_MatrixBase.<locals>.<genexpr>zLFull Matrix Support in Rust need Crates (https://crates.io/keywords/matrix).)rg   r   r   )r?   Ar   )r?   r   _print_MatrixBase  s    
z!RustCodePrinter._print_MatrixBasec             C   s"   d|j |j|j|j jd   f S )Nz%s[%s]r   )r   rf   re   ri   )r?   rz   r   r   r   _print_MatrixElement  s    z$RustCodePrinter._print_MatrixElementc                s*   t t| |}|| jkr"d| S |S d S )Nz(*%s))r@   rF   _print_SymbolrU   )r?   rz   r^   )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   )IndexedBaserL   z%s = %s)	Zsympy.tensor.indexedr   lhsrhsr   ZhasZ_doprint_loopsrp   r[   )r?   rz   r   r   r   Zlhs_codeZrhs_coder   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
}x^t|D ]R\}}	|	dks|	dkr||	 qt||| 8 }|d|| |	f  ||| 7 }qtW |S )z0Accepts a string of code or a list of code linesTr,   z    ){ru   z{
z(
)rn   rv   c             S   s   g | ]}| d qS )z 	)lstrip)rd   liner   r   r   
<listcomp>  s    z/RustCodePrinter.indent_code.<locals>.<listcomp>c                s    g | ]}t tt|j qS r   )r   anymapendswith)rd   r   )	inc_tokenr   r   r     s    c                s    g | ]}t tt|j qS r   )r   r   r   
startswith)rd   r   )	dec_tokenr   r   r     s   r   r   z%s%s)r   r	   ra   
splitlinesr   r   ro   )
r?   codeZ
code_linesZtabZincreaseZdecreaseZprettylevelnr   r   )r   r   r   ra     s(    



zRustCodePrinter.indent_code)F)F)F)F)F)F)F)F)F)F).r   
__module____qualname____doc__ZprintmethodZlanguagerT   Z_default_settingsrO   rZ   r[   r]   r`   rc   rj   rt   r{   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   Z_print_DenseMatrixZ_print_MutableDenseMatrixZ_print_ImmutableMatrixZ_print_ImmutableDenseMatrixr   r   ra   __classcell__r   r   )r   r   rF      s^   3








	rF   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()];
    )rF   Zdoprint)rz   Z	assign_torW   r   r   r   	rust_code  s    mr   c             K   s   t t| f| dS )z3Prints Rust representation of the given expression.N)printr   )rz   rW   r   r   r   print_rust_codeo  s    r   )N)r   Z
__future__r   r   Z
sympy.corer   r   r   r   r   Zsympy.core.compatibilityr	   r
   Zsympy.printing.codeprinterr   r   Zsympy.printing.precedencer   rQ   rV   rF   r   r   r   r   r   r   <module>
   s   ;  '
p