a
    HSick%                     @   sF   d dl Z d dlZd dlZd dlZd dlZd dlZG dd de jZdS )    Nc                   @   sP   e Zd ZdZejjddddZej	e
edddZd	d
 Zdd Zdd ZdS )AttributeTypeIsSupportedCheckera  
    Checks the ``__init__`` method of a given ``nn.Module`` to ensure
    that all instance-level attributes can be properly initialized.

    Specifically, we do type inference based on attribute values...even
    if the attribute in question has already been typed using
    Python3-style annotations or ``torch.jit.annotate``. This means that
    setting an instance-level attribute to ``[]`` (for ``List``),
    ``{}`` for ``Dict``), or ``None`` (for ``Optional``) isn't enough
    information for us to properly initialize that attribute.

    An object of this class can walk a given ``nn.Module``'s AST and
    determine if it meets our requirements or not.

    Known limitations
    1. We can only check the AST nodes for certain constructs; we can't
    ``eval`` arbitrary expressions. This means that function calls,
    class instantiations, and complex expressions that resolve to one of
    the "empty" values specified above will NOT be flagged as
    problematic.
    2. We match on string literals, so if the user decides to use a
    non-standard import (e.g. `from typing import List as foo`), we
    won't catch it.

    Example:

        .. code-block:: python

            class M(torch.nn.Module):
                def fn(self):
                    return []

                def __init__(self):
                    super().__init__()
                    self.x: List[int] = []

                def forward(self, x: List[int]):
                    self.x = x
                    return 1

        The above code will pass the ``AttributeTypeIsSupportedChecker``
        check since we have a function call in ``__init__``. However,
        it will still fail later with the ``RuntimeError`` "Tried to set
        nonexistent attribute: x. Did you forget to initialize it in
        __init__()?".

    Args:
        nn_module - The instance of ``torch.nn.Module`` whose
            ``__init__`` method we wish to check
    N)	nn_modulereturnc                    st   t jdk | _t|jj}dd  d fdd|dD }t	
t|}t|j | _d| _| | d S )N)      c                 S   s   |   } | do| d S )N#z# type:)strip
startswith)line r   L/var/www/html/django/DPS/env/lib/python3.9/site-packages/torch/jit/_check.pyis_useless_commentD   s    zAAttributeTypeIsSupportedChecker.check.<locals>.is_useless_comment
c                    s   g | ]} |s|qS r   r   ).0lr   r   r   
<listcomp>G       z9AttributeTypeIsSupportedChecker.check.<locals>.<listcomp>F)sysversion_infousing_deprecated_astinspect	getsource	__class____init__joinsplitastparsetextwrapdedentlist__annotations__keysclass_level_annotationsvisiting_class_level_annvisit)selfr   source_linesZinit_astr   r   r   check=   s    z%AttributeTypeIsSupportedChecker.check)nodeann_typer   c                 C   s   |dkr$t |tjsdS |jrdS nb|dkrHt |tjs<dS |jrdS n>|dkr| jsft |tjsfdS | jr|t |tjs|dS |j	rdS dS )NListFDictOptionalT)

isinstancer   r,   eltsr-   r#   r   ConstantNameConstantvalue)r'   r*   r+   r   r   r   _is_empty_containerT   s,    

z3AttributeTypeIsSupportedChecker._is_empty_containerc                 C   sT   z*t |jtjr(|jd j| jv r(d| _W n ty>   Y dS 0 | 	| d| _dS )a  
        If we're visiting a Call Node (the right-hand side of an
        assignment statement), we won't be able to check the variable
        that we're assigning to (the left-hand side of an assignment).
        Because of this, we need to store this state in visitAssign.
        (Luckily, we only have to do this if we're assigning to a Call
        Node, i.e. ``torch.jit.annotate``. If we're using normal Python
        annotations, we'll be visiting an AnnAssign Node, which has its
        target built in.)
        r   TNF)
r/   r3   r   Calltargetsattrr$   r%   AttributeErrorgeneric_visit)r'   r*   r   r   r   visit_Assignr   s    

z,AttributeTypeIsSupportedChecker.visit_Assignc                 C   s   z|j jjdkrW dS W n ty,   Y dS 0 |j j| jv r@dS h d}z|jjj|vr^W dS W n tyt   Y dS 0 |jjj}| |j|sdS t	d dS )z
        Visit an AnnAssign node in an ``nn.Module``'s ``__init__``
        method and see if it conforms to our attribute annotation rules.
        r'   N>   r.   r,   r-   The TorchScript type system doesn't support instance-level annotations on empty non-base types in `__init__`. Instead, either 1) use a type annotation in the class body, or 2) wrap the type in `torch.jit.Attribute`.)
targetr3   idr8   r7   r$   
annotationr4   warningswarnr'   r*   Z
containersr+   r   r   r   visit_AnnAssign   s"    


z/AttributeTypeIsSupportedChecker.visit_AnnAssignc                 C   s  | j r
dS zb|jjjjdks6|jjjdks6|jjdkrB| | n(|jjjjdks`|jjjdkrj| | W n ty   | | Y n0 t|jdkrdS t	|jd t
jsdS h d}z|jd jj}W n ty   Y dS 0 ||vrdS | |jd |sdS td	 dS )
z
        Visit a Call node in an ``nn.Module``'s ``__init__``
        method and determine if it's ``torch.jit.annotate``. If so,
        see if it conforms to our attribute annotation rules.
        Ntorchjitannotate   r   >   r.   r,   r-      r;   )r%   funcr3   r=   r7   r9   r8   lenargsr/   r   	Subscriptr4   r?   r@   rA   r   r   r   
visit_Call   s:    
z*AttributeTypeIsSupportedChecker.visit_Call)__name__
__module____qualname____doc__rC   nnModuler)   r   ASTstrboolr4   r:   rB   rL   r   r   r   r   r   	   s   35r   )r   r   r   r   rC   r?   NodeVisitorr   r   r   r   r   <module>   s   