o
    oh                     @  s  d Z ddlm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mZmZ ddlmZ ddlmZmZ dd	lmZmZmZ dd
lmZmZmZ ddlmZmZm Z m!Z! dd Z"G dd deZ#G dd de#Z$G dd de$Z%e% Z&G dd de$Z'e' Z(G dd de$Z)e) Z*G dd de#Z+G dd de+Z,G dd de+Z-G dd de-Z.G d d! d!e-Z/G d"d# d#e-Z0G d$d% d%e-Z1G d&d' d'e-Z2d(d) e.e/e0e1e2fD Z3d*d+ Z4G d,d- d-e#Z5G d.d/ d/e$Z6G d0d1 d1ee$Z7G d2d3 d3e7Z8G d4d5 d5e7Z9G d6d7 d7e$Z:G d8d9 d9e$Z;G d:d; d;e;Z<G d<d= d=e<Z=G d>d? d?e=Z>G d@dA dAe=Z?edBZ@G dCdD dDe;ZAG dEdF dFeAZBG dGdH dHeAZCG dIdJ dJeCeBZDe<dKZEe<dLZFe>dMdNZGe>dOdPZHe>dQdRZIe>dSdTZJe?dUdNZKe?dVdPZLe?dWdRZMe?dXdTZNeBdYdPdZd[d\ZOeBd]dRdNd^d\ZPeBd_dTd`dad\ZQeBdbdcddded\ZReBdfdgdddhd\ZSeBdidjdkdld\ZTeDddndTiePjUdodpZVeDddndgieQjUdodpZWe;drZXeAdsZYe<dtZZeCduZ[e;dvZ\G dwdx dxe$Z]e]dyZ^e]dzZ_G d{d| d|e:Z`G d}d~ d~e`ZaG dd de$ZbG dd de$ZcG dd de$ZdG dd de$ZeG dd de$ZfefdZgefdZhG dd de$ZiG dd de:ZjG dd dejZkG dd de$ZlG dd de$eZmG dd de$ZnG dd de$ZodS )a|  
Types used to represent a full function/module as an Abstract Syntax Tree.

Most types are small, and are merely used as tokens in the AST. A tree diagram
has been included below to illustrate the relationships between the AST types.


AST Type Tree
-------------
::

  *Basic*
       |
       |
   CodegenAST
       |
       |--->AssignmentBase
       |             |--->Assignment
       |             |--->AugmentedAssignment
       |                                    |--->AddAugmentedAssignment
       |                                    |--->SubAugmentedAssignment
       |                                    |--->MulAugmentedAssignment
       |                                    |--->DivAugmentedAssignment
       |                                    |--->ModAugmentedAssignment
       |
       |--->CodeBlock
       |
       |
       |--->Token
                |--->Attribute
                |--->For
                |--->String
                |       |--->QuotedString
                |       |--->Comment
                |--->Type
                |       |--->IntBaseType
                |       |              |--->_SizedIntType
                |       |                               |--->SignedIntType
                |       |                               |--->UnsignedIntType
                |       |--->FloatBaseType
                |                        |--->FloatType
                |                        |--->ComplexBaseType
                |                                           |--->ComplexType
                |--->Node
                |       |--->Variable
                |       |           |---> Pointer
                |       |--->FunctionPrototype
                |                            |--->FunctionDefinition
                |--->Element
                |--->Declaration
                |--->While
                |--->Scope
                |--->Stream
                |--->Print
                |--->FunctionCall
                |--->BreakToken
                |--->ContinueToken
                |--->NoneToken
                |--->Return


Predefined types
----------------

A number of ``Type`` instances are provided in the ``sympy.codegen.ast`` module
for convenience. Perhaps the two most common ones for code-generation (of numeric
codes) are ``float32`` and ``float64`` (known as single and double precision respectively).
There are also precision generic versions of Types (for which the codeprinters selects the
underlying data type at time of printing): ``real``, ``integer``, ``complex_``, ``bool_``.

The other ``Type`` instances defined are:

- ``intc``: Integer type used by C's "int".
- ``intp``: Integer type used by C's "unsigned".
- ``int8``, ``int16``, ``int32``, ``int64``: n-bit integers.
- ``uint8``, ``uint16``, ``uint32``, ``uint64``: n-bit unsigned integers.
- ``float80``: known as "extended precision" on modern x86/amd64 hardware.
- ``complex64``: Complex number represented by two ``float32`` numbers
- ``complex128``: Complex number represented by two ``float64`` numbers

Using the nodes
---------------

It is possible to construct simple algorithms using the AST nodes. Let's construct a loop applying
Newton's method::

    >>> from sympy import symbols, cos
    >>> from sympy.codegen.ast import While, Assignment, aug_assign, Print, QuotedString
    >>> t, dx, x = symbols('tol delta val')
    >>> expr = cos(x) - x**3
    >>> whl = While(abs(dx) > t, [
    ...     Assignment(dx, -expr/expr.diff(x)),
    ...     aug_assign(x, '+', dx),
    ...     Print([x])
    ... ])
    >>> from sympy import pycode
    >>> py_str = pycode(whl)
    >>> print(py_str)
    while (abs(delta) > tol):
        delta = (val**3 - math.cos(val))/(-3*val**2 - math.sin(val))
        val += delta
        print(val)
    >>> import math
    >>> tol, val, delta = 1e-5, 0.5, float('inf')
    >>> exec(py_str)
    1.1121416371
    0.909672693737
    0.867263818209
    0.865477135298
    0.865474033111
    >>> print('%3.1g' % (math.cos(val) - val**3))
    -3e-11

If we want to generate Fortran code for the same while loop we simple call ``fcode``::

    >>> from sympy import fcode
    >>> print(fcode(whl, standard=2003, source_format='free'))
    do while (abs(delta) > tol)
       delta = (val**3 - cos(val))/(-3*val**2 - sin(val))
       val = val + delta
       print *, val
    end do

There is a function constructing a loop (or a complete function) like this in
:mod:`sympy.codegen.algorithms`.

    )annotations)Any)defaultdict)GeGtLeLt)SymbolTupleDummy)Basic)ExprAtom)FloatIntegeroo)_sympifysympifySympifyError)iterabletopological_sortnumbered_symbolsfilter_symbolsc                 C  s   dd | D } t |  S )z
    Create a SymPy Tuple object from an iterable, converting Python strings to
    AST strings.

    Parameters
    ==========

    args: iterable
        Arguments to :class:`sympy.Tuple`.

    Returns
    =======

    sympy.Tuple
    c                 S  s"   g | ]}t |trt|n|qS  )
isinstancestrString.0argr   r   e/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/sympy/codegen/ast.py
<listcomp>   s   " z_mk_Tuple.<locals>.<listcomp>r
   argsr   r   r    	_mk_Tuple   s   r%   c                   @     e Zd ZdZdS )
