a
    lc'z                     @   s  d Z ddlZddlm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mZ ddlmZ ddlmZ ddlmZmZ ddlm Z  ddlm!Z! ddl"m#Z#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l0m1Z1 ddl2m3Z3 ddl4m5Z5 ddl6m7Z7 ddl8m9Z9m:Z: dd l;m<Z< dd!l=m>Z> e?d" G d#d$ d$Z@G d%d& d&e@ZAd'd( ZBe
jCd)d)d)fd*d+ZDdS ),aQ  
The API basically only provides one class. You can create a :class:`Script` and
use its methods.

Additionally you can add a debug function with :func:`set_debug_function`.
Alternatively, if you don't need a custom function and are happy with printing
debug messages to stdout, simply call :func:`set_debug_function` without
arguments.
    N)Path)tree)get_executable_nodes)debug)settings)cache)KnownContentFileIO)classes)interpreter)helpers)validate_line_column)
Completionsearch_in_module)KeywordName)InterpreterEnvironment)get_default_projectProject)parso_to_jedi_errors)refactoring)extract_functionextract_variable)InferenceState)imports)find_references)try_iter_content)infer_call_of_leaf)transform_path_to_dotted)tree_name_to_values)ModuleValue)ValueSet)unpack_tuple_to_dict)convert_namesconvert_values)load_proper_stub_module)to_listi  c                   @   s@  e Zd ZdZd7ddddddZejdd Zdd	 Zd
d Z	e
d8ddddZe
d9dddddZe
d:dddddddZddddZed;ddZdd Ze
d<ddZe
d=dd Ze
d>d!d"Ze
d?d#d$Zd%d& Zd'd( Zd)d* Zd@d,d-ZdAd.d/Ze
ddd0d1d2Ze
ddd0d3d4ZdBd5d6ZdS )CScriptaK
  
    A Script is the base for completions, goto or whatever you want to do with
    Jedi. The counter part of this class is :class:`Interpreter`, which works
    with actual dictionaries and can work with a REPL. This class
    should be used when a user edits code in an editor.

    You can either use the ``code`` parameter or ``path`` to read a file.
    Usually you're going to want to use both of them (in an editor).

    The Script's ``sys.path`` is very customizable:

    - If `project` is provided with a ``sys_path``, that is going to be used.
    - If `environment` is provided, its ``sys.path`` will be used
      (see :func:`Environment.get_sys_path <jedi.api.environment.Environment.get_sys_path>`);
    - Otherwise ``sys.path`` will match that of the default environment of
      Jedi, which typically matches the sys path that was used at the time
      when Jedi was imported.

    Most methods have a ``line`` and a ``column`` parameter. Lines in Jedi are
    always 1-based and columns are always zero based. To avoid repetition they
    are not always documented. You can omit both line and column. Jedi will
    then just do whatever action you are calling at the end of the file. If you
    provide only the line, just will complete at the end of that line.

    .. warning:: By default :attr:`jedi.settings.fast_parser` is enabled, which means
        that parso reuses modules (i.e. they are not immutable). With this setting
        Jedi is **not thread safe** and it is also not safe to use multiple
        :class:`.Script` instances and its definitions at the same time.

        If you are a normal plugin developer this should not be an issue. It is
        an issue for people that do more complex stuff with Jedi.

        This is purely a performance optimization and works pretty well for all
        typical usages, however consider to turn the setting off if it causes
        you problems. See also
        `this discussion <https://github.com/davidhalter/jedi/issues/1240>`_.

    :param code: The source code of the current file, separated by newlines.
    :type code: str
    :param path: The path of the file in the file system, or ``''`` if
        it hasn't been saved yet.
    :type path: str or pathlib.Path or None
    :param Environment environment: Provide a predefined :ref:`Environment <environments>`
        to work with a specific Python version or virtualenv.
    :param Project project: Provide a :class:`.Project` to make sure finding
        references works well, because the right folder is searched. There are
        also ways to modify the sys path and other things.
    N)pathenvironmentprojectc                C   s  || _ t|trt|}|r$| nd | _|d u rt|d u rBtdt|d}| }W d    n1 sj0    Y  |d u rt	| jd u rd n| jj
}t||| jd| _td | jj|| j|o|jdkdtjtjd\| _}td tj|d	d
| _|| _t  t  d S )Nz)Must provide at least one of code or pathrb)r'   Zscript_pathinit.pyiF)coder&   Zuse_latest_grammarr   Z
diff_cache
cache_pathparsedT)keepends)
_orig_path
isinstancestrr   absoluter&   
ValueErroropenreadr   parentr   _inference_stater   speedZparse_and_get_codesuffixr   Zfast_parserZcache_directory_module_nodeparsosplit_lines_code_lines_coder   Zclear_time_cachesZ
reset_time)selfr,   r&   r'   r(   f rB   M/var/www/html/django/DPS/env/lib/python3.9/site-packages/jedi/api/__init__.py__init__d   s8    
&

