o
    ohR                     @  sV  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 i 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!dfgd#d$d%d&d'd(d)d)d*d*d+d+d,d,d-d-d.d.d/d/d0d0d1d2d3d4d5dd6Zg d7ZG d8d9 d9eZd?d;d<Zd=d> Zd:S )@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                 C  
   t |dS )Nr   baseexp r   g/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/sympy/printing/rust.py<lambda>I      
 r   recip   c                 C  r   )Ng      ?r   r   r   r   r   r   J   r   sqrtc                 C  r   )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   s    cbrtc                 C  s
   t | dS )Nr   r   r   r   r   r   r   M   r   exp2r    c                 C     |j S N
is_integerr   r   r   r   r   N   s    powir   c                 C  s   |j  S r$   r%   r   r   r   r   r   O   s    powfr   c                 C     dS )NTr   )r   r   r   r   r   P   s    loglnMaxmaxMinminsincostanasinacosatanatan2sinhcoshtanhasinhacoshatanh)r8   r9   r:   r;   r<   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                      sx  e Zd ZU dZdZdZeejfi 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dN fd"d#	Zd$d% Zd&d' Zd(d) Zd*d+ Zd,d- ZdNd.d/ZdNd0d1ZdNd2d3ZdNd4d5Z dNd6d7Z!dNd8d9Z"dNd:d;Z#dNd<d=Z$d>d? Z%d@dA Z&dBdC Z'dDdE Z(dFdG Z) fdHdIZ*dJdK Z+dLdM Z,  Z-S )ORustCodePrinterz>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                 C  sN   t | | tt| _|di }| j| t|dg | _tt| _d S )Nrv   rx   )	r
   __init__dictknown_functionsgetupdateset_dereferencereserved_words)ra   settings	userfuncsr   r   r   rz      s   
zRustCodePrinter.__init__c                 C  s   |d S )N   r   )ra   pr   r   r   _rate_index_position      z$RustCodePrinter._rate_index_positionc                 C     d| S )Nz%s;r   )ra   
codestringr   r   r   _get_statement   r   zRustCodePrinter._get_statementc                 C  r   )Nz// %sr   )ra   textr   r   r   _get_comment   r   zRustCodePrinter._get_commentc                 C  s   d||f S )Nzconst %s: f64 = %s;r   )ra   namevaluer   r   r   _declare_number_const      z%RustCodePrinter._declare_number_constc                 C  
   |  |S r$   )indent_code)ra   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>)shaper   )ra   matrowsr   r   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)ra   indices
open_linesclose_lines	loopstartr   r   r   r   _get_loop_opening_ending  s   

z(RustCodePrinter._get_loop_opening_endingc                 C  s>   t |jdkrd| | d S |jr| j|ddS | |S )Nr   ()T)_type)lenargsr   	is_numberra   exprr   r   r   _print_caller_var  s
   
z!RustCodePrinter._print_caller_varc           	        s  |j j jv r j|j j }d}d}t|tr|}n|D ]\}}}||j r( nq|dur|dkrSd |jd |t|jdkrL |jdd dndd }|S |dkrfd	 |jd |d
 }|S |dkryd	 |jd |d
 }|S d| |jdd }|S dS t	|drt|j
tr |j
|j S |j j jv rɈ j|j j \}} |rt fdd|D rǈ ||S dS dS  |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      | ]}  |V  qd S r$   )
_can_print)r   fra   r   r   r   M      z2RustCodePrinter._print_Function.<locals>.<genexpr>)r   __name__r|   
isinstancestrr   r   r   	stringifyhasattrr   r   r   _rewriteable_functionsr   allrewrite_print_not_supported)	ra   r   	cond_funcr   stylecondrettarget_frequired_fsr   r   r   _print_Function  sX   

&	 
zRustCodePrinter._print_Functionc                 C  s:   |j jr|jjst|t|j |j}| |S | |S r$   )r   r&   r   rh   r   r   r   r   r   r   r   
_print_PowR  s   

