a
    ]9ag                     @   s~  d dl Z d dlZd dlZd dlZd dlZd dlmZ d dlmZ d dlm	Z	 d dlm
Z
 d dlmZ d dlmZ d dlmZ d d	lmZ d d
lmZ d dlmZ d dlmZ d2ddZdd Zd3ddZd4ddZd5ddZdd Zdd ZG dd deZeZG d d! d!eZd6d"d#Zd$d% Z d&d' 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 d0d1 d1eZ&dS )7    N)builtins)
exceptions)libutils)pynames)
pynamesdef)	pyobjects)pyobjectsdef)pyscopes)worder)	fixsyntax)functionutils   Tc                 C   s2   |durt jdtdd t| |||||d}| S )am  Return python code completions as a list of `CodeAssistProposal`

    `resource` is a `rope.base.resources.Resource` object.  If
    provided, relative imports are handled.

    `maxfixes` is the maximum number of errors to fix if the code has
    errors in it.

    If `later_locals` is `False` names defined in this scope and after
    this line is ignored.

    Nz'Codeassist no longer supports templates   
stacklevel)resourcemaxfixeslater_locals)warningswarnDeprecationWarning_PythonCodeAssist)projectsource_codeoffsetr   Z	templatesr   r   Zassist r   6lib/python3.9/site-packages/rope/contrib/codeassist.pycode_assist   s    r   c                 C   s    t | d}||\}}}|S )aN  Return the offset in which the completion should be inserted

    Usually code assist proposals should be inserted like::

        completion = proposal.name
        result = (source_code[:starting_offset] +
                  completion + source_code[offset:])

    Where starting_offset is the offset returned by this function.

    Tr
   Worderget_splitted_primary_beforer   r   word_finder
expressionstartingstarting_offsetr   r   r   r%   8   s
    
r%   c                 C   s:   t | |||}||}|du r&dS | }t |S )zGet the pydocN)r   	FixSyntax	pyname_at
get_objectPyDocExtractorget_doc)r   r   r   r   r   fixerpynamepyobjectr   r   r   r*   K   s    
r*   Fc           
      C   s>   t | |||}||}|du r&dS | }	t |	||S )ay  Get the calltip of a function

    The format of the returned string is
    ``module_name.holding_scope_names.function_name(arguments)``.  For
    classes `__init__()` and for normal objects `__call__()` function
    is used.

    Note that the offset is on the function itself *not* after the its
    open parenthesis.  (Actually it used to be the other way but it
    was easily confused when string literals were involved.  So I
    decided it is better for it not to try to be too clever when it
    cannot be clever enough).  You can use a simple search like::

        offset = source_code.rindex('(', 0, offset) - 1

    to handle simple situations.

    If `ignore_unknown` is `True`, `None` is returned for functions
    without source-code like builtins and extensions.

    If `remove_self` is `True`, the first parameter whose name is self
    will be removed for methods.
    N)r   r&   r'   r(   r)   get_calltip)
r   r   r   r   r   ignore_unknownremove_selfr+   r,   r-   r   r   r   r.   U   s     
r.   c           	      C   sJ   t | |||}||}|durF| \}}|durF|  |fS dS )aS  Return the definition location of the python name at `offset`

    Return a (`rope.base.resources.Resource`, lineno) tuple.  If no
    `resource` is given and the definition is inside the same module,
    the first element of the returned tuple would be `None`.  If the
    location cannot be determined ``(None, None)`` is returned.

    N)NN)r   r&   r'   get_definition_location
get_moduleget_resource)	r   r   r   r   r   r+   r,   modulelinenor   r   r   r1   }   s    	
r1   c                  O   s,   dd l }tjdtdd |jjj| i |S )Nr   z4Use `rope.contrib.findit.find_occurrences()` insteadr   r   )Zrope.contrib.finditr   r   r   ZcontribZfinditfind_occurrences)argskwdsroper   r   r   r6      s    r6   c           
      C   s   |  |}tjj||}| \}}|s.dS | |}g }t|t	j
rdt| |dfg}n"t|t	jrt| |dfg}|jrt|tjrd}	nt|tjrd}	nd}	||j |	f |j}q|| jdf |  |S )a  Get the canonical path to an object.

    Given the offset of the object, this returns a list of
    (name, name_type) tuples representing the canonical path to the
    object. For example, the 'x' in the following code:

        class Foo(object):
            def bar(self):
                class Qux(object):
                    def mux(self, x):
                        pass

    we will return:

        [('Foo', 'CLASS'), ('bar', 'FUNCTION'), ('Qux', 'CLASS'),
         ('mux', 'FUNCTION'), ('x', 'PARAMETER')]

    `resource` is a `rope.base.resources.Resource` object.

    `offset` is the offset of the pyname you want the path to.

    NZ	PARAMETERZVARIABLEZFUNCTIONZCLASSZMODULE)get_pymoduler9   baseevaluateZeval_locationr1   	get_scopeget_inner_scope_for_line