zScript.__init__c                 C   s   d }d}| j d ur<t| jjdd| j \}}|d ur<|}|}| j d u rLd }nt| j | j}| j d ur| j jdkrt| j| jj||| j	}|d ur|S |d u rd}t
| j| j	||| j|d}|d dvr| jj|t|g |S )NF)Zadd_parent_pathsr+   __main__)file_iostring_names
code_lines
is_packager   )builtinstyping)r&   r   r8   Zget_sys_pathr   r?   r:   r#   Zlatest_grammarr;   r   r>   Zmodule_cacheaddr   )r@   namesrJ   import_namesZis_prG   Zstub_modulemodulerB   rB   rC   _get_module   sF    

zScript._get_modulec                 C   s   |    S N)rQ   
as_contextr@   rB   rB   rC   _get_module_context   s    zScript._get_module_contextc                 C   s   d| j jt| j| jjf S )Nz<%s: %s %r>)	__class____name__reprr0   r8   r'   rT   rB   rB   rC   __repr__   s
    zScript.__repr__Ffuzzyc             	   C   sX   t d: t| j|  | j||f| j|d}| W  d   S 1 sJ0    Y  dS )a+  
        Completes objects under the cursor.

        Those objects contain information about the completions, more than just
        names.

        :param fuzzy: Default False. Will return fuzzy completions, which means
            that e.g. ``ooa`` will match ``foobar``.
        :return: Completion objects, sorted by name. Normal names appear
            before "private" names that start with ``_`` and those appear
            before magic methods and name mangled names that start with ``__``.
        :rtype: list of :class:`.Completion`
        completerZ   N)r   Zincrease_indent_cmr   r8   rU   r>   get_signaturesr\   )r@   linecolumnr[   
completionrB   rB   rC   r\      s    zScript.complete
only_stubsprefer_stubsc                   s   ||f} j |}|du rx j |}|du s:|jdkr>g S |j||fkrx|jdkrx| }|j|jkrx|jdv rx|}  |}t	
 j||}	t|	||d}	 fdd|	D }
t	t|
S )a  
        Return the definitions of under the cursor. It is basically a wrapper
        around Jedi's type inference.

        This method follows complicated paths and returns the end, not the
        first definition. The big difference between :meth:`goto` and
        :meth:`infer` is that :meth:`goto` doesn't
        follow imports and statements. Multiple objects may be returned,
        because depending on an option you can have two different versions of a
        function.

        :param only_stubs: Only return stubs for this method.
        :param prefer_stubs: Prefer stubs to Python objects for this method.
        :rtype: list of :class:`.Name`
        Nstringoperator)numberrd   keywordra   c                    s   g | ]}t  j|jqS rB   )r	   Namer8   name).0crT   rB   rC   
<listcomp>       z Script.infer.<locals>.<listcomp>)r;   get_name_of_positionget_leaf_for_positiontypeend_posZget_next_leaf	start_posrU   create_contextr   inferr8   r"   sorted_definitionsset)r@   r^   r_   rb   rc   posleafZnext_contextvaluesdefsrB   rT   rC   rt      s*    zScript.infer)follow_importsfollow_builtin_importsrb   rc   c                   s    j ||f}|du r* j||||dS   |}g }	|j r|j r|jj	}
  