CodegenASTr   N)__name__
__module____qualname__	__slots__r   r   r   r    r'          r'   c                      s   e Zd ZU dZdZded< eZi Zded< g Zded< d	gZ	e
d
d Zedd Zedd Zdd Zdd Zdd Z fddZdd Zdd ZddddZeZd d! Zd%d#d$Z  ZS )&Tokena   Base class for the AST types.

    Explanation
    ===========

    Defining fields are set in ``_fields``. Attributes (defined in _fields)
    are only allowed to contain instances of Basic (unless atomic, see
    ``String``). The arguments to ``__new__()`` correspond to the attributes in
    the order defined in ``_fields`. The ``defaults`` class attribute is a
    dictionary mapping attribute names to their default values.

    Subclasses should not need to override the ``__new__()`` method. They may
    define a class or static method named ``_construct_<attr>`` for each
    attribute to process the value passed to ``__new__()``. Attributes listed
    in the class attribute ``not_in_args`` are not passed to :class:`~.Basic`.
    r   tuple[str, ...]r+   dict[str, Any]defaultsz	list[str]not_in_argsbodyc                 C  s   t | jdkS Nr   )len_fieldsselfr   r   r    is_Atom      zToken.is_Atomc                 C  s   t | d| dd S )z8 Get the constructor function for an attribute by name. z_construct_%sc                 S  s   | S Nr   )xr   r   r    <lambda>       z(Token._get_constructor.<locals>.<lambda>getattr)clsattrr   r   r    _get_constructor   s   zToken._get_constructorc                 C  s2   |dkr| j |tS t|tr|S | ||S )zE Construct an attribute value from argument passed to ``__new__()``. N)r0   getnoner   r   rB   )r@   rA   r   r   r   r    
_construct   s
   
zToken._constructc           
        sZ  t |dkr|st|d  r|d S t |t  jkr)tdt |t  jf g }t j|D ]\}}||v r?td| | || q1 jt |d  D ]&}||v r^||}n| j	v ri j	| }ntd| | || qR|rtdd
|  fdd	t j|D }tj g|R  }t j|D ]
\}}	t|||	 q|S )
N   r   z,Too many arguments (%d), expected at most %dz$Got multiple values for attribute %rz2No value for %r given and attribute has no defaultzUnknown keyword arguments: %s c                   s   g | ]\}}| j vr|qS r   )r1   )r   rA   valr@   r   r    r!      s
    
z!Token.__new__.<locals>.<listcomp>)r4   r   r5   
ValueErrorzip	TypeErrorappendrE   popr0   joinr'   __new__setattr)
r@   r$   kwargsattrvalsattrnameargval
basic_argsobjrA   r   r   rI   r    rP      s2   


zToken.__new__c                 C  s:   t || jsdS | jD ]}t| |t||kr dS qdS )NFT)r   	__class__r5   r?   )r7   otherrA   r   r   r    __eq__  s   
zToken.__eq__c                   s   t  fdd jD S )Nc                      g | ]}t  |qS r   r>   )r   rA   r6   r   r    r!         z+Token._hashable_content.<locals>.<listcomp>)tupler5   r6   r   r6   r    _hashable_content  s   zToken._hashable_contentc                   
   t   S r:   super__hash__r6   rX   r   r    rb        
zToken.__hash__c                 C  s   || j v rdd|  S dS )N,
rG   , )indented_args)r7   kindent_levelr   r   r    _joiner  s   zToken._joinerc                   s   j d fdd t|trN fdd|jD }jv r=dd  | d dd	   d
 S t|jdkrId|S d|S  |S )Nri   c                   sF   t | trj| g R diS j| g R i S )Njoiner)r   r-   _printrj   r   )r$   ilrh   rR   printerr7   r   r    rl     s   
$zToken._indented.<locals>._printc                   s   g | ]} |qS r   r   r   rl   r   r    r!         z#Token._indented.<locals>.<listcomp>z(
rG   re      )rF   z({0},)z({0}))	_contextr   r
   rj   rO   r$   rg   r4   format)r7   ro   rh   vr$   rR   joinedr   )rl   r$   rn   rh   rR   ro   r7   r    	_indented  s   

"
$"zToken._indentedrf   )rk   c             	     s  ddl m} |dd} fdd jD }|jdd}g }	tt j|D ]X\}
\}}||v r2q'| jv r?| j| kr?q'| jv rH|d nd}|||d	  j	|||g|R i |}W d    n1 siw   Y  |	
|
dkrvd
nd||  q'd jj||	S )Nr   )printer_contextexcluder   c                   r[   r   r>   r   rh   r6   r   r    r!   (  r\   z$Token._sympyrepr.<locals>.<listcomp>ri   rr   )ri   z{1}z{0}={1}z{}({}))sympy.printing.printerry   rC   r5   rt   	enumeraterK   r0   rg   rx   rM   ru   lstriprX   r(   rO   )r7   ro   rk   r$   rR   ry   rz   valuesri   	arg_reprsirA   valueilvlindentedr   r6   r    
_sympyrepr%  s    $zToken._sympyreprc                 C  s   ddl m} || S )Nr   )srepr)sympy.printingr   )r7   r   r   r   r    __repr__>  s   zToken.__repr__Nc                   s8   fddj D } dur fdd| D S |S )a   Get instance's attributes as dict of keyword arguments.

        Parameters
        ==========

        exclude : collection of str
            Collection of keywords to exclude.

        apply : callable, optional
            Function to apply to all values.
        c                   s    i | ]}| vr|t |qS r   r>   r{   )rz   r7   r   r    
<dictcomp>N  s     z Token.kwargs.<locals>.<dictcomp>Nc                   s   i | ]	\}}| |qS r   r   )r   rh   rv   )applyr   r    r   P      )r5   items)r7   rz   r   rR   r   )r   rz   r7   r    rR   B  s   zToken.kwargsr   N)r(   r)   r*   __doc__r+   __annotations__r5   r0   r1   rg   propertyr8   classmethodrB   rE   rP   rZ   r^   rb   rj   rx   r   	_sympystrr   rR   __classcell__r   r   rc   r    r-      s.   
 


.r-   c                   @  r&   )
BreakTokenaD   Represents 'break' in C/Python ('exit' in Fortran).

    Use the premade instance ``break_`` or instantiate manually.

    Examples
    ========

    >>> from sympy import ccode, fcode
    >>> from sympy.codegen.ast import break_
    >>> ccode(break_)
    'break'
    >>> fcode(break_, source_format='free')
    'exit'
    Nr(   r)   r*   r   r   r   r   r    r   T  r,   r   c                   @  r&   )ContinueTokenaW   Represents 'continue' in C/Python ('cycle' in Fortran)

    Use the premade instance ``continue_`` or instantiate manually.

    Examples
    ========

    >>> from sympy import ccode, fcode
    >>> from sympy.codegen.ast import continue_
    >>> ccode(continue_)
    'continue'
    >>> fcode(continue_, source_format='free')
    'cycle'
    Nr   r   r   r   r    r   g  r,   r   c                      s0   e Zd ZdZdd Zdd Z fddZ  ZS )	NoneTokena0   The AST equivalence of Python's NoneType

    The corresponding instance of Python's ``None`` is ``none``.

    Examples
    ========

    >>> from sympy.codegen.ast import none, Variable
    >>> from sympy import pycode
    >>> print(pycode(Variable('x').as_Declaration(value=none)))
    x = None

    c                 C  s   |d u pt |tS r:   )r   r   r7   rY   r   r   r    rZ     s   zNoneToken.__eq__c                 C     dS )Nr   r   r6   r   r   r    r^        zNoneToken._hashable_contentc                   r_   r:   r`   r6   rc   r   r    rb     rd   zNoneToken.__hash__)r(   r)   r*   r   rZ   r^   rb   r   r   r   rc   r    r   y  s
    r   c                      sD   e Zd ZdZ fddZedd Zedd Zedd	 Z	  Z