isinstancer   ZParameterNamer
   Zget_name_atr3   ZAssignedNameparentr	   ZFunctionScopeZ
ClassScopeappendr-   get_nameZ	real_pathreverse)
r   r   r   Zpymodr,   defmodr5   scopenamesZ
scope_typer   r   r   get_canonical_path   s,    
rG   c                   @   s^   e Zd ZdZdddZdd Zdd Zed	d
 Zedd Z	dd Z
dd Zedd ZdS )CompletionProposala  A completion proposal

    The `scope` instance variable shows where proposed name came from
    and can be 'global', 'local', 'builtin', 'attribute', 'keyword',
    'imported', 'parameter_keyword'.

    The `type` instance variable shows the approximate type of the
    proposed object and can be 'instance', 'class', 'function', 'module',
    and `None`.

    All possible relations between proposal's `scope` and `type` are shown
    in the table below (different scopes in rows and types in columns):

                      | instance | class | function | module | None
                local |    +     |   +   |    +     |   +    |
               global |    +     |   +   |    +     |   +    |
              builtin |    +     |   +   |    +     |        |
            attribute |    +     |   +   |    +     |   +    |
             imported |    +     |   +   |    +     |   +    |
              keyword |          |       |          |        |  +
    parameter_keyword |          |       |          |        |  +

    Nc                 C   s   || _ || _| || _d S N)namer,   
_get_scoperE   )selfrJ   rE   r,   r   r   r   __init__   s    zCompletionProposal.__init__c                 C   s   d| j | j| jf S )Nz%s (%s, %s))rJ   rE   typerL   r   r   r   __str__   s    zCompletionProposal.__str__c                 C   s   t | S rI   )strrO   r   r   r   __repr__   s    zCompletionProposal.__repr__c                 C   sF   | j }t|tjr| }t|tjrB| }t|tjrB|	 S dS )ztThe names of the parameters the function takes.

        Returns None if this completion is not a function.
        N)
r,   r?   r   ImportedNameZ_get_imported_pynameDefinedNamer(   r   AbstractFunctionget_param_namesrL   r,   r-   r   r   r   
parameters   s    zCompletionProposal.parametersc                 C   s   | j }t|tjrX| }t|tjr*dS t|tjr:dS t|tjsRt|tjrdS nPt|tj	rhdS t|tj
st|tjr| }t|tjrdS t|tjrdS dS )Nfunctionclassinstancer4   )r,   r?   r   BuiltinNamer(   ZBuiltinFunctionZBuiltinClassZBuiltinObjectr   ImportedModulerS   rT   r   rU   AbstractClassrW   r   r   r   rN     s,    zCompletionProposal.typec                 C   s6   t | jtjrdS t | jtjs.t | jtjr2dS |S )Nbuiltinimported)r?   r,   r   r\   r   r]   rS   )rL   rE   r   r   r   rK     s    zCompletionProposal._get_scopec                 C   s0   | j s
dS | j  }t|ds"dS | j   S )zYGet the proposed object's docstring.

        Returns None if it can not be get.
        Nr*   )r,   r(   hasattrr*   rL   r-   r   r   r   r*   &  s    

zCompletionProposal.get_docc                 C   s   t d | jS )NzAthe proposal's `kind` property is deprecated, use `scope` instead)r   r   rE   rO   r   r   r   kind2  s    zCompletionProposal.kind)N)__name__
__module____qualname____doc__rM   rP   rR   propertyrX   rN   rK   r*   rc   r   r   r   r   rH      s   


	rH   c                       s(   e Zd ZdZ fddZdd Z  ZS )NamedParamProposalzA parameter keyword completion proposal

    Holds reference to ``_function`` -- the function which
    parameter ``name`` belongs to. This allows to determine
    default value for this parameter.
    c                    s*   || _ d| }tt| |d || _d S )Nz%s=parameter_keyword)argnamesuperri   rM   	_function)rL   rJ   rY   	__class__r   r   rM   F  s    zNamedParamProposal.__init__c                 C   s4   t j| j}|jD ]\}}| j|kr|  S qdS )zGet a string representation of a param's default value.

        Returns None if there is no default value for this param.
        N)r   DefinitionInforeadrm   Zargs_with_defaultsrk   )rL   Zdefinfoargdefaultr   r   r   get_defaultL  s
    