zRustCodePrinter._print_PowFc                      t  |}|r|d S |S )N_f64)re   _print_Floatra   r   r   r   	__class__r   r   r   X     zRustCodePrinter._print_Floatc                   r   )N_i32)re   _print_Integerr   r   r   r   r   _  r   zRustCodePrinter._print_Integerc                 C  s"   t |jt |j}}d||f S )Nz%d_f64/%d.0)intr   q)ra   r   r   r   r   r   r   _print_Rationalf  s   zRustCodePrinter._print_Rationalc                 C  s,   |  |j}|  |j}|j}d|||S )Nz{} {} {})r   lhsrhsrel_opformat)ra   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])r   r   ZeroOnereversedr   rankr   r   r   label)ra   r   dimselemoffsetr   r   r   r   _print_Indexedp  s   zRustCodePrinter._print_Indexedc                 C  s   |j jS r$   )r   r   r   r   r   r   
_print_Idxz  r   zRustCodePrinter._print_Idxc                 C  r#   r$   )r   r   r   r   r   _print_Dummy}  s   zRustCodePrinter._print_Dummyc                 C  r)   )NEr   ra   r   r   r   r   r   _print_Exp1     zRustCodePrinter._print_Exp1c                 C  r)   )NPIr   r   r   r   r   	_print_Pi  r   zRustCodePrinter._print_Pic                 C  r)   )NINFINITYr   r   r   r   r   _print_Infinity  r   zRustCodePrinter._print_Infinityc                 C  r)   )NNEG_INFINITYr   r   r   r   r   _print_NegativeInfinity  r   z'RustCodePrinter._print_NegativeInfinityc                 C  r)   )Nrg   r   r   r   r   r   _print_BooleanTrue  r   z"RustCodePrinter._print_BooleanTruec                 C  r)   )NrJ   r   r   r   r   r   _print_BooleanFalse  r   z#RustCodePrinter._print_BooleanFalsec                 C  s   t | S r$   )r   r   r   r   r   r   _print_bool  r   zRustCodePrinter._print_boolc                 C  r)   )NNANr   r   r   r   r   
_print_NaN  r   zRustCodePrinter._print_NaNc                 C  s   |j d jdkrtdg }t|j D ]G\}\}}|dkr(|d| |  n#|t|j d kr>|dkr>|d  d7  < n|d  d| | 7  < | |}|| |d	 q| jd
 red|S d|S )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)ra   r   r   r   eccode0r   r   r   _print_Piecewise  s   




z RustCodePrinter._print_Piecewisec                 C  s    ddl m} | |j|ddS )Nr   )	PiecewiseF)deep)sympy.functionsr  r   r   )ra   r   r  r   r   r   
_print_ITE  s   zRustCodePrinter._print_ITEc                   s.   |j dkrdd fdd|D  S td)Nr   z[%s]r   c                 3  r   r$   )r   )r   ar   r   r   r     r   z4RustCodePrinter._print_MatrixBase.<locals>.<genexpr>zLFull Matrix Support in Rust need Crates (https://crates.io/keywords/matrix).)r   r  r  )ra   Ar   r   r   _print_MatrixBase  s   
z!RustCodePrinter._print_MatrixBasec                 C  r   r$   )r   )ra   r   r   r   r   _print_SparseRepMatrix  s   
z&RustCodePrinter._print_SparseRepMatrixc                 C  s"   d|j |j|j|j jd   f S )Nr   r   )parentr   r   r   r   r   r   r   _print_MatrixElement  s   z$RustCodePrinter._print_MatrixElementc                   s"   t  |}|| jv rd| S |S )Nz(*%s))re   _print_Symbolr   )ra   r   r   r   r   r   r    s   
zRustCodePrinter._print_Symbolc                 C  sh   ddl m} |j}|j}| jd r!||s||r!| ||S | |}| |}| d||f S )Nr   )IndexedBaserw   z%s = %s)	sympy.tensor.indexedr  r   r   r  has_doprint_loopsr   r   )ra   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 ]%\}}	|	dv rG||	 q9||| 8 }|d|| |	f  ||| 7 }q9|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r   liner   r   r   
<listcomp>  s    z/RustCodePrinter.indent_code.<locals>.<listcomp>c                       g | ]}t tt|j qS r   )r   anymapendswithr  )	inc_tokenr   r   r    s     c                   r   r   )r   r!  r"  
startswithr  )	dec_tokenr   r   r    s    r   )r   r  z%s%s)r   r   r   
splitlinesr  r  r   )
ra   code
code_linestabincreasedecreaseprettylevelnr  r   )r&  r$  r   r     s*   



zRustCodePrinter.indent_code)F).r   
__module____qualname____doc__printmethodlanguager{   r
   ry   r   __annotations__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
  r  r  r  r  r  r  r   __classcell__r   r   r   r   rq      sX   
 
8








	rq   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()];
    )rq   doprint)r   	assign_tor   r   r   r   	rust_code  s   mr9  c                 K  s   t t| fi | dS )z3Prints Rust representation of the given expression.N)printr9  )r   r   r   r   r   print_rust_codei  s   r;  r$   )r2  
__future__r   typingr   
sympy.corer   r   r   r   sympy.core.numbersr	   sympy.printing.codeprinterr
   r|   r   rq   r9  r;  r   r   r   r   <module>   sz    !!"#$%&'+,l6  
 p