|
}| }t| |D ]}||j}	|	rz qqz|	st| }	|rt|	|}	t|	||d}	 fddt|	D }ttt|S )a~  
        Goes to the name that defined the object under the cursor. Optionally
        you can follow imports.
        Multiple objects may be returned, depending on an if you can have two
        different versions of a function.

        :param follow_imports: The method will follow imports.
        :param follow_builtin_imports: If ``follow_imports`` is True will try
            to look up names in builtins (i.e. compiled or extension modules).
        :param only_stubs: Only return stubs for this method.
        :param prefer_stubs: Prefer stubs to Python objects for this method.
        :rtype: list of :class:`.Name`
        Nra   c                    s   g | ]}t  j|qS rB   r	   rh   r8   rj   drT   rB   rC   rl   3  rm   zScript.goto.<locals>.<listcomp>)r;   rn   rt   rU   create_name	tree_nameZis_definitionparent_contextZis_classZ	tree_nodecreate_valueZ	py__mro__nextgotovaluelistr   Zfilter_follow_importsr!   rv   ru   )r@   r^   r_   r|   r}   rb   rc   r   ri   rN   Z
class_nodeZclass_valuemroclsr{   rB   rT   rC   r     s2    zScript.goto
all_scopesc                C   s   | j ||dS )a  
        Searches a name in the current file. For a description of how the
        search string should look like, please have a look at
        :meth:`.Project.search`.

        :param bool all_scopes: Default False; searches not only for
            definitions on the top level of a module level, but also in
            functions and classes.
        :yields: :class:`.Name`
        r   _search_func)r@   rd   r   rB   rB   rC   search7  s    zScript.searchc              	   C   s6   | j |d}t|\}}t| j|  |||||dS )Nr   )rN   wanted_typewanted_namesr\   r[   )_namesr   Zsplit_search_stringr   r8   rU   )r@   rd   r   r\   r[   rN   r   r   rB   rB   rC   r   D  s    zScript._search_funcc                 K   s   | j |fddi|S )a  
        Like :meth:`.Script.search`, but completes that string. If you want to
        have all possible definitions in a file you can also provide an empty
        string.

        :param bool all_scopes: Default False; searches not only for
            definitions on the top level of a module level, but also in
            functions and classes.
        :param fuzzy: Default False. Will return fuzzy completions, which means
            that e.g. ``ooa`` will match ``foobar``.
        :yields: :class:`.Completion`
        r\   Tr   )r@   rd   kwargsrB   rB   rC   complete_searchR  s    zScript.complete_searchc                    sp   j ||dd}|r|S j||f  durl jdv rl fdd}| rltj j}tj|gS g S )a*  
        Used to display a help window to users.  Uses :meth:`.Script.goto` and
        returns additional definitions for keywords and operators.

        Typically you will want to display :meth:`.BaseName.docstring` to the
        user for all the returned definitions.

        The additional definitions are ``Name(...).type == 'keyword'``.
        These definitions do not have a lot of value apart from their docstring
        attribute, which contains the output of Python's :func:`help` function.

        :rtype: list of :class:`.Name`
        T)r|   N)rg   re   Z
error_leafc                     sH    j dv r* jjdkrdS  jjdkr*dS jj} | jj } j |v S )N)()[]trailerFZatom)r   r7   rp   r8   grammarZ_pgen_grammarZreserved_syntax_stringskeys)r   reservedrx   r@   rB   rC   
need_pydocu  s    
zScript.help.<locals>.need_pydoc)	r   r;   ro   rp   r   r8   r   r	   rh   )r@   r^   r_   definitionsr   ri   rB   r   rC   helpa  s    zScript.helpc                    s    d fdd	}|f i |S )a  
        Lists all references of a variable in a project. Since this can be
        quite hard to do for Jedi, if it is too complicated, Jedi will stop
        searching.

        :param include_builtins: Default ``True``. If ``False``, checks if a definition
            is a builtin (e.g. ``sys``) and in that case does not return it.
        :param scope: Default ``'project'``. If ``'file'``, include references in
            the current module only.
        :rtype: list of :class:`.Name`
        Tr(   c                    sv   |dvrt dj f}|d u r,g S t ||dk}fdd|D }| r^|dkrldd |D }t|S )N)r(   filez0Only the scopes "file" and "project" are allowedr   c                    s   g | ]}t  j|qS rB   r~   rj   nrT   rB   rC   rl     rm   z>Script.get_references.<locals>._references.<locals>.<listcomp>c                 S   s   g | ]}|  s|qS rB   )Zin_builtin_moduler   rB   rB   rC   rl     rm   )r4   r;   rn   r   rU   r   ru   )include_builtinsscoper   rN   r   r_   r^   r@   rB   rC   _references  s    z*Script.get_references.<locals>._references)Tr(   rB   )r@   r^   r_   r   r   rB   r   rC   get_references  s    zScript.get_referencesc                    sl   ||f}t j|  du r"g S   j}t j| jj|}t	