zNamedParamProposal.get_default)rd   re   rf   rg   rM   rt   __classcell__r   r   rn   r   ri   >  s   ri   c                 C   s   t | ||}| S )a  Sort a list of proposals

    Return a sorted list of the given `CodeAssistProposal`.

    `scopepref` can be a list of proposal scopes.  Defaults to
    ``['parameter_keyword', 'local', 'global', 'imported',
    'attribute', 'builtin', 'keyword']``.

    `typepref` can be a list of proposal types.  Defaults to
    ``['class', 'function', 'instance', 'module', None]``.
    (`None` stands for completions with no type like keywords.)
    )_ProposalSorterget_sorted_proposal_list)	proposals	scopepreftypeprefZsorterr   r   r   sorted_proposalsX  s    r{   c                 C   s0   t | d}||\}}}|r,|d | S |S )z!Return the expression to completeT.r   r!   r   r   r   starting_expressioni  s    
r}   c                   C   s   t jdtdd i S )Nz"default_templates() is deprecated.r   r   )r   r   r   r   r   r   r   default_templatest  s    r~   c                   @   sn   e Zd ZdddZejZdd Zdd	 Zd
d Z	dd Z
dddZdd Zdd Zdd Zdd Zdd ZdS )r   Nr   Tc                 C   sH   || _ || _|| _|| _|| _t|d| _| j|\| _	| _
| _d S )NT)r   coder   r   r   r
   r   r"   r    r#   r$   r   )rL   r   r   r   r   r   r   r   r   r   rM   |  s    
z_PythonCodeAssist.__init__c                 C   s:   |d }|dkr2||   s(|| dv r2|d8 }q|d S )Nr   r   _)isalnum)rL   r   r   Zcurrent_offsetr   r   r   _find_starting_offset  s    


z'_PythonCodeAssist._find_starting_offsetc                 C   s.   g }| j D ]}||r
|t|d q
|S )Nkeyword)keywords
startswithrA   rH   )rL   r$   resultkwr   r   r   _matching_keywords  s
    