S )
AssignmentBasez Abstract base class for Assignment and AugmentedAssignment.

    Attributes:
    ===========

    op : str
        Symbol for assignment operator, e.g. "=", "+=", etc.
    c                   s,   t |}t |}| || t | ||S r:   )r   _check_argsra   rP   )r@   lhsrhsrc   r   r    rP     s   zAssignmentBase.__new__c                 C  
   | j d S r3   r#   r6   r   r   r    r        
zAssignmentBase.lhsc                 C  r   )NrF   r#   r6   r   r   r    r     r   zAssignmentBase.rhsc           
      C  s   ddl m}m} ddlm} ddlm} t|||tt	|f}t
||s*tdt| t|do4t
|| }t|do?t
|| }	|rT|	sHtd|j|jkrRtdd
S |	r\|s^td	d
S d
S )z Check arguments to __new__ and raise exception if any problems found.

        Derived classes may wish to override this.
        r   )MatrixElementMatrixSymbol)Indexed)ArrayElementz Cannot assign to lhs of type %s.shapez#Cannot assign a scalar to a matrix.z'Dimensions of lhs and rhs do not align.z#Cannot assign a matrix to a scalar.N)"sympy.matrices.expressions.matexprr   r   sympy.tensor.indexedr   sympy.tensor.array.expressionsr   r	   ElementVariabler   rL   typehasattrrJ   r   )
r@   r   r   r   r   r   r   
assignable
lhs_is_mat
rhs_is_matr   r   r    r     s&   
zAssignmentBase._check_args)r(   r)   r*   r   rP   r   r   r   r   r   r   r   r   rc   r    r     s    	

r   c                   @     e Zd ZdZdZdS )
Assignmentam  
    Represents variable assignment for code generation.

    Parameters
    ==========

    lhs : Expr
        SymPy object representing the lhs of the expression. These should be
        singular objects, such as one would use in writing code. Notable types
        include Symbol, MatrixSymbol, MatrixElement, and Indexed. Types that
        subclass these types are also supported.

    rhs : Expr
        SymPy object representing the rhs of the expression. This can be any
        type, provided its shape corresponds to that of the lhs. For example,
        a Matrix type can be assigned to MatrixSymbol, but not to Symbol, as
        the dimensions will not align.

    Examples
    ========

    >>> from sympy import symbols, MatrixSymbol, Matrix
    >>> from sympy.codegen.ast import Assignment
    >>> x, y, z = symbols('x, y, z')
    >>> Assignment(x, y)
    Assignment(x, y)
    >>> Assignment(x, 0)
    Assignment(x, 0)
    >>> A = MatrixSymbol('A', 1, 3)
    >>> mat = Matrix([x, y, z]).T
    >>> Assignment(A, mat)
    Assignment(A, Matrix([[x, y, z]]))
    >>> Assignment(A[0, 1], x)
    Assignment(A[0, 1], x)
    z:=N)r(   r)   r*   r   opr   r   r   r    r     s    $r   c                   @  s    e Zd ZdZdZedd ZdS )AugmentedAssignmentz
    Base class for augmented assignments.

    Attributes:
    ===========

    binop : str
       Symbol for binary operation being applied in the assignment, such as "+",
       "*", etc.
    Nc                 C  s
   | j d S )N=binopr6   r   r   r    r     r   zAugmentedAssignment.op)r(   r)   r*   r   r   r   r   r   r   r   r    r     s
    
r   c                   @  r&   )AddAugmentedAssignment+Nr(   r)   r*   r   r   r   r   r    r   	  r,   r   c                   @  r&   )SubAugmentedAssignment-Nr   r   r   r   r    r     r,   r   c                   @  r&   )MulAugmentedAssignment*Nr   r   r   r   r    r     r,   r   c                   @  r&   )DivAugmentedAssignment/Nr   r   r   r   r    r     r,   r   c                   @  r&   )ModAugmentedAssignment%Nr   r   r   r   r    r     r,   r   c                 C  s   i | ]}|j |qS r   r   )r   r@   r   r   r    r     s    r   c                 C  s"   |t vr
td| t | | |S )ao  
    Create 'lhs op= rhs'.

    Explanation
    ===========

    Represents augmented variable assignment for code generation. This is a
    convenience function. You can also use the AugmentedAssignment classes
    directly, like AddAugmentedAssignment(x, y).

    Parameters
    ==========

    lhs : Expr
        SymPy object representing the lhs of the expression. These should be
        singular objects, such as one would use in writing code. Notable types
        include Symbol, MatrixSymbol, MatrixElement, and Indexed. Types that
        subclass these types are also supported.

    op : str
        Operator (+, -, /, \*, %).

    rhs : Expr
        SymPy object representing the rhs of the expression. This can be any
        type, provided its shape corresponds to that of the lhs. For example,
        a Matrix type can be assigned to MatrixSymbol, but not to Symbol, as
        the dimensions will not align.

    Examples
    ========

    >>> from sympy import symbols
    >>> from sympy.codegen.ast import aug_assign
    >>> x, y = symbols('x, y')
    >>> aug_assign(x, '+', y)
    AddAugmentedAssignment(x, y)
    zUnrecognized operator %s)augassign_classesrJ   )r   r   r   r   r   r    
aug_assign&  s   &r   c                      sZ   e Zd ZdZdd Zdd Zdd ZeZe fdd	Z	e
d
d Z		dddZ  ZS )	CodeBlocka_  
    Represents a block of code.

    Explanation
    ===========

    For now only assignments are supported. This restriction will be lifted in
    the future.

    Useful attributes on this object are:

    ``left_hand_sides``:
        Tuple of left-hand sides of assignments, in order.
    ``left_hand_sides``:
        Tuple of right-hand sides of assignments, in order.
    ``free_symbols``: Free symbols of the expressions in the right-hand sides
        which do not appear in the left-hand side of an assignment.

    Useful methods on this object are:

    ``topological_sort``:
        Class method. Return a CodeBlock with assignments
        sorted so that variables are assigned before they
        are used.
    ``cse``:
        Return a new CodeBlock with common subexpressions eliminated and
        pulled out as assignments.

    Examples
    ========

    >>> from sympy import symbols, ccode
    >>> from sympy.codegen.ast import CodeBlock, Assignment
    >>> x, y = symbols('x y')
    >>> c = CodeBlock(Assignment(x, 1), Assignment(y, x + 1))
    >>> print(ccode(c))
    x = 1;
    y = x + 1;

    c                 G  sd   g }g }|D ]}t |tr|j\}}|| || qtj| g|R  }t| |_t| |_|S r:   )	r   r   r$   rM   r'   rP   r
   left_hand_sidesright_hand_sides)r@   r$   r   r   r   r   r   rW   r   r   r    rP   z  s   