d  fdd| D S )aZ  
        Return the function object of the call under the cursor.

        E.g. if the cursor is here::

            abs(# <-- cursor is here

        This would return the ``abs`` function. On the other hand::

            abs()# <-- cursor is here

        This would return an empty list..

        :rtype: list of :class:`.Signature`
        Nzfunc_call followedc                    s   g | ]}t j| qS rB   )r	   	Signaturer8   )rj   	signatureZcall_detailsr@   rB   rC   rl     s   z)Script.get_signatures.<locals>.<listcomp>)r   Zget_signature_detailsr;   rU   rs   Zbracket_leafZcache_signaturesr8   r>   r   r9   r]   )r@   r^   r_   rw   ry   r   rB   r   rC   r]     s     
zScript.get_signaturesc                 C   s   ||f}| j j|dd}|j|ks,|jdkr@| }|dur@|}|  }t|dd}|dur|j|  k r||jd jkrn n|	|
 }n
||}|jdu r|j}qt| j|j}	|	jdkr|	j}
|
j}|dur| }|jd	 |k rq|	 }	q|	S )
z
        Returns the scope context under the cursor. This basically means the
        function, class or module where the cursor is at.

        :rtype: :class:`.Name`
        T)Zinclude_prefixesZ	endmarkerNfuncdefclassdefrP      )r;   ro   rr   rp   Zget_previous_leafrU   r   Zsearch_ancestorchildrenr   rS   rs   ri   r   r	   rh   r8   _namer   Zget_definitionr7   )r@   r^   r_   rw   rx   Zprevious_leafmodule_contextr   ry   Z
definitionri   r   r   rB   rB   rC   get_context  s.    *



zScript.get_contextc           
         s\  d j _ jg j _  }z.t jD ]}||}|jdv rXt j ||j	d  nt
|tjrt| }| r|tdd | D O }|D ]}t|| qnd|jdkr||}|j	d dd D ]}t||| qn,|jd	kr j ||}n
t||}t|  j   q* fd
d j jD }	tt|	dd dW d j _S d j _0 d S )NT)r   r   r   c                 s   s   | ]}|d  V  qdS )r   NrB   )rj   r&   rB   rB   rC   	<genexpr>  rm   z#Script._analysis.<locals>.<genexpr>Z	expr_stmtr      ri   c                    s   g | ]} j |j kr|qS rB   )r&   )rj   arT   rB   rC   rl     rm   z$Script._analysis.<locals>.<listcomp>c                 S   s   | j S rR   )r^   xrB   rB   rC   <lambda>  rm   z"Script._analysis.<locals>.<lambda>keyF)r8   Zis_analysisr;   Zanalysis_modulesrU   r   rs   rp   r   r   r1   r   Importrv   Zget_defined_namesZ	is_nested	get_pathsr   Zinfer_importZ
infer_noder    rt   r   r   Zreset_recursion_limitationsZanalysissorted)
r@   rP   nodery   rO   r   typesZtestlistr{   ZanarB   rT   rC   	_analysis  s8    





zScript._analysisc                    s"    j f i |} fdd|D S )a  
        Returns names defined in the current file.

        :param all_scopes: If True lists the names of all scopes instead of
            only the module namespace.
        :param definitions: If True lists the names that have been defined by a
            class, function or a statement (``a = b`` returns ``a``).
        :param references: If True lists all the names that are not listed by
            ``definitions=True``. E.g. ``a = b`` returns ``b``.
        :rtype: list of :class:`.Name`
        c                    s   g | ]}t  j|qS rB   r~   r   rT   rB   rC   rl   !  rm   z$Script.get_names.<locals>.<listcomp>)r   )r@   r   rN   rB   rT   rC   	get_names  s    zScript.get_namesc                 C   s   t | jj| jS )zm
        Lists all syntax errors in the current file.

        :rtype: list of :class:`.SyntaxError`
        )r   r8   r   r;   rT   rB   rB   rC   get_syntax_errors#  s    zScript.get_syntax_errorsTc                    s:   |     fddtj| j|||dD }t|dd dS )Nc                    s   g | ]}  |qS rB   )r   )rj   ri   r   rB   rC   rl   .  s   z!Script._names.<locals>.<listcomp>)r   r   