z$_PythonCodeAssist._matching_keywordsc                 C   sV   | j t| jkrg S t|   }| j dkrR| j dkrR|	| 
| j |S )N )r   lenr   list_code_completionsvaluesr#   stripr$   extendr   )rL   Zcompletionsr   r   r   __call__  s    z_PythonCodeAssist.__call__c           	      C   sv   i }t jj|| j}|d urr| }d}t|tjtj	fr@d}|
  D ]$\}}|| jrLt|||||< qL|S )N	attributer`   )r9   r;   r<   eval_strr#   r(   r?   r   ZPyModuleZ	PyPackageZget_attributesitemsr   r$   rH   )	rL   module_scopeZholding_scoper   Zfound_pynameelementcompl_scoperJ   r,   r   r   r   _dotted_completions  s    z%_PythonCodeAssist._dotted_completionsc                 C   s   |j d ur| |j | |d u r*| }n| }| D ]T\}}|| jr:d}| dkrbd}|d u s~| js~| 	|||s:t
|||||< q:d S )NlocalZModuleglobal)r@   _undotted_completionsZget_propagated_namesZ	get_namesr   r   r$   Zget_kindr   _is_defined_afterrH   )rL   rE   r   r5   rF   rJ   r,   r   r   r   r   r     s"    

z'_PythonCodeAssist._undotted_completionsc                 C   sZ   | j | j}|d u ri S | ||}i }|D ]&}|| jr.t|d|| d||< q.|S )Nr   )rE   r,   )r"   Zget_from_moduler   _find_moduler   r$   rH   )rL   pymodulemodule_namer   rJ   r   r   r   _from_import_completions  s    
z*_PythonCodeAssist._from_import_completionsc                 C   s8   d}|| dkr|d7 }qt |||d  |}| S )Nr   r|   r   )r   r]   r(   )rL   r   r   Zdotsr,   r   r   r   r     s
    
z_PythonCodeAssist._find_modulec                 C   sV   |  }|d urR|d d urR|d |j krR||d   krJ| krRn ndS d S )Nr   r   T)r1   r-   r2   Zget_end)rL   rE   r,   r5   locationr   r   r   r     s    
z#_PythonCodeAssist._is_defined_afterc                 C   s   | j dd| jd }t| j| j | j| j}| }|	 }|j
}|d}i }t||}t||d  }	|||	}
| j| jr| |S | j dkr|| ||
 n$|| |j|
 | j|
||d |S )N
r   r   r   )r5   )r   countr   r   r&   r   r   r   r:   r=   r   splitZ_logical_startZ_get_line_indentsr>   r"   Zis_a_name_after_from_importr   r#   r   updater   _keyword_parametersr-   r   )rL   r5   r+   r   r   r   linesr   startindentsZinner_scoper   r   r   r     s&    

z#_PythonCodeAssist._code_completionsc                 C   s,  | j }|dkri S t| jd}||d r(||d }||d }ztjj	
||}W n tjyx   i  Y S 0 |d ur(| }t|tjrn6t|tjrd|v r|d  }nd|v r|d  }t|tjr(g }	|	|jdd i }
|	D ]&}|| j rt|||
|d <  q|
S i S )	Nr   Tr   rM   r   F)Zspecial_args=)r   r
   r   r   Zis_on_function_call_keywordZfind_parens_start_from_insideZget_primary_atr9   r;   r<   r   r   ZBadIdentifierErrorr(   r?   r   rU   r^   r   rV   r   r$   ri   )rL   r   rE   r   r"   Zfunction_parensZprimaryZfunction_pynamer-   Zparam_namesr   rJ   r   r   r   r     s>    


z%_PythonCodeAssist._keyword_parameters)Nr   T)N)rd   re   rf   rM   r   kwlistr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   {  s    

	r   c                   @   s*   e Zd ZdZd	ddZdd Zdd ZdS )
rv   z$Sort a list of code assist proposalsNc                 C   sH   || _ |d u rg d}|| _|d u r,g d}tdd t|D | _d S )N)rj   r   r   r`   r   r_   r   )rZ   rY   r[   r4   Nc                 s   s   | ]\}}||fV  qd S rI   r   ).0indexrN   r   r   r   	<genexpr>+      z+_ProposalSorter.__init__.<locals>.<genexpr>)rx   ry   dict	enumeratetyperank)rL   Zcode_assist_proposalsry   rz   r   r   r   rM     s    	z_ProposalSorter.__init__c                    sn   i } j D ]}||jg | q
g } jD ]:}||g } fdd|D }|j jd || q.|S )z%Return a list of `CodeAssistProposal`c                    s   g | ]}|j  jv r|qS r   )rN   r   )r   proposalrO   r   r   
<listcomp>5  s   z<_ProposalSorter.get_sorted_proposal_list.<locals>.<listcomp>)key)	rx   
setdefaultrE   rA   ry   getsort_proposal_keyr   )rL   rx   r   r   rE   Zscope_proposalsr   rO   r   rw   -  s    


z(_ProposalSorter.get_sorted_proposal_listc                 C   s&   dd }| j |jd||j|jfS )Nc                 S   s   t dd | D S )Nc                 s   s   | ]}|d krdV  qdS )r   r   Nr   )r   cr   r   r   r   @  r   zJ_ProposalSorter._proposal_key.<locals>._underline_count.<locals>.<genexpr>)sum)rJ   r   r   r   _underline_count?  s    z7_ProposalSorter._proposal_key.<locals>._underline_countd   )r   r   rN   rJ   )rL   Z	proposal1r   r   r   r   r   >  s
    z_ProposalSorter._proposal_key)NN)rd   re   rf   rg   rM   rw   r   r   r   r   r   rv     s   
rv   c                       st   e Zd Zdd ZdddZ fddZdd	 Zd
d Zdd Zdd Z	dddZ
dddZdd ZdddZ  ZS )r)   c                 C   sJ   t |tjr| |S t |tjr,| |S t |tjrF| | S d S rI   )	r?   r   rU   _get_function_docstringr^   _get_class_docstringAbstractModule_trim_docstringr*   rb   r   r   r   r*   O  s    

zPyDocExtractor.get_docFc                 C   s   z4t |tjr|d  }t |tjs2|d  }W n tjyJ   Y d S 0 |r`t |tjs`d S t |tjr| j|dd}|r| 	|r|
dd
ddS |S d S )	NrM   r   T)
add_modulez(self)z()z(self, ()r?   r   r^   r(   rU   r   ZAttributeNotFoundError
PyFunction_get_function_signature
_is_methodreplace)rL   r-   r/   r0   r   r   r   r   r.   X  s    zPyDocExtractor.get_calltipc                    sv   |  | d} fdd| D }d| d|f | }d|v rr|d  }t|tjrr|d| 	| 7 }|S )Nr   c                    s   g | ]}|  qS r   )rB   )r   rl   rn   r   r   r   j  r   z7PyDocExtractor._get_class_docstring.<locals>.<listcomp>zclass %s(%s):