zCodeBlock.__new__c                 C  
   t | jS r:   )iterr$   r6   r   r   r    __iter__  rd   zCodeBlock.__iter__c                 O  sh   |j dd}dd|  }|t|j| j}dd|d  | jj d|  | d d|d   d S )	Nri   r   re   rG   z{}(
rr   
rs   )	rt   rC   rO   maprl   r$   ru   rX   r(   )r7   ro   r$   rR   rn   rk   rw   r   r   r    r     s   
zCodeBlock._sympyreprc                   s   t  jt| j S r:   )ra   free_symbolssetr   r6   rc   r   r    r        zCodeBlock.free_symbolsc                 C  s   t dd |D stdtdd |D rtdtt|}tt}|D ]}|\}}||j | q&g }|D ]}|\}}|jj	D ]}	||	 D ]	}
||
|f qIqCq9t
||g}| dd |D  S )a  
        Return a CodeBlock with topologically sorted assignments so that
        variables are assigned before they are used.

        Examples
        ========

        The existing order of assignments is preserved as much as possible.

        This function assumes that variables are assigned to only once.

        This is a class constructor so that the default constructor for
        CodeBlock can error when variables are used before they are assigned.

        >>> from sympy import symbols
        >>> from sympy.codegen.ast import CodeBlock, Assignment
        >>> x, y, z = symbols('x y z')

        >>> assignments = [
        ...     Assignment(x, y + z),
        ...     Assignment(y, z + 1),
        ...     Assignment(z, 2),
        ... ]
        >>> CodeBlock.topological_sort(assignments)
        CodeBlock(
            Assignment(z, 2),
            Assignment(y, z + 1),
            Assignment(x, y + z)
        )

        c                 s      | ]}t |tV  qd S r:   r   r   r   r   r   r   r    	<genexpr>      z-CodeBlock.topological_sort.<locals>.<genexpr>z4CodeBlock.topological_sort only supports Assignmentsc                 s  r   r:   r   r   r   r   r   r    r     r   zFCodeBlock.topological_sort does not yet work with AugmentedAssignmentsc                 S  s   g | ]\}}|qS r   r   )r   r   ar   r   r    r!     rq   z.CodeBlock.topological_sort.<locals>.<listcomp>)allNotImplementedErroranylistr}   r   r   rM   r   r   r   )r@   assignmentsAvar_mapnoder   r   Edst_nodessrc_nodeordered_assignmentsr   r   r    r     s&   "zCodeBlock.topological_sortN	canonicalc                 C  s   ddl m} tdd | jD stdtdd | jD r"tdt| jD ]\}}|| jd| v r:td	| q'| t	}|du rGt
 }t||}|t| j||||d
\}	}
dd t| j|
D }dd |	D }| || S )a  
        Return a new code block with common subexpressions eliminated.

        Explanation
        ===========

        See the docstring of :func:`sympy.simplify.cse_main.cse` for more
        information.

        Examples
        ========

        >>> from sympy import symbols, sin
        >>> from sympy.codegen.ast import CodeBlock, Assignment
        >>> x, y, z = symbols('x y z')

        >>> c = CodeBlock(
        ...     Assignment(x, 1),
        ...     Assignment(y, sin(x) + 1),
        ...     Assignment(z, sin(x) - 1),
        ... )
        ...
        >>> c.cse()
        CodeBlock(
            Assignment(x, 1),
            Assignment(x0, sin(x)),
            Assignment(y, x0 + 1),
            Assignment(z, x0 - 1)
        )

        r   )csec                 s  r   r:   r   r   r   r   r    r     r   z CodeBlock.cse.<locals>.<genexpr>z'CodeBlock.cse only supports Assignmentsc                 s  r   r:   r   r   r   r   r    r     r   z9CodeBlock.cse does not yet work with AugmentedAssignmentsNzEDuplicate assignments to the same variable are not yet supported (%s))symbolsoptimizationspostprocessorderc                 S     g | ]	\}}t ||qS r   r   r   varexprr   r   r    r!   $  r   z!CodeBlock.cse.<locals>.<listcomp>c                 S  r   r   r   r   r   r   r    r!   &  r   )sympy.simplify.cse_mainr   r   r$   r   r   r}   r   atomsr	   r   r   r   r   rK   r   )r7   r   r   r   r   r   r   r   existing_symbolsreplacementsreduced_exprs	new_blocknew_assignmentsr   r   r    r     s0   !




zCodeBlock.cse)NNNr   )r(   r)   r*   r   rP   r   r   r   r   r   r   r   r   r   r   r   rc   r    r   Q  s    (
Pr   c                   @  s8   e Zd ZdZd ZZeeZe	dd Z
e	dd ZdS )Fora  Represents a 'for-loop' in the code.

    Expressions are of the form:
        "for target in iter:
            body..."

    Parameters
    ==========

    target : symbol
    iter : iterable
    body : CodeBlock or iterable
!        When passed an iterable it is used to instantiate a CodeBlock.

    Examples
    ========

    >>> from sympy import symbols, Range
    >>> from sympy.codegen.ast import aug_assign, For
    >>> x, i, j, k = symbols('x i j k')
    >>> for_i = For(i, Range(10), [aug_assign(x, '+', i*j*k)])
    >>> for_i  # doctest: -NORMALIZE_WHITESPACE
    For(i, iterable=Range(0, 10, 1), body=CodeBlock(
        AddAugmentedAssignment(x, i*j*k)
    ))
    >>> for_ji = For(j, Range(7), [for_i])
    >>> for_ji  # doctest: -NORMALIZE_WHITESPACE
    For(j, iterable=Range(0, 7, 1), body=CodeBlock(
        For(i, iterable=Range(0, 10, 1), body=CodeBlock(
            AddAugmentedAssignment(x, i*j*k)
        ))
    ))
    >>> for_kji =For(k, Range(5), [for_ji])
    >>> for_kji  # doctest: -NORMALIZE_WHITESPACE
    For(k, iterable=Range(0, 5, 1), body=CodeBlock(
        For(j, iterable=Range(0, 7, 1), body=CodeBlock(
            For(i, iterable=Range(0, 10, 1), body=CodeBlock(
                AddAugmentedAssignment(x, i*j*k)
            ))
        ))
    ))
    )targetr   r2   c                 C     t |tr|S t| S r:   r   r   r@   itrr   r   r    _construct_bodyX     
zFor._construct_bodyc                 C  s*   t |stdt|trt|}t|S )Nziterable must be an iterable)r   rL   r   r   r]   r   r   r   r   r    _construct_iterable_  s
   
zFor._construct_iterableN)r(   r)   r*   r   r+   r5   staticmethodr   _construct_targetr   r   r   r   r   r   r    r   *  s    *
r   c                   @  sT   e Zd ZdZd ZZdgZdZedd Z	dd Z
dddZedd Zdd Zd
S )r   ao   SymPy object representing a string.

    Atomic object which is not an expression (as opposed to Symbol).

    Parameters
    ==========

    text : str

    Examples
    ========

    >>> from sympy.codegen.ast import String
    >>> f = String('foo')
    >>> f
    foo
    >>> str(f)
    'foo'
    >>> f.text
    'foo'
    >>> print(repr(f))
    String('foo')

    textr  Tc                 C  s   t |ts	td|S )Nz#Argument text is not a string type.)r   r   rL   )r@   r  r   r   r    _construct_text  s   
zString._construct_textc                 O  s   | j S r:   r   r7   ro   r$   rR   r   r   r    r     s   zString._sympystrr   Nc                 C  s   i S r:   r   )r7   rz   r   r   r   r    rR     r   zString.kwargsc                   s    fddS )Nc                     s    S r:   r   r   r6   r   r    r<     r=   zString.func.<locals>.<lambda>r   r6   r   r6   r    func  s   zString.funcc                 C  s   ddl m} d|| jS )Nr   latex_escapez\texttt{{"{}"}})sympy.printing.latexr  ru   r  )r7   ro   r  r   r   r    _latex  s   zString._latexr   )r(   r)   r*   r   r+   r5   r1   r8   r   r  r   rR   r   r  r  r   r   r   r    r   h  s    