referencesc                 S   s   | j S rR   )rr   r   rB   rB   rC   r   7  rm   zScript._names.<locals>.<lambda>r   )rU   r   Zget_module_namesr;   r   )r@   r   r   r   r{   rB   r   rC   r   +  s    
	zScript._namesc                C   s    | j ||dd}t| j||S )z
        Renames all references of the variable under the cursor.

        :param new_name: The variable under the cursor will be renamed to this
            string.
        :raises: :exc:`.RefactoringError`
        :rtype: :class:`.Refactoring`
        Fr   )r   r   renamer8   )r@   r^   r_   new_namer   rB   rB   rC   r   9  s    	zScript.rename)
until_lineuntil_columnc                C   s`   |du r|du rd}n.|du r"|}|du r<t | j|d  }||f}t| j| j| j|||f|S )a;  
        Moves an expression to a new statemenet.

        For example if you have the cursor on ``foo`` and provide a
        ``new_name`` called ``bar``::

            foo = 3.1
            x = int(foo + 1)

        the code above will become::

            foo = 3.1
            bar = foo + 1
            x = int(bar)

        :param new_name: The expression under the cursor will be renamed to
            this string.
        :param int until_line: The the selection range ends at this line, when
            omitted, Jedi will be clever and try to define the range itself.
        :param int until_column: The the selection range ends at this column, when
            omitted, Jedi will be clever and try to define the range itself.
        :raises: :exc:`.RefactoringError`
        :rtype: :class:`.Refactoring`
        Nr   )lenr>   r   r8   r&   r;   r@   r^   r_   r   r   r   Z	until_posrB   rB   rC   r   E  s    
zScript.extract_variablec                C   sb   |du r|du rd}n.|du r"|}|du r<t | j|d  }||f}t| j| j|  |||f|S )a  
        Moves an expression to a new function.

        For example if you have the cursor on ``foo`` and provide a
        ``new_name`` called ``bar``::

            global_var = 3

            def x():
                foo = 3.1
                x = int(foo + 1 + global_var)

        the code above will become::

            global_var = 3

            def bar(foo):
                return int(foo + 1 + global_var)

            def x():
                foo = 3.1
                x = bar(foo)

        :param new_name: The expression under the cursor will be replaced with
            a function with this name.
        :param int until_line: The the selection range ends at this line, when
            omitted, Jedi will be clever and try to define the range itself.
        :param int until_column: The the selection range ends at this column, when
            omitted, Jedi will be clever and try to define the range itself.
        :raises: :exc:`.RefactoringError`
        :rtype: :class:`.Refactoring`
        Nr   )r   r>   r   r8   r&   rU   r   rB   rB   rC   r   l  s    "
zScript.extract_functionc                 C   s(   dd | j ||ddD }t| j|S )a  
        Inlines a variable under the cursor. This is basically the opposite of
        extracting a variable. For example with the cursor on bar::

            foo = 3.1
            bar = foo + 1
            x = int(bar)

        the code above will become::

            foo = 3.1
            x = int(foo + 1)

        :raises: :exc:`.RefactoringError`
        :rtype: :class:`.Refactoring`
        c                 S   s   g | ]
}|j qS rB   )r   r   rB   rB   rC   rl     rm   z!Script.inline.<locals>.<listcomp>Tr   )r   r   inliner8   )r@   r^   r_   rN   rB   rB   rC   r     s    zScript.inline)N)NN)NN)NN)FFF)NN)NN)NN)NN)FTF)NN)NN)rW   
__module____qualname____doc__rD   r   memoize_methodrQ   rU   rY   r   r\   rt   r   r   r$   r   r   r   r   r]   r   r   r   r   r   r   r   r   r   rB   rB   rB   rC   r%   3   sH   0(
++2$$("

&.r%   c                       s8   e Zd ZdZdZdd fdd
Zejdd Z  Z	S )	Interpretera	  
    Jedi's API for Python REPLs.

    Implements all of the methods that are present in :class:`.Script` as well.

    In addition to completions that normal REPL completion does like
    ``str.upper``, Jedi also supports code completion based on static code
    analysis. For example Jedi will complete ``str().upper``.

    >>> from os.path import join
    >>> namespace = locals()
    >>> script = Interpreter('join("").up', [namespace])
    >>> print(script.complete()[0].name)
    upper

    All keyword arguments are same as the arguments for :class:`.Script`.

    :param str code: Code to parse.
    :type namespaces: typing.List[dict]
    :param namespaces: A list of namespace dictionaries such as the one
        returned by :func:`globals` and :func:`locals`.
    TN)r(   c                   s   zdd |D }W n t y,   tdY n0 |dd }|d u rJt }nt|ts\td|d u rptt }t j	|f||d| || _
| j| j_d S )Nc                 S   s   g | ]}t |qS rB   )dictr   rB   rB   rC   rl     rm   z(Interpreter.__init__.<locals>.<listcomp>z-namespaces must be a non-empty list of dicts.r'   z?The environment needs to be an InterpreterEnvironment subclass.)r'   r(   )	Exception	TypeErrorgetr   r1   r   r   cwdsuperrD   
namespaces!_allow_descriptor_getattr_defaultr8   Zallow_descriptor_getattr)r@   r,   r   r(   kwdsr'   rV   rB   rC   rD     s    
zInterpreter.__init__c                 C   sD   | j d u rd }nt| j | j}t| j| j|d| jd}t|| j	S )NrE   )rG   rH   rI   )
r&   r   r?   r   r8   r;   r>   r
   ZMixedModuleContextr   )r@   rG   Ztree_module_valuerB   rB   rC   rU     s    
zInterpreter._get_module_context)
rW   r   r   r   r   rD   r   r   rU   __classcell__rB   rB   r   rC   r     s
   r   c                  G   s*   | D ] }d| }t |dt| qdS )z
    Preloading modules tells Jedi to load a module now, instead of lazy parsing
    of modules. This can be useful for IDEs, to control which modules to load
    on startup.

    :param modules: different module names, list of string.
    zimport %s as x; x.r   N)r%   r\   r   )modulesmsrB   rB   rC   preload_module  s    r   Tc                 C   s   | t _|t _|t _|t _dS )z
    Define a callback debug function to get all the debug messages.

    If you don't specify any arguments, debug messages will be printed to stdout.

    :param func_cb: The callback function for debug messages.
    N)r   Zdebug_functionZenable_warningZenable_noticeZenable_speed)Zfunc_cbwarningsZnoticesr9   rB   rB   rC   set_debug_function  s    	r   )Er   syspathlibr   r<   Zparso.pythonr   Zjedi.parser_utilsr   Zjedir   r   r   Zjedi.file_ior   Zjedi.apir	   r
   r   Zjedi.api.helpersr   Zjedi.api.completionr   r   Zjedi.api.keywordsr   Zjedi.api.environmentr   Zjedi.api.projectr   r   Zjedi.api.errorsr   r   Zjedi.api.refactoring.extractr   r   Zjedi.inferencer   r   Zjedi.inference.referencesr   Zjedi.inference.argumentsr   Zjedi.inference.helpersr   Zjedi.inference.sys_pathr   Zjedi.inference.syntax_treer   Zjedi.inference.valuer   Zjedi.inference.base_valuer   Zjedi.inference.value.iterabler    Z!jedi.inference.gradual.conversionr!   r"   Zjedi.inference.gradual.utilsr#   Zjedi.inference.utilsr$   setrecursionlimitr%   r   r   Zprint_to_stdoutr   rB   rB   rB   rC   <module>   sZ   	
     @