, rM   

)
r   r*   get_superclassesrB   joinr(   r?   r   rU   _get_single_function_docstring)rL   pyclasscontentsZsupersdocinitrn   r   r   r   h  s    z#PyDocExtractor._get_class_docstringc                    s@   |g}  |r(| |j|  d fdd|D S )Nr   c                    s   g | ]}  |qS r   )r   )r   rY   rO   r   r   r   z  r   z:PyDocExtractor._get_function_docstring.<locals>.<listcomp>)r   r   _get_super_methodsr@   rB   r   )rL   
pyfunctionZ	functionsr   rO   r   r   s  s    
z&PyDocExtractor._get_function_docstringc                 C   s   t |tjot |jtjS rI   )r?   r   r   r@   ZPyClass)rL   r   r   r   r   r   }  s    zPyDocExtractor._is_methodc                 C   s(   |  |}| j| dd}|d | S )Nr   r   z:

)r   r   r*   )rL   r   Z	signatureZdocsr   r   r   r     s    
z-PyDocExtractor._get_single_function_docstringc                 C   sR   g }|  D ]@}||v r:||  }t|tjr:|| || || q|S rI   )r   r(   r?   r   rU   rA   r   r   )rL   r   rJ   r   Zsuper_classrY   r   r   r   r     s    
z!PyDocExtractor._get_super_methodsc                 C   sR   |  ||}t|tjr0tj|}||  S d||  d	|
 f S d S )Nz%s(%s)r   )	_locationr?   r   r   r   rp   rq   Z	to_stringrB   r   rV   )rL   r   r   r   infor   r   r   r     s    
z&PyDocExtractor._get_function_signaturec                 C   s   g }|j }|r:t|tjs:||  |d |j }q
|r|t|tjr\|d| | t|t	j
r||d| d  d|S )Nr|   r   r   )r@   r?   r   r   rA   rB   r   insert_get_moduler   ZBuiltinModuler   )rL   r-   r   r   r@   r   r   r   r     s    
zPyDocExtractor._locationc                 C   s2   |  }|d ur.| }|d ur.t|d S dS )Nr|   r   )r2   r3   r   modname)rL   r   r4   r   r   r   r   r     s    zPyDocExtractor._get_moduler   c                    s   |sdS |   }tj}|dd D ]&}| }|r&t|t|t| }q&|d  g}|tjk r|dd D ]}|||d 	  qr|r|d s|
  q|r|d s|
d qd fdd|D S )	zThe sample code from :PEP:`257`r   r   Nr   r   c                 3   s   | ]}d   | V  qdS ) Nr   )r   liner   r   r   r     r   z1PyDocExtractor._trim_docstring.<locals>.<genexpr>)
expandtabs
splitlinessysmaxsizelstripminr   r   rA   rstrippopr   )rL   Z	docstringr   r   indentr   strippedZtrimmedr   r   r   r     s"    

zPyDocExtractor._trim_docstring)FF)F)F)r   )rd   re   rf   r*   r.   r   r   r   r   r   r   r   r   r   ru   r   r   rn   r   r)   N  s   	




r)   c                       s   e Zd Z fddZ  ZS )TemplateProposalc                    s,   t jdtdd tt| |d || _d S )NzTemplateProposal is deprecated.r   r   template)r   r   r   rl   r   rM   r   )rL   rJ   r   rn   r   r   rM     s
    zTemplateProposal.__init__)rd   re   rf   rM   ru   r   r   rn   r   r     s   r   c                   @   s,   e Zd Zdd Zdd Zdd Zdd Zd	S )
Templatec                 C   s   || _ tjdtdd d S )NzTemplate is deprecated.r   r   )r   r   r   r   )rL   r   r   r   r   rM     s    zTemplate.__init__c                 C   s   g S rI   r   rO   r   r   r   	variables  s    zTemplate.variablesc                 C   s   | j S rI   )r   rL   mappingr   r   r   
substitute  s    zTemplate.substitutec                 C   s
   t | jS rI   )r   r   r   r   r   r   get_cursor_location  s    zTemplate.get_cursor_locationN)rd   re   rf   rM   r   r   r   r   r   r   r   r     s   r   )NNr   T)Nr   )Nr   FF)Nr   )NN)'r   r   r   Zrope.base.codeanalyzer9   Zrope.base.evaluateZ	rope.baser   r   r   r   r   r   r   r	   r
   Zrope.contribr   Zrope.refactorr   r   r%   r*   r.   r1   r6   rG   objectrH   ZCodeAssistProposalri   r{   r}   r~   r   rv   r)   r   r   r   r   r   r   <module>   sV       
$
    
(
8i
 5 	