r   c                   @  r&   )QuotedStringz: Represents a string which should be printed with quotes. Nr   r   r   r   r    r	    r,   r	  c                   @  r&   )Commentz Represents a comment. Nr   r   r   r   r    r
    r,   r
  c                   @  sD   e Zd ZU dZdZded< eZde iZded< e	e
Zdd	 Zd
S )Nodea|   Subclass of Token, carrying the attribute 'attrs' (Tuple)

    Examples
    ========

    >>> from sympy.codegen.ast import Node, value_const, pointer_const
    >>> n1 = Node([value_const])
    >>> n1.attr_params('value_const')  # get the parameters of attribute (by name)
    ()
    >>> from sympy.codegen.fnodes import dimension
    >>> n2 = Node([value_const, dimension(5, 3)])
    >>> n2.attr_params(value_const)  # get the parameters of attribute (by Attribute instance)
    ()
    >>> n2.attr_params('dimension')  # get the parameters of attribute (by name)
    (5, 3)
    >>> n2.attr_params(pointer_const) is None
    True

    )attrsr.   r+   r  r/   r0   c                 C  s,   | j D ]}t|jt|kr|j  S qdS )zQ Returns the parameters of the Attribute with name ``looking_for`` in self.attrs N)r  r   name
parameters)r7   looking_forrA   r   r   r    attr_params  s
   

zNode.attr_paramsN)r(   r)   r*   r   r+   r   r5   r
   r0   r   r%   _construct_attrsr  r   r   r   r    r    s   
 r  c                   @  sT   e Zd ZU dZdZded< eZeZdd Z	e
dd Zd	d
 ZdddZdd ZdS )Typea   Represents a type.

    Explanation
    ===========

    The naming is a super-set of NumPy naming. Type has a classmethod
    ``from_expr`` which offer type deduction. It also has a method
    ``cast_check`` which casts the argument to its type, possibly raising an
    exception if rounding error is not within tolerances, or if the value is not
    representable by the underlying data type (e.g. unsigned integers).

    Parameters
    ==========

    name : str
        Name of the type, e.g. ``object``, ``int16``, ``float16`` (where the latter two
        would use the ``Type`` sub-classes ``IntType`` and ``FloatType`` respectively).
        If a ``Type`` instance is given, the said instance is returned.

    Examples
    ========

    >>> from sympy.codegen.ast import Type
    >>> t = Type.from_expr(42)
    >>> t
    integer
    >>> print(repr(t))
    IntBaseType(String('integer'))
    >>> from sympy.codegen.ast import uint8
    >>> uint8.cast_check(-1)   # doctest: +ELLIPSIS
    Traceback (most recent call last):
      ...
    ValueError: Minimum value for data type bigger than new value.
    >>> from sympy.codegen.ast import float32
    >>> v6 = 0.123456
    >>> float32.cast_check(v6)
    0.123456
    >>> v10 = 12345.67894
    >>> float32.cast_check(v10)  # doctest: +ELLIPSIS
    Traceback (most recent call last):
      ...
    ValueError: Casting gives a significantly different value.
    >>> boost_mp50 = Type('boost::multiprecision::cpp_dec_float_50')
    >>> from sympy import cxxcode
    >>> from sympy.codegen.ast import Declaration, Variable
    >>> cxxcode(Declaration(Variable('x', type=boost_mp50)))
    'boost::multiprecision::cpp_dec_float_50 x'

    References
    ==========

    .. [1] https://numpy.org/doc/stable/user/basics.types.html

    r  r.   r+   c                 O  r   r:   )r   r  r  r   r   r    r     rd   zType._sympystrc                 C  s|   t |ttfr	tS t |ttfst|ddrtS t|ddr tS t |ts+t|ddr-t	S t |t
s8t|ddr:tS td)a   Deduces type from an expression or a ``Symbol``.

        Parameters
        ==========

        expr : number or SymPy object
            The type will be deduced from type or properties.

        Examples
        ========

        >>> from sympy.codegen.ast import Type, integer, complex_
        >>> Type.from_expr(2) == integer
        True
        >>> from sympy import Symbol
        >>> Type.from_expr(Symbol('z', complex=True)) == complex_
        True
        >>> Type.from_expr(sum)  # doctest: +ELLIPSIS
        Traceback (most recent call last):
          ...
        ValueError: Could not deduce type from expr.

        Raises
        ======

        ValueError when type deduction fails.

        
is_integerFis_real
is_complexis_Relationalz Could not deduce type from expr.)r   floatr   realintr   r?   integercomplexcomplex_boolbool_rJ   )r@   r   r   r   r    	from_expr  s   zType.from_exprc                 C  s   d S r:   r   r7   r   r   r   r    _check-  r   zType._checkNr   c                   s   t |}td}t| dd}du r|du rdnd||    fdd}| |}	| |	 |	| }
t|
||kr@td|	S )	a[   Casts a value to the data type of the instance.

        Parameters
        ==========

        value : number
        rtol : floating point number
            Relative tolerance. (will be deduced if not given).
        atol : floating point number
            Absolute tolerance (in addition to ``rtol``).
        type_aliases : dict
            Maps substitutions for Type, e.g. {integer: int64, real: float32}

        Examples
        ========

        >>> from sympy.codegen.ast import integer, float32, int8
        >>> integer.cast_check(3.0) == 3
        True
        >>> float32.cast_check(1e-40)  # doctest: +ELLIPSIS
        Traceback (most recent call last):
          ...
        ValueError: Minimum value for data type bigger than new value.
        >>> int8.cast_check(256)  # doctest: +ELLIPSIS
        Traceback (most recent call last):
          ...
        ValueError: Maximum value for data type smaller than new value.
        >>> v10 = 12345.67894
        >>> float32.cast_check(v10)  # doctest: +ELLIPSIS
        Traceback (most recent call last):
          ...
        ValueError: Casting gives a significantly different value.
        >>> from sympy.codegen.ast import float64
        >>> float64.cast_check(v10)
        12345.67894
        >>> from sympy import Float
        >>> v18 = Float('0.123456789012345646')
        >>> float64.cast_check(v18)
        Traceback (most recent call last):
          ...
        ValueError: Casting gives a significantly different value.
        >>> from sympy.codegen.ast import float80
        >>> float80.cast_check(v18)
        0.123456789012345649

        
   decimal_digNgV瞯<g       @c                   s    t |   S r:   )abs)numatolrtolr   r    tolg  s   zType.cast_check.<locals>.tolz.Casting gives a significantly different value.)r   r   r?   cast_nocheckr"  r%  rJ   )r7   r   r)  r(  precision_targetsrH   tenexp10r*  new_valdeltar   r'  r    
cast_check0  s   /

zType.cast_checkc                 C  s0   ddl m} || jj}|| jj}d||S )Nr   r  z%\text{{{}}}\left(\texttt{{{}}}\right))r  r  rX   r(   r  r  ru   )r7   ro   r  	type_namer  r   r   r    r  s  s   zType._latex)Nr   N)r(   r)   r*   r   r+   r   r5   r   _construct_namer   r   r   r"  r1  r  r   r   r   r    r    s   
 6
*
Cr  c                   @     e Zd ZdZdZdd ZdS )IntBaseTypez2 Integer base type, contains no size information. r   c                 C  s   t t|S r:   )r   r  )r7   r   r   r   r    r<   }      zIntBaseType.<lambda>N)r(   r)   r*   r   r+   r+  r   r   r   r    r5  z  s    r5  c                   @  s&   e Zd ZdZeje ZeZdd ZdS )_SizedIntTypenbitsc                 C  s<   || j k rtd|| j f || jkrtd|| jf d S )NValue is too small: %d < %dValue is too big: %d > %d)minrJ   maxr!  r   r   r    r"    s
   

z_SizedIntType._checkN)	r(   r)   r*   r+   r  r5   r   _construct_nbitsr"  r   r   r   r    r7    s
    
r7  c                   @  ,   e Zd ZdZdZedd Zedd ZdS )SignedIntTypez# Represents a signed integer type. r   c                 C  s   d| j d   S N   rF   r8  r6   r   r   r    r<    s   zSignedIntType.minc                 C  s   d| j d  d S rA  r8  r6   r   r   r    r=    r   zSignedIntType.maxNr(   r)   r*   r   r+   r   r<  r=  r   r   r   r    r@        
r@  c                   @  r?  )UnsignedIntTypez& Represents an unsigned integer type. r   c                 C  r   r3   r   r6   r   r   r    r<    s   zUnsignedIntType.minc                 C  s   d| j  d S rA  r8  r6   r   r   r    r=    r9   zUnsignedIntType.maxNrC  r   r   r   r    rE    rD  rE  rB  c                   @  s   e Zd ZdZdZeZdS )FloatBaseTypez* Represents a floating point number type. r   N)r(   r)   r*   r   r+   r   r+  r   r   r   r    rF    s    rF  c                   @  s   e Zd ZdZdZeje Ze Z Z	Z
edd Zedd Zedd Zed	d
 Zedd Zedd Zedd Zdd Zdd ZdS )	FloatTypea   Represents a floating point type with fixed bit width.

    Base 2 & one sign bit is assumed.

    Parameters
    ==========

    name : str
        Name of the type.
    nbits : integer
        Number of bits used (storage).
    nmant : integer
        Number of bits used to represent the mantissa.
    nexp : integer
        Number of bits used to represent the mantissa.

    Examples
    ========

    >>> from sympy import S
    >>> from sympy.codegen.ast import FloatType
    >>> half_precision = FloatType('f16', nbits=16, nmant=10, nexp=5)
    >>> half_precision.max
    65504
    >>> half_precision.tiny == S(2)**-14
    True
    >>> half_precision.eps == S(2)**-10
    True
    >>> half_precision.dig == 3
    True
    >>> half_precision.decimal_dig == 5
    True
    >>> half_precision.cast_check(1.0)
    1.0
    >>> half_precision.cast_check(1e5)  # doctest: +ELLIPSIS
    Traceback (most recent call last):
      ...
    ValueError: Maximum value for data type smaller than new value.
    )r9  nmantnexpc                 C     t | jd  S )zV The largest positive number n, such that 2**(n - 1) is a representable finite value. rF   )tworI  r6   r   r   r    max_exponent  s   zFloatType.max_exponentc                 C  s
   d| j  S )zR The lowest negative number n, such that 2**(n - 1) is a valid normalized number.    )rL  r6   r   r   r    min_exponent  s   
zFloatType.min_exponentc                 C  s   dt | jd    t | j  S )z Maximum value representable. rF   )rK  rH  rL  r6   r   r   r    r=    s   zFloatType.maxc                 C  rJ  )z( The minimum positive normalized value. rF   )rK  rN  r6   r   r   r    tiny  s   zFloatType.tinyc                 C  s   t | j  S )z: Difference between 1.0 and the next representable value. )rK  rH  r6   r   r   r    eps  s   zFloatType.epsc                 C  s*   ddl m}m} || j|d |d S )z Number of decimal digits that are guaranteed to be preserved in text.

        When converting text -> float -> text, you are guaranteed that at least ``dig``
        number of digits are preserved with respect to rounding or overflow.
        r   )floorlogrB  r#  )sympy.functionsrQ  rR  rH  )r7   rQ  rR  r   r   r    dig  s   zFloatType.digc                 C  s2   ddl m}m} || jd |d |d d S )a}   Number of digits needed to store & load without loss.

        Explanation
        ===========

        Number of decimal digits needed to guarantee that two consecutive conversions
        (float -> text -> float) to be idempotent. This is useful when one do not want
        to loose precision due to rounding errors when storing a floating point value
        as text.
        r   )ceilingrR  rF   rB  r#  )rS  rU  rR  rH  )r7   rU  rR  r   r   r    r$    s   "zFloatType.decimal_digc                 C  s@   |t krtt S |t  krtt  S ttt|| j| jS )7 Casts without checking if out of bounds or subnormal. )r   r  r   r   r   evalfr$  r!  r   r   r    r+    s
   

zFloatType.cast_nocheckc                 C  sV   || j  k rtd|| j  f || j krtd|| j f t|| jk r)tdd S )Nr:  r;  z>Smallest (absolute) value for data type bigger than new value.)r=  rJ   r%  rO  r!  r   r   r    r"    s   
zFloatType._checkN)r(   r)   r*   r   r+   r  r5   r   r>  _construct_nmant_construct_nexpr   rL  rN  r=  rO  rP  rT  r$  r+  r"  r   r   r   r    rG    s*    (






	
rG  c                      s,   e Zd ZdZ fddZ fddZ  ZS )ComplexBaseTyper   c                   s4   ddl m}m} t ||t ||d  S )rV  r   reimy              ?)rS  r\  r]  ra   r+  r7   r   r\  r]  rc   r   r    r+  &  s
   zComplexBaseType.cast_nocheckc                   s4   ddl m}m} t || t || d S )Nr   r[  )rS  r\  r]  ra   r"  r^  rc   r   r    r"  .  s   zComplexBaseType._check)r(   r)   r*   r+   r+  r"  r   r   r   rc   r    rZ  "  s    rZ  c                   @  r   )ComplexTypez- Represents a complex floating point number. r   N)r(   r)   r*   r   r+   r   r   r   r    r_  4  s    r_  intcintpint8   int16   int32    int64@   uint8uint16uint32uint64float16   r#  )rI  rH  float32   float64   4   float80P      ?   float128   p   float256         	complex64r9  )r  r9  rz   
complex128untypedr  r  r  r  c                   @  s6   e Zd ZdZd ZZde iZeZ	e
eZdd ZdS )	Attributea   Attribute (possibly parametrized)

    For use with :class:`sympy.codegen.ast.Node` (which takes instances of
    ``Attribute`` as ``attrs``).

    Parameters
    ==========

    name : str
    parameters : Tuple

    Examples
    ========

    >>> from sympy.codegen.ast import Attribute
    >>> volatile = Attribute('volatile')
    >>> volatile
    volatile
    >>> print(repr(volatile))
    Attribute(String('volatile'))
    >>> a = Attribute('foo', [1, 2, 3])
    >>> a
    foo(1, 2, 3)
    >>> a.parameters == (1, 2, 3)
    True
    )r  r  r  c                   s:   t | j}| jr|dd fdd| jD  7 }|S )Nz(%s)rf   c                 3  s(    | ]}j |g R i V  qd S r:   rp   r   r$   rR   ro   r   r    r   z  s    z&Attribute._sympystr.<locals>.<genexpr>)r   r  r  rO   )r7   ro   r$   rR   resultr   r  r    r   w  s   
zAttribute._sympystrN)r(   r)   r*   r   r+   r5   r
   r0   r   r3  r   r%   _construct_parametersr   r   r   r   r    r  V  s    
r  value_constpointer_constc                   @  s   e Zd ZdZdZeej Zej Ze	e
ed eeZeeZede dfddZdd	 Zd
d Zdd Zdd Zdd Zdd ZdS )r   a   Represents a variable.

    Parameters
    ==========

    symbol : Symbol
    type : Type (optional)
        Type of the variable.
    attrs : iterable of Attribute instances
        Will be stored as a Tuple.

    Examples
    ========

    >>> from sympy import Symbol
    >>> from sympy.codegen.ast import Variable, float32, integer
    >>> x = Symbol('x')
    >>> v = Variable(x, type=float32)
    >>> v.attrs
    ()
    >>> v == Variable('x')
    False
    >>> v == Variable('x', type=float32)
    True
    >>> v
    Variable(x, type=float32)

    One may also construct a ``Variable`` instance with the type deduced from
    assumptions about the symbol using the ``deduced`` classmethod:

    >>> i = Symbol('i', integer=True)
    >>> v = Variable.deduced(i)
    >>> v.type == integer
    True
    >>> v == Variable('i')
    False
    >>> from sympy.codegen.ast import value_const
    >>> value_const in v.attrs
    False
    >>> w = Variable('w', attrs=[value_const])
    >>> w
    Variable(w, attrs=(value_const,))
    >>> value_const in w.attrs
    True
    >>> w.as_Declaration(value=42)
    Declaration(Variable(w, value=42, attrs=(value_const,)))

    )symbolr   r   )r   r   NTc                 C  s`   t |tr|S zt|}W n ty   t|}Y nw |dur(|r(||}| ||||dS )a`   Alt. constructor with type deduction from ``Type.from_expr``.

        Deduces type primarily from ``symbol``, secondarily from ``value``.

        Parameters
        ==========

        symbol : Symbol
        value : expr
            (optional) value of the variable.
        attrs : iterable of Attribute instances
        cast_check : bool
            Whether to apply ``Type.cast_check`` on ``value``.

        Examples
        ========

        >>> from sympy import Symbol
        >>> from sympy.codegen.ast import Variable, complex_
        >>> n = Symbol('n', integer=True)
        >>> str(Variable.deduced(n).type)
        'integer'
        >>> x = Symbol('x', real=True)
        >>> v = Variable.deduced(x)
        >>> v.type
        real
        >>> z = Symbol('z', complex=True)
        >>> Variable.deduced(z).type == complex_
        True

        N)r   r   r  )r   r   r  r   rJ   r1  )r@   r  r   r  r1  type_r   r   r    deduced  s   
!
zVariable.deducedc                 K  s&   |   }|| t| jdi |S )aV   Convenience method for creating a Declaration instance.

        Explanation
        ===========

        If the variable of the Declaration need to wrap a modified
        variable keyword arguments may be passed (overriding e.g.
        the ``value`` of the Variable instance).

        Examples
        ========

        >>> from sympy.codegen.ast import Variable, NoneToken
        >>> x = Variable('x')
        >>> decl1 = x.as_Declaration()
        >>> # value is special NoneToken() which must be tested with == operator
        >>> decl1.variable.value is None  # won't work
        False
        >>> decl1.variable.value == None  # not PEP-8 compliant
        True
        >>> decl1.variable.value == NoneToken()  # OK
        True
        >>> decl2 = x.as_Declaration(value=42.0)
        >>> decl2.variable.value == 42.0
        True

        Nr   )rR   updateDeclarationr  )r7   rR   kwr   r   r    as_Declaration  s   
zVariable.as_Declarationc                 C  s:   zt |}W n ty   td| |f w || |ddS )NzInvalid comparison %s < %sF)evaluate)r   r   rL   )r7   r   r   r   r   r    	_relation
  s   zVariable._relationc                 C     |  |tS r:   )r  r   r   r   r   r    r<     r6  zVariable.<lambda>c                 C  r  r:   )r  r   r   r   r   r    r<     r6  c                 C  r  r:   )r  r   r   r   r   r    r<     r6  c                 C  r  r:   )r  r   r   r   r   r    r<     r6  )r(   r)   r*   r   r+   r  r5   r0   copyr  r  rD   r   r   _construct_symbol_construct_valuer   r
   r  r  r  __lt____le____ge____gt__r   r   r   r    r     s     1

, r   c                   @  r4  )Pointera2   Represents a pointer. See ``Variable``.

    Examples
    ========

    Can create instances of ``Element``:

    >>> from sympy import Symbol
    >>> from sympy.codegen.ast import Pointer
    >>> i = Symbol('i', integer=True)
    >>> p = Pointer('x')
    >>> p[i+1]
    Element(x, indices=(i + 1,))

    r   c                 C  s0   zt | j|W S  ty   t | j|f Y S w r:   )r   r  rL   )r7   keyr   r   r    __getitem__(  s
   zPointer.__getitem__N)r(   r)   r*   r   r+   r  r   r   r   r    r    s    r  c                   @  sJ   e Zd ZdZd ZZeedZee	Z
edd Zedd Zee	ZdS )r   a   Element in (a possibly N-dimensional) array.

    Examples
    ========

    >>> from sympy.codegen.ast import Element
    >>> elem = Element('x', 'ijk')
    >>> elem.symbol.name == 'x'
    True
    >>> elem.indices
    (i, j, k)
    >>> from sympy import ccode
    >>> ccode(elem)
    'x[i][j][k]'
    >>> ccode(Element('x', 'ijk', strides='lmn', offset='o'))
    'x[i*l + j*m + k*n + o]'

    )r  indicesstridesoffset)r  r  c                 C     t |  S r:   r"   rm   r   r   r    r<   E      zElement.<lambda>c                 C  r  r:   r"   rm   r   r   r    r<   F  r  N)r(   r)   r*   r   r+   r5   rD   r0   r   r   r  _construct_indices_construct_strides_construct_offsetr   r   r   r    r   /  s    
r   c                   @     e Zd ZdZd ZZeZdS )r  a   Represents a variable declaration

    Parameters
    ==========

    variable : Variable

    Examples
    ========

    >>> from sympy.codegen.ast import Declaration, NoneToken, untyped
    >>> z = Declaration('z')
    >>> z.variable.type == untyped
    True
    >>> # value is special NoneToken() which must be tested with == operator
    >>> z.variable.value is None  # won't work
    False
    >>> z.variable.value == None  # not PEP-8 compliant
    True
    >>> z.variable.value == NoneToken()  # OK
    True
    )variableN)r(   r)   r*   r   r+   r5   r   _construct_variabler   r   r   r    r  J  s    r  c                   @  s0   e Zd ZdZd ZZedd Zedd Z	dS )Whilea}   Represents a 'for-loop' in the code.

    Expressions are of the form:
        "while condition:
             body..."

    Parameters
    ==========

    condition : expression convertible to Boolean
    body : CodeBlock or iterable
        When passed an iterable it is used to instantiate a CodeBlock.

    Examples
    ========

    >>> from sympy import symbols, Gt, Abs
    >>> from sympy.codegen import aug_assign, Assignment, While
    >>> x, dx = symbols('x dx')
    >>> expr = 1 - x**2
    >>> whl = While(Gt(Abs(dx), 1e-9), [
    ...     Assignment(dx, -expr/expr.diff(x)),
    ...     aug_assign(x, '+', dx)
    ... ])

    )	conditionr2   c                 C  s   t | S r:   )r   )condr   r   r    r<     r  zWhile.<lambda>c                 C  r   r:   r   r   r   r   r    r     r   zWhile._construct_bodyN)
r(   r)   r*   r   r+   r5   r   _construct_conditionr   r   r   r   r   r    r  e  s    r  c                   @  s$   e Zd ZdZd ZZedd ZdS )Scopez Represents a scope in the code.

    Parameters
    ==========

    body : CodeBlock or iterable
        When passed an iterable it is used to instantiate a CodeBlock.

    r2   c                 C  r   r:   r   r   r   r   r    r     r   zScope._construct_bodyN)r(   r)   r*   r   r+   r5   r   r   r   r   r   r    r    s
    	r  c                   @  r  )Streama   Represents a stream.

    There are two predefined Stream instances ``stdout`` & ``stderr``.

    Parameters
    ==========

    name : str

    Examples
    ========

    >>> from sympy import pycode, Symbol
    >>> from sympy.codegen.ast import Print, stderr, QuotedString
    >>> print(pycode(Print(['x'], file=stderr)))
    print(x, file=sys.stderr)
    >>> x = Symbol('x')
    >>> print(pycode(Print([QuotedString('x')], file=stderr)))  # print literally "x"
    print("x", file=sys.stderr)

    r  N)r(   r)   r*   r   r+   r5   r   r3  r   r   r   r    r    s    r  stdoutstderrc                   @  s2   e Zd ZdZd ZZeedZee	Z
eZeZdS )Printa   Represents print command in the code.

    Parameters
    ==========

    formatstring : str
    *args : Basic instances (or convertible to such through sympify)

    Examples
    ========

    >>> from sympy.codegen.ast import Print
    >>> from sympy import pycode
    >>> print(pycode(Print('x y'.split(), "coordinate: %12.5g %12.5g\\n")))
    print("coordinate: %12.5g %12.5g\n" % (x, y), end="")

    )
print_argsformat_stringfile)r  r  N)r(   r)   r*   r   r+   r5   rD   r0   r   r%   _construct_print_argsr	  _construct_format_stringr  _construct_filer   r   r   r    r    s    
r  c                   @  sH   e Zd ZU dZdZeej Zded< eZ	e
Zedd Zedd Zd	S )
FunctionPrototypea"   Represents a function prototype

    Allows the user to generate forward declaration in e.g. C/C++.

    Parameters
    ==========

    return_type : Type
    name : str
    parameters: iterable of Variable instances
    attrs : iterable of Attribute instances

    Examples
    ========

    >>> from sympy import ccode, symbols
    >>> from sympy.codegen.ast import real, FunctionPrototype
    >>> x, y = symbols('x y', real=True)
    >>> fp = FunctionPrototype(real, 'foo', [x, y])
    >>> ccode(fp)
    'double foo(double x, double y)'

    )return_typer  r  r.   r5   c                 C  s   dd }t t||  S )Nc                 S  s(   t | tr| jS t | tr| S t| S r:   )r   r  r  r   r  rm   r   r   r    _var  s
   


z5FunctionPrototype._construct_parameters.<locals>._var)r
   r   )r$   r  r   r   r    r    s   z'FunctionPrototype._construct_parametersc                 C  s(   t |ts	td| di |jddS )Nz1func_def is not an instance of FunctionDefinitionr  r  r   )r   FunctionDefinitionrL   rR   )r@   func_defr   r   r    from_FunctionDefinition     
z)FunctionPrototype.from_FunctionDefinitionN)r(   r)   r*   r   r+   r  r5   r   r  _construct_return_typer   r3  r   r  r   r  r   r   r   r    r    s   
 

r  c                   @  sD   e Zd ZdZdZejdd e ej Zedd Z	edd Z
dS )	r  a   Represents a function definition in the code.

    Parameters
    ==========

    return_type : Type
    name : str
    parameters: iterable of Variable instances
    body : CodeBlock or iterable
    attrs : iterable of Attribute instances

    Examples
    ========

    >>> from sympy import ccode, symbols
    >>> from sympy.codegen.ast import real, FunctionPrototype
    >>> x, y = symbols('x y', real=True)
    >>> fp = FunctionPrototype(real, 'foo', [x, y])
    >>> ccode(fp)
    'double foo(double x, double y)'
    >>> from sympy.codegen.ast import FunctionDefinition, Return
    >>> body = [Return(x*y)]
    >>> fd = FunctionDefinition.from_FunctionPrototype(fp, body)
    >>> print(ccode(fd))
    double foo(double x, double y){
        return x*y;
    }
    r  Nc                 C  r   r:   r   r   r   r   r    r   )  r   z"FunctionDefinition._construct_bodyc                 C  s(   t |ts	td| dd|i| S )Nz2func_proto is not an instance of FunctionPrototyper2   r   )r   r  rL   rR   )r@   
func_protor2   r   r   r    from_FunctionPrototype0  r  z)FunctionDefinition.from_FunctionPrototype)r(   r)   r*   r   r+   r  r5   r  r   r   r  r   r   r   r    r    s    
r  c                   @  s    e Zd ZdZd ZZeeZdS )ReturnaC   Represents a return command in the code.

    Parameters
    ==========

    return : Basic

    Examples
    ========

    >>> from sympy.codegen.ast import Return
    >>> from sympy.printing.pycode import pycode
    >>> from sympy import Symbol
    >>> x = Symbol('x')
    >>> print(pycode(Return(x)))
    return x

    )returnN)	r(   r)   r*   r   r+   r5   r   r   _construct_returnr   r   r   r    r  7  s    r  c                   @  s(   e Zd ZdZd ZZeZedd Z	dS )FunctionCallaR   Represents a call to a function in the code.

    Parameters
    ==========

    name : str
    function_args : Tuple

    Examples
    ========

    >>> from sympy.codegen.ast import FunctionCall
    >>> from sympy import pycode
    >>> fcall = FunctionCall('foo', 'bar baz'.split())
    >>> print(pycode(fcall))
    foo(bar, baz)

    )r  function_argsc                 C  r  r:   r"   r#   r   r   r    r<   d  r  zFunctionCall.<lambda>N)
r(   r)   r*   r   r+   r5   r   r3  r   _construct_function_argsr   r   r   r    r  N  s
    r  c                   @  s   e Zd ZdZd ZZdS )Raisez4 Prints as 'raise ...' in Python, 'throw ...' in C++)	exceptionN)r(   r)   r*   r   r+   r5   r   r   r   r    r  g  s    r  c                   @  r  )RuntimeError_z Represents 'std::runtime_error' in C++ and 'RuntimeError' in Python.

    Note that the latter is uncommon, and you might want to use e.g. ValueError.
    )messageN)r(   r)   r*   r   r+   r5   r   _construct_messager   r   r   r    r  l  s    r  N)r  )r  )pr   
__future__r   typingr   collectionsr   sympy.core.relationalr   r   r   r   
sympy.corer	   r
   r   sympy.core.basicr   sympy.core.exprr   r   sympy.core.numbersr   r   r   sympy.core.sympifyr   r   r   sympy.utilities.iterablesr   r   r   r   r%   r'   r-   r   break_r   	continue_r   rD   r   r   r   r   r   r   r   r   r   r   r   r   r   r	  r
  r  r  r5  r7  r@  rE  rK  rF  rG  rZ  r_  r`  ra  rb  rd  rf  rh  rj  rk  rl  rm  rn  rp  rr  ru  ry  r|  rR   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    <module>   s      -;(+ Z>2# 8w







( &1/