Add files using upload-large-folder tool
Browse files- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/__init__.py +798 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/classes.py +895 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/completion.py +696 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/completion_cache.py +31 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/environment.py +480 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/errors.py +46 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/exceptions.py +31 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/file_name.py +155 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/helpers.py +522 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/interpreter.py +74 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/keywords.py +51 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/project.py +448 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/refactoring/__init__.py +264 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/refactoring/extract.py +386 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/replstartup.py +29 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/strings.py +111 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/__init__.py +199 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/analysis.py +213 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/arguments.py +335 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/base_value.py +558 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/cache.py +126 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/context.py +499 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/docstring_utils.py +21 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/docstrings.py +286 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/dynamic_params.py +224 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/filters.py +371 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/finder.py +146 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/flow_analysis.py +125 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/helpers.py +202 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/imports.py +592 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/lazy_value.py +61 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/names.py +677 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/param.py +257 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/parser_cache.py +6 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/recursion.py +153 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/references.py +319 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/signature.py +152 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/star_args.py +220 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/syntax_tree.py +903 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/sys_path.py +272 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/utils.py +90 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/value/decorator.py +34 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/value/dynamic_arrays.py +200 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/value/function.py +461 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/value/instance.py +610 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/value/iterable.py +647 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/value/module.py +230 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/value/namespace.py +74 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/plugins/__init__.py +47 -0
- home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/plugins/pytest.py +269 -0
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/__init__.py
ADDED
|
@@ -0,0 +1,798 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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class:`Script` and
|
| 3 |
+
use its methods.
|
| 4 |
+
|
| 5 |
+
Additionally you can add a debug function with :func:`set_debug_function`.
|
| 6 |
+
Alternatively, if you don't need a custom function and are happy with printing
|
| 7 |
+
debug messages to stdout, simply call :func:`set_debug_function` without
|
| 8 |
+
arguments.
|
| 9 |
+
"""
|
| 10 |
+
import sys
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
import parso
|
| 14 |
+
from parso.python import tree
|
| 15 |
+
|
| 16 |
+
from jedi.parser_utils import get_executable_nodes
|
| 17 |
+
from jedi import debug
|
| 18 |
+
from jedi import settings
|
| 19 |
+
from jedi import cache
|
| 20 |
+
from jedi.file_io import KnownContentFileIO
|
| 21 |
+
from jedi.api import classes
|
| 22 |
+
from jedi.api import interpreter
|
| 23 |
+
from jedi.api import helpers
|
| 24 |
+
from jedi.api.helpers import validate_line_column
|
| 25 |
+
from jedi.api.completion import Completion, search_in_module
|
| 26 |
+
from jedi.api.keywords import KeywordName
|
| 27 |
+
from jedi.api.environment import InterpreterEnvironment
|
| 28 |
+
from jedi.api.project import get_default_project, Project
|
| 29 |
+
from jedi.api.errors import parso_to_jedi_errors
|
| 30 |
+
from jedi.api import refactoring
|
| 31 |
+
from jedi.api.refactoring.extract import extract_function, extract_variable
|
| 32 |
+
from jedi.inference import InferenceState
|
| 33 |
+
from jedi.inference import imports
|
| 34 |
+
from jedi.inference.references import find_references
|
| 35 |
+
from jedi.inference.arguments import try_iter_content
|
| 36 |
+
from jedi.inference.helpers import infer_call_of_leaf
|
| 37 |
+
from jedi.inference.sys_path import transform_path_to_dotted
|
| 38 |
+
from jedi.inference.syntax_tree import tree_name_to_values
|
| 39 |
+
from jedi.inference.value import ModuleValue
|
| 40 |
+
from jedi.inference.base_value import ValueSet
|
| 41 |
+
from jedi.inference.value.iterable import unpack_tuple_to_dict
|
| 42 |
+
from jedi.inference.gradual.conversion import convert_names, convert_values
|
| 43 |
+
from jedi.inference.gradual.utils import load_proper_stub_module
|
| 44 |
+
from jedi.inference.utils import to_list
|
| 45 |
+
|
| 46 |
+
# Jedi uses lots and lots of recursion. By setting this a little bit higher, we
|
| 47 |
+
# can remove some "maximum recursion depth" errors.
|
| 48 |
+
sys.setrecursionlimit(3000)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class Script:
|
| 52 |
+
"""
|
| 53 |
+
A Script is the base for completions, goto or whatever you want to do with
|
| 54 |
+
Jedi. The counter part of this class is :class:`Interpreter`, which works
|
| 55 |
+
with actual dictionaries and can work with a REPL. This class
|
| 56 |
+
should be used when a user edits code in an editor.
|
| 57 |
+
|
| 58 |
+
You can either use the ``code`` parameter or ``path`` to read a file.
|
| 59 |
+
Usually you're going to want to use both of them (in an editor).
|
| 60 |
+
|
| 61 |
+
The Script's ``sys.path`` is very customizable:
|
| 62 |
+
|
| 63 |
+
- If `project` is provided with a ``sys_path``, that is going to be used.
|
| 64 |
+
- If `environment` is provided, its ``sys.path`` will be used
|
| 65 |
+
(see :func:`Environment.get_sys_path <jedi.api.environment.Environment.get_sys_path>`);
|
| 66 |
+
- Otherwise ``sys.path`` will match that of the default environment of
|
| 67 |
+
Jedi, which typically matches the sys path that was used at the time
|
| 68 |
+
when Jedi was imported.
|
| 69 |
+
|
| 70 |
+
Most methods have a ``line`` and a ``column`` parameter. Lines in Jedi are
|
| 71 |
+
always 1-based and columns are always zero based. To avoid repetition they
|
| 72 |
+
are not always documented. You can omit both line and column. Jedi will
|
| 73 |
+
then just do whatever action you are calling at the end of the file. If you
|
| 74 |
+
provide only the line, just will complete at the end of that line.
|
| 75 |
+
|
| 76 |
+
.. warning:: By default :attr:`jedi.settings.fast_parser` is enabled, which means
|
| 77 |
+
that parso reuses modules (i.e. they are not immutable). With this setting
|
| 78 |
+
Jedi is **not thread safe** and it is also not safe to use multiple
|
| 79 |
+
:class:`.Script` instances and its definitions at the same time.
|
| 80 |
+
|
| 81 |
+
If you are a normal plugin developer this should not be an issue. It is
|
| 82 |
+
an issue for people that do more complex stuff with Jedi.
|
| 83 |
+
|
| 84 |
+
This is purely a performance optimization and works pretty well for all
|
| 85 |
+
typical usages, however consider to turn the setting off if it causes
|
| 86 |
+
you problems. See also
|
| 87 |
+
`this discussion <https://github.com/davidhalter/jedi/issues/1240>`_.
|
| 88 |
+
|
| 89 |
+
:param code: The source code of the current file, separated by newlines.
|
| 90 |
+
:type code: str
|
| 91 |
+
:param path: The path of the file in the file system, or ``''`` if
|
| 92 |
+
it hasn't been saved yet.
|
| 93 |
+
:type path: str or pathlib.Path or None
|
| 94 |
+
:param Environment environment: Provide a predefined :ref:`Environment <environments>`
|
| 95 |
+
to work with a specific Python version or virtualenv.
|
| 96 |
+
:param Project project: Provide a :class:`.Project` to make sure finding
|
| 97 |
+
references works well, because the right folder is searched. There are
|
| 98 |
+
also ways to modify the sys path and other things.
|
| 99 |
+
"""
|
| 100 |
+
def __init__(self, code=None, *, path=None, environment=None, project=None):
|
| 101 |
+
self._orig_path = path
|
| 102 |
+
if isinstance(path, str):
|
| 103 |
+
path = Path(path)
|
| 104 |
+
|
| 105 |
+
self.path = path.absolute() if path else None
|
| 106 |
+
|
| 107 |
+
if code is None:
|
| 108 |
+
if path is None:
|
| 109 |
+
raise ValueError("Must provide at least one of code or path")
|
| 110 |
+
|
| 111 |
+
# TODO add a better warning than the traceback!
|
| 112 |
+
with open(path, 'rb') as f:
|
| 113 |
+
code = f.read()
|
| 114 |
+
|
| 115 |
+
if project is None:
|
| 116 |
+
# Load the Python grammar of the current interpreter.
|
| 117 |
+
project = get_default_project(None if self.path is None else self.path.parent)
|
| 118 |
+
|
| 119 |
+
self._inference_state = InferenceState(
|
| 120 |
+
project, environment=environment, script_path=self.path
|
| 121 |
+
)
|
| 122 |
+
debug.speed('init')
|
| 123 |
+
self._module_node, code = self._inference_state.parse_and_get_code(
|
| 124 |
+
code=code,
|
| 125 |
+
path=self.path,
|
| 126 |
+
use_latest_grammar=path and path.suffix == '.pyi',
|
| 127 |
+
cache=False, # No disk cache, because the current script often changes.
|
| 128 |
+
diff_cache=settings.fast_parser,
|
| 129 |
+
cache_path=settings.cache_directory,
|
| 130 |
+
)
|
| 131 |
+
debug.speed('parsed')
|
| 132 |
+
self._code_lines = parso.split_lines(code, keepends=True)
|
| 133 |
+
self._code = code
|
| 134 |
+
|
| 135 |
+
cache.clear_time_caches()
|
| 136 |
+
debug.reset_time()
|
| 137 |
+
|
| 138 |
+
# Cache the module, this is mostly useful for testing, since this shouldn't
|
| 139 |
+
# be called multiple times.
|
| 140 |
+
@cache.memoize_method
|
| 141 |
+
def _get_module(self):
|
| 142 |
+
names = None
|
| 143 |
+
is_package = False
|
| 144 |
+
if self.path is not None:
|
| 145 |
+
import_names, is_p = transform_path_to_dotted(
|
| 146 |
+
self._inference_state.get_sys_path(add_parent_paths=False),
|
| 147 |
+
self.path
|
| 148 |
+
)
|
| 149 |
+
if import_names is not None:
|
| 150 |
+
names = import_names
|
| 151 |
+
is_package = is_p
|
| 152 |
+
|
| 153 |
+
if self.path is None:
|
| 154 |
+
file_io = None
|
| 155 |
+
else:
|
| 156 |
+
file_io = KnownContentFileIO(self.path, self._code)
|
| 157 |
+
if self.path is not None and self.path.suffix == '.pyi':
|
| 158 |
+
# We are in a stub file. Try to load the stub properly.
|
| 159 |
+
stub_module = load_proper_stub_module(
|
| 160 |
+
self._inference_state,
|
| 161 |
+
self._inference_state.latest_grammar,
|
| 162 |
+
file_io,
|
| 163 |
+
names,
|
| 164 |
+
self._module_node
|
| 165 |
+
)
|
| 166 |
+
if stub_module is not None:
|
| 167 |
+
return stub_module
|
| 168 |
+
|
| 169 |
+
if names is None:
|
| 170 |
+
names = ('__main__',)
|
| 171 |
+
|
| 172 |
+
module = ModuleValue(
|
| 173 |
+
self._inference_state, self._module_node,
|
| 174 |
+
file_io=file_io,
|
| 175 |
+
string_names=names,
|
| 176 |
+
code_lines=self._code_lines,
|
| 177 |
+
is_package=is_package,
|
| 178 |
+
)
|
| 179 |
+
if names[0] not in ('builtins', 'typing'):
|
| 180 |
+
# These modules are essential for Jedi, so don't overwrite them.
|
| 181 |
+
self._inference_state.module_cache.add(names, ValueSet([module]))
|
| 182 |
+
return module
|
| 183 |
+
|
| 184 |
+
def _get_module_context(self):
|
| 185 |
+
return self._get_module().as_context()
|
| 186 |
+
|
| 187 |
+
def __repr__(self):
|
| 188 |
+
return '<%s: %s %r>' % (
|
| 189 |
+
self.__class__.__name__,
|
| 190 |
+
repr(self._orig_path),
|
| 191 |
+
self._inference_state.environment,
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
@validate_line_column
|
| 195 |
+
def complete(self, line=None, column=None, *, fuzzy=False):
|
| 196 |
+
"""
|
| 197 |
+
Completes objects under the cursor.
|
| 198 |
+
|
| 199 |
+
Those objects contain information about the completions, more than just
|
| 200 |
+
names.
|
| 201 |
+
|
| 202 |
+
:param fuzzy: Default False. Will return fuzzy completions, which means
|
| 203 |
+
that e.g. ``ooa`` will match ``foobar``.
|
| 204 |
+
:return: Completion objects, sorted by name. Normal names appear
|
| 205 |
+
before "private" names that start with ``_`` and those appear
|
| 206 |
+
before magic methods and name mangled names that start with ``__``.
|
| 207 |
+
:rtype: list of :class:`.Completion`
|
| 208 |
+
"""
|
| 209 |
+
self._inference_state.reset_recursion_limitations()
|
| 210 |
+
with debug.increase_indent_cm('complete'):
|
| 211 |
+
completion = Completion(
|
| 212 |
+
self._inference_state, self._get_module_context(), self._code_lines,
|
| 213 |
+
(line, column), self.get_signatures, fuzzy=fuzzy,
|
| 214 |
+
)
|
| 215 |
+
return completion.complete()
|
| 216 |
+
|
| 217 |
+
@validate_line_column
|
| 218 |
+
def infer(self, line=None, column=None, *, only_stubs=False, prefer_stubs=False):
|
| 219 |
+
"""
|
| 220 |
+
Return the definitions of under the cursor. It is basically a wrapper
|
| 221 |
+
around Jedi's type inference.
|
| 222 |
+
|
| 223 |
+
This method follows complicated paths and returns the end, not the
|
| 224 |
+
first definition. The big difference between :meth:`goto` and
|
| 225 |
+
:meth:`infer` is that :meth:`goto` doesn't
|
| 226 |
+
follow imports and statements. Multiple objects may be returned,
|
| 227 |
+
because depending on an option you can have two different versions of a
|
| 228 |
+
function.
|
| 229 |
+
|
| 230 |
+
:param only_stubs: Only return stubs for this method.
|
| 231 |
+
:param prefer_stubs: Prefer stubs to Python objects for this method.
|
| 232 |
+
:rtype: list of :class:`.Name`
|
| 233 |
+
"""
|
| 234 |
+
self._inference_state.reset_recursion_limitations()
|
| 235 |
+
pos = line, column
|
| 236 |
+
leaf = self._module_node.get_name_of_position(pos)
|
| 237 |
+
if leaf is None:
|
| 238 |
+
leaf = self._module_node.get_leaf_for_position(pos)
|
| 239 |
+
if leaf is None or leaf.type == 'string':
|
| 240 |
+
return []
|
| 241 |
+
if leaf.end_pos == (line, column) and leaf.type == 'operator':
|
| 242 |
+
next_ = leaf.get_next_leaf()
|
| 243 |
+
if next_.start_pos == leaf.end_pos \
|
| 244 |
+
and next_.type in ('number', 'string', 'keyword'):
|
| 245 |
+
leaf = next_
|
| 246 |
+
|
| 247 |
+
context = self._get_module_context().create_context(leaf)
|
| 248 |
+
|
| 249 |
+
values = helpers.infer(self._inference_state, context, leaf)
|
| 250 |
+
values = convert_values(
|
| 251 |
+
values,
|
| 252 |
+
only_stubs=only_stubs,
|
| 253 |
+
prefer_stubs=prefer_stubs,
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
defs = [classes.Name(self._inference_state, c.name) for c in values]
|
| 257 |
+
# The additional set here allows the definitions to become unique in an
|
| 258 |
+
# API sense. In the internals we want to separate more things than in
|
| 259 |
+
# the API.
|
| 260 |
+
return helpers.sorted_definitions(set(defs))
|
| 261 |
+
|
| 262 |
+
@validate_line_column
|
| 263 |
+
def goto(self, line=None, column=None, *, follow_imports=False, follow_builtin_imports=False,
|
| 264 |
+
only_stubs=False, prefer_stubs=False):
|
| 265 |
+
"""
|
| 266 |
+
Goes to the name that defined the object under the cursor. Optionally
|
| 267 |
+
you can follow imports.
|
| 268 |
+
Multiple objects may be returned, depending on an if you can have two
|
| 269 |
+
different versions of a function.
|
| 270 |
+
|
| 271 |
+
:param follow_imports: The method will follow imports.
|
| 272 |
+
:param follow_builtin_imports: If ``follow_imports`` is True will try
|
| 273 |
+
to look up names in builtins (i.e. compiled or extension modules).
|
| 274 |
+
:param only_stubs: Only return stubs for this method.
|
| 275 |
+
:param prefer_stubs: Prefer stubs to Python objects for this method.
|
| 276 |
+
:rtype: list of :class:`.Name`
|
| 277 |
+
"""
|
| 278 |
+
self._inference_state.reset_recursion_limitations()
|
| 279 |
+
tree_name = self._module_node.get_name_of_position((line, column))
|
| 280 |
+
if tree_name is None:
|
| 281 |
+
# Without a name we really just want to jump to the result e.g.
|
| 282 |
+
# executed by `foo()`, if we the cursor is after `)`.
|
| 283 |
+
return self.infer(line, column, only_stubs=only_stubs, prefer_stubs=prefer_stubs)
|
| 284 |
+
name = self._get_module_context().create_name(tree_name)
|
| 285 |
+
|
| 286 |
+
# Make it possible to goto the super class function/attribute
|
| 287 |
+
# definitions, when they are overwritten.
|
| 288 |
+
names = []
|
| 289 |
+
if name.tree_name.is_definition() and name.parent_context.is_class():
|
| 290 |
+
class_node = name.parent_context.tree_node
|
| 291 |
+
class_value = self._get_module_context().create_value(class_node)
|
| 292 |
+
mro = class_value.py__mro__()
|
| 293 |
+
next(mro) # Ignore the first entry, because it's the class itself.
|
| 294 |
+
for cls in mro:
|
| 295 |
+
names = cls.goto(tree_name.value)
|
| 296 |
+
if names:
|
| 297 |
+
break
|
| 298 |
+
|
| 299 |
+
if not names:
|
| 300 |
+
names = list(name.goto())
|
| 301 |
+
|
| 302 |
+
if follow_imports:
|
| 303 |
+
names = helpers.filter_follow_imports(names, follow_builtin_imports)
|
| 304 |
+
names = convert_names(
|
| 305 |
+
names,
|
| 306 |
+
only_stubs=only_stubs,
|
| 307 |
+
prefer_stubs=prefer_stubs,
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
defs = [classes.Name(self._inference_state, d) for d in set(names)]
|
| 311 |
+
# Avoid duplicates
|
| 312 |
+
return list(set(helpers.sorted_definitions(defs)))
|
| 313 |
+
|
| 314 |
+
def search(self, string, *, all_scopes=False):
|
| 315 |
+
"""
|
| 316 |
+
Searches a name in the current file. For a description of how the
|
| 317 |
+
search string should look like, please have a look at
|
| 318 |
+
:meth:`.Project.search`.
|
| 319 |
+
|
| 320 |
+
:param bool all_scopes: Default False; searches not only for
|
| 321 |
+
definitions on the top level of a module level, but also in
|
| 322 |
+
functions and classes.
|
| 323 |
+
:yields: :class:`.Name`
|
| 324 |
+
"""
|
| 325 |
+
return self._search_func(string, all_scopes=all_scopes)
|
| 326 |
+
|
| 327 |
+
@to_list
|
| 328 |
+
def _search_func(self, string, all_scopes=False, complete=False, fuzzy=False):
|
| 329 |
+
names = self._names(all_scopes=all_scopes)
|
| 330 |
+
wanted_type, wanted_names = helpers.split_search_string(string)
|
| 331 |
+
return search_in_module(
|
| 332 |
+
self._inference_state,
|
| 333 |
+
self._get_module_context(),
|
| 334 |
+
names=names,
|
| 335 |
+
wanted_type=wanted_type,
|
| 336 |
+
wanted_names=wanted_names,
|
| 337 |
+
complete=complete,
|
| 338 |
+
fuzzy=fuzzy,
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
def complete_search(self, string, **kwargs):
|
| 342 |
+
"""
|
| 343 |
+
Like :meth:`.Script.search`, but completes that string. If you want to
|
| 344 |
+
have all possible definitions in a file you can also provide an empty
|
| 345 |
+
string.
|
| 346 |
+
|
| 347 |
+
:param bool all_scopes: Default False; searches not only for
|
| 348 |
+
definitions on the top level of a module level, but also in
|
| 349 |
+
functions and classes.
|
| 350 |
+
:param fuzzy: Default False. Will return fuzzy completions, which means
|
| 351 |
+
that e.g. ``ooa`` will match ``foobar``.
|
| 352 |
+
:yields: :class:`.Completion`
|
| 353 |
+
"""
|
| 354 |
+
return self._search_func(string, complete=True, **kwargs)
|
| 355 |
+
|
| 356 |
+
@validate_line_column
|
| 357 |
+
def help(self, line=None, column=None):
|
| 358 |
+
"""
|
| 359 |
+
Used to display a help window to users. Uses :meth:`.Script.goto` and
|
| 360 |
+
returns additional definitions for keywords and operators.
|
| 361 |
+
|
| 362 |
+
Typically you will want to display :meth:`.BaseName.docstring` to the
|
| 363 |
+
user for all the returned definitions.
|
| 364 |
+
|
| 365 |
+
The additional definitions are ``Name(...).type == 'keyword'``.
|
| 366 |
+
These definitions do not have a lot of value apart from their docstring
|
| 367 |
+
attribute, which contains the output of Python's :func:`help` function.
|
| 368 |
+
|
| 369 |
+
:rtype: list of :class:`.Name`
|
| 370 |
+
"""
|
| 371 |
+
self._inference_state.reset_recursion_limitations()
|
| 372 |
+
definitions = self.goto(line, column, follow_imports=True)
|
| 373 |
+
if definitions:
|
| 374 |
+
return definitions
|
| 375 |
+
leaf = self._module_node.get_leaf_for_position((line, column))
|
| 376 |
+
|
| 377 |
+
if leaf is not None and leaf.end_pos == (line, column) and leaf.type == 'newline':
|
| 378 |
+
next_ = leaf.get_next_leaf()
|
| 379 |
+
if next_ is not None and next_.start_pos == leaf.end_pos:
|
| 380 |
+
leaf = next_
|
| 381 |
+
|
| 382 |
+
if leaf is not None and leaf.type in ('keyword', 'operator', 'error_leaf'):
|
| 383 |
+
def need_pydoc():
|
| 384 |
+
if leaf.value in ('(', ')', '[', ']'):
|
| 385 |
+
if leaf.parent.type == 'trailer':
|
| 386 |
+
return False
|
| 387 |
+
if leaf.parent.type == 'atom':
|
| 388 |
+
return False
|
| 389 |
+
grammar = self._inference_state.grammar
|
| 390 |
+
# This parso stuff is not public, but since I control it, this
|
| 391 |
+
# is fine :-) ~dave
|
| 392 |
+
reserved = grammar._pgen_grammar.reserved_syntax_strings.keys()
|
| 393 |
+
return leaf.value in reserved
|
| 394 |
+
|
| 395 |
+
if need_pydoc():
|
| 396 |
+
name = KeywordName(self._inference_state, leaf.value)
|
| 397 |
+
return [classes.Name(self._inference_state, name)]
|
| 398 |
+
return []
|
| 399 |
+
|
| 400 |
+
@validate_line_column
|
| 401 |
+
def get_references(self, line=None, column=None, **kwargs):
|
| 402 |
+
"""
|
| 403 |
+
Lists all references of a variable in a project. Since this can be
|
| 404 |
+
quite hard to do for Jedi, if it is too complicated, Jedi will stop
|
| 405 |
+
searching.
|
| 406 |
+
|
| 407 |
+
:param include_builtins: Default ``True``. If ``False``, checks if a definition
|
| 408 |
+
is a builtin (e.g. ``sys``) and in that case does not return it.
|
| 409 |
+
:param scope: Default ``'project'``. If ``'file'``, include references in
|
| 410 |
+
the current module only.
|
| 411 |
+
:rtype: list of :class:`.Name`
|
| 412 |
+
"""
|
| 413 |
+
self._inference_state.reset_recursion_limitations()
|
| 414 |
+
|
| 415 |
+
def _references(include_builtins=True, scope='project'):
|
| 416 |
+
if scope not in ('project', 'file'):
|
| 417 |
+
raise ValueError('Only the scopes "file" and "project" are allowed')
|
| 418 |
+
tree_name = self._module_node.get_name_of_position((line, column))
|
| 419 |
+
if tree_name is None:
|
| 420 |
+
# Must be syntax
|
| 421 |
+
return []
|
| 422 |
+
|
| 423 |
+
names = find_references(self._get_module_context(), tree_name, scope == 'file')
|
| 424 |
+
|
| 425 |
+
definitions = [classes.Name(self._inference_state, n) for n in names]
|
| 426 |
+
if not include_builtins or scope == 'file':
|
| 427 |
+
definitions = [d for d in definitions if not d.in_builtin_module()]
|
| 428 |
+
return helpers.sorted_definitions(definitions)
|
| 429 |
+
return _references(**kwargs)
|
| 430 |
+
|
| 431 |
+
@validate_line_column
|
| 432 |
+
def get_signatures(self, line=None, column=None):
|
| 433 |
+
"""
|
| 434 |
+
Return the function object of the call under the cursor.
|
| 435 |
+
|
| 436 |
+
E.g. if the cursor is here::
|
| 437 |
+
|
| 438 |
+
abs(# <-- cursor is here
|
| 439 |
+
|
| 440 |
+
This would return the ``abs`` function. On the other hand::
|
| 441 |
+
|
| 442 |
+
abs()# <-- cursor is here
|
| 443 |
+
|
| 444 |
+
This would return an empty list..
|
| 445 |
+
|
| 446 |
+
:rtype: list of :class:`.Signature`
|
| 447 |
+
"""
|
| 448 |
+
self._inference_state.reset_recursion_limitations()
|
| 449 |
+
pos = line, column
|
| 450 |
+
call_details = helpers.get_signature_details(self._module_node, pos)
|
| 451 |
+
if call_details is None:
|
| 452 |
+
return []
|
| 453 |
+
|
| 454 |
+
context = self._get_module_context().create_context(call_details.bracket_leaf)
|
| 455 |
+
definitions = helpers.cache_signatures(
|
| 456 |
+
self._inference_state,
|
| 457 |
+
context,
|
| 458 |
+
call_details.bracket_leaf,
|
| 459 |
+
self._code_lines,
|
| 460 |
+
pos
|
| 461 |
+
)
|
| 462 |
+
debug.speed('func_call followed')
|
| 463 |
+
|
| 464 |
+
# TODO here we use stubs instead of the actual values. We should use
|
| 465 |
+
# the signatures from stubs, but the actual values, probably?!
|
| 466 |
+
return [classes.Signature(self._inference_state, signature, call_details)
|
| 467 |
+
for signature in definitions.get_signatures()]
|
| 468 |
+
|
| 469 |
+
@validate_line_column
|
| 470 |
+
def get_context(self, line=None, column=None):
|
| 471 |
+
"""
|
| 472 |
+
Returns the scope context under the cursor. This basically means the
|
| 473 |
+
function, class or module where the cursor is at.
|
| 474 |
+
|
| 475 |
+
:rtype: :class:`.Name`
|
| 476 |
+
"""
|
| 477 |
+
pos = (line, column)
|
| 478 |
+
leaf = self._module_node.get_leaf_for_position(pos, include_prefixes=True)
|
| 479 |
+
if leaf.start_pos > pos or leaf.type == 'endmarker':
|
| 480 |
+
previous_leaf = leaf.get_previous_leaf()
|
| 481 |
+
if previous_leaf is not None:
|
| 482 |
+
leaf = previous_leaf
|
| 483 |
+
|
| 484 |
+
module_context = self._get_module_context()
|
| 485 |
+
|
| 486 |
+
n = tree.search_ancestor(leaf, 'funcdef', 'classdef')
|
| 487 |
+
if n is not None and n.start_pos < pos <= n.children[-1].start_pos:
|
| 488 |
+
# This is a bit of a special case. The context of a function/class
|
| 489 |
+
# name/param/keyword is always it's parent context, not the
|
| 490 |
+
# function itself. Catch all the cases here where we are before the
|
| 491 |
+
# suite object, but still in the function.
|
| 492 |
+
context = module_context.create_value(n).as_context()
|
| 493 |
+
else:
|
| 494 |
+
context = module_context.create_context(leaf)
|
| 495 |
+
|
| 496 |
+
while context.name is None:
|
| 497 |
+
context = context.parent_context # comprehensions
|
| 498 |
+
|
| 499 |
+
definition = classes.Name(self._inference_state, context.name)
|
| 500 |
+
while definition.type != 'module':
|
| 501 |
+
name = definition._name # TODO private access
|
| 502 |
+
tree_name = name.tree_name
|
| 503 |
+
if tree_name is not None: # Happens with lambdas.
|
| 504 |
+
scope = tree_name.get_definition()
|
| 505 |
+
if scope.start_pos[1] < column:
|
| 506 |
+
break
|
| 507 |
+
definition = definition.parent()
|
| 508 |
+
return definition
|
| 509 |
+
|
| 510 |
+
def _analysis(self):
|
| 511 |
+
self._inference_state.is_analysis = True
|
| 512 |
+
self._inference_state.analysis_modules = [self._module_node]
|
| 513 |
+
module = self._get_module_context()
|
| 514 |
+
try:
|
| 515 |
+
for node in get_executable_nodes(self._module_node):
|
| 516 |
+
context = module.create_context(node)
|
| 517 |
+
if node.type in ('funcdef', 'classdef'):
|
| 518 |
+
# Resolve the decorators.
|
| 519 |
+
tree_name_to_values(self._inference_state, context, node.children[1])
|
| 520 |
+
elif isinstance(node, tree.Import):
|
| 521 |
+
import_names = set(node.get_defined_names())
|
| 522 |
+
if node.is_nested():
|
| 523 |
+
import_names |= set(path[-1] for path in node.get_paths())
|
| 524 |
+
for n in import_names:
|
| 525 |
+
imports.infer_import(context, n)
|
| 526 |
+
elif node.type == 'expr_stmt':
|
| 527 |
+
types = context.infer_node(node)
|
| 528 |
+
for testlist in node.children[:-1:2]:
|
| 529 |
+
# Iterate tuples.
|
| 530 |
+
unpack_tuple_to_dict(context, types, testlist)
|
| 531 |
+
else:
|
| 532 |
+
if node.type == 'name':
|
| 533 |
+
defs = self._inference_state.infer(context, node)
|
| 534 |
+
else:
|
| 535 |
+
defs = infer_call_of_leaf(context, node)
|
| 536 |
+
try_iter_content(defs)
|
| 537 |
+
self._inference_state.reset_recursion_limitations()
|
| 538 |
+
|
| 539 |
+
ana = [a for a in self._inference_state.analysis if self.path == a.path]
|
| 540 |
+
return sorted(set(ana), key=lambda x: x.line)
|
| 541 |
+
finally:
|
| 542 |
+
self._inference_state.is_analysis = False
|
| 543 |
+
|
| 544 |
+
def get_names(self, **kwargs):
|
| 545 |
+
"""
|
| 546 |
+
Returns names defined in the current file.
|
| 547 |
+
|
| 548 |
+
:param all_scopes: If True lists the names of all scopes instead of
|
| 549 |
+
only the module namespace.
|
| 550 |
+
:param definitions: If True lists the names that have been defined by a
|
| 551 |
+
class, function or a statement (``a = b`` returns ``a``).
|
| 552 |
+
:param references: If True lists all the names that are not listed by
|
| 553 |
+
``definitions=True``. E.g. ``a = b`` returns ``b``.
|
| 554 |
+
:rtype: list of :class:`.Name`
|
| 555 |
+
"""
|
| 556 |
+
names = self._names(**kwargs)
|
| 557 |
+
return [classes.Name(self._inference_state, n) for n in names]
|
| 558 |
+
|
| 559 |
+
def get_syntax_errors(self):
|
| 560 |
+
"""
|
| 561 |
+
Lists all syntax errors in the current file.
|
| 562 |
+
|
| 563 |
+
:rtype: list of :class:`.SyntaxError`
|
| 564 |
+
"""
|
| 565 |
+
return parso_to_jedi_errors(self._inference_state.grammar, self._module_node)
|
| 566 |
+
|
| 567 |
+
def _names(self, all_scopes=False, definitions=True, references=False):
|
| 568 |
+
self._inference_state.reset_recursion_limitations()
|
| 569 |
+
# Set line/column to a random position, because they don't matter.
|
| 570 |
+
module_context = self._get_module_context()
|
| 571 |
+
defs = [
|
| 572 |
+
module_context.create_name(name)
|
| 573 |
+
for name in helpers.get_module_names(
|
| 574 |
+
self._module_node,
|
| 575 |
+
all_scopes=all_scopes,
|
| 576 |
+
definitions=definitions,
|
| 577 |
+
references=references,
|
| 578 |
+
)
|
| 579 |
+
]
|
| 580 |
+
return sorted(defs, key=lambda x: x.start_pos)
|
| 581 |
+
|
| 582 |
+
def rename(self, line=None, column=None, *, new_name):
|
| 583 |
+
"""
|
| 584 |
+
Renames all references of the variable under the cursor.
|
| 585 |
+
|
| 586 |
+
:param new_name: The variable under the cursor will be renamed to this
|
| 587 |
+
string.
|
| 588 |
+
:raises: :exc:`.RefactoringError`
|
| 589 |
+
:rtype: :class:`.Refactoring`
|
| 590 |
+
"""
|
| 591 |
+
definitions = self.get_references(line, column, include_builtins=False)
|
| 592 |
+
return refactoring.rename(self._inference_state, definitions, new_name)
|
| 593 |
+
|
| 594 |
+
@validate_line_column
|
| 595 |
+
def extract_variable(self, line, column, *, new_name, until_line=None, until_column=None):
|
| 596 |
+
"""
|
| 597 |
+
Moves an expression to a new statement.
|
| 598 |
+
|
| 599 |
+
For example if you have the cursor on ``foo`` and provide a
|
| 600 |
+
``new_name`` called ``bar``::
|
| 601 |
+
|
| 602 |
+
foo = 3.1
|
| 603 |
+
x = int(foo + 1)
|
| 604 |
+
|
| 605 |
+
the code above will become::
|
| 606 |
+
|
| 607 |
+
foo = 3.1
|
| 608 |
+
bar = foo + 1
|
| 609 |
+
x = int(bar)
|
| 610 |
+
|
| 611 |
+
:param new_name: The expression under the cursor will be renamed to
|
| 612 |
+
this string.
|
| 613 |
+
:param int until_line: The the selection range ends at this line, when
|
| 614 |
+
omitted, Jedi will be clever and try to define the range itself.
|
| 615 |
+
:param int until_column: The the selection range ends at this column, when
|
| 616 |
+
omitted, Jedi will be clever and try to define the range itself.
|
| 617 |
+
:raises: :exc:`.RefactoringError`
|
| 618 |
+
:rtype: :class:`.Refactoring`
|
| 619 |
+
"""
|
| 620 |
+
if until_line is None and until_column is None:
|
| 621 |
+
until_pos = None
|
| 622 |
+
else:
|
| 623 |
+
if until_line is None:
|
| 624 |
+
until_line = line
|
| 625 |
+
if until_column is None:
|
| 626 |
+
until_column = len(self._code_lines[until_line - 1])
|
| 627 |
+
until_pos = until_line, until_column
|
| 628 |
+
return extract_variable(
|
| 629 |
+
self._inference_state, self.path, self._module_node,
|
| 630 |
+
new_name, (line, column), until_pos
|
| 631 |
+
)
|
| 632 |
+
|
| 633 |
+
@validate_line_column
|
| 634 |
+
def extract_function(self, line, column, *, new_name, until_line=None, until_column=None):
|
| 635 |
+
"""
|
| 636 |
+
Moves an expression to a new function.
|
| 637 |
+
|
| 638 |
+
For example if you have the cursor on ``foo`` and provide a
|
| 639 |
+
``new_name`` called ``bar``::
|
| 640 |
+
|
| 641 |
+
global_var = 3
|
| 642 |
+
|
| 643 |
+
def x():
|
| 644 |
+
foo = 3.1
|
| 645 |
+
x = int(foo + 1 + global_var)
|
| 646 |
+
|
| 647 |
+
the code above will become::
|
| 648 |
+
|
| 649 |
+
global_var = 3
|
| 650 |
+
|
| 651 |
+
def bar(foo):
|
| 652 |
+
return int(foo + 1 + global_var)
|
| 653 |
+
|
| 654 |
+
def x():
|
| 655 |
+
foo = 3.1
|
| 656 |
+
x = bar(foo)
|
| 657 |
+
|
| 658 |
+
:param new_name: The expression under the cursor will be replaced with
|
| 659 |
+
a function with this name.
|
| 660 |
+
:param int until_line: The the selection range ends at this line, when
|
| 661 |
+
omitted, Jedi will be clever and try to define the range itself.
|
| 662 |
+
:param int until_column: The the selection range ends at this column, when
|
| 663 |
+
omitted, Jedi will be clever and try to define the range itself.
|
| 664 |
+
:raises: :exc:`.RefactoringError`
|
| 665 |
+
:rtype: :class:`.Refactoring`
|
| 666 |
+
"""
|
| 667 |
+
if until_line is None and until_column is None:
|
| 668 |
+
until_pos = None
|
| 669 |
+
else:
|
| 670 |
+
if until_line is None:
|
| 671 |
+
until_line = line
|
| 672 |
+
if until_column is None:
|
| 673 |
+
until_column = len(self._code_lines[until_line - 1])
|
| 674 |
+
until_pos = until_line, until_column
|
| 675 |
+
return extract_function(
|
| 676 |
+
self._inference_state, self.path, self._get_module_context(),
|
| 677 |
+
new_name, (line, column), until_pos
|
| 678 |
+
)
|
| 679 |
+
|
| 680 |
+
def inline(self, line=None, column=None):
|
| 681 |
+
"""
|
| 682 |
+
Inlines a variable under the cursor. This is basically the opposite of
|
| 683 |
+
extracting a variable. For example with the cursor on bar::
|
| 684 |
+
|
| 685 |
+
foo = 3.1
|
| 686 |
+
bar = foo + 1
|
| 687 |
+
x = int(bar)
|
| 688 |
+
|
| 689 |
+
the code above will become::
|
| 690 |
+
|
| 691 |
+
foo = 3.1
|
| 692 |
+
x = int(foo + 1)
|
| 693 |
+
|
| 694 |
+
:raises: :exc:`.RefactoringError`
|
| 695 |
+
:rtype: :class:`.Refactoring`
|
| 696 |
+
"""
|
| 697 |
+
names = [d._name for d in self.get_references(line, column, include_builtins=True)]
|
| 698 |
+
return refactoring.inline(self._inference_state, names)
|
| 699 |
+
|
| 700 |
+
|
| 701 |
+
class Interpreter(Script):
|
| 702 |
+
"""
|
| 703 |
+
Jedi's API for Python REPLs.
|
| 704 |
+
|
| 705 |
+
Implements all of the methods that are present in :class:`.Script` as well.
|
| 706 |
+
|
| 707 |
+
In addition to completions that normal REPL completion does like
|
| 708 |
+
``str.upper``, Jedi also supports code completion based on static code
|
| 709 |
+
analysis. For example Jedi will complete ``str().upper``.
|
| 710 |
+
|
| 711 |
+
>>> from os.path import join
|
| 712 |
+
>>> namespace = locals()
|
| 713 |
+
>>> script = Interpreter('join("").up', [namespace])
|
| 714 |
+
>>> print(script.complete()[0].name)
|
| 715 |
+
upper
|
| 716 |
+
|
| 717 |
+
All keyword arguments are same as the arguments for :class:`.Script`.
|
| 718 |
+
|
| 719 |
+
:param str code: Code to parse.
|
| 720 |
+
:type namespaces: typing.List[dict]
|
| 721 |
+
:param namespaces: A list of namespace dictionaries such as the one
|
| 722 |
+
returned by :func:`globals` and :func:`locals`.
|
| 723 |
+
"""
|
| 724 |
+
|
| 725 |
+
def __init__(self, code, namespaces, *, project=None, **kwds):
|
| 726 |
+
try:
|
| 727 |
+
namespaces = [dict(n) for n in namespaces]
|
| 728 |
+
except Exception:
|
| 729 |
+
raise TypeError("namespaces must be a non-empty list of dicts.")
|
| 730 |
+
|
| 731 |
+
environment = kwds.get('environment', None)
|
| 732 |
+
if environment is None:
|
| 733 |
+
environment = InterpreterEnvironment()
|
| 734 |
+
else:
|
| 735 |
+
if not isinstance(environment, InterpreterEnvironment):
|
| 736 |
+
raise TypeError("The environment needs to be an InterpreterEnvironment subclass.")
|
| 737 |
+
|
| 738 |
+
if project is None:
|
| 739 |
+
project = Project(Path.cwd())
|
| 740 |
+
|
| 741 |
+
super().__init__(code, environment=environment, project=project, **kwds)
|
| 742 |
+
|
| 743 |
+
self.namespaces = namespaces
|
| 744 |
+
self._inference_state.allow_unsafe_executions = \
|
| 745 |
+
settings.allow_unsafe_interpreter_executions
|
| 746 |
+
# Dynamic params search is important when we work on functions that are
|
| 747 |
+
# called by other pieces of code. However for interpreter completions
|
| 748 |
+
# this is not important at all, because the current code is always new
|
| 749 |
+
# and will never be called by something.
|
| 750 |
+
# Also sometimes this logic goes a bit too far like in
|
| 751 |
+
# https://github.com/ipython/ipython/issues/13866, where it takes
|
| 752 |
+
# seconds to do a simple completion.
|
| 753 |
+
self._inference_state.do_dynamic_params_search = False
|
| 754 |
+
|
| 755 |
+
@cache.memoize_method
|
| 756 |
+
def _get_module_context(self):
|
| 757 |
+
if self.path is None:
|
| 758 |
+
file_io = None
|
| 759 |
+
else:
|
| 760 |
+
file_io = KnownContentFileIO(self.path, self._code)
|
| 761 |
+
tree_module_value = ModuleValue(
|
| 762 |
+
self._inference_state, self._module_node,
|
| 763 |
+
file_io=file_io,
|
| 764 |
+
string_names=('__main__',),
|
| 765 |
+
code_lines=self._code_lines,
|
| 766 |
+
)
|
| 767 |
+
return interpreter.MixedModuleContext(
|
| 768 |
+
tree_module_value,
|
| 769 |
+
self.namespaces,
|
| 770 |
+
)
|
| 771 |
+
|
| 772 |
+
|
| 773 |
+
def preload_module(*modules):
|
| 774 |
+
"""
|
| 775 |
+
Preloading modules tells Jedi to load a module now, instead of lazy parsing
|
| 776 |
+
of modules. This can be useful for IDEs, to control which modules to load
|
| 777 |
+
on startup.
|
| 778 |
+
|
| 779 |
+
:param modules: different module names, list of string.
|
| 780 |
+
"""
|
| 781 |
+
for m in modules:
|
| 782 |
+
s = "import %s as x; x." % m
|
| 783 |
+
Script(s).complete(1, len(s))
|
| 784 |
+
|
| 785 |
+
|
| 786 |
+
def set_debug_function(func_cb=debug.print_to_stdout, warnings=True,
|
| 787 |
+
notices=True, speed=True):
|
| 788 |
+
"""
|
| 789 |
+
Define a callback debug function to get all the debug messages.
|
| 790 |
+
|
| 791 |
+
If you don't specify any arguments, debug messages will be printed to stdout.
|
| 792 |
+
|
| 793 |
+
:param func_cb: The callback function for debug messages.
|
| 794 |
+
"""
|
| 795 |
+
debug.debug_function = func_cb
|
| 796 |
+
debug.enable_warning = warnings
|
| 797 |
+
debug.enable_notice = notices
|
| 798 |
+
debug.enable_speed = speed
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/classes.py
ADDED
|
@@ -0,0 +1,895 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
There are a couple of classes documented in here:
|
| 3 |
+
|
| 4 |
+
- :class:`.BaseName` as an abstact base class for almost everything.
|
| 5 |
+
- :class:`.Name` used in a lot of places
|
| 6 |
+
- :class:`.Completion` for completions
|
| 7 |
+
- :class:`.BaseSignature` as a base class for signatures
|
| 8 |
+
- :class:`.Signature` for :meth:`.Script.get_signatures` only
|
| 9 |
+
- :class:`.ParamName` used for parameters of signatures
|
| 10 |
+
- :class:`.Refactoring` for refactorings
|
| 11 |
+
- :class:`.SyntaxError` for :meth:`.Script.get_syntax_errors` only
|
| 12 |
+
|
| 13 |
+
These classes are the much biggest part of the API, because they contain
|
| 14 |
+
the interesting information about all operations.
|
| 15 |
+
"""
|
| 16 |
+
import re
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
from typing import Optional
|
| 19 |
+
|
| 20 |
+
from parso.tree import search_ancestor
|
| 21 |
+
|
| 22 |
+
from jedi import settings
|
| 23 |
+
from jedi import debug
|
| 24 |
+
from jedi.inference.utils import unite
|
| 25 |
+
from jedi.cache import memoize_method
|
| 26 |
+
from jedi.inference.compiled.mixed import MixedName
|
| 27 |
+
from jedi.inference.names import ImportName, SubModuleName
|
| 28 |
+
from jedi.inference.gradual.stub_value import StubModuleValue
|
| 29 |
+
from jedi.inference.gradual.conversion import convert_names, convert_values
|
| 30 |
+
from jedi.inference.base_value import ValueSet, HasNoContext
|
| 31 |
+
from jedi.api.keywords import KeywordName
|
| 32 |
+
from jedi.api import completion_cache
|
| 33 |
+
from jedi.api.helpers import filter_follow_imports
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _sort_names_by_start_pos(names):
|
| 37 |
+
return sorted(names, key=lambda s: s.start_pos or (0, 0))
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def defined_names(inference_state, value):
|
| 41 |
+
"""
|
| 42 |
+
List sub-definitions (e.g., methods in class).
|
| 43 |
+
|
| 44 |
+
:type scope: Scope
|
| 45 |
+
:rtype: list of Name
|
| 46 |
+
"""
|
| 47 |
+
try:
|
| 48 |
+
context = value.as_context()
|
| 49 |
+
except HasNoContext:
|
| 50 |
+
return []
|
| 51 |
+
filter = next(context.get_filters())
|
| 52 |
+
names = [name for name in filter.values()]
|
| 53 |
+
return [Name(inference_state, n) for n in _sort_names_by_start_pos(names)]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _values_to_definitions(values):
|
| 57 |
+
return [Name(c.inference_state, c.name) for c in values]
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class BaseName:
|
| 61 |
+
"""
|
| 62 |
+
The base class for all definitions, completions and signatures.
|
| 63 |
+
"""
|
| 64 |
+
_mapping = {
|
| 65 |
+
'posixpath': 'os.path',
|
| 66 |
+
'riscospath': 'os.path',
|
| 67 |
+
'ntpath': 'os.path',
|
| 68 |
+
'os2emxpath': 'os.path',
|
| 69 |
+
'macpath': 'os.path',
|
| 70 |
+
'genericpath': 'os.path',
|
| 71 |
+
'posix': 'os',
|
| 72 |
+
'_io': 'io',
|
| 73 |
+
'_functools': 'functools',
|
| 74 |
+
'_collections': 'collections',
|
| 75 |
+
'_socket': 'socket',
|
| 76 |
+
'_sqlite3': 'sqlite3',
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
_tuple_mapping = dict((tuple(k.split('.')), v) for (k, v) in {
|
| 80 |
+
'argparse._ActionsContainer': 'argparse.ArgumentParser',
|
| 81 |
+
}.items())
|
| 82 |
+
|
| 83 |
+
def __init__(self, inference_state, name):
|
| 84 |
+
self._inference_state = inference_state
|
| 85 |
+
self._name = name
|
| 86 |
+
"""
|
| 87 |
+
An instance of :class:`parso.python.tree.Name` subclass.
|
| 88 |
+
"""
|
| 89 |
+
self.is_keyword = isinstance(self._name, KeywordName)
|
| 90 |
+
|
| 91 |
+
@memoize_method
|
| 92 |
+
def _get_module_context(self):
|
| 93 |
+
# This can take a while to complete, because in the worst case of
|
| 94 |
+
# imports (consider `import a` completions), we need to load all
|
| 95 |
+
# modules starting with a first.
|
| 96 |
+
return self._name.get_root_context()
|
| 97 |
+
|
| 98 |
+
@property
|
| 99 |
+
def module_path(self) -> Optional[Path]:
|
| 100 |
+
"""
|
| 101 |
+
Shows the file path of a module. e.g. ``/usr/lib/python3.9/os.py``
|
| 102 |
+
"""
|
| 103 |
+
module = self._get_module_context()
|
| 104 |
+
if module.is_stub() or not module.is_compiled():
|
| 105 |
+
# Compiled modules should not return a module path even if they
|
| 106 |
+
# have one.
|
| 107 |
+
path: Optional[Path] = self._get_module_context().py__file__()
|
| 108 |
+
return path
|
| 109 |
+
|
| 110 |
+
return None
|
| 111 |
+
|
| 112 |
+
@property
|
| 113 |
+
def name(self):
|
| 114 |
+
"""
|
| 115 |
+
Name of variable/function/class/module.
|
| 116 |
+
|
| 117 |
+
For example, for ``x = None`` it returns ``'x'``.
|
| 118 |
+
|
| 119 |
+
:rtype: str or None
|
| 120 |
+
"""
|
| 121 |
+
return self._name.get_public_name()
|
| 122 |
+
|
| 123 |
+
@property
|
| 124 |
+
def type(self):
|
| 125 |
+
"""
|
| 126 |
+
The type of the definition.
|
| 127 |
+
|
| 128 |
+
Here is an example of the value of this attribute. Let's consider
|
| 129 |
+
the following source. As what is in ``variable`` is unambiguous
|
| 130 |
+
to Jedi, :meth:`jedi.Script.infer` should return a list of
|
| 131 |
+
definition for ``sys``, ``f``, ``C`` and ``x``.
|
| 132 |
+
|
| 133 |
+
>>> from jedi import Script
|
| 134 |
+
>>> source = '''
|
| 135 |
+
... import keyword
|
| 136 |
+
...
|
| 137 |
+
... class C:
|
| 138 |
+
... pass
|
| 139 |
+
...
|
| 140 |
+
... class D:
|
| 141 |
+
... pass
|
| 142 |
+
...
|
| 143 |
+
... x = D()
|
| 144 |
+
...
|
| 145 |
+
... def f():
|
| 146 |
+
... pass
|
| 147 |
+
...
|
| 148 |
+
... for variable in [keyword, f, C, x]:
|
| 149 |
+
... variable'''
|
| 150 |
+
|
| 151 |
+
>>> script = Script(source)
|
| 152 |
+
>>> defs = script.infer()
|
| 153 |
+
|
| 154 |
+
Before showing what is in ``defs``, let's sort it by :attr:`line`
|
| 155 |
+
so that it is easy to relate the result to the source code.
|
| 156 |
+
|
| 157 |
+
>>> defs = sorted(defs, key=lambda d: d.line)
|
| 158 |
+
>>> print(defs) # doctest: +NORMALIZE_WHITESPACE
|
| 159 |
+
[<Name full_name='keyword', description='module keyword'>,
|
| 160 |
+
<Name full_name='__main__.C', description='class C'>,
|
| 161 |
+
<Name full_name='__main__.D', description='instance D'>,
|
| 162 |
+
<Name full_name='__main__.f', description='def f'>]
|
| 163 |
+
|
| 164 |
+
Finally, here is what you can get from :attr:`type`:
|
| 165 |
+
|
| 166 |
+
>>> defs = [d.type for d in defs]
|
| 167 |
+
>>> defs[0]
|
| 168 |
+
'module'
|
| 169 |
+
>>> defs[1]
|
| 170 |
+
'class'
|
| 171 |
+
>>> defs[2]
|
| 172 |
+
'instance'
|
| 173 |
+
>>> defs[3]
|
| 174 |
+
'function'
|
| 175 |
+
|
| 176 |
+
Valid values for type are ``module``, ``class``, ``instance``, ``function``,
|
| 177 |
+
``param``, ``path``, ``keyword``, ``property`` and ``statement``.
|
| 178 |
+
|
| 179 |
+
"""
|
| 180 |
+
tree_name = self._name.tree_name
|
| 181 |
+
resolve = False
|
| 182 |
+
if tree_name is not None:
|
| 183 |
+
# TODO move this to their respective names.
|
| 184 |
+
definition = tree_name.get_definition()
|
| 185 |
+
if definition is not None and definition.type == 'import_from' and \
|
| 186 |
+
tree_name.is_definition():
|
| 187 |
+
resolve = True
|
| 188 |
+
|
| 189 |
+
if isinstance(self._name, SubModuleName) or resolve:
|
| 190 |
+
for value in self._name.infer():
|
| 191 |
+
return value.api_type
|
| 192 |
+
return self._name.api_type
|
| 193 |
+
|
| 194 |
+
@property
|
| 195 |
+
def module_name(self):
|
| 196 |
+
"""
|
| 197 |
+
The module name, a bit similar to what ``__name__`` is in a random
|
| 198 |
+
Python module.
|
| 199 |
+
|
| 200 |
+
>>> from jedi import Script
|
| 201 |
+
>>> source = 'import json'
|
| 202 |
+
>>> script = Script(source, path='example.py')
|
| 203 |
+
>>> d = script.infer()[0]
|
| 204 |
+
>>> print(d.module_name) # doctest: +ELLIPSIS
|
| 205 |
+
json
|
| 206 |
+
"""
|
| 207 |
+
return self._get_module_context().py__name__()
|
| 208 |
+
|
| 209 |
+
def in_builtin_module(self):
|
| 210 |
+
"""
|
| 211 |
+
Returns True, if this is a builtin module.
|
| 212 |
+
"""
|
| 213 |
+
value = self._get_module_context().get_value()
|
| 214 |
+
if isinstance(value, StubModuleValue):
|
| 215 |
+
return any(v.is_compiled() for v in value.non_stub_value_set)
|
| 216 |
+
return value.is_compiled()
|
| 217 |
+
|
| 218 |
+
@property
|
| 219 |
+
def line(self):
|
| 220 |
+
"""The line where the definition occurs (starting with 1)."""
|
| 221 |
+
start_pos = self._name.start_pos
|
| 222 |
+
if start_pos is None:
|
| 223 |
+
return None
|
| 224 |
+
return start_pos[0]
|
| 225 |
+
|
| 226 |
+
@property
|
| 227 |
+
def column(self):
|
| 228 |
+
"""The column where the definition occurs (starting with 0)."""
|
| 229 |
+
start_pos = self._name.start_pos
|
| 230 |
+
if start_pos is None:
|
| 231 |
+
return None
|
| 232 |
+
return start_pos[1]
|
| 233 |
+
|
| 234 |
+
def get_definition_start_position(self):
|
| 235 |
+
"""
|
| 236 |
+
The (row, column) of the start of the definition range. Rows start with
|
| 237 |
+
1, columns start with 0.
|
| 238 |
+
|
| 239 |
+
:rtype: Optional[Tuple[int, int]]
|
| 240 |
+
"""
|
| 241 |
+
if self._name.tree_name is None:
|
| 242 |
+
return None
|
| 243 |
+
definition = self._name.tree_name.get_definition()
|
| 244 |
+
if definition is None:
|
| 245 |
+
return self._name.start_pos
|
| 246 |
+
return definition.start_pos
|
| 247 |
+
|
| 248 |
+
def get_definition_end_position(self):
|
| 249 |
+
"""
|
| 250 |
+
The (row, column) of the end of the definition range. Rows start with
|
| 251 |
+
1, columns start with 0.
|
| 252 |
+
|
| 253 |
+
:rtype: Optional[Tuple[int, int]]
|
| 254 |
+
"""
|
| 255 |
+
if self._name.tree_name is None:
|
| 256 |
+
return None
|
| 257 |
+
definition = self._name.tree_name.get_definition()
|
| 258 |
+
if definition is None:
|
| 259 |
+
return self._name.tree_name.end_pos
|
| 260 |
+
if self.type in ("function", "class"):
|
| 261 |
+
last_leaf = definition.get_last_leaf()
|
| 262 |
+
if last_leaf.type == "newline":
|
| 263 |
+
return last_leaf.get_previous_leaf().end_pos
|
| 264 |
+
return last_leaf.end_pos
|
| 265 |
+
return definition.end_pos
|
| 266 |
+
|
| 267 |
+
def docstring(self, raw=False, fast=True):
|
| 268 |
+
r"""
|
| 269 |
+
Return a document string for this completion object.
|
| 270 |
+
|
| 271 |
+
Example:
|
| 272 |
+
|
| 273 |
+
>>> from jedi import Script
|
| 274 |
+
>>> source = '''\
|
| 275 |
+
... def f(a, b=1):
|
| 276 |
+
... "Document for function f."
|
| 277 |
+
... '''
|
| 278 |
+
>>> script = Script(source, path='example.py')
|
| 279 |
+
>>> doc = script.infer(1, len('def f'))[0].docstring()
|
| 280 |
+
>>> print(doc)
|
| 281 |
+
f(a, b=1)
|
| 282 |
+
<BLANKLINE>
|
| 283 |
+
Document for function f.
|
| 284 |
+
|
| 285 |
+
Notice that useful extra information is added to the actual
|
| 286 |
+
docstring, e.g. function signatures are prepended to their docstrings.
|
| 287 |
+
If you need the actual docstring, use ``raw=True`` instead.
|
| 288 |
+
|
| 289 |
+
>>> print(script.infer(1, len('def f'))[0].docstring(raw=True))
|
| 290 |
+
Document for function f.
|
| 291 |
+
|
| 292 |
+
:param fast: Don't follow imports that are only one level deep like
|
| 293 |
+
``import foo``, but follow ``from foo import bar``. This makes
|
| 294 |
+
sense for speed reasons. Completing `import a` is slow if you use
|
| 295 |
+
the ``foo.docstring(fast=False)`` on every object, because it
|
| 296 |
+
parses all libraries starting with ``a``.
|
| 297 |
+
"""
|
| 298 |
+
if isinstance(self._name, ImportName) and fast:
|
| 299 |
+
return ''
|
| 300 |
+
doc = self._get_docstring()
|
| 301 |
+
if raw:
|
| 302 |
+
return doc
|
| 303 |
+
|
| 304 |
+
signature_text = self._get_docstring_signature()
|
| 305 |
+
if signature_text and doc:
|
| 306 |
+
return signature_text + '\n\n' + doc
|
| 307 |
+
else:
|
| 308 |
+
return signature_text + doc
|
| 309 |
+
|
| 310 |
+
def _get_docstring(self):
|
| 311 |
+
return self._name.py__doc__()
|
| 312 |
+
|
| 313 |
+
def _get_docstring_signature(self):
|
| 314 |
+
return '\n'.join(
|
| 315 |
+
signature.to_string()
|
| 316 |
+
for signature in self._get_signatures(for_docstring=True)
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
@property
|
| 320 |
+
def description(self):
|
| 321 |
+
"""
|
| 322 |
+
A description of the :class:`.Name` object, which is heavily used
|
| 323 |
+
in testing. e.g. for ``isinstance`` it returns ``def isinstance``.
|
| 324 |
+
|
| 325 |
+
Example:
|
| 326 |
+
|
| 327 |
+
>>> from jedi import Script
|
| 328 |
+
>>> source = '''
|
| 329 |
+
... def f():
|
| 330 |
+
... pass
|
| 331 |
+
...
|
| 332 |
+
... class C:
|
| 333 |
+
... pass
|
| 334 |
+
...
|
| 335 |
+
... variable = f if random.choice([0,1]) else C'''
|
| 336 |
+
>>> script = Script(source) # line is maximum by default
|
| 337 |
+
>>> defs = script.infer(column=3)
|
| 338 |
+
>>> defs = sorted(defs, key=lambda d: d.line)
|
| 339 |
+
>>> print(defs) # doctest: +NORMALIZE_WHITESPACE
|
| 340 |
+
[<Name full_name='__main__.f', description='def f'>,
|
| 341 |
+
<Name full_name='__main__.C', description='class C'>]
|
| 342 |
+
>>> str(defs[0].description)
|
| 343 |
+
'def f'
|
| 344 |
+
>>> str(defs[1].description)
|
| 345 |
+
'class C'
|
| 346 |
+
|
| 347 |
+
"""
|
| 348 |
+
typ = self.type
|
| 349 |
+
tree_name = self._name.tree_name
|
| 350 |
+
if typ == 'param':
|
| 351 |
+
return typ + ' ' + self._name.to_string()
|
| 352 |
+
if typ in ('function', 'class', 'module', 'instance') or tree_name is None:
|
| 353 |
+
if typ == 'function':
|
| 354 |
+
# For the description we want a short and a pythonic way.
|
| 355 |
+
typ = 'def'
|
| 356 |
+
return typ + ' ' + self._name.get_public_name()
|
| 357 |
+
|
| 358 |
+
definition = tree_name.get_definition(include_setitem=True) or tree_name
|
| 359 |
+
# Remove the prefix, because that's not what we want for get_code
|
| 360 |
+
# here.
|
| 361 |
+
txt = definition.get_code(include_prefix=False)
|
| 362 |
+
# Delete comments:
|
| 363 |
+
txt = re.sub(r'#[^\n]+\n', ' ', txt)
|
| 364 |
+
# Delete multi spaces/newlines
|
| 365 |
+
txt = re.sub(r'\s+', ' ', txt).strip()
|
| 366 |
+
return txt
|
| 367 |
+
|
| 368 |
+
@property
|
| 369 |
+
def full_name(self):
|
| 370 |
+
"""
|
| 371 |
+
Dot-separated path of this object.
|
| 372 |
+
|
| 373 |
+
It is in the form of ``<module>[.<submodule>[...]][.<object>]``.
|
| 374 |
+
It is useful when you want to look up Python manual of the
|
| 375 |
+
object at hand.
|
| 376 |
+
|
| 377 |
+
Example:
|
| 378 |
+
|
| 379 |
+
>>> from jedi import Script
|
| 380 |
+
>>> source = '''
|
| 381 |
+
... import os
|
| 382 |
+
... os.path.join'''
|
| 383 |
+
>>> script = Script(source, path='example.py')
|
| 384 |
+
>>> print(script.infer(3, len('os.path.join'))[0].full_name)
|
| 385 |
+
os.path.join
|
| 386 |
+
|
| 387 |
+
Notice that it returns ``'os.path.join'`` instead of (for example)
|
| 388 |
+
``'posixpath.join'``. This is not correct, since the modules name would
|
| 389 |
+
be ``<module 'posixpath' ...>```. However most users find the latter
|
| 390 |
+
more practical.
|
| 391 |
+
"""
|
| 392 |
+
if not self._name.is_value_name:
|
| 393 |
+
return None
|
| 394 |
+
|
| 395 |
+
names = self._name.get_qualified_names(include_module_names=True)
|
| 396 |
+
if names is None:
|
| 397 |
+
return None
|
| 398 |
+
|
| 399 |
+
names = list(names)
|
| 400 |
+
try:
|
| 401 |
+
names[0] = self._mapping[names[0]]
|
| 402 |
+
except KeyError:
|
| 403 |
+
pass
|
| 404 |
+
|
| 405 |
+
return '.'.join(names)
|
| 406 |
+
|
| 407 |
+
def is_stub(self):
|
| 408 |
+
"""
|
| 409 |
+
Returns True if the current name is defined in a stub file.
|
| 410 |
+
"""
|
| 411 |
+
if not self._name.is_value_name:
|
| 412 |
+
return False
|
| 413 |
+
|
| 414 |
+
return self._name.get_root_context().is_stub()
|
| 415 |
+
|
| 416 |
+
def is_side_effect(self):
|
| 417 |
+
"""
|
| 418 |
+
Checks if a name is defined as ``self.foo = 3``. In case of self, this
|
| 419 |
+
function would return False, for foo it would return True.
|
| 420 |
+
"""
|
| 421 |
+
tree_name = self._name.tree_name
|
| 422 |
+
if tree_name is None:
|
| 423 |
+
return False
|
| 424 |
+
return tree_name.is_definition() and tree_name.parent.type == 'trailer'
|
| 425 |
+
|
| 426 |
+
@debug.increase_indent_cm('goto on name')
|
| 427 |
+
def goto(self, *, follow_imports=False, follow_builtin_imports=False,
|
| 428 |
+
only_stubs=False, prefer_stubs=False):
|
| 429 |
+
|
| 430 |
+
"""
|
| 431 |
+
Like :meth:`.Script.goto` (also supports the same params), but does it
|
| 432 |
+
for the current name. This is typically useful if you are using
|
| 433 |
+
something like :meth:`.Script.get_names()`.
|
| 434 |
+
|
| 435 |
+
:param follow_imports: The goto call will follow imports.
|
| 436 |
+
:param follow_builtin_imports: If follow_imports is True will try to
|
| 437 |
+
look up names in builtins (i.e. compiled or extension modules).
|
| 438 |
+
:param only_stubs: Only return stubs for this goto call.
|
| 439 |
+
:param prefer_stubs: Prefer stubs to Python objects for this goto call.
|
| 440 |
+
:rtype: list of :class:`Name`
|
| 441 |
+
"""
|
| 442 |
+
if not self._name.is_value_name:
|
| 443 |
+
return []
|
| 444 |
+
|
| 445 |
+
names = self._name.goto()
|
| 446 |
+
if follow_imports:
|
| 447 |
+
names = filter_follow_imports(names, follow_builtin_imports)
|
| 448 |
+
names = convert_names(
|
| 449 |
+
names,
|
| 450 |
+
only_stubs=only_stubs,
|
| 451 |
+
prefer_stubs=prefer_stubs,
|
| 452 |
+
)
|
| 453 |
+
return [self if n == self._name else Name(self._inference_state, n)
|
| 454 |
+
for n in names]
|
| 455 |
+
|
| 456 |
+
@debug.increase_indent_cm('infer on name')
|
| 457 |
+
def infer(self, *, only_stubs=False, prefer_stubs=False):
|
| 458 |
+
"""
|
| 459 |
+
Like :meth:`.Script.infer`, it can be useful to understand which type
|
| 460 |
+
the current name has.
|
| 461 |
+
|
| 462 |
+
Return the actual definitions. I strongly recommend not using it for
|
| 463 |
+
your completions, because it might slow down |jedi|. If you want to
|
| 464 |
+
read only a few objects (<=20), it might be useful, especially to get
|
| 465 |
+
the original docstrings. The basic problem of this function is that it
|
| 466 |
+
follows all results. This means with 1000 completions (e.g. numpy),
|
| 467 |
+
it's just very, very slow.
|
| 468 |
+
|
| 469 |
+
:param only_stubs: Only return stubs for this goto call.
|
| 470 |
+
:param prefer_stubs: Prefer stubs to Python objects for this type
|
| 471 |
+
inference call.
|
| 472 |
+
:rtype: list of :class:`Name`
|
| 473 |
+
"""
|
| 474 |
+
assert not (only_stubs and prefer_stubs)
|
| 475 |
+
|
| 476 |
+
if not self._name.is_value_name:
|
| 477 |
+
return []
|
| 478 |
+
|
| 479 |
+
# First we need to make sure that we have stub names (if possible) that
|
| 480 |
+
# we can follow. If we don't do that, we can end up with the inferred
|
| 481 |
+
# results of Python objects instead of stubs.
|
| 482 |
+
names = convert_names([self._name], prefer_stubs=True)
|
| 483 |
+
values = convert_values(
|
| 484 |
+
ValueSet.from_sets(n.infer() for n in names),
|
| 485 |
+
only_stubs=only_stubs,
|
| 486 |
+
prefer_stubs=prefer_stubs,
|
| 487 |
+
)
|
| 488 |
+
resulting_names = [c.name for c in values]
|
| 489 |
+
return [self if n == self._name else Name(self._inference_state, n)
|
| 490 |
+
for n in resulting_names]
|
| 491 |
+
|
| 492 |
+
def parent(self):
|
| 493 |
+
"""
|
| 494 |
+
Returns the parent scope of this identifier.
|
| 495 |
+
|
| 496 |
+
:rtype: Name
|
| 497 |
+
"""
|
| 498 |
+
if not self._name.is_value_name:
|
| 499 |
+
return None
|
| 500 |
+
|
| 501 |
+
if self.type in ('function', 'class', 'param') and self._name.tree_name is not None:
|
| 502 |
+
# Since the parent_context doesn't really match what the user
|
| 503 |
+
# thinks of that the parent is here, we do these cases separately.
|
| 504 |
+
# The reason for this is the following:
|
| 505 |
+
# - class: Nested classes parent_context is always the
|
| 506 |
+
# parent_context of the most outer one.
|
| 507 |
+
# - function: Functions in classes have the module as
|
| 508 |
+
# parent_context.
|
| 509 |
+
# - param: The parent_context of a param is not its function but
|
| 510 |
+
# e.g. the outer class or module.
|
| 511 |
+
cls_or_func_node = self._name.tree_name.get_definition()
|
| 512 |
+
parent = search_ancestor(cls_or_func_node, 'funcdef', 'classdef', 'file_input')
|
| 513 |
+
context = self._get_module_context().create_value(parent).as_context()
|
| 514 |
+
else:
|
| 515 |
+
context = self._name.parent_context
|
| 516 |
+
|
| 517 |
+
if context is None:
|
| 518 |
+
return None
|
| 519 |
+
while context.name is None:
|
| 520 |
+
# Happens for comprehension contexts
|
| 521 |
+
context = context.parent_context
|
| 522 |
+
|
| 523 |
+
return Name(self._inference_state, context.name)
|
| 524 |
+
|
| 525 |
+
def __repr__(self):
|
| 526 |
+
return "<%s %sname=%r, description=%r>" % (
|
| 527 |
+
self.__class__.__name__,
|
| 528 |
+
'full_' if self.full_name else '',
|
| 529 |
+
self.full_name or self.name,
|
| 530 |
+
self.description,
|
| 531 |
+
)
|
| 532 |
+
|
| 533 |
+
def get_line_code(self, before=0, after=0):
|
| 534 |
+
"""
|
| 535 |
+
Returns the line of code where this object was defined.
|
| 536 |
+
|
| 537 |
+
:param before: Add n lines before the current line to the output.
|
| 538 |
+
:param after: Add n lines after the current line to the output.
|
| 539 |
+
|
| 540 |
+
:return str: Returns the line(s) of code or an empty string if it's a
|
| 541 |
+
builtin.
|
| 542 |
+
"""
|
| 543 |
+
if not self._name.is_value_name:
|
| 544 |
+
return ''
|
| 545 |
+
|
| 546 |
+
lines = self._name.get_root_context().code_lines
|
| 547 |
+
if lines is None:
|
| 548 |
+
# Probably a builtin module, just ignore in that case.
|
| 549 |
+
return ''
|
| 550 |
+
|
| 551 |
+
index = self._name.start_pos[0] - 1
|
| 552 |
+
start_index = max(index - before, 0)
|
| 553 |
+
return ''.join(lines[start_index:index + after + 1])
|
| 554 |
+
|
| 555 |
+
def _get_signatures(self, for_docstring=False):
|
| 556 |
+
if self._name.api_type == 'property':
|
| 557 |
+
return []
|
| 558 |
+
if for_docstring and self._name.api_type == 'statement' and not self.is_stub():
|
| 559 |
+
# For docstrings we don't resolve signatures if they are simple
|
| 560 |
+
# statements and not stubs. This is a speed optimization.
|
| 561 |
+
return []
|
| 562 |
+
|
| 563 |
+
if isinstance(self._name, MixedName):
|
| 564 |
+
# While this would eventually happen anyway, it's basically just a
|
| 565 |
+
# shortcut to not infer anything tree related, because it's really
|
| 566 |
+
# not necessary.
|
| 567 |
+
return self._name.infer_compiled_value().get_signatures()
|
| 568 |
+
|
| 569 |
+
names = convert_names([self._name], prefer_stubs=True)
|
| 570 |
+
return [sig for name in names for sig in name.infer().get_signatures()]
|
| 571 |
+
|
| 572 |
+
def get_signatures(self):
|
| 573 |
+
"""
|
| 574 |
+
Returns all potential signatures for a function or a class. Multiple
|
| 575 |
+
signatures are typical if you use Python stubs with ``@overload``.
|
| 576 |
+
|
| 577 |
+
:rtype: list of :class:`BaseSignature`
|
| 578 |
+
"""
|
| 579 |
+
return [
|
| 580 |
+
BaseSignature(self._inference_state, s)
|
| 581 |
+
for s in self._get_signatures()
|
| 582 |
+
]
|
| 583 |
+
|
| 584 |
+
def execute(self):
|
| 585 |
+
"""
|
| 586 |
+
Uses type inference to "execute" this identifier and returns the
|
| 587 |
+
executed objects.
|
| 588 |
+
|
| 589 |
+
:rtype: list of :class:`Name`
|
| 590 |
+
"""
|
| 591 |
+
return _values_to_definitions(self._name.infer().execute_with_values())
|
| 592 |
+
|
| 593 |
+
def get_type_hint(self):
|
| 594 |
+
"""
|
| 595 |
+
Returns type hints like ``Iterable[int]`` or ``Union[int, str]``.
|
| 596 |
+
|
| 597 |
+
This method might be quite slow, especially for functions. The problem
|
| 598 |
+
is finding executions for those functions to return something like
|
| 599 |
+
``Callable[[int, str], str]``.
|
| 600 |
+
|
| 601 |
+
:rtype: str
|
| 602 |
+
"""
|
| 603 |
+
return self._name.infer().get_type_hint()
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
class Completion(BaseName):
|
| 607 |
+
"""
|
| 608 |
+
``Completion`` objects are returned from :meth:`.Script.complete`. They
|
| 609 |
+
provide additional information about a completion.
|
| 610 |
+
"""
|
| 611 |
+
def __init__(self, inference_state, name, stack, like_name_length,
|
| 612 |
+
is_fuzzy, cached_name=None):
|
| 613 |
+
super().__init__(inference_state, name)
|
| 614 |
+
|
| 615 |
+
self._like_name_length = like_name_length
|
| 616 |
+
self._stack = stack
|
| 617 |
+
self._is_fuzzy = is_fuzzy
|
| 618 |
+
self._cached_name = cached_name
|
| 619 |
+
|
| 620 |
+
# Completion objects with the same Completion name (which means
|
| 621 |
+
# duplicate items in the completion)
|
| 622 |
+
self._same_name_completions = []
|
| 623 |
+
|
| 624 |
+
def _complete(self, like_name):
|
| 625 |
+
append = ''
|
| 626 |
+
if settings.add_bracket_after_function \
|
| 627 |
+
and self.type == 'function':
|
| 628 |
+
append = '('
|
| 629 |
+
|
| 630 |
+
name = self._name.get_public_name()
|
| 631 |
+
if like_name:
|
| 632 |
+
name = name[self._like_name_length:]
|
| 633 |
+
return name + append
|
| 634 |
+
|
| 635 |
+
@property
|
| 636 |
+
def complete(self):
|
| 637 |
+
"""
|
| 638 |
+
Only works with non-fuzzy completions. Returns None if fuzzy
|
| 639 |
+
completions are used.
|
| 640 |
+
|
| 641 |
+
Return the rest of the word, e.g. completing ``isinstance``::
|
| 642 |
+
|
| 643 |
+
isinstan# <-- Cursor is here
|
| 644 |
+
|
| 645 |
+
would return the string 'ce'. It also adds additional stuff, depending
|
| 646 |
+
on your ``settings.py``.
|
| 647 |
+
|
| 648 |
+
Assuming the following function definition::
|
| 649 |
+
|
| 650 |
+
def foo(param=0):
|
| 651 |
+
pass
|
| 652 |
+
|
| 653 |
+
completing ``foo(par`` would give a ``Completion`` which ``complete``
|
| 654 |
+
would be ``am=``.
|
| 655 |
+
"""
|
| 656 |
+
if self._is_fuzzy:
|
| 657 |
+
return None
|
| 658 |
+
return self._complete(True)
|
| 659 |
+
|
| 660 |
+
@property
|
| 661 |
+
def name_with_symbols(self):
|
| 662 |
+
"""
|
| 663 |
+
Similar to :attr:`.name`, but like :attr:`.name` returns also the
|
| 664 |
+
symbols, for example assuming the following function definition::
|
| 665 |
+
|
| 666 |
+
def foo(param=0):
|
| 667 |
+
pass
|
| 668 |
+
|
| 669 |
+
completing ``foo(`` would give a ``Completion`` which
|
| 670 |
+
``name_with_symbols`` would be "param=".
|
| 671 |
+
|
| 672 |
+
"""
|
| 673 |
+
return self._complete(False)
|
| 674 |
+
|
| 675 |
+
def docstring(self, raw=False, fast=True):
|
| 676 |
+
"""
|
| 677 |
+
Documented under :meth:`BaseName.docstring`.
|
| 678 |
+
"""
|
| 679 |
+
if self._like_name_length >= 3:
|
| 680 |
+
# In this case we can just resolve the like name, because we
|
| 681 |
+
# wouldn't load like > 100 Python modules anymore.
|
| 682 |
+
fast = False
|
| 683 |
+
|
| 684 |
+
return super().docstring(raw=raw, fast=fast)
|
| 685 |
+
|
| 686 |
+
def _get_docstring(self):
|
| 687 |
+
if self._cached_name is not None:
|
| 688 |
+
return completion_cache.get_docstring(
|
| 689 |
+
self._cached_name,
|
| 690 |
+
self._name.get_public_name(),
|
| 691 |
+
lambda: self._get_cache()
|
| 692 |
+
)
|
| 693 |
+
return super()._get_docstring()
|
| 694 |
+
|
| 695 |
+
def _get_docstring_signature(self):
|
| 696 |
+
if self._cached_name is not None:
|
| 697 |
+
return completion_cache.get_docstring_signature(
|
| 698 |
+
self._cached_name,
|
| 699 |
+
self._name.get_public_name(),
|
| 700 |
+
lambda: self._get_cache()
|
| 701 |
+
)
|
| 702 |
+
return super()._get_docstring_signature()
|
| 703 |
+
|
| 704 |
+
def _get_cache(self):
|
| 705 |
+
return (
|
| 706 |
+
super().type,
|
| 707 |
+
super()._get_docstring_signature(),
|
| 708 |
+
super()._get_docstring(),
|
| 709 |
+
)
|
| 710 |
+
|
| 711 |
+
@property
|
| 712 |
+
def type(self):
|
| 713 |
+
"""
|
| 714 |
+
Documented under :meth:`BaseName.type`.
|
| 715 |
+
"""
|
| 716 |
+
# Purely a speed optimization.
|
| 717 |
+
if self._cached_name is not None:
|
| 718 |
+
return completion_cache.get_type(
|
| 719 |
+
self._cached_name,
|
| 720 |
+
self._name.get_public_name(),
|
| 721 |
+
lambda: self._get_cache()
|
| 722 |
+
)
|
| 723 |
+
|
| 724 |
+
return super().type
|
| 725 |
+
|
| 726 |
+
def get_completion_prefix_length(self):
|
| 727 |
+
"""
|
| 728 |
+
Returns the length of the prefix being completed.
|
| 729 |
+
For example, completing ``isinstance``::
|
| 730 |
+
|
| 731 |
+
isinstan# <-- Cursor is here
|
| 732 |
+
|
| 733 |
+
would return 8, because len('isinstan') == 8.
|
| 734 |
+
|
| 735 |
+
Assuming the following function definition::
|
| 736 |
+
|
| 737 |
+
def foo(param=0):
|
| 738 |
+
pass
|
| 739 |
+
|
| 740 |
+
completing ``foo(par`` would return 3.
|
| 741 |
+
"""
|
| 742 |
+
return self._like_name_length
|
| 743 |
+
|
| 744 |
+
def __repr__(self):
|
| 745 |
+
return '<%s: %s>' % (type(self).__name__, self._name.get_public_name())
|
| 746 |
+
|
| 747 |
+
|
| 748 |
+
class Name(BaseName):
|
| 749 |
+
"""
|
| 750 |
+
*Name* objects are returned from many different APIs including
|
| 751 |
+
:meth:`.Script.goto` or :meth:`.Script.infer`.
|
| 752 |
+
"""
|
| 753 |
+
def __init__(self, inference_state, definition):
|
| 754 |
+
super().__init__(inference_state, definition)
|
| 755 |
+
|
| 756 |
+
@memoize_method
|
| 757 |
+
def defined_names(self):
|
| 758 |
+
"""
|
| 759 |
+
List sub-definitions (e.g., methods in class).
|
| 760 |
+
|
| 761 |
+
:rtype: list of :class:`Name`
|
| 762 |
+
"""
|
| 763 |
+
defs = self._name.infer()
|
| 764 |
+
return sorted(
|
| 765 |
+
unite(defined_names(self._inference_state, d) for d in defs),
|
| 766 |
+
key=lambda s: s._name.start_pos or (0, 0)
|
| 767 |
+
)
|
| 768 |
+
|
| 769 |
+
def is_definition(self):
|
| 770 |
+
"""
|
| 771 |
+
Returns True, if defined as a name in a statement, function or class.
|
| 772 |
+
Returns False, if it's a reference to such a definition.
|
| 773 |
+
"""
|
| 774 |
+
if self._name.tree_name is None:
|
| 775 |
+
return True
|
| 776 |
+
else:
|
| 777 |
+
return self._name.tree_name.is_definition()
|
| 778 |
+
|
| 779 |
+
def __eq__(self, other):
|
| 780 |
+
return self._name.start_pos == other._name.start_pos \
|
| 781 |
+
and self.module_path == other.module_path \
|
| 782 |
+
and self.name == other.name \
|
| 783 |
+
and self._inference_state == other._inference_state
|
| 784 |
+
|
| 785 |
+
def __ne__(self, other):
|
| 786 |
+
return not self.__eq__(other)
|
| 787 |
+
|
| 788 |
+
def __hash__(self):
|
| 789 |
+
return hash((self._name.start_pos, self.module_path, self.name, self._inference_state))
|
| 790 |
+
|
| 791 |
+
|
| 792 |
+
class BaseSignature(Name):
|
| 793 |
+
"""
|
| 794 |
+
These signatures are returned by :meth:`BaseName.get_signatures`
|
| 795 |
+
calls.
|
| 796 |
+
"""
|
| 797 |
+
def __init__(self, inference_state, signature):
|
| 798 |
+
super().__init__(inference_state, signature.name)
|
| 799 |
+
self._signature = signature
|
| 800 |
+
|
| 801 |
+
@property
|
| 802 |
+
def params(self):
|
| 803 |
+
"""
|
| 804 |
+
Returns definitions for all parameters that a signature defines.
|
| 805 |
+
This includes stuff like ``*args`` and ``**kwargs``.
|
| 806 |
+
|
| 807 |
+
:rtype: list of :class:`.ParamName`
|
| 808 |
+
"""
|
| 809 |
+
return [ParamName(self._inference_state, n)
|
| 810 |
+
for n in self._signature.get_param_names(resolve_stars=True)]
|
| 811 |
+
|
| 812 |
+
def to_string(self):
|
| 813 |
+
"""
|
| 814 |
+
Returns a text representation of the signature. This could for example
|
| 815 |
+
look like ``foo(bar, baz: int, **kwargs)``.
|
| 816 |
+
|
| 817 |
+
:rtype: str
|
| 818 |
+
"""
|
| 819 |
+
return self._signature.to_string()
|
| 820 |
+
|
| 821 |
+
|
| 822 |
+
class Signature(BaseSignature):
|
| 823 |
+
"""
|
| 824 |
+
A full signature object is the return value of
|
| 825 |
+
:meth:`.Script.get_signatures`.
|
| 826 |
+
"""
|
| 827 |
+
def __init__(self, inference_state, signature, call_details):
|
| 828 |
+
super().__init__(inference_state, signature)
|
| 829 |
+
self._call_details = call_details
|
| 830 |
+
self._signature = signature
|
| 831 |
+
|
| 832 |
+
@property
|
| 833 |
+
def index(self):
|
| 834 |
+
"""
|
| 835 |
+
Returns the param index of the current cursor position.
|
| 836 |
+
Returns None if the index cannot be found in the curent call.
|
| 837 |
+
|
| 838 |
+
:rtype: int
|
| 839 |
+
"""
|
| 840 |
+
return self._call_details.calculate_index(
|
| 841 |
+
self._signature.get_param_names(resolve_stars=True)
|
| 842 |
+
)
|
| 843 |
+
|
| 844 |
+
@property
|
| 845 |
+
def bracket_start(self):
|
| 846 |
+
"""
|
| 847 |
+
Returns a line/column tuple of the bracket that is responsible for the
|
| 848 |
+
last function call. The first line is 1 and the first column 0.
|
| 849 |
+
|
| 850 |
+
:rtype: int, int
|
| 851 |
+
"""
|
| 852 |
+
return self._call_details.bracket_leaf.start_pos
|
| 853 |
+
|
| 854 |
+
def __repr__(self):
|
| 855 |
+
return '<%s: index=%r %s>' % (
|
| 856 |
+
type(self).__name__,
|
| 857 |
+
self.index,
|
| 858 |
+
self._signature.to_string(),
|
| 859 |
+
)
|
| 860 |
+
|
| 861 |
+
|
| 862 |
+
class ParamName(Name):
|
| 863 |
+
def infer_default(self):
|
| 864 |
+
"""
|
| 865 |
+
Returns default values like the ``1`` of ``def foo(x=1):``.
|
| 866 |
+
|
| 867 |
+
:rtype: list of :class:`.Name`
|
| 868 |
+
"""
|
| 869 |
+
return _values_to_definitions(self._name.infer_default())
|
| 870 |
+
|
| 871 |
+
def infer_annotation(self, **kwargs):
|
| 872 |
+
"""
|
| 873 |
+
:param execute_annotation: Default True; If False, values are not
|
| 874 |
+
executed and classes are returned instead of instances.
|
| 875 |
+
:rtype: list of :class:`.Name`
|
| 876 |
+
"""
|
| 877 |
+
return _values_to_definitions(self._name.infer_annotation(ignore_stars=True, **kwargs))
|
| 878 |
+
|
| 879 |
+
def to_string(self):
|
| 880 |
+
"""
|
| 881 |
+
Returns a simple representation of a param, like
|
| 882 |
+
``f: Callable[..., Any]``.
|
| 883 |
+
|
| 884 |
+
:rtype: str
|
| 885 |
+
"""
|
| 886 |
+
return self._name.to_string()
|
| 887 |
+
|
| 888 |
+
@property
|
| 889 |
+
def kind(self):
|
| 890 |
+
"""
|
| 891 |
+
Returns an enum instance of :mod:`inspect`'s ``Parameter`` enum.
|
| 892 |
+
|
| 893 |
+
:rtype: :py:attr:`inspect.Parameter.kind`
|
| 894 |
+
"""
|
| 895 |
+
return self._name.get_kind()
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/completion.py
ADDED
|
@@ -0,0 +1,696 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
from textwrap import dedent
|
| 3 |
+
from inspect import Parameter
|
| 4 |
+
|
| 5 |
+
from parso.python.token import PythonTokenTypes
|
| 6 |
+
from parso.python import tree
|
| 7 |
+
from parso.tree import search_ancestor, Leaf
|
| 8 |
+
from parso import split_lines
|
| 9 |
+
|
| 10 |
+
from jedi import debug
|
| 11 |
+
from jedi import settings
|
| 12 |
+
from jedi.api import classes
|
| 13 |
+
from jedi.api import helpers
|
| 14 |
+
from jedi.api import keywords
|
| 15 |
+
from jedi.api.strings import complete_dict
|
| 16 |
+
from jedi.api.file_name import complete_file_name
|
| 17 |
+
from jedi.inference import imports
|
| 18 |
+
from jedi.inference.base_value import ValueSet
|
| 19 |
+
from jedi.inference.helpers import infer_call_of_leaf, parse_dotted_names
|
| 20 |
+
from jedi.inference.context import get_global_filters
|
| 21 |
+
from jedi.inference.value import TreeInstance
|
| 22 |
+
from jedi.inference.docstring_utils import DocstringModule
|
| 23 |
+
from jedi.inference.names import ParamNameWrapper, SubModuleName
|
| 24 |
+
from jedi.inference.gradual.conversion import convert_values, convert_names
|
| 25 |
+
from jedi.parser_utils import cut_value_at_position
|
| 26 |
+
from jedi.plugins import plugin_manager
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class ParamNameWithEquals(ParamNameWrapper):
|
| 30 |
+
def get_public_name(self):
|
| 31 |
+
return self.string_name + '='
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _get_signature_param_names(signatures, positional_count, used_kwargs):
|
| 35 |
+
# Add named params
|
| 36 |
+
for call_sig in signatures:
|
| 37 |
+
for i, p in enumerate(call_sig.params):
|
| 38 |
+
kind = p.kind
|
| 39 |
+
if i < positional_count and kind == Parameter.POSITIONAL_OR_KEYWORD:
|
| 40 |
+
continue
|
| 41 |
+
if kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY) \
|
| 42 |
+
and p.name not in used_kwargs:
|
| 43 |
+
yield ParamNameWithEquals(p._name)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _must_be_kwarg(signatures, positional_count, used_kwargs):
|
| 47 |
+
if used_kwargs:
|
| 48 |
+
return True
|
| 49 |
+
|
| 50 |
+
must_be_kwarg = True
|
| 51 |
+
for signature in signatures:
|
| 52 |
+
for i, p in enumerate(signature.params):
|
| 53 |
+
kind = p.kind
|
| 54 |
+
if kind is Parameter.VAR_POSITIONAL:
|
| 55 |
+
# In case there were not already kwargs, the next param can
|
| 56 |
+
# always be a normal argument.
|
| 57 |
+
return False
|
| 58 |
+
|
| 59 |
+
if i >= positional_count and kind in (Parameter.POSITIONAL_OR_KEYWORD,
|
| 60 |
+
Parameter.POSITIONAL_ONLY):
|
| 61 |
+
must_be_kwarg = False
|
| 62 |
+
break
|
| 63 |
+
if not must_be_kwarg:
|
| 64 |
+
break
|
| 65 |
+
return must_be_kwarg
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def filter_names(inference_state, completion_names, stack, like_name, fuzzy,
|
| 69 |
+
imported_names, cached_name):
|
| 70 |
+
comp_dct = set()
|
| 71 |
+
if settings.case_insensitive_completion:
|
| 72 |
+
like_name = like_name.lower()
|
| 73 |
+
for name in completion_names:
|
| 74 |
+
string = name.string_name
|
| 75 |
+
if string in imported_names and string != like_name:
|
| 76 |
+
continue
|
| 77 |
+
if settings.case_insensitive_completion:
|
| 78 |
+
string = string.lower()
|
| 79 |
+
if helpers.match(string, like_name, fuzzy=fuzzy):
|
| 80 |
+
new = classes.Completion(
|
| 81 |
+
inference_state,
|
| 82 |
+
name,
|
| 83 |
+
stack,
|
| 84 |
+
len(like_name),
|
| 85 |
+
is_fuzzy=fuzzy,
|
| 86 |
+
cached_name=cached_name,
|
| 87 |
+
)
|
| 88 |
+
k = (new.name, new.complete) # key
|
| 89 |
+
if k not in comp_dct:
|
| 90 |
+
comp_dct.add(k)
|
| 91 |
+
tree_name = name.tree_name
|
| 92 |
+
if tree_name is not None:
|
| 93 |
+
definition = tree_name.get_definition()
|
| 94 |
+
if definition is not None and definition.type == 'del_stmt':
|
| 95 |
+
continue
|
| 96 |
+
yield new
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _remove_duplicates(completions, other_completions):
|
| 100 |
+
names = {d.name for d in other_completions}
|
| 101 |
+
return [c for c in completions if c.name not in names]
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def get_user_context(module_context, position):
|
| 105 |
+
"""
|
| 106 |
+
Returns the scope in which the user resides. This includes flows.
|
| 107 |
+
"""
|
| 108 |
+
leaf = module_context.tree_node.get_leaf_for_position(position, include_prefixes=True)
|
| 109 |
+
return module_context.create_context(leaf)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def get_flow_scope_node(module_node, position):
|
| 113 |
+
node = module_node.get_leaf_for_position(position, include_prefixes=True)
|
| 114 |
+
while not isinstance(node, (tree.Scope, tree.Flow)):
|
| 115 |
+
node = node.parent
|
| 116 |
+
|
| 117 |
+
return node
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
@plugin_manager.decorate()
|
| 121 |
+
def complete_param_names(context, function_name, decorator_nodes):
|
| 122 |
+
# Basically there's no way to do param completion. The plugins are
|
| 123 |
+
# responsible for this.
|
| 124 |
+
return []
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class Completion:
|
| 128 |
+
def __init__(self, inference_state, module_context, code_lines, position,
|
| 129 |
+
signatures_callback, fuzzy=False):
|
| 130 |
+
self._inference_state = inference_state
|
| 131 |
+
self._module_context = module_context
|
| 132 |
+
self._module_node = module_context.tree_node
|
| 133 |
+
self._code_lines = code_lines
|
| 134 |
+
|
| 135 |
+
# The first step of completions is to get the name
|
| 136 |
+
self._like_name = helpers.get_on_completion_name(self._module_node, code_lines, position)
|
| 137 |
+
# The actual cursor position is not what we need to calculate
|
| 138 |
+
# everything. We want the start of the name we're on.
|
| 139 |
+
self._original_position = position
|
| 140 |
+
self._signatures_callback = signatures_callback
|
| 141 |
+
|
| 142 |
+
self._fuzzy = fuzzy
|
| 143 |
+
|
| 144 |
+
# Return list of completions in this order:
|
| 145 |
+
# - Beginning with what user is typing
|
| 146 |
+
# - Public (alphabet)
|
| 147 |
+
# - Private ("_xxx")
|
| 148 |
+
# - Dunder ("__xxx")
|
| 149 |
+
def complete(self):
|
| 150 |
+
leaf = self._module_node.get_leaf_for_position(
|
| 151 |
+
self._original_position,
|
| 152 |
+
include_prefixes=True
|
| 153 |
+
)
|
| 154 |
+
string, start_leaf, quote = _extract_string_while_in_string(leaf, self._original_position)
|
| 155 |
+
|
| 156 |
+
prefixed_completions = complete_dict(
|
| 157 |
+
self._module_context,
|
| 158 |
+
self._code_lines,
|
| 159 |
+
start_leaf or leaf,
|
| 160 |
+
self._original_position,
|
| 161 |
+
None if string is None else quote + string,
|
| 162 |
+
fuzzy=self._fuzzy,
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
if string is not None and not prefixed_completions:
|
| 166 |
+
prefixed_completions = list(complete_file_name(
|
| 167 |
+
self._inference_state, self._module_context, start_leaf, quote, string,
|
| 168 |
+
self._like_name, self._signatures_callback,
|
| 169 |
+
self._code_lines, self._original_position,
|
| 170 |
+
self._fuzzy
|
| 171 |
+
))
|
| 172 |
+
if string is not None:
|
| 173 |
+
if not prefixed_completions and '\n' in string:
|
| 174 |
+
# Complete only multi line strings
|
| 175 |
+
prefixed_completions = self._complete_in_string(start_leaf, string)
|
| 176 |
+
return prefixed_completions
|
| 177 |
+
|
| 178 |
+
cached_name, completion_names = self._complete_python(leaf)
|
| 179 |
+
|
| 180 |
+
imported_names = []
|
| 181 |
+
if leaf.parent is not None and leaf.parent.type in ['import_as_names', 'dotted_as_names']:
|
| 182 |
+
imported_names.extend(extract_imported_names(leaf.parent))
|
| 183 |
+
|
| 184 |
+
completions = list(filter_names(self._inference_state, completion_names,
|
| 185 |
+
self.stack, self._like_name,
|
| 186 |
+
self._fuzzy, imported_names, cached_name=cached_name))
|
| 187 |
+
|
| 188 |
+
return (
|
| 189 |
+
# Removing duplicates mostly to remove False/True/None duplicates.
|
| 190 |
+
_remove_duplicates(prefixed_completions, completions)
|
| 191 |
+
+ sorted(completions, key=lambda x: (not x.name.startswith(self._like_name),
|
| 192 |
+
x.name.startswith('__'),
|
| 193 |
+
x.name.startswith('_'),
|
| 194 |
+
x.name.lower()))
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
def _complete_python(self, leaf):
|
| 198 |
+
"""
|
| 199 |
+
Analyzes the current context of a completion and decides what to
|
| 200 |
+
return.
|
| 201 |
+
|
| 202 |
+
Technically this works by generating a parser stack and analysing the
|
| 203 |
+
current stack for possible grammar nodes.
|
| 204 |
+
|
| 205 |
+
Possible enhancements:
|
| 206 |
+
- global/nonlocal search global
|
| 207 |
+
- yield from / raise from <- could be only exceptions/generators
|
| 208 |
+
- In args: */**: no completion
|
| 209 |
+
- In params (also lambda): no completion before =
|
| 210 |
+
"""
|
| 211 |
+
grammar = self._inference_state.grammar
|
| 212 |
+
self.stack = stack = None
|
| 213 |
+
self._position = (
|
| 214 |
+
self._original_position[0],
|
| 215 |
+
self._original_position[1] - len(self._like_name)
|
| 216 |
+
)
|
| 217 |
+
cached_name = None
|
| 218 |
+
|
| 219 |
+
try:
|
| 220 |
+
self.stack = stack = helpers.get_stack_at_position(
|
| 221 |
+
grammar, self._code_lines, leaf, self._position
|
| 222 |
+
)
|
| 223 |
+
except helpers.OnErrorLeaf as e:
|
| 224 |
+
value = e.error_leaf.value
|
| 225 |
+
if value == '.':
|
| 226 |
+
# After ErrorLeaf's that are dots, we will not do any
|
| 227 |
+
# completions since this probably just confuses the user.
|
| 228 |
+
return cached_name, []
|
| 229 |
+
|
| 230 |
+
# If we don't have a value, just use global completion.
|
| 231 |
+
return cached_name, self._complete_global_scope()
|
| 232 |
+
|
| 233 |
+
allowed_transitions = \
|
| 234 |
+
list(stack._allowed_transition_names_and_token_types())
|
| 235 |
+
|
| 236 |
+
if 'if' in allowed_transitions:
|
| 237 |
+
leaf = self._module_node.get_leaf_for_position(self._position, include_prefixes=True)
|
| 238 |
+
previous_leaf = leaf.get_previous_leaf()
|
| 239 |
+
|
| 240 |
+
indent = self._position[1]
|
| 241 |
+
if not (leaf.start_pos <= self._position <= leaf.end_pos):
|
| 242 |
+
indent = leaf.start_pos[1]
|
| 243 |
+
|
| 244 |
+
if previous_leaf is not None:
|
| 245 |
+
stmt = previous_leaf
|
| 246 |
+
while True:
|
| 247 |
+
stmt = search_ancestor(
|
| 248 |
+
stmt, 'if_stmt', 'for_stmt', 'while_stmt', 'try_stmt',
|
| 249 |
+
'error_node',
|
| 250 |
+
)
|
| 251 |
+
if stmt is None:
|
| 252 |
+
break
|
| 253 |
+
|
| 254 |
+
type_ = stmt.type
|
| 255 |
+
if type_ == 'error_node':
|
| 256 |
+
first = stmt.children[0]
|
| 257 |
+
if isinstance(first, Leaf):
|
| 258 |
+
type_ = first.value + '_stmt'
|
| 259 |
+
# Compare indents
|
| 260 |
+
if stmt.start_pos[1] == indent:
|
| 261 |
+
if type_ == 'if_stmt':
|
| 262 |
+
allowed_transitions += ['elif', 'else']
|
| 263 |
+
elif type_ == 'try_stmt':
|
| 264 |
+
allowed_transitions += ['except', 'finally', 'else']
|
| 265 |
+
elif type_ == 'for_stmt':
|
| 266 |
+
allowed_transitions.append('else')
|
| 267 |
+
|
| 268 |
+
completion_names = []
|
| 269 |
+
|
| 270 |
+
kwargs_only = False
|
| 271 |
+
if any(t in allowed_transitions for t in (PythonTokenTypes.NAME,
|
| 272 |
+
PythonTokenTypes.INDENT)):
|
| 273 |
+
# This means that we actually have to do type inference.
|
| 274 |
+
|
| 275 |
+
nonterminals = [stack_node.nonterminal for stack_node in stack]
|
| 276 |
+
|
| 277 |
+
nodes = _gather_nodes(stack)
|
| 278 |
+
if nodes and nodes[-1] in ('as', 'def', 'class'):
|
| 279 |
+
# No completions for ``with x as foo`` and ``import x as foo``.
|
| 280 |
+
# Also true for defining names as a class or function.
|
| 281 |
+
return cached_name, list(self._complete_inherited(is_function=True))
|
| 282 |
+
elif "import_stmt" in nonterminals:
|
| 283 |
+
level, names = parse_dotted_names(nodes, "import_from" in nonterminals)
|
| 284 |
+
|
| 285 |
+
only_modules = not ("import_from" in nonterminals and 'import' in nodes)
|
| 286 |
+
completion_names += self._get_importer_names(
|
| 287 |
+
names,
|
| 288 |
+
level,
|
| 289 |
+
only_modules=only_modules,
|
| 290 |
+
)
|
| 291 |
+
elif nonterminals[-1] in ('trailer', 'dotted_name') and nodes[-1] == '.':
|
| 292 |
+
dot = self._module_node.get_leaf_for_position(self._position)
|
| 293 |
+
if dot.type == "endmarker":
|
| 294 |
+
# This is a bit of a weird edge case, maybe we can somehow
|
| 295 |
+
# generalize this.
|
| 296 |
+
dot = leaf.get_previous_leaf()
|
| 297 |
+
cached_name, n = self._complete_trailer(dot.get_previous_leaf())
|
| 298 |
+
completion_names += n
|
| 299 |
+
elif self._is_parameter_completion():
|
| 300 |
+
completion_names += self._complete_params(leaf)
|
| 301 |
+
else:
|
| 302 |
+
# Apparently this looks like it's good enough to filter most cases
|
| 303 |
+
# so that signature completions don't randomly appear.
|
| 304 |
+
# To understand why this works, three things are important:
|
| 305 |
+
# 1. trailer with a `,` in it is either a subscript or an arglist.
|
| 306 |
+
# 2. If there's no `,`, it's at the start and only signatures start
|
| 307 |
+
# with `(`. Other trailers could start with `.` or `[`.
|
| 308 |
+
# 3. Decorators are very primitive and have an optional `(` with
|
| 309 |
+
# optional arglist in them.
|
| 310 |
+
if nodes[-1] in ['(', ','] \
|
| 311 |
+
and nonterminals[-1] in ('trailer', 'arglist', 'decorator'):
|
| 312 |
+
signatures = self._signatures_callback(*self._position)
|
| 313 |
+
if signatures:
|
| 314 |
+
call_details = signatures[0]._call_details
|
| 315 |
+
used_kwargs = list(call_details.iter_used_keyword_arguments())
|
| 316 |
+
positional_count = call_details.count_positional_arguments()
|
| 317 |
+
|
| 318 |
+
completion_names += _get_signature_param_names(
|
| 319 |
+
signatures,
|
| 320 |
+
positional_count,
|
| 321 |
+
used_kwargs,
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
kwargs_only = _must_be_kwarg(signatures, positional_count, used_kwargs)
|
| 325 |
+
|
| 326 |
+
if not kwargs_only:
|
| 327 |
+
completion_names += self._complete_global_scope()
|
| 328 |
+
completion_names += self._complete_inherited(is_function=False)
|
| 329 |
+
|
| 330 |
+
if not kwargs_only:
|
| 331 |
+
current_line = self._code_lines[self._position[0] - 1][:self._position[1]]
|
| 332 |
+
completion_names += self._complete_keywords(
|
| 333 |
+
allowed_transitions,
|
| 334 |
+
only_values=not (not current_line or current_line[-1] in ' \t.;'
|
| 335 |
+
and current_line[-3:] != '...')
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
return cached_name, completion_names
|
| 339 |
+
|
| 340 |
+
def _is_parameter_completion(self):
|
| 341 |
+
tos = self.stack[-1]
|
| 342 |
+
if tos.nonterminal == 'lambdef' and len(tos.nodes) == 1:
|
| 343 |
+
# We are at the position `lambda `, where basically the next node
|
| 344 |
+
# is a param.
|
| 345 |
+
return True
|
| 346 |
+
if tos.nonterminal in 'parameters':
|
| 347 |
+
# Basically we are at the position `foo(`, there's nothing there
|
| 348 |
+
# yet, so we have no `typedargslist`.
|
| 349 |
+
return True
|
| 350 |
+
# var args is for lambdas and typed args for normal functions
|
| 351 |
+
return tos.nonterminal in ('typedargslist', 'varargslist') and tos.nodes[-1] == ','
|
| 352 |
+
|
| 353 |
+
def _complete_params(self, leaf):
|
| 354 |
+
stack_node = self.stack[-2]
|
| 355 |
+
if stack_node.nonterminal == 'parameters':
|
| 356 |
+
stack_node = self.stack[-3]
|
| 357 |
+
if stack_node.nonterminal == 'funcdef':
|
| 358 |
+
context = get_user_context(self._module_context, self._position)
|
| 359 |
+
node = search_ancestor(leaf, 'error_node', 'funcdef')
|
| 360 |
+
if node is not None:
|
| 361 |
+
if node.type == 'error_node':
|
| 362 |
+
n = node.children[0]
|
| 363 |
+
if n.type == 'decorators':
|
| 364 |
+
decorators = n.children
|
| 365 |
+
elif n.type == 'decorator':
|
| 366 |
+
decorators = [n]
|
| 367 |
+
else:
|
| 368 |
+
decorators = []
|
| 369 |
+
else:
|
| 370 |
+
decorators = node.get_decorators()
|
| 371 |
+
function_name = stack_node.nodes[1]
|
| 372 |
+
|
| 373 |
+
return complete_param_names(context, function_name.value, decorators)
|
| 374 |
+
return []
|
| 375 |
+
|
| 376 |
+
def _complete_keywords(self, allowed_transitions, only_values):
|
| 377 |
+
for k in allowed_transitions:
|
| 378 |
+
if isinstance(k, str) and k.isalpha():
|
| 379 |
+
if not only_values or k in ('True', 'False', 'None'):
|
| 380 |
+
yield keywords.KeywordName(self._inference_state, k)
|
| 381 |
+
|
| 382 |
+
def _complete_global_scope(self):
|
| 383 |
+
context = get_user_context(self._module_context, self._position)
|
| 384 |
+
debug.dbg('global completion scope: %s', context)
|
| 385 |
+
flow_scope_node = get_flow_scope_node(self._module_node, self._position)
|
| 386 |
+
filters = get_global_filters(
|
| 387 |
+
context,
|
| 388 |
+
self._position,
|
| 389 |
+
flow_scope_node
|
| 390 |
+
)
|
| 391 |
+
completion_names = []
|
| 392 |
+
for filter in filters:
|
| 393 |
+
completion_names += filter.values()
|
| 394 |
+
return completion_names
|
| 395 |
+
|
| 396 |
+
def _complete_trailer(self, previous_leaf):
|
| 397 |
+
inferred_context = self._module_context.create_context(previous_leaf)
|
| 398 |
+
values = infer_call_of_leaf(inferred_context, previous_leaf)
|
| 399 |
+
debug.dbg('trailer completion values: %s', values, color='MAGENTA')
|
| 400 |
+
|
| 401 |
+
# The cached name simply exists to make speed optimizations for certain
|
| 402 |
+
# modules.
|
| 403 |
+
cached_name = None
|
| 404 |
+
if len(values) == 1:
|
| 405 |
+
v, = values
|
| 406 |
+
if v.is_module():
|
| 407 |
+
if len(v.string_names) == 1:
|
| 408 |
+
module_name = v.string_names[0]
|
| 409 |
+
if module_name in ('numpy', 'tensorflow', 'matplotlib', 'pandas'):
|
| 410 |
+
cached_name = module_name
|
| 411 |
+
|
| 412 |
+
return cached_name, self._complete_trailer_for_values(values)
|
| 413 |
+
|
| 414 |
+
def _complete_trailer_for_values(self, values):
|
| 415 |
+
user_context = get_user_context(self._module_context, self._position)
|
| 416 |
+
|
| 417 |
+
return complete_trailer(user_context, values)
|
| 418 |
+
|
| 419 |
+
def _get_importer_names(self, names, level=0, only_modules=True):
|
| 420 |
+
names = [n.value for n in names]
|
| 421 |
+
i = imports.Importer(self._inference_state, names, self._module_context, level)
|
| 422 |
+
return i.completion_names(self._inference_state, only_modules=only_modules)
|
| 423 |
+
|
| 424 |
+
def _complete_inherited(self, is_function=True):
|
| 425 |
+
"""
|
| 426 |
+
Autocomplete inherited methods when overriding in child class.
|
| 427 |
+
"""
|
| 428 |
+
leaf = self._module_node.get_leaf_for_position(self._position, include_prefixes=True)
|
| 429 |
+
cls = tree.search_ancestor(leaf, 'classdef')
|
| 430 |
+
if cls is None:
|
| 431 |
+
return
|
| 432 |
+
|
| 433 |
+
# Complete the methods that are defined in the super classes.
|
| 434 |
+
class_value = self._module_context.create_value(cls)
|
| 435 |
+
|
| 436 |
+
if cls.start_pos[1] >= leaf.start_pos[1]:
|
| 437 |
+
return
|
| 438 |
+
|
| 439 |
+
filters = class_value.get_filters(is_instance=True)
|
| 440 |
+
# The first dict is the dictionary of class itself.
|
| 441 |
+
next(filters)
|
| 442 |
+
for filter in filters:
|
| 443 |
+
for name in filter.values():
|
| 444 |
+
# TODO we should probably check here for properties
|
| 445 |
+
if (name.api_type == 'function') == is_function:
|
| 446 |
+
yield name
|
| 447 |
+
|
| 448 |
+
def _complete_in_string(self, start_leaf, string):
|
| 449 |
+
"""
|
| 450 |
+
To make it possible for people to have completions in doctests or
|
| 451 |
+
generally in "Python" code in docstrings, we use the following
|
| 452 |
+
heuristic:
|
| 453 |
+
|
| 454 |
+
- Having an indented block of code
|
| 455 |
+
- Having some doctest code that starts with `>>>`
|
| 456 |
+
- Having backticks that doesn't have whitespace inside it
|
| 457 |
+
"""
|
| 458 |
+
|
| 459 |
+
def iter_relevant_lines(lines):
|
| 460 |
+
include_next_line = False
|
| 461 |
+
for l in code_lines:
|
| 462 |
+
if include_next_line or l.startswith('>>>') or l.startswith(' '):
|
| 463 |
+
yield re.sub(r'^( *>>> ?| +)', '', l)
|
| 464 |
+
else:
|
| 465 |
+
yield None
|
| 466 |
+
|
| 467 |
+
include_next_line = bool(re.match(' *>>>', l))
|
| 468 |
+
|
| 469 |
+
string = dedent(string)
|
| 470 |
+
code_lines = split_lines(string, keepends=True)
|
| 471 |
+
relevant_code_lines = list(iter_relevant_lines(code_lines))
|
| 472 |
+
if relevant_code_lines[-1] is not None:
|
| 473 |
+
# Some code lines might be None, therefore get rid of that.
|
| 474 |
+
relevant_code_lines = ['\n' if c is None else c for c in relevant_code_lines]
|
| 475 |
+
return self._complete_code_lines(relevant_code_lines)
|
| 476 |
+
match = re.search(r'`([^`\s]+)', code_lines[-1])
|
| 477 |
+
if match:
|
| 478 |
+
return self._complete_code_lines([match.group(1)])
|
| 479 |
+
return []
|
| 480 |
+
|
| 481 |
+
def _complete_code_lines(self, code_lines):
|
| 482 |
+
module_node = self._inference_state.grammar.parse(''.join(code_lines))
|
| 483 |
+
module_value = DocstringModule(
|
| 484 |
+
in_module_context=self._module_context,
|
| 485 |
+
inference_state=self._inference_state,
|
| 486 |
+
module_node=module_node,
|
| 487 |
+
code_lines=code_lines,
|
| 488 |
+
)
|
| 489 |
+
return Completion(
|
| 490 |
+
self._inference_state,
|
| 491 |
+
module_value.as_context(),
|
| 492 |
+
code_lines=code_lines,
|
| 493 |
+
position=module_node.end_pos,
|
| 494 |
+
signatures_callback=lambda *args, **kwargs: [],
|
| 495 |
+
fuzzy=self._fuzzy
|
| 496 |
+
).complete()
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
def _gather_nodes(stack):
|
| 500 |
+
nodes = []
|
| 501 |
+
for stack_node in stack:
|
| 502 |
+
if stack_node.dfa.from_rule == 'small_stmt':
|
| 503 |
+
nodes = []
|
| 504 |
+
else:
|
| 505 |
+
nodes += stack_node.nodes
|
| 506 |
+
return nodes
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
_string_start = re.compile(r'^\w*(\'{3}|"{3}|\'|")')
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
def _extract_string_while_in_string(leaf, position):
|
| 513 |
+
def return_part_of_leaf(leaf):
|
| 514 |
+
kwargs = {}
|
| 515 |
+
if leaf.line == position[0]:
|
| 516 |
+
kwargs['endpos'] = position[1] - leaf.column
|
| 517 |
+
match = _string_start.match(leaf.value, **kwargs)
|
| 518 |
+
if not match:
|
| 519 |
+
return None, None, None
|
| 520 |
+
start = match.group(0)
|
| 521 |
+
if leaf.line == position[0] and position[1] < leaf.column + match.end():
|
| 522 |
+
return None, None, None
|
| 523 |
+
return cut_value_at_position(leaf, position)[match.end():], leaf, start
|
| 524 |
+
|
| 525 |
+
if position < leaf.start_pos:
|
| 526 |
+
return None, None, None
|
| 527 |
+
|
| 528 |
+
if leaf.type == 'string':
|
| 529 |
+
return return_part_of_leaf(leaf)
|
| 530 |
+
|
| 531 |
+
leaves = []
|
| 532 |
+
while leaf is not None:
|
| 533 |
+
if leaf.type == 'error_leaf' and ('"' in leaf.value or "'" in leaf.value):
|
| 534 |
+
if len(leaf.value) > 1:
|
| 535 |
+
return return_part_of_leaf(leaf)
|
| 536 |
+
prefix_leaf = None
|
| 537 |
+
if not leaf.prefix:
|
| 538 |
+
prefix_leaf = leaf.get_previous_leaf()
|
| 539 |
+
if prefix_leaf is None or prefix_leaf.type != 'name' \
|
| 540 |
+
or not all(c in 'rubf' for c in prefix_leaf.value.lower()):
|
| 541 |
+
prefix_leaf = None
|
| 542 |
+
|
| 543 |
+
return (
|
| 544 |
+
''.join(cut_value_at_position(l, position) for l in leaves),
|
| 545 |
+
prefix_leaf or leaf,
|
| 546 |
+
('' if prefix_leaf is None else prefix_leaf.value)
|
| 547 |
+
+ cut_value_at_position(leaf, position),
|
| 548 |
+
)
|
| 549 |
+
if leaf.line != position[0]:
|
| 550 |
+
# Multi line strings are always simple error leaves and contain the
|
| 551 |
+
# whole string, single line error leaves are atherefore important
|
| 552 |
+
# now and since the line is different, it's not really a single
|
| 553 |
+
# line string anymore.
|
| 554 |
+
break
|
| 555 |
+
leaves.insert(0, leaf)
|
| 556 |
+
leaf = leaf.get_previous_leaf()
|
| 557 |
+
return None, None, None
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
def complete_trailer(user_context, values):
|
| 561 |
+
completion_names = []
|
| 562 |
+
for value in values:
|
| 563 |
+
for filter in value.get_filters(origin_scope=user_context.tree_node):
|
| 564 |
+
completion_names += filter.values()
|
| 565 |
+
|
| 566 |
+
if not value.is_stub() and isinstance(value, TreeInstance):
|
| 567 |
+
completion_names += _complete_getattr(user_context, value)
|
| 568 |
+
|
| 569 |
+
python_values = convert_values(values)
|
| 570 |
+
for c in python_values:
|
| 571 |
+
if c not in values:
|
| 572 |
+
for filter in c.get_filters(origin_scope=user_context.tree_node):
|
| 573 |
+
completion_names += filter.values()
|
| 574 |
+
return completion_names
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
def _complete_getattr(user_context, instance):
|
| 578 |
+
"""
|
| 579 |
+
A heuristic to make completion for proxy objects work. This is not
|
| 580 |
+
intended to work in all cases. It works exactly in this case:
|
| 581 |
+
|
| 582 |
+
def __getattr__(self, name):
|
| 583 |
+
...
|
| 584 |
+
return getattr(any_object, name)
|
| 585 |
+
|
| 586 |
+
It is important that the return contains getattr directly, otherwise it
|
| 587 |
+
won't work anymore. It's really just a stupid heuristic. It will not
|
| 588 |
+
work if you write e.g. `return (getatr(o, name))`, because of the
|
| 589 |
+
additional parentheses. It will also not work if you move the getattr
|
| 590 |
+
to some other place that is not the return statement itself.
|
| 591 |
+
|
| 592 |
+
It is intentional that it doesn't work in all cases. Generally it's
|
| 593 |
+
really hard to do even this case (as you can see below). Most people
|
| 594 |
+
will write it like this anyway and the other ones, well they are just
|
| 595 |
+
out of luck I guess :) ~dave.
|
| 596 |
+
"""
|
| 597 |
+
names = (instance.get_function_slot_names('__getattr__')
|
| 598 |
+
or instance.get_function_slot_names('__getattribute__'))
|
| 599 |
+
functions = ValueSet.from_sets(
|
| 600 |
+
name.infer()
|
| 601 |
+
for name in names
|
| 602 |
+
)
|
| 603 |
+
for func in functions:
|
| 604 |
+
tree_node = func.tree_node
|
| 605 |
+
if tree_node is None or tree_node.type != 'funcdef':
|
| 606 |
+
continue
|
| 607 |
+
|
| 608 |
+
for return_stmt in tree_node.iter_return_stmts():
|
| 609 |
+
# Basically until the next comment we just try to find out if a
|
| 610 |
+
# return statement looks exactly like `return getattr(x, name)`.
|
| 611 |
+
if return_stmt.type != 'return_stmt':
|
| 612 |
+
continue
|
| 613 |
+
atom_expr = return_stmt.children[1]
|
| 614 |
+
if atom_expr.type != 'atom_expr':
|
| 615 |
+
continue
|
| 616 |
+
atom = atom_expr.children[0]
|
| 617 |
+
trailer = atom_expr.children[1]
|
| 618 |
+
if len(atom_expr.children) != 2 or atom.type != 'name' \
|
| 619 |
+
or atom.value != 'getattr':
|
| 620 |
+
continue
|
| 621 |
+
arglist = trailer.children[1]
|
| 622 |
+
if arglist.type != 'arglist' or len(arglist.children) < 3:
|
| 623 |
+
continue
|
| 624 |
+
context = func.as_context()
|
| 625 |
+
object_node = arglist.children[0]
|
| 626 |
+
|
| 627 |
+
# Make sure it's a param: foo in __getattr__(self, foo)
|
| 628 |
+
name_node = arglist.children[2]
|
| 629 |
+
name_list = context.goto(name_node, name_node.start_pos)
|
| 630 |
+
if not any(n.api_type == 'param' for n in name_list):
|
| 631 |
+
continue
|
| 632 |
+
|
| 633 |
+
# Now that we know that these are most probably completion
|
| 634 |
+
# objects, we just infer the object and return them as
|
| 635 |
+
# completions.
|
| 636 |
+
objects = context.infer_node(object_node)
|
| 637 |
+
return complete_trailer(user_context, objects)
|
| 638 |
+
return []
|
| 639 |
+
|
| 640 |
+
|
| 641 |
+
def search_in_module(inference_state, module_context, names, wanted_names,
|
| 642 |
+
wanted_type, complete=False, fuzzy=False,
|
| 643 |
+
ignore_imports=False, convert=False):
|
| 644 |
+
for s in wanted_names[:-1]:
|
| 645 |
+
new_names = []
|
| 646 |
+
for n in names:
|
| 647 |
+
if s == n.string_name:
|
| 648 |
+
if n.tree_name is not None and n.api_type in ('module', 'namespace') \
|
| 649 |
+
and ignore_imports:
|
| 650 |
+
continue
|
| 651 |
+
new_names += complete_trailer(
|
| 652 |
+
module_context,
|
| 653 |
+
n.infer()
|
| 654 |
+
)
|
| 655 |
+
debug.dbg('dot lookup on search %s from %s', new_names, names[:10])
|
| 656 |
+
names = new_names
|
| 657 |
+
|
| 658 |
+
last_name = wanted_names[-1].lower()
|
| 659 |
+
for n in names:
|
| 660 |
+
string = n.string_name.lower()
|
| 661 |
+
if complete and helpers.match(string, last_name, fuzzy=fuzzy) \
|
| 662 |
+
or not complete and string == last_name:
|
| 663 |
+
if isinstance(n, SubModuleName):
|
| 664 |
+
names = [v.name for v in n.infer()]
|
| 665 |
+
else:
|
| 666 |
+
names = [n]
|
| 667 |
+
if convert:
|
| 668 |
+
names = convert_names(names)
|
| 669 |
+
for n2 in names:
|
| 670 |
+
if complete:
|
| 671 |
+
def_ = classes.Completion(
|
| 672 |
+
inference_state, n2,
|
| 673 |
+
stack=None,
|
| 674 |
+
like_name_length=len(last_name),
|
| 675 |
+
is_fuzzy=fuzzy,
|
| 676 |
+
)
|
| 677 |
+
else:
|
| 678 |
+
def_ = classes.Name(inference_state, n2)
|
| 679 |
+
if not wanted_type or wanted_type == def_.type:
|
| 680 |
+
yield def_
|
| 681 |
+
|
| 682 |
+
|
| 683 |
+
def extract_imported_names(node):
|
| 684 |
+
imported_names = []
|
| 685 |
+
|
| 686 |
+
if node.type in ['import_as_names', 'dotted_as_names', 'import_as_name']:
|
| 687 |
+
for index, child in enumerate(node.children):
|
| 688 |
+
if child.type == 'name':
|
| 689 |
+
if (index > 0 and node.children[index - 1].type == "keyword"
|
| 690 |
+
and node.children[index - 1].value == "as"):
|
| 691 |
+
continue
|
| 692 |
+
imported_names.append(child.value)
|
| 693 |
+
elif child.type == 'import_as_name':
|
| 694 |
+
imported_names.extend(extract_imported_names(child))
|
| 695 |
+
|
| 696 |
+
return imported_names
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/completion_cache.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, Tuple, Callable
|
| 2 |
+
|
| 3 |
+
CacheValues = Tuple[str, str, str]
|
| 4 |
+
CacheValuesCallback = Callable[[], CacheValues]
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
_cache: Dict[str, Dict[str, CacheValues]] = {}
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def save_entry(module_name: str, name: str, cache: CacheValues) -> None:
|
| 11 |
+
try:
|
| 12 |
+
module_cache = _cache[module_name]
|
| 13 |
+
except KeyError:
|
| 14 |
+
module_cache = _cache[module_name] = {}
|
| 15 |
+
module_cache[name] = cache
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _create_get_from_cache(number: int) -> Callable[[str, str, CacheValuesCallback], str]:
|
| 19 |
+
def _get_from_cache(module_name: str, name: str, get_cache_values: CacheValuesCallback) -> str:
|
| 20 |
+
try:
|
| 21 |
+
return _cache[module_name][name][number]
|
| 22 |
+
except KeyError:
|
| 23 |
+
v = get_cache_values()
|
| 24 |
+
save_entry(module_name, name, v)
|
| 25 |
+
return v[number]
|
| 26 |
+
return _get_from_cache
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
get_type = _create_get_from_cache(0)
|
| 30 |
+
get_docstring_signature = _create_get_from_cache(1)
|
| 31 |
+
get_docstring = _create_get_from_cache(2)
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/environment.py
ADDED
|
@@ -0,0 +1,480 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Environments are a way to activate different Python versions or Virtualenvs for
|
| 3 |
+
static analysis. The Python binary in that environment is going to be executed.
|
| 4 |
+
"""
|
| 5 |
+
import os
|
| 6 |
+
import sys
|
| 7 |
+
import hashlib
|
| 8 |
+
import filecmp
|
| 9 |
+
from collections import namedtuple
|
| 10 |
+
from shutil import which
|
| 11 |
+
from typing import TYPE_CHECKING
|
| 12 |
+
|
| 13 |
+
from jedi.cache import memoize_method, time_cache
|
| 14 |
+
from jedi.inference.compiled.subprocess import CompiledSubprocess, \
|
| 15 |
+
InferenceStateSameProcess, InferenceStateSubprocess
|
| 16 |
+
|
| 17 |
+
import parso
|
| 18 |
+
|
| 19 |
+
if TYPE_CHECKING:
|
| 20 |
+
from jedi.inference import InferenceState
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
_VersionInfo = namedtuple('VersionInfo', 'major minor micro') # type: ignore[name-match]
|
| 24 |
+
|
| 25 |
+
_SUPPORTED_PYTHONS = ['3.13', '3.12', '3.11', '3.10', '3.9', '3.8', '3.7', '3.6']
|
| 26 |
+
_SAFE_PATHS = ['/usr/bin', '/usr/local/bin']
|
| 27 |
+
_CONDA_VAR = 'CONDA_PREFIX'
|
| 28 |
+
_CURRENT_VERSION = '%s.%s' % (sys.version_info.major, sys.version_info.minor)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class InvalidPythonEnvironment(Exception):
|
| 32 |
+
"""
|
| 33 |
+
If you see this exception, the Python executable or Virtualenv you have
|
| 34 |
+
been trying to use is probably not a correct Python version.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class _BaseEnvironment:
|
| 39 |
+
@memoize_method
|
| 40 |
+
def get_grammar(self):
|
| 41 |
+
version_string = '%s.%s' % (self.version_info.major, self.version_info.minor)
|
| 42 |
+
return parso.load_grammar(version=version_string)
|
| 43 |
+
|
| 44 |
+
@property
|
| 45 |
+
def _sha256(self):
|
| 46 |
+
try:
|
| 47 |
+
return self._hash
|
| 48 |
+
except AttributeError:
|
| 49 |
+
self._hash = _calculate_sha256_for_file(self.executable)
|
| 50 |
+
return self._hash
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _get_info():
|
| 54 |
+
return (
|
| 55 |
+
sys.executable,
|
| 56 |
+
sys.prefix,
|
| 57 |
+
sys.version_info[:3],
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class Environment(_BaseEnvironment):
|
| 62 |
+
"""
|
| 63 |
+
This class is supposed to be created by internal Jedi architecture. You
|
| 64 |
+
should not create it directly. Please use create_environment or the other
|
| 65 |
+
functions instead. It is then returned by that function.
|
| 66 |
+
"""
|
| 67 |
+
_subprocess = None
|
| 68 |
+
|
| 69 |
+
def __init__(self, executable, env_vars=None):
|
| 70 |
+
self._start_executable = executable
|
| 71 |
+
self._env_vars = env_vars
|
| 72 |
+
# Initialize the environment
|
| 73 |
+
self._get_subprocess()
|
| 74 |
+
|
| 75 |
+
def _get_subprocess(self):
|
| 76 |
+
if self._subprocess is not None and not self._subprocess.is_crashed:
|
| 77 |
+
return self._subprocess
|
| 78 |
+
|
| 79 |
+
try:
|
| 80 |
+
self._subprocess = CompiledSubprocess(self._start_executable,
|
| 81 |
+
env_vars=self._env_vars)
|
| 82 |
+
info = self._subprocess._send(None, _get_info)
|
| 83 |
+
except Exception as exc:
|
| 84 |
+
raise InvalidPythonEnvironment(
|
| 85 |
+
"Could not get version information for %r: %r" % (
|
| 86 |
+
self._start_executable,
|
| 87 |
+
exc))
|
| 88 |
+
|
| 89 |
+
# Since it could change and might not be the same(?) as the one given,
|
| 90 |
+
# set it here.
|
| 91 |
+
self.executable = info[0]
|
| 92 |
+
"""
|
| 93 |
+
The Python executable, matches ``sys.executable``.
|
| 94 |
+
"""
|
| 95 |
+
self.path = info[1]
|
| 96 |
+
"""
|
| 97 |
+
The path to an environment, matches ``sys.prefix``.
|
| 98 |
+
"""
|
| 99 |
+
self.version_info = _VersionInfo(*info[2])
|
| 100 |
+
"""
|
| 101 |
+
Like :data:`sys.version_info`: a tuple to show the current
|
| 102 |
+
Environment's Python version.
|
| 103 |
+
"""
|
| 104 |
+
return self._subprocess
|
| 105 |
+
|
| 106 |
+
def __repr__(self):
|
| 107 |
+
version = '.'.join(str(i) for i in self.version_info)
|
| 108 |
+
return '<%s: %s in %s>' % (self.__class__.__name__, version, self.path)
|
| 109 |
+
|
| 110 |
+
def get_inference_state_subprocess(
|
| 111 |
+
self,
|
| 112 |
+
inference_state: 'InferenceState',
|
| 113 |
+
) -> InferenceStateSubprocess:
|
| 114 |
+
return InferenceStateSubprocess(inference_state, self._get_subprocess())
|
| 115 |
+
|
| 116 |
+
@memoize_method
|
| 117 |
+
def get_sys_path(self):
|
| 118 |
+
"""
|
| 119 |
+
The sys path for this environment. Does not include potential
|
| 120 |
+
modifications from e.g. appending to :data:`sys.path`.
|
| 121 |
+
|
| 122 |
+
:returns: list of str
|
| 123 |
+
"""
|
| 124 |
+
# It's pretty much impossible to generate the sys path without actually
|
| 125 |
+
# executing Python. The sys path (when starting with -S) itself depends
|
| 126 |
+
# on how the Python version was compiled (ENV variables).
|
| 127 |
+
# If you omit -S when starting Python (normal case), additionally
|
| 128 |
+
# site.py gets executed.
|
| 129 |
+
return self._get_subprocess().get_sys_path()
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class _SameEnvironmentMixin:
|
| 133 |
+
def __init__(self):
|
| 134 |
+
self._start_executable = self.executable = sys.executable
|
| 135 |
+
self.path = sys.prefix
|
| 136 |
+
self.version_info = _VersionInfo(*sys.version_info[:3])
|
| 137 |
+
self._env_vars = None
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class SameEnvironment(_SameEnvironmentMixin, Environment):
|
| 141 |
+
pass
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
class InterpreterEnvironment(_SameEnvironmentMixin, _BaseEnvironment):
|
| 145 |
+
def get_inference_state_subprocess(
|
| 146 |
+
self,
|
| 147 |
+
inference_state: 'InferenceState',
|
| 148 |
+
) -> InferenceStateSameProcess:
|
| 149 |
+
return InferenceStateSameProcess(inference_state)
|
| 150 |
+
|
| 151 |
+
def get_sys_path(self):
|
| 152 |
+
return sys.path
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def _get_virtual_env_from_var(env_var='VIRTUAL_ENV'):
|
| 156 |
+
"""Get virtualenv environment from VIRTUAL_ENV environment variable.
|
| 157 |
+
|
| 158 |
+
It uses `safe=False` with ``create_environment``, because the environment
|
| 159 |
+
variable is considered to be safe / controlled by the user solely.
|
| 160 |
+
"""
|
| 161 |
+
var = os.environ.get(env_var)
|
| 162 |
+
if var:
|
| 163 |
+
# Under macOS in some cases - notably when using Pipenv - the
|
| 164 |
+
# sys.prefix of the virtualenv is /path/to/env/bin/.. instead of
|
| 165 |
+
# /path/to/env so we need to fully resolve the paths in order to
|
| 166 |
+
# compare them.
|
| 167 |
+
if os.path.realpath(var) == os.path.realpath(sys.prefix):
|
| 168 |
+
return _try_get_same_env()
|
| 169 |
+
|
| 170 |
+
try:
|
| 171 |
+
return create_environment(var, safe=False)
|
| 172 |
+
except InvalidPythonEnvironment:
|
| 173 |
+
pass
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def _calculate_sha256_for_file(path):
|
| 177 |
+
sha256 = hashlib.sha256()
|
| 178 |
+
with open(path, 'rb') as f:
|
| 179 |
+
for block in iter(lambda: f.read(filecmp.BUFSIZE), b''):
|
| 180 |
+
sha256.update(block)
|
| 181 |
+
return sha256.hexdigest()
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def get_default_environment():
|
| 185 |
+
"""
|
| 186 |
+
Tries to return an active Virtualenv or conda environment.
|
| 187 |
+
If there is no VIRTUAL_ENV variable or no CONDA_PREFIX variable set
|
| 188 |
+
set it will return the latest Python version installed on the system. This
|
| 189 |
+
makes it possible to use as many new Python features as possible when using
|
| 190 |
+
autocompletion and other functionality.
|
| 191 |
+
|
| 192 |
+
:returns: :class:`.Environment`
|
| 193 |
+
"""
|
| 194 |
+
virtual_env = _get_virtual_env_from_var()
|
| 195 |
+
if virtual_env is not None:
|
| 196 |
+
return virtual_env
|
| 197 |
+
|
| 198 |
+
conda_env = _get_virtual_env_from_var(_CONDA_VAR)
|
| 199 |
+
if conda_env is not None:
|
| 200 |
+
return conda_env
|
| 201 |
+
|
| 202 |
+
return _try_get_same_env()
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def _try_get_same_env():
|
| 206 |
+
env = SameEnvironment()
|
| 207 |
+
if not os.path.basename(env.executable).lower().startswith('python'):
|
| 208 |
+
# This tries to counter issues with embedding. In some cases (e.g.
|
| 209 |
+
# VIM's Python Mac/Windows, sys.executable is /foo/bar/vim. This
|
| 210 |
+
# happens, because for Mac a function called `_NSGetExecutablePath` is
|
| 211 |
+
# used and for Windows `GetModuleFileNameW`. These are both platform
|
| 212 |
+
# specific functions. For all other systems sys.executable should be
|
| 213 |
+
# alright. However here we try to generalize:
|
| 214 |
+
#
|
| 215 |
+
# 1. Check if the executable looks like python (heuristic)
|
| 216 |
+
# 2. In case it's not try to find the executable
|
| 217 |
+
# 3. In case we don't find it use an interpreter environment.
|
| 218 |
+
#
|
| 219 |
+
# The last option will always work, but leads to potential crashes of
|
| 220 |
+
# Jedi - which is ok, because it happens very rarely and even less,
|
| 221 |
+
# because the code below should work for most cases.
|
| 222 |
+
if os.name == 'nt':
|
| 223 |
+
# The first case would be a virtualenv and the second a normal
|
| 224 |
+
# Python installation.
|
| 225 |
+
checks = (r'Scripts\python.exe', 'python.exe')
|
| 226 |
+
else:
|
| 227 |
+
# For unix it looks like Python is always in a bin folder.
|
| 228 |
+
checks = (
|
| 229 |
+
'bin/python%s.%s' % (sys.version_info[0], sys.version[1]),
|
| 230 |
+
'bin/python%s' % (sys.version_info[0]),
|
| 231 |
+
'bin/python',
|
| 232 |
+
)
|
| 233 |
+
for check in checks:
|
| 234 |
+
guess = os.path.join(sys.exec_prefix, check)
|
| 235 |
+
if os.path.isfile(guess):
|
| 236 |
+
# Bingo - We think we have our Python.
|
| 237 |
+
return Environment(guess)
|
| 238 |
+
# It looks like there is no reasonable Python to be found.
|
| 239 |
+
return InterpreterEnvironment()
|
| 240 |
+
# If no virtualenv is found, use the environment we're already
|
| 241 |
+
# using.
|
| 242 |
+
return env
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def get_cached_default_environment():
|
| 246 |
+
var = os.environ.get('VIRTUAL_ENV') or os.environ.get(_CONDA_VAR)
|
| 247 |
+
environment = _get_cached_default_environment()
|
| 248 |
+
|
| 249 |
+
# Under macOS in some cases - notably when using Pipenv - the
|
| 250 |
+
# sys.prefix of the virtualenv is /path/to/env/bin/.. instead of
|
| 251 |
+
# /path/to/env so we need to fully resolve the paths in order to
|
| 252 |
+
# compare them.
|
| 253 |
+
if var and os.path.realpath(var) != os.path.realpath(environment.path):
|
| 254 |
+
_get_cached_default_environment.clear_cache()
|
| 255 |
+
return _get_cached_default_environment()
|
| 256 |
+
return environment
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
@time_cache(seconds=10 * 60) # 10 Minutes
|
| 260 |
+
def _get_cached_default_environment():
|
| 261 |
+
try:
|
| 262 |
+
return get_default_environment()
|
| 263 |
+
except InvalidPythonEnvironment:
|
| 264 |
+
# It's possible that `sys.executable` is wrong. Typically happens
|
| 265 |
+
# when Jedi is used in an executable that embeds Python. For further
|
| 266 |
+
# information, have a look at:
|
| 267 |
+
# https://github.com/davidhalter/jedi/issues/1531
|
| 268 |
+
return InterpreterEnvironment()
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def find_virtualenvs(paths=None, *, safe=True, use_environment_vars=True):
|
| 272 |
+
"""
|
| 273 |
+
:param paths: A list of paths in your file system to be scanned for
|
| 274 |
+
Virtualenvs. It will search in these paths and potentially execute the
|
| 275 |
+
Python binaries.
|
| 276 |
+
:param safe: Default True. In case this is False, it will allow this
|
| 277 |
+
function to execute potential `python` environments. An attacker might
|
| 278 |
+
be able to drop an executable in a path this function is searching by
|
| 279 |
+
default. If the executable has not been installed by root, it will not
|
| 280 |
+
be executed.
|
| 281 |
+
:param use_environment_vars: Default True. If True, the VIRTUAL_ENV
|
| 282 |
+
variable will be checked if it contains a valid VirtualEnv.
|
| 283 |
+
CONDA_PREFIX will be checked to see if it contains a valid conda
|
| 284 |
+
environment.
|
| 285 |
+
|
| 286 |
+
:yields: :class:`.Environment`
|
| 287 |
+
"""
|
| 288 |
+
if paths is None:
|
| 289 |
+
paths = []
|
| 290 |
+
|
| 291 |
+
_used_paths = set()
|
| 292 |
+
|
| 293 |
+
if use_environment_vars:
|
| 294 |
+
# Using this variable should be safe, because attackers might be
|
| 295 |
+
# able to drop files (via git) but not environment variables.
|
| 296 |
+
virtual_env = _get_virtual_env_from_var()
|
| 297 |
+
if virtual_env is not None:
|
| 298 |
+
yield virtual_env
|
| 299 |
+
_used_paths.add(virtual_env.path)
|
| 300 |
+
|
| 301 |
+
conda_env = _get_virtual_env_from_var(_CONDA_VAR)
|
| 302 |
+
if conda_env is not None:
|
| 303 |
+
yield conda_env
|
| 304 |
+
_used_paths.add(conda_env.path)
|
| 305 |
+
|
| 306 |
+
for directory in paths:
|
| 307 |
+
if not os.path.isdir(directory):
|
| 308 |
+
continue
|
| 309 |
+
|
| 310 |
+
directory = os.path.abspath(directory)
|
| 311 |
+
for path in os.listdir(directory):
|
| 312 |
+
path = os.path.join(directory, path)
|
| 313 |
+
if path in _used_paths:
|
| 314 |
+
# A path shouldn't be inferred twice.
|
| 315 |
+
continue
|
| 316 |
+
_used_paths.add(path)
|
| 317 |
+
|
| 318 |
+
try:
|
| 319 |
+
executable = _get_executable_path(path, safe=safe)
|
| 320 |
+
yield Environment(executable)
|
| 321 |
+
except InvalidPythonEnvironment:
|
| 322 |
+
pass
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def find_system_environments(*, env_vars=None):
|
| 326 |
+
"""
|
| 327 |
+
Ignores virtualenvs and returns the Python versions that were installed on
|
| 328 |
+
your system. This might return nothing, if you're running Python e.g. from
|
| 329 |
+
a portable version.
|
| 330 |
+
|
| 331 |
+
The environments are sorted from latest to oldest Python version.
|
| 332 |
+
|
| 333 |
+
:yields: :class:`.Environment`
|
| 334 |
+
"""
|
| 335 |
+
for version_string in _SUPPORTED_PYTHONS:
|
| 336 |
+
try:
|
| 337 |
+
yield get_system_environment(version_string, env_vars=env_vars)
|
| 338 |
+
except InvalidPythonEnvironment:
|
| 339 |
+
pass
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
# TODO: this function should probably return a list of environments since
|
| 343 |
+
# multiple Python installations can be found on a system for the same version.
|
| 344 |
+
def get_system_environment(version, *, env_vars=None):
|
| 345 |
+
"""
|
| 346 |
+
Return the first Python environment found for a string of the form 'X.Y'
|
| 347 |
+
where X and Y are the major and minor versions of Python.
|
| 348 |
+
|
| 349 |
+
:raises: :exc:`.InvalidPythonEnvironment`
|
| 350 |
+
:returns: :class:`.Environment`
|
| 351 |
+
"""
|
| 352 |
+
exe = which('python' + version)
|
| 353 |
+
if exe:
|
| 354 |
+
if exe == sys.executable:
|
| 355 |
+
return SameEnvironment()
|
| 356 |
+
return Environment(exe)
|
| 357 |
+
|
| 358 |
+
if os.name == 'nt':
|
| 359 |
+
for exe in _get_executables_from_windows_registry(version):
|
| 360 |
+
try:
|
| 361 |
+
return Environment(exe, env_vars=env_vars)
|
| 362 |
+
except InvalidPythonEnvironment:
|
| 363 |
+
pass
|
| 364 |
+
raise InvalidPythonEnvironment("Cannot find executable python%s." % version)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def create_environment(path, *, safe=True, env_vars=None):
|
| 368 |
+
"""
|
| 369 |
+
Make it possible to manually create an Environment object by specifying a
|
| 370 |
+
Virtualenv path or an executable path and optional environment variables.
|
| 371 |
+
|
| 372 |
+
:raises: :exc:`.InvalidPythonEnvironment`
|
| 373 |
+
:returns: :class:`.Environment`
|
| 374 |
+
"""
|
| 375 |
+
if os.path.isfile(path):
|
| 376 |
+
_assert_safe(path, safe)
|
| 377 |
+
return Environment(path, env_vars=env_vars)
|
| 378 |
+
return Environment(_get_executable_path(path, safe=safe), env_vars=env_vars)
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
def _get_executable_path(path, safe=True):
|
| 382 |
+
"""
|
| 383 |
+
Returns None if it's not actually a virtual env.
|
| 384 |
+
"""
|
| 385 |
+
|
| 386 |
+
if os.name == 'nt':
|
| 387 |
+
pythons = [os.path.join(path, 'Scripts', 'python.exe'), os.path.join(path, 'python.exe')]
|
| 388 |
+
else:
|
| 389 |
+
pythons = [os.path.join(path, 'bin', 'python')]
|
| 390 |
+
for python in pythons:
|
| 391 |
+
if os.path.exists(python):
|
| 392 |
+
break
|
| 393 |
+
else:
|
| 394 |
+
raise InvalidPythonEnvironment("%s seems to be missing." % python)
|
| 395 |
+
|
| 396 |
+
_assert_safe(python, safe)
|
| 397 |
+
return python
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
def _get_executables_from_windows_registry(version):
|
| 401 |
+
import winreg
|
| 402 |
+
|
| 403 |
+
# TODO: support Python Anaconda.
|
| 404 |
+
sub_keys = [
|
| 405 |
+
r'SOFTWARE\Python\PythonCore\{version}\InstallPath',
|
| 406 |
+
r'SOFTWARE\Wow6432Node\Python\PythonCore\{version}\InstallPath',
|
| 407 |
+
r'SOFTWARE\Python\PythonCore\{version}-32\InstallPath',
|
| 408 |
+
r'SOFTWARE\Wow6432Node\Python\PythonCore\{version}-32\InstallPath'
|
| 409 |
+
]
|
| 410 |
+
for root_key in [winreg.HKEY_CURRENT_USER, winreg.HKEY_LOCAL_MACHINE]:
|
| 411 |
+
for sub_key in sub_keys:
|
| 412 |
+
sub_key = sub_key.format(version=version)
|
| 413 |
+
try:
|
| 414 |
+
with winreg.OpenKey(root_key, sub_key) as key:
|
| 415 |
+
prefix = winreg.QueryValueEx(key, '')[0]
|
| 416 |
+
exe = os.path.join(prefix, 'python.exe')
|
| 417 |
+
if os.path.isfile(exe):
|
| 418 |
+
yield exe
|
| 419 |
+
except WindowsError:
|
| 420 |
+
pass
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
def _assert_safe(executable_path, safe):
|
| 424 |
+
if safe and not _is_safe(executable_path):
|
| 425 |
+
raise InvalidPythonEnvironment(
|
| 426 |
+
"The python binary is potentially unsafe.")
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
def _is_safe(executable_path):
|
| 430 |
+
# Resolve sym links. A venv typically is a symlink to a known Python
|
| 431 |
+
# binary. Only virtualenvs copy symlinks around.
|
| 432 |
+
real_path = os.path.realpath(executable_path)
|
| 433 |
+
|
| 434 |
+
if _is_unix_safe_simple(real_path):
|
| 435 |
+
return True
|
| 436 |
+
|
| 437 |
+
# Just check the list of known Python versions. If it's not in there,
|
| 438 |
+
# it's likely an attacker or some Python that was not properly
|
| 439 |
+
# installed in the system.
|
| 440 |
+
for environment in find_system_environments():
|
| 441 |
+
if environment.executable == real_path:
|
| 442 |
+
return True
|
| 443 |
+
|
| 444 |
+
# If the versions don't match, just compare the binary files. If we
|
| 445 |
+
# don't do that, only venvs will be working and not virtualenvs.
|
| 446 |
+
# venvs are symlinks while virtualenvs are actual copies of the
|
| 447 |
+
# Python files.
|
| 448 |
+
# This still means that if the system Python is updated and the
|
| 449 |
+
# virtualenv's Python is not (which is probably never going to get
|
| 450 |
+
# upgraded), it will not work with Jedi. IMO that's fine, because
|
| 451 |
+
# people should just be using venv. ~ dave
|
| 452 |
+
if environment._sha256 == _calculate_sha256_for_file(real_path):
|
| 453 |
+
return True
|
| 454 |
+
return False
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
def _is_unix_safe_simple(real_path):
|
| 458 |
+
if _is_unix_admin():
|
| 459 |
+
# In case we are root, just be conservative and
|
| 460 |
+
# only execute known paths.
|
| 461 |
+
return any(real_path.startswith(p) for p in _SAFE_PATHS)
|
| 462 |
+
|
| 463 |
+
uid = os.stat(real_path).st_uid
|
| 464 |
+
# The interpreter needs to be owned by root. This means that it wasn't
|
| 465 |
+
# written by a user and therefore attacking Jedi is not as simple.
|
| 466 |
+
# The attack could look like the following:
|
| 467 |
+
# 1. A user clones a repository.
|
| 468 |
+
# 2. The repository has an innocent looking folder called foobar. jedi
|
| 469 |
+
# searches for the folder and executes foobar/bin/python --version if
|
| 470 |
+
# there's also a foobar/bin/activate.
|
| 471 |
+
# 3. The attacker has gained code execution, since he controls
|
| 472 |
+
# foobar/bin/python.
|
| 473 |
+
return uid == 0
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
def _is_unix_admin():
|
| 477 |
+
try:
|
| 478 |
+
return os.getuid() == 0
|
| 479 |
+
except AttributeError:
|
| 480 |
+
return False # Windows
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/errors.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This file is about errors in Python files and not about exception handling in
|
| 3 |
+
Jedi.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def parso_to_jedi_errors(grammar, module_node):
|
| 8 |
+
return [SyntaxError(e) for e in grammar.iter_errors(module_node)]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class SyntaxError:
|
| 12 |
+
"""
|
| 13 |
+
Syntax errors are generated by :meth:`.Script.get_syntax_errors`.
|
| 14 |
+
"""
|
| 15 |
+
def __init__(self, parso_error):
|
| 16 |
+
self._parso_error = parso_error
|
| 17 |
+
|
| 18 |
+
@property
|
| 19 |
+
def line(self):
|
| 20 |
+
"""The line where the error starts (starting with 1)."""
|
| 21 |
+
return self._parso_error.start_pos[0]
|
| 22 |
+
|
| 23 |
+
@property
|
| 24 |
+
def column(self):
|
| 25 |
+
"""The column where the error starts (starting with 0)."""
|
| 26 |
+
return self._parso_error.start_pos[1]
|
| 27 |
+
|
| 28 |
+
@property
|
| 29 |
+
def until_line(self):
|
| 30 |
+
"""The line where the error ends (starting with 1)."""
|
| 31 |
+
return self._parso_error.end_pos[0]
|
| 32 |
+
|
| 33 |
+
@property
|
| 34 |
+
def until_column(self):
|
| 35 |
+
"""The column where the error ends (starting with 0)."""
|
| 36 |
+
return self._parso_error.end_pos[1]
|
| 37 |
+
|
| 38 |
+
def get_message(self):
|
| 39 |
+
return self._parso_error.message
|
| 40 |
+
|
| 41 |
+
def __repr__(self):
|
| 42 |
+
return '<%s from=%s to=%s>' % (
|
| 43 |
+
self.__class__.__name__,
|
| 44 |
+
self._parso_error.start_pos,
|
| 45 |
+
self._parso_error.end_pos,
|
| 46 |
+
)
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/exceptions.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class _JediError(Exception):
|
| 2 |
+
pass
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class InternalError(_JediError):
|
| 6 |
+
"""
|
| 7 |
+
This error might happen a subprocess is crashing. The reason for this is
|
| 8 |
+
usually broken C code in third party libraries. This is not a very common
|
| 9 |
+
thing and it is safe to use Jedi again. However using the same calls might
|
| 10 |
+
result in the same error again.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class WrongVersion(_JediError):
|
| 15 |
+
"""
|
| 16 |
+
This error is reserved for the future, shouldn't really be happening at the
|
| 17 |
+
moment.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class RefactoringError(_JediError):
|
| 22 |
+
"""
|
| 23 |
+
Refactorings can fail for various reasons. So if you work with refactorings
|
| 24 |
+
like :meth:`.Script.rename`, :meth:`.Script.inline`,
|
| 25 |
+
:meth:`.Script.extract_variable` and :meth:`.Script.extract_function`, make
|
| 26 |
+
sure to catch these. The descriptions in the errors are usually valuable
|
| 27 |
+
for end users.
|
| 28 |
+
|
| 29 |
+
A typical ``RefactoringError`` would tell the user that inlining is not
|
| 30 |
+
possible if no name is under the cursor.
|
| 31 |
+
"""
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/file_name.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
from jedi.api import classes
|
| 4 |
+
from jedi.api.strings import StringName, get_quote_ending
|
| 5 |
+
from jedi.api.helpers import match
|
| 6 |
+
from jedi.inference.helpers import get_str_or_none
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class PathName(StringName):
|
| 10 |
+
api_type = 'path'
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def complete_file_name(inference_state, module_context, start_leaf, quote, string,
|
| 14 |
+
like_name, signatures_callback, code_lines, position, fuzzy):
|
| 15 |
+
# First we want to find out what can actually be changed as a name.
|
| 16 |
+
like_name_length = len(os.path.basename(string))
|
| 17 |
+
|
| 18 |
+
addition = _get_string_additions(module_context, start_leaf)
|
| 19 |
+
if string.startswith('~'):
|
| 20 |
+
string = os.path.expanduser(string)
|
| 21 |
+
if addition is None:
|
| 22 |
+
return
|
| 23 |
+
string = addition + string
|
| 24 |
+
|
| 25 |
+
# Here we use basename again, because if strings are added like
|
| 26 |
+
# `'foo' + 'bar`, it should complete to `foobar/`.
|
| 27 |
+
must_start_with = os.path.basename(string)
|
| 28 |
+
string = os.path.dirname(string)
|
| 29 |
+
|
| 30 |
+
sigs = signatures_callback(*position)
|
| 31 |
+
is_in_os_path_join = sigs and all(s.full_name == 'os.path.join' for s in sigs)
|
| 32 |
+
if is_in_os_path_join:
|
| 33 |
+
to_be_added = _add_os_path_join(module_context, start_leaf, sigs[0].bracket_start)
|
| 34 |
+
if to_be_added is None:
|
| 35 |
+
is_in_os_path_join = False
|
| 36 |
+
else:
|
| 37 |
+
string = to_be_added + string
|
| 38 |
+
base_path = os.path.join(inference_state.project.path, string)
|
| 39 |
+
try:
|
| 40 |
+
listed = sorted(os.scandir(base_path), key=lambda e: e.name)
|
| 41 |
+
# OSError: [Errno 36] File name too long: '...'
|
| 42 |
+
except (FileNotFoundError, OSError):
|
| 43 |
+
return
|
| 44 |
+
quote_ending = get_quote_ending(quote, code_lines, position)
|
| 45 |
+
for entry in listed:
|
| 46 |
+
name = entry.name
|
| 47 |
+
if match(name, must_start_with, fuzzy=fuzzy):
|
| 48 |
+
if is_in_os_path_join or not entry.is_dir():
|
| 49 |
+
name += quote_ending
|
| 50 |
+
else:
|
| 51 |
+
name += os.path.sep
|
| 52 |
+
|
| 53 |
+
yield classes.Completion(
|
| 54 |
+
inference_state,
|
| 55 |
+
PathName(inference_state, name[len(must_start_with) - like_name_length:]),
|
| 56 |
+
stack=None,
|
| 57 |
+
like_name_length=like_name_length,
|
| 58 |
+
is_fuzzy=fuzzy,
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def _get_string_additions(module_context, start_leaf):
|
| 63 |
+
def iterate_nodes():
|
| 64 |
+
node = addition.parent
|
| 65 |
+
was_addition = True
|
| 66 |
+
for child_node in reversed(node.children[:node.children.index(addition)]):
|
| 67 |
+
if was_addition:
|
| 68 |
+
was_addition = False
|
| 69 |
+
yield child_node
|
| 70 |
+
continue
|
| 71 |
+
|
| 72 |
+
if child_node != '+':
|
| 73 |
+
break
|
| 74 |
+
was_addition = True
|
| 75 |
+
|
| 76 |
+
addition = start_leaf.get_previous_leaf()
|
| 77 |
+
if addition != '+':
|
| 78 |
+
return ''
|
| 79 |
+
context = module_context.create_context(start_leaf)
|
| 80 |
+
return _add_strings(context, reversed(list(iterate_nodes())))
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _add_strings(context, nodes, add_slash=False):
|
| 84 |
+
string = ''
|
| 85 |
+
first = True
|
| 86 |
+
for child_node in nodes:
|
| 87 |
+
values = context.infer_node(child_node)
|
| 88 |
+
if len(values) != 1:
|
| 89 |
+
return None
|
| 90 |
+
c, = values
|
| 91 |
+
s = get_str_or_none(c)
|
| 92 |
+
if s is None:
|
| 93 |
+
return None
|
| 94 |
+
if not first and add_slash:
|
| 95 |
+
string += os.path.sep
|
| 96 |
+
string += s
|
| 97 |
+
first = False
|
| 98 |
+
return string
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _add_os_path_join(module_context, start_leaf, bracket_start):
|
| 102 |
+
def check(maybe_bracket, nodes):
|
| 103 |
+
if maybe_bracket.start_pos != bracket_start:
|
| 104 |
+
return None
|
| 105 |
+
|
| 106 |
+
if not nodes:
|
| 107 |
+
return ''
|
| 108 |
+
context = module_context.create_context(nodes[0])
|
| 109 |
+
return _add_strings(context, nodes, add_slash=True) or ''
|
| 110 |
+
|
| 111 |
+
if start_leaf.type == 'error_leaf':
|
| 112 |
+
# Unfinished string literal, like `join('`
|
| 113 |
+
value_node = start_leaf.parent
|
| 114 |
+
index = value_node.children.index(start_leaf)
|
| 115 |
+
if index > 0:
|
| 116 |
+
error_node = value_node.children[index - 1]
|
| 117 |
+
if error_node.type == 'error_node' and len(error_node.children) >= 2:
|
| 118 |
+
index = -2
|
| 119 |
+
if error_node.children[-1].type == 'arglist':
|
| 120 |
+
arglist_nodes = error_node.children[-1].children
|
| 121 |
+
index -= 1
|
| 122 |
+
else:
|
| 123 |
+
arglist_nodes = []
|
| 124 |
+
|
| 125 |
+
return check(error_node.children[index + 1], arglist_nodes[::2])
|
| 126 |
+
return None
|
| 127 |
+
|
| 128 |
+
# Maybe an arglist or some weird error case. Therefore checked below.
|
| 129 |
+
searched_node_child = start_leaf
|
| 130 |
+
while searched_node_child.parent is not None \
|
| 131 |
+
and searched_node_child.parent.type not in ('arglist', 'trailer', 'error_node'):
|
| 132 |
+
searched_node_child = searched_node_child.parent
|
| 133 |
+
|
| 134 |
+
if searched_node_child.get_first_leaf() is not start_leaf:
|
| 135 |
+
return None
|
| 136 |
+
searched_node = searched_node_child.parent
|
| 137 |
+
if searched_node is None:
|
| 138 |
+
return None
|
| 139 |
+
|
| 140 |
+
index = searched_node.children.index(searched_node_child)
|
| 141 |
+
arglist_nodes = searched_node.children[:index]
|
| 142 |
+
if searched_node.type == 'arglist':
|
| 143 |
+
trailer = searched_node.parent
|
| 144 |
+
if trailer.type == 'error_node':
|
| 145 |
+
trailer_index = trailer.children.index(searched_node)
|
| 146 |
+
assert trailer_index >= 2
|
| 147 |
+
assert trailer.children[trailer_index - 1] == '('
|
| 148 |
+
return check(trailer.children[trailer_index - 1], arglist_nodes[::2])
|
| 149 |
+
elif trailer.type == 'trailer':
|
| 150 |
+
return check(trailer.children[0], arglist_nodes[::2])
|
| 151 |
+
elif searched_node.type == 'trailer':
|
| 152 |
+
return check(searched_node.children[0], [])
|
| 153 |
+
elif searched_node.type == 'error_node':
|
| 154 |
+
# Stuff like `join(""`
|
| 155 |
+
return check(arglist_nodes[-1], [])
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/helpers.py
ADDED
|
@@ -0,0 +1,522 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Helpers for the API
|
| 3 |
+
"""
|
| 4 |
+
import re
|
| 5 |
+
from collections import namedtuple
|
| 6 |
+
from textwrap import dedent
|
| 7 |
+
from itertools import chain
|
| 8 |
+
from functools import wraps
|
| 9 |
+
from inspect import Parameter
|
| 10 |
+
|
| 11 |
+
from parso.python.parser import Parser
|
| 12 |
+
from parso.python import tree
|
| 13 |
+
|
| 14 |
+
from jedi.inference.base_value import NO_VALUES
|
| 15 |
+
from jedi.inference.syntax_tree import infer_atom
|
| 16 |
+
from jedi.inference.helpers import infer_call_of_leaf
|
| 17 |
+
from jedi.inference.compiled import get_string_value_set
|
| 18 |
+
from jedi.cache import signature_time_cache, memoize_method
|
| 19 |
+
from jedi.parser_utils import get_parent_scope
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
CompletionParts = namedtuple('CompletionParts', ['path', 'has_dot', 'name'])
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _start_match(string, like_name):
|
| 26 |
+
return string.startswith(like_name)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _fuzzy_match(string, like_name):
|
| 30 |
+
if len(like_name) <= 1:
|
| 31 |
+
return like_name in string
|
| 32 |
+
pos = string.find(like_name[0])
|
| 33 |
+
if pos >= 0:
|
| 34 |
+
return _fuzzy_match(string[pos + 1:], like_name[1:])
|
| 35 |
+
return False
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def match(string, like_name, fuzzy=False):
|
| 39 |
+
if fuzzy:
|
| 40 |
+
return _fuzzy_match(string, like_name)
|
| 41 |
+
else:
|
| 42 |
+
return _start_match(string, like_name)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def sorted_definitions(defs):
|
| 46 |
+
# Note: `or ''` below is required because `module_path` could be
|
| 47 |
+
return sorted(defs, key=lambda x: (str(x.module_path or ''),
|
| 48 |
+
x.line or 0,
|
| 49 |
+
x.column or 0,
|
| 50 |
+
x.name))
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def get_on_completion_name(module_node, lines, position):
|
| 54 |
+
leaf = module_node.get_leaf_for_position(position)
|
| 55 |
+
if leaf is None or leaf.type in ('string', 'error_leaf'):
|
| 56 |
+
# Completions inside strings are a bit special, we need to parse the
|
| 57 |
+
# string. The same is true for comments and error_leafs.
|
| 58 |
+
line = lines[position[0] - 1]
|
| 59 |
+
# The first step of completions is to get the name
|
| 60 |
+
return re.search(r'(?!\d)\w+$|$', line[:position[1]]).group(0)
|
| 61 |
+
elif leaf.type not in ('name', 'keyword'):
|
| 62 |
+
return ''
|
| 63 |
+
|
| 64 |
+
return leaf.value[:position[1] - leaf.start_pos[1]]
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _get_code(code_lines, start_pos, end_pos):
|
| 68 |
+
# Get relevant lines.
|
| 69 |
+
lines = code_lines[start_pos[0] - 1:end_pos[0]]
|
| 70 |
+
# Remove the parts at the end of the line.
|
| 71 |
+
lines[-1] = lines[-1][:end_pos[1]]
|
| 72 |
+
# Remove first line indentation.
|
| 73 |
+
lines[0] = lines[0][start_pos[1]:]
|
| 74 |
+
return ''.join(lines)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class OnErrorLeaf(Exception):
|
| 78 |
+
@property
|
| 79 |
+
def error_leaf(self):
|
| 80 |
+
return self.args[0]
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _get_code_for_stack(code_lines, leaf, position):
|
| 84 |
+
# It might happen that we're on whitespace or on a comment. This means
|
| 85 |
+
# that we would not get the right leaf.
|
| 86 |
+
if leaf.start_pos >= position:
|
| 87 |
+
# If we're not on a comment simply get the previous leaf and proceed.
|
| 88 |
+
leaf = leaf.get_previous_leaf()
|
| 89 |
+
if leaf is None:
|
| 90 |
+
return '' # At the beginning of the file.
|
| 91 |
+
|
| 92 |
+
is_after_newline = leaf.type == 'newline'
|
| 93 |
+
while leaf.type == 'newline':
|
| 94 |
+
leaf = leaf.get_previous_leaf()
|
| 95 |
+
if leaf is None:
|
| 96 |
+
return ''
|
| 97 |
+
|
| 98 |
+
if leaf.type == 'error_leaf' or leaf.type == 'string':
|
| 99 |
+
if leaf.start_pos[0] < position[0]:
|
| 100 |
+
# On a different line, we just begin anew.
|
| 101 |
+
return ''
|
| 102 |
+
|
| 103 |
+
# Error leafs cannot be parsed, completion in strings is also
|
| 104 |
+
# impossible.
|
| 105 |
+
raise OnErrorLeaf(leaf)
|
| 106 |
+
else:
|
| 107 |
+
user_stmt = leaf
|
| 108 |
+
while True:
|
| 109 |
+
if user_stmt.parent.type in ('file_input', 'suite', 'simple_stmt'):
|
| 110 |
+
break
|
| 111 |
+
user_stmt = user_stmt.parent
|
| 112 |
+
|
| 113 |
+
if is_after_newline:
|
| 114 |
+
if user_stmt.start_pos[1] > position[1]:
|
| 115 |
+
# This means that it's actually a dedent and that means that we
|
| 116 |
+
# start without value (part of a suite).
|
| 117 |
+
return ''
|
| 118 |
+
|
| 119 |
+
# This is basically getting the relevant lines.
|
| 120 |
+
return _get_code(code_lines, user_stmt.get_start_pos_of_prefix(), position)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def get_stack_at_position(grammar, code_lines, leaf, pos):
|
| 124 |
+
"""
|
| 125 |
+
Returns the possible node names (e.g. import_from, xor_test or yield_stmt).
|
| 126 |
+
"""
|
| 127 |
+
class EndMarkerReached(Exception):
|
| 128 |
+
pass
|
| 129 |
+
|
| 130 |
+
def tokenize_without_endmarker(code):
|
| 131 |
+
# TODO This is for now not an official parso API that exists purely
|
| 132 |
+
# for Jedi.
|
| 133 |
+
tokens = grammar._tokenize(code)
|
| 134 |
+
for token in tokens:
|
| 135 |
+
if token.string == safeword:
|
| 136 |
+
raise EndMarkerReached()
|
| 137 |
+
elif token.prefix.endswith(safeword):
|
| 138 |
+
# This happens with comments.
|
| 139 |
+
raise EndMarkerReached()
|
| 140 |
+
elif token.string.endswith(safeword):
|
| 141 |
+
yield token # Probably an f-string literal that was not finished.
|
| 142 |
+
raise EndMarkerReached()
|
| 143 |
+
else:
|
| 144 |
+
yield token
|
| 145 |
+
|
| 146 |
+
# The code might be indedented, just remove it.
|
| 147 |
+
code = dedent(_get_code_for_stack(code_lines, leaf, pos))
|
| 148 |
+
# We use a word to tell Jedi when we have reached the start of the
|
| 149 |
+
# completion.
|
| 150 |
+
# Use Z as a prefix because it's not part of a number suffix.
|
| 151 |
+
safeword = 'ZZZ_USER_WANTS_TO_COMPLETE_HERE_WITH_JEDI'
|
| 152 |
+
code = code + ' ' + safeword
|
| 153 |
+
|
| 154 |
+
p = Parser(grammar._pgen_grammar, error_recovery=True)
|
| 155 |
+
try:
|
| 156 |
+
p.parse(tokens=tokenize_without_endmarker(code))
|
| 157 |
+
except EndMarkerReached:
|
| 158 |
+
return p.stack
|
| 159 |
+
raise SystemError(
|
| 160 |
+
"This really shouldn't happen. There's a bug in Jedi:\n%s"
|
| 161 |
+
% list(tokenize_without_endmarker(code))
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def infer(inference_state, context, leaf):
|
| 166 |
+
if leaf.type == 'name':
|
| 167 |
+
return inference_state.infer(context, leaf)
|
| 168 |
+
|
| 169 |
+
parent = leaf.parent
|
| 170 |
+
definitions = NO_VALUES
|
| 171 |
+
if parent.type == 'atom':
|
| 172 |
+
# e.g. `(a + b)`
|
| 173 |
+
definitions = context.infer_node(leaf.parent)
|
| 174 |
+
elif parent.type == 'trailer':
|
| 175 |
+
# e.g. `a()`
|
| 176 |
+
definitions = infer_call_of_leaf(context, leaf)
|
| 177 |
+
elif isinstance(leaf, tree.Literal):
|
| 178 |
+
# e.g. `"foo"` or `1.0`
|
| 179 |
+
return infer_atom(context, leaf)
|
| 180 |
+
elif leaf.type in ('fstring_string', 'fstring_start', 'fstring_end'):
|
| 181 |
+
return get_string_value_set(inference_state)
|
| 182 |
+
return definitions
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def filter_follow_imports(names, follow_builtin_imports=False):
|
| 186 |
+
for name in names:
|
| 187 |
+
if name.is_import():
|
| 188 |
+
new_names = list(filter_follow_imports(
|
| 189 |
+
name.goto(),
|
| 190 |
+
follow_builtin_imports=follow_builtin_imports,
|
| 191 |
+
))
|
| 192 |
+
found_builtin = False
|
| 193 |
+
if follow_builtin_imports:
|
| 194 |
+
for new_name in new_names:
|
| 195 |
+
if new_name.start_pos is None:
|
| 196 |
+
found_builtin = True
|
| 197 |
+
|
| 198 |
+
if found_builtin:
|
| 199 |
+
yield name
|
| 200 |
+
else:
|
| 201 |
+
yield from new_names
|
| 202 |
+
else:
|
| 203 |
+
yield name
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
class CallDetails:
|
| 207 |
+
def __init__(self, bracket_leaf, children, position):
|
| 208 |
+
self.bracket_leaf = bracket_leaf
|
| 209 |
+
self._children = children
|
| 210 |
+
self._position = position
|
| 211 |
+
|
| 212 |
+
@property
|
| 213 |
+
def index(self):
|
| 214 |
+
return _get_index_and_key(self._children, self._position)[0]
|
| 215 |
+
|
| 216 |
+
@property
|
| 217 |
+
def keyword_name_str(self):
|
| 218 |
+
return _get_index_and_key(self._children, self._position)[1]
|
| 219 |
+
|
| 220 |
+
@memoize_method
|
| 221 |
+
def _list_arguments(self):
|
| 222 |
+
return list(_iter_arguments(self._children, self._position))
|
| 223 |
+
|
| 224 |
+
def calculate_index(self, param_names):
|
| 225 |
+
positional_count = 0
|
| 226 |
+
used_names = set()
|
| 227 |
+
star_count = -1
|
| 228 |
+
args = self._list_arguments()
|
| 229 |
+
if not args:
|
| 230 |
+
if param_names:
|
| 231 |
+
return 0
|
| 232 |
+
else:
|
| 233 |
+
return None
|
| 234 |
+
|
| 235 |
+
is_kwarg = False
|
| 236 |
+
for i, (star_count, key_start, had_equal) in enumerate(args):
|
| 237 |
+
is_kwarg |= had_equal | (star_count == 2)
|
| 238 |
+
if star_count:
|
| 239 |
+
pass # For now do nothing, we don't know what's in there here.
|
| 240 |
+
else:
|
| 241 |
+
if i + 1 != len(args): # Not last
|
| 242 |
+
if had_equal:
|
| 243 |
+
used_names.add(key_start)
|
| 244 |
+
else:
|
| 245 |
+
positional_count += 1
|
| 246 |
+
|
| 247 |
+
for i, param_name in enumerate(param_names):
|
| 248 |
+
kind = param_name.get_kind()
|
| 249 |
+
|
| 250 |
+
if not is_kwarg:
|
| 251 |
+
if kind == Parameter.VAR_POSITIONAL:
|
| 252 |
+
return i
|
| 253 |
+
if kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.POSITIONAL_ONLY):
|
| 254 |
+
if i == positional_count:
|
| 255 |
+
return i
|
| 256 |
+
|
| 257 |
+
if key_start is not None and not star_count == 1 or star_count == 2:
|
| 258 |
+
if param_name.string_name not in used_names \
|
| 259 |
+
and (kind == Parameter.KEYWORD_ONLY
|
| 260 |
+
or kind == Parameter.POSITIONAL_OR_KEYWORD
|
| 261 |
+
and positional_count <= i):
|
| 262 |
+
if star_count:
|
| 263 |
+
return i
|
| 264 |
+
if had_equal:
|
| 265 |
+
if param_name.string_name == key_start:
|
| 266 |
+
return i
|
| 267 |
+
else:
|
| 268 |
+
if param_name.string_name.startswith(key_start):
|
| 269 |
+
return i
|
| 270 |
+
|
| 271 |
+
if kind == Parameter.VAR_KEYWORD:
|
| 272 |
+
return i
|
| 273 |
+
return None
|
| 274 |
+
|
| 275 |
+
def iter_used_keyword_arguments(self):
|
| 276 |
+
for star_count, key_start, had_equal in list(self._list_arguments()):
|
| 277 |
+
if had_equal and key_start:
|
| 278 |
+
yield key_start
|
| 279 |
+
|
| 280 |
+
def count_positional_arguments(self):
|
| 281 |
+
count = 0
|
| 282 |
+
for star_count, key_start, had_equal in self._list_arguments()[:-1]:
|
| 283 |
+
if star_count or key_start:
|
| 284 |
+
break
|
| 285 |
+
count += 1
|
| 286 |
+
return count
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def _iter_arguments(nodes, position):
|
| 290 |
+
def remove_after_pos(name):
|
| 291 |
+
if name.type != 'name':
|
| 292 |
+
return None
|
| 293 |
+
return name.value[:position[1] - name.start_pos[1]]
|
| 294 |
+
|
| 295 |
+
# Returns Generator[Tuple[star_count, Optional[key_start: str], had_equal]]
|
| 296 |
+
nodes_before = [c for c in nodes if c.start_pos < position]
|
| 297 |
+
if nodes_before[-1].type == 'arglist':
|
| 298 |
+
yield from _iter_arguments(nodes_before[-1].children, position)
|
| 299 |
+
return
|
| 300 |
+
|
| 301 |
+
previous_node_yielded = False
|
| 302 |
+
stars_seen = 0
|
| 303 |
+
for i, node in enumerate(nodes_before):
|
| 304 |
+
if node.type == 'argument':
|
| 305 |
+
previous_node_yielded = True
|
| 306 |
+
first = node.children[0]
|
| 307 |
+
second = node.children[1]
|
| 308 |
+
if second == '=':
|
| 309 |
+
if second.start_pos < position and first.type == 'name':
|
| 310 |
+
yield 0, first.value, True
|
| 311 |
+
else:
|
| 312 |
+
yield 0, remove_after_pos(first), False
|
| 313 |
+
elif first in ('*', '**'):
|
| 314 |
+
yield len(first.value), remove_after_pos(second), False
|
| 315 |
+
else:
|
| 316 |
+
# Must be a Comprehension
|
| 317 |
+
first_leaf = node.get_first_leaf()
|
| 318 |
+
if first_leaf.type == 'name' and first_leaf.start_pos >= position:
|
| 319 |
+
yield 0, remove_after_pos(first_leaf), False
|
| 320 |
+
else:
|
| 321 |
+
yield 0, None, False
|
| 322 |
+
stars_seen = 0
|
| 323 |
+
elif node.type == 'testlist_star_expr':
|
| 324 |
+
for n in node.children[::2]:
|
| 325 |
+
if n.type == 'star_expr':
|
| 326 |
+
stars_seen = 1
|
| 327 |
+
n = n.children[1]
|
| 328 |
+
yield stars_seen, remove_after_pos(n), False
|
| 329 |
+
stars_seen = 0
|
| 330 |
+
# The count of children is even if there's a comma at the end.
|
| 331 |
+
previous_node_yielded = bool(len(node.children) % 2)
|
| 332 |
+
elif isinstance(node, tree.PythonLeaf) and node.value == ',':
|
| 333 |
+
if not previous_node_yielded:
|
| 334 |
+
yield stars_seen, '', False
|
| 335 |
+
stars_seen = 0
|
| 336 |
+
previous_node_yielded = False
|
| 337 |
+
elif isinstance(node, tree.PythonLeaf) and node.value in ('*', '**'):
|
| 338 |
+
stars_seen = len(node.value)
|
| 339 |
+
elif node == '=' and nodes_before[-1]:
|
| 340 |
+
previous_node_yielded = True
|
| 341 |
+
before = nodes_before[i - 1]
|
| 342 |
+
if before.type == 'name':
|
| 343 |
+
yield 0, before.value, True
|
| 344 |
+
else:
|
| 345 |
+
yield 0, None, False
|
| 346 |
+
# Just ignore the star that is probably a syntax error.
|
| 347 |
+
stars_seen = 0
|
| 348 |
+
|
| 349 |
+
if not previous_node_yielded:
|
| 350 |
+
if nodes_before[-1].type == 'name':
|
| 351 |
+
yield stars_seen, remove_after_pos(nodes_before[-1]), False
|
| 352 |
+
else:
|
| 353 |
+
yield stars_seen, '', False
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
def _get_index_and_key(nodes, position):
|
| 357 |
+
"""
|
| 358 |
+
Returns the amount of commas and the keyword argument string.
|
| 359 |
+
"""
|
| 360 |
+
nodes_before = [c for c in nodes if c.start_pos < position]
|
| 361 |
+
if nodes_before[-1].type == 'arglist':
|
| 362 |
+
return _get_index_and_key(nodes_before[-1].children, position)
|
| 363 |
+
|
| 364 |
+
key_str = None
|
| 365 |
+
|
| 366 |
+
last = nodes_before[-1]
|
| 367 |
+
if last.type == 'argument' and last.children[1] == '=' \
|
| 368 |
+
and last.children[1].end_pos <= position:
|
| 369 |
+
# Checked if the argument
|
| 370 |
+
key_str = last.children[0].value
|
| 371 |
+
elif last == '=':
|
| 372 |
+
key_str = nodes_before[-2].value
|
| 373 |
+
|
| 374 |
+
return nodes_before.count(','), key_str
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def _get_signature_details_from_error_node(node, additional_children, position):
|
| 378 |
+
for index, element in reversed(list(enumerate(node.children))):
|
| 379 |
+
# `index > 0` means that it's a trailer and not an atom.
|
| 380 |
+
if element == '(' and element.end_pos <= position and index > 0:
|
| 381 |
+
# It's an error node, we don't want to match too much, just
|
| 382 |
+
# until the parentheses is enough.
|
| 383 |
+
children = node.children[index:]
|
| 384 |
+
name = element.get_previous_leaf()
|
| 385 |
+
if name is None:
|
| 386 |
+
continue
|
| 387 |
+
if name.type == 'name' or name.parent.type in ('trailer', 'atom'):
|
| 388 |
+
return CallDetails(element, children + additional_children, position)
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
def get_signature_details(module, position):
|
| 392 |
+
leaf = module.get_leaf_for_position(position, include_prefixes=True)
|
| 393 |
+
# It's easier to deal with the previous token than the next one in this
|
| 394 |
+
# case.
|
| 395 |
+
if leaf.start_pos >= position:
|
| 396 |
+
# Whitespace / comments after the leaf count towards the previous leaf.
|
| 397 |
+
leaf = leaf.get_previous_leaf()
|
| 398 |
+
if leaf is None:
|
| 399 |
+
return None
|
| 400 |
+
|
| 401 |
+
# Now that we know where we are in the syntax tree, we start to look at
|
| 402 |
+
# parents for possible function definitions.
|
| 403 |
+
node = leaf.parent
|
| 404 |
+
while node is not None:
|
| 405 |
+
if node.type in ('funcdef', 'classdef', 'decorated', 'async_stmt'):
|
| 406 |
+
# Don't show signatures if there's stuff before it that just
|
| 407 |
+
# makes it feel strange to have a signature.
|
| 408 |
+
return None
|
| 409 |
+
|
| 410 |
+
additional_children = []
|
| 411 |
+
for n in reversed(node.children):
|
| 412 |
+
if n.start_pos < position:
|
| 413 |
+
if n.type == 'error_node':
|
| 414 |
+
result = _get_signature_details_from_error_node(
|
| 415 |
+
n, additional_children, position
|
| 416 |
+
)
|
| 417 |
+
if result is not None:
|
| 418 |
+
return result
|
| 419 |
+
|
| 420 |
+
additional_children[0:0] = n.children
|
| 421 |
+
continue
|
| 422 |
+
additional_children.insert(0, n)
|
| 423 |
+
|
| 424 |
+
# Find a valid trailer
|
| 425 |
+
if node.type == 'trailer' and node.children[0] == '(' \
|
| 426 |
+
or node.type == 'decorator' and node.children[2] == '(':
|
| 427 |
+
# Additionally we have to check that an ending parenthesis isn't
|
| 428 |
+
# interpreted wrong. There are two cases:
|
| 429 |
+
# 1. Cursor before paren -> The current signature is good
|
| 430 |
+
# 2. Cursor after paren -> We need to skip the current signature
|
| 431 |
+
if not (leaf is node.children[-1] and position >= leaf.end_pos):
|
| 432 |
+
leaf = node.get_previous_leaf()
|
| 433 |
+
if leaf is None:
|
| 434 |
+
return None
|
| 435 |
+
return CallDetails(
|
| 436 |
+
node.children[0] if node.type == 'trailer' else node.children[2],
|
| 437 |
+
node.children,
|
| 438 |
+
position
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
node = node.parent
|
| 442 |
+
|
| 443 |
+
return None
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
@signature_time_cache("call_signatures_validity")
|
| 447 |
+
def cache_signatures(inference_state, context, bracket_leaf, code_lines, user_pos):
|
| 448 |
+
"""This function calculates the cache key."""
|
| 449 |
+
line_index = user_pos[0] - 1
|
| 450 |
+
|
| 451 |
+
before_cursor = code_lines[line_index][:user_pos[1]]
|
| 452 |
+
other_lines = code_lines[bracket_leaf.start_pos[0]:line_index]
|
| 453 |
+
whole = ''.join(other_lines + [before_cursor])
|
| 454 |
+
before_bracket = re.match(r'.*\(', whole, re.DOTALL)
|
| 455 |
+
|
| 456 |
+
module_path = context.get_root_context().py__file__()
|
| 457 |
+
if module_path is None:
|
| 458 |
+
yield None # Don't cache!
|
| 459 |
+
else:
|
| 460 |
+
yield (module_path, before_bracket, bracket_leaf.start_pos)
|
| 461 |
+
yield infer(
|
| 462 |
+
inference_state,
|
| 463 |
+
context,
|
| 464 |
+
bracket_leaf.get_previous_leaf(),
|
| 465 |
+
)
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def validate_line_column(func):
|
| 469 |
+
@wraps(func)
|
| 470 |
+
def wrapper(self, line=None, column=None, *args, **kwargs):
|
| 471 |
+
line = max(len(self._code_lines), 1) if line is None else line
|
| 472 |
+
if not (0 < line <= len(self._code_lines)):
|
| 473 |
+
raise ValueError('`line` parameter is not in a valid range.')
|
| 474 |
+
|
| 475 |
+
line_string = self._code_lines[line - 1]
|
| 476 |
+
line_len = len(line_string)
|
| 477 |
+
if line_string.endswith('\r\n'):
|
| 478 |
+
line_len -= 2
|
| 479 |
+
elif line_string.endswith('\n'):
|
| 480 |
+
line_len -= 1
|
| 481 |
+
|
| 482 |
+
column = line_len if column is None else column
|
| 483 |
+
if not (0 <= column <= line_len):
|
| 484 |
+
raise ValueError('`column` parameter (%d) is not in a valid range '
|
| 485 |
+
'(0-%d) for line %d (%r).' % (
|
| 486 |
+
column, line_len, line, line_string))
|
| 487 |
+
return func(self, line, column, *args, **kwargs)
|
| 488 |
+
return wrapper
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def get_module_names(module, all_scopes, definitions=True, references=False):
|
| 492 |
+
"""
|
| 493 |
+
Returns a dictionary with name parts as keys and their call paths as
|
| 494 |
+
values.
|
| 495 |
+
"""
|
| 496 |
+
def def_ref_filter(name):
|
| 497 |
+
is_def = name.is_definition()
|
| 498 |
+
return definitions and is_def or references and not is_def
|
| 499 |
+
|
| 500 |
+
names = list(chain.from_iterable(module.get_used_names().values()))
|
| 501 |
+
if not all_scopes:
|
| 502 |
+
# We have to filter all the names that don't have the module as a
|
| 503 |
+
# parent_scope. There's None as a parent, because nodes in the module
|
| 504 |
+
# node have the parent module and not suite as all the others.
|
| 505 |
+
# Therefore it's important to catch that case.
|
| 506 |
+
|
| 507 |
+
def is_module_scope_name(name):
|
| 508 |
+
parent_scope = get_parent_scope(name)
|
| 509 |
+
# async functions have an extra wrapper. Strip it.
|
| 510 |
+
if parent_scope and parent_scope.type == 'async_stmt':
|
| 511 |
+
parent_scope = parent_scope.parent
|
| 512 |
+
return parent_scope in (module, None)
|
| 513 |
+
|
| 514 |
+
names = [n for n in names if is_module_scope_name(n)]
|
| 515 |
+
return filter(def_ref_filter, names)
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
def split_search_string(name):
|
| 519 |
+
type, _, dotted_names = name.rpartition(' ')
|
| 520 |
+
if type == 'def':
|
| 521 |
+
type = 'function'
|
| 522 |
+
return type, dotted_names.split('.')
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/interpreter.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
TODO Some parts of this module are still not well documented.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from jedi.inference import compiled
|
| 6 |
+
from jedi.inference.base_value import ValueSet
|
| 7 |
+
from jedi.inference.filters import ParserTreeFilter, MergedFilter
|
| 8 |
+
from jedi.inference.names import TreeNameDefinition
|
| 9 |
+
from jedi.inference.compiled import mixed
|
| 10 |
+
from jedi.inference.compiled.access import create_access_path
|
| 11 |
+
from jedi.inference.context import ModuleContext
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _create(inference_state, obj):
|
| 15 |
+
return compiled.create_from_access_path(
|
| 16 |
+
inference_state, create_access_path(inference_state, obj)
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class NamespaceObject:
|
| 21 |
+
def __init__(self, dct):
|
| 22 |
+
self.__dict__ = dct
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class MixedTreeName(TreeNameDefinition):
|
| 26 |
+
def infer(self):
|
| 27 |
+
"""
|
| 28 |
+
In IPython notebook it is typical that some parts of the code that is
|
| 29 |
+
provided was already executed. In that case if something is not properly
|
| 30 |
+
inferred, it should still infer from the variables it already knows.
|
| 31 |
+
"""
|
| 32 |
+
inferred = super().infer()
|
| 33 |
+
if not inferred:
|
| 34 |
+
for compiled_value in self.parent_context.mixed_values:
|
| 35 |
+
for f in compiled_value.get_filters():
|
| 36 |
+
values = ValueSet.from_sets(
|
| 37 |
+
n.infer() for n in f.get(self.string_name)
|
| 38 |
+
)
|
| 39 |
+
if values:
|
| 40 |
+
return values
|
| 41 |
+
return inferred
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class MixedParserTreeFilter(ParserTreeFilter):
|
| 45 |
+
name_class = MixedTreeName
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class MixedModuleContext(ModuleContext):
|
| 49 |
+
def __init__(self, tree_module_value, namespaces):
|
| 50 |
+
super().__init__(tree_module_value)
|
| 51 |
+
self.mixed_values = [
|
| 52 |
+
self._get_mixed_object(
|
| 53 |
+
_create(self.inference_state, NamespaceObject(n))
|
| 54 |
+
) for n in namespaces
|
| 55 |
+
]
|
| 56 |
+
|
| 57 |
+
def _get_mixed_object(self, compiled_value):
|
| 58 |
+
return mixed.MixedObject(
|
| 59 |
+
compiled_value=compiled_value,
|
| 60 |
+
tree_value=self._value
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
def get_filters(self, until_position=None, origin_scope=None):
|
| 64 |
+
yield MergedFilter(
|
| 65 |
+
MixedParserTreeFilter(
|
| 66 |
+
parent_context=self,
|
| 67 |
+
until_position=until_position,
|
| 68 |
+
origin_scope=origin_scope
|
| 69 |
+
),
|
| 70 |
+
self.get_global_filter(),
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
for mixed_object in self.mixed_values:
|
| 74 |
+
yield from mixed_object.get_filters(until_position, origin_scope)
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/keywords.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pydoc
|
| 2 |
+
from contextlib import suppress
|
| 3 |
+
from typing import Dict, Optional
|
| 4 |
+
|
| 5 |
+
from jedi.inference.names import AbstractArbitraryName
|
| 6 |
+
|
| 7 |
+
try:
|
| 8 |
+
from pydoc_data import topics
|
| 9 |
+
pydoc_topics: Optional[Dict[str, str]] = topics.topics
|
| 10 |
+
except ImportError:
|
| 11 |
+
# Python 3.6.8 embeddable does not have pydoc_data.
|
| 12 |
+
pydoc_topics = None
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class KeywordName(AbstractArbitraryName):
|
| 16 |
+
api_type = 'keyword'
|
| 17 |
+
|
| 18 |
+
def py__doc__(self):
|
| 19 |
+
return imitate_pydoc(self.string_name)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def imitate_pydoc(string):
|
| 23 |
+
"""
|
| 24 |
+
It's not possible to get the pydoc's without starting the annoying pager
|
| 25 |
+
stuff.
|
| 26 |
+
"""
|
| 27 |
+
if pydoc_topics is None:
|
| 28 |
+
return ''
|
| 29 |
+
|
| 30 |
+
h = pydoc.help
|
| 31 |
+
with suppress(KeyError):
|
| 32 |
+
# try to access symbols
|
| 33 |
+
string = h.symbols[string]
|
| 34 |
+
string, _, related = string.partition(' ')
|
| 35 |
+
|
| 36 |
+
def get_target(s):
|
| 37 |
+
return h.topics.get(s, h.keywords.get(s))
|
| 38 |
+
|
| 39 |
+
while isinstance(string, str):
|
| 40 |
+
string = get_target(string)
|
| 41 |
+
|
| 42 |
+
try:
|
| 43 |
+
# is a tuple now
|
| 44 |
+
label, related = string
|
| 45 |
+
except TypeError:
|
| 46 |
+
return ''
|
| 47 |
+
|
| 48 |
+
try:
|
| 49 |
+
return pydoc_topics[label].strip() if pydoc_topics else ''
|
| 50 |
+
except KeyError:
|
| 51 |
+
return ''
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/project.py
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Projects are a way to handle Python projects within Jedi. For simpler plugins
|
| 3 |
+
you might not want to deal with projects, but if you want to give the user more
|
| 4 |
+
flexibility to define sys paths and Python interpreters for a project,
|
| 5 |
+
:class:`.Project` is the perfect way to allow for that.
|
| 6 |
+
|
| 7 |
+
Projects can be saved to disk and loaded again, to allow project definitions to
|
| 8 |
+
be used across repositories.
|
| 9 |
+
"""
|
| 10 |
+
import json
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from itertools import chain
|
| 13 |
+
|
| 14 |
+
from jedi import debug
|
| 15 |
+
from jedi.api.environment import get_cached_default_environment, create_environment
|
| 16 |
+
from jedi.api.exceptions import WrongVersion
|
| 17 |
+
from jedi.api.completion import search_in_module
|
| 18 |
+
from jedi.api.helpers import split_search_string, get_module_names
|
| 19 |
+
from jedi.inference.imports import load_module_from_path, \
|
| 20 |
+
load_namespace_from_path, iter_module_names
|
| 21 |
+
from jedi.inference.sys_path import discover_buildout_paths
|
| 22 |
+
from jedi.inference.cache import inference_state_as_method_param_cache
|
| 23 |
+
from jedi.inference.references import recurse_find_python_folders_and_files, search_in_file_ios
|
| 24 |
+
from jedi.file_io import FolderIO
|
| 25 |
+
|
| 26 |
+
_CONFIG_FOLDER = '.jedi'
|
| 27 |
+
_CONTAINS_POTENTIAL_PROJECT = \
|
| 28 |
+
'setup.py', '.git', '.hg', 'requirements.txt', 'MANIFEST.in', 'pyproject.toml'
|
| 29 |
+
|
| 30 |
+
_SERIALIZER_VERSION = 1
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _try_to_skip_duplicates(func):
|
| 34 |
+
def wrapper(*args, **kwargs):
|
| 35 |
+
found_tree_nodes = []
|
| 36 |
+
found_modules = []
|
| 37 |
+
for definition in func(*args, **kwargs):
|
| 38 |
+
tree_node = definition._name.tree_name
|
| 39 |
+
if tree_node is not None and tree_node in found_tree_nodes:
|
| 40 |
+
continue
|
| 41 |
+
if definition.type == 'module' and definition.module_path is not None:
|
| 42 |
+
if definition.module_path in found_modules:
|
| 43 |
+
continue
|
| 44 |
+
found_modules.append(definition.module_path)
|
| 45 |
+
yield definition
|
| 46 |
+
found_tree_nodes.append(tree_node)
|
| 47 |
+
return wrapper
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _remove_duplicates_from_path(path):
|
| 51 |
+
used = set()
|
| 52 |
+
for p in path:
|
| 53 |
+
if p in used:
|
| 54 |
+
continue
|
| 55 |
+
used.add(p)
|
| 56 |
+
yield p
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class Project:
|
| 60 |
+
"""
|
| 61 |
+
Projects are a simple way to manage Python folders and define how Jedi does
|
| 62 |
+
import resolution. It is mostly used as a parameter to :class:`.Script`.
|
| 63 |
+
Additionally there are functions to search a whole project.
|
| 64 |
+
"""
|
| 65 |
+
_environment = None
|
| 66 |
+
|
| 67 |
+
@staticmethod
|
| 68 |
+
def _get_config_folder_path(base_path):
|
| 69 |
+
return base_path.joinpath(_CONFIG_FOLDER)
|
| 70 |
+
|
| 71 |
+
@staticmethod
|
| 72 |
+
def _get_json_path(base_path):
|
| 73 |
+
return Project._get_config_folder_path(base_path).joinpath('project.json')
|
| 74 |
+
|
| 75 |
+
@classmethod
|
| 76 |
+
def load(cls, path):
|
| 77 |
+
"""
|
| 78 |
+
Loads a project from a specific path. You should not provide the path
|
| 79 |
+
to ``.jedi/project.json``, but rather the path to the project folder.
|
| 80 |
+
|
| 81 |
+
:param path: The path of the directory you want to use as a project.
|
| 82 |
+
"""
|
| 83 |
+
if isinstance(path, str):
|
| 84 |
+
path = Path(path)
|
| 85 |
+
with open(cls._get_json_path(path)) as f:
|
| 86 |
+
version, data = json.load(f)
|
| 87 |
+
|
| 88 |
+
if version == 1:
|
| 89 |
+
return cls(**data)
|
| 90 |
+
else:
|
| 91 |
+
raise WrongVersion(
|
| 92 |
+
"The Jedi version of this project seems newer than what we can handle."
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
def save(self):
|
| 96 |
+
"""
|
| 97 |
+
Saves the project configuration in the project in ``.jedi/project.json``.
|
| 98 |
+
"""
|
| 99 |
+
data = dict(self.__dict__)
|
| 100 |
+
data.pop('_environment', None)
|
| 101 |
+
data.pop('_django', None) # TODO make django setting public?
|
| 102 |
+
data = {k.lstrip('_'): v for k, v in data.items()}
|
| 103 |
+
data['path'] = str(data['path'])
|
| 104 |
+
|
| 105 |
+
self._get_config_folder_path(self._path).mkdir(parents=True, exist_ok=True)
|
| 106 |
+
with open(self._get_json_path(self._path), 'w') as f:
|
| 107 |
+
return json.dump((_SERIALIZER_VERSION, data), f)
|
| 108 |
+
|
| 109 |
+
def __init__(
|
| 110 |
+
self,
|
| 111 |
+
path,
|
| 112 |
+
*,
|
| 113 |
+
environment_path=None,
|
| 114 |
+
load_unsafe_extensions=False,
|
| 115 |
+
sys_path=None,
|
| 116 |
+
added_sys_path=(),
|
| 117 |
+
smart_sys_path=True,
|
| 118 |
+
) -> None:
|
| 119 |
+
"""
|
| 120 |
+
:param path: The base path for this project.
|
| 121 |
+
:param environment_path: The Python executable path, typically the path
|
| 122 |
+
of a virtual environment.
|
| 123 |
+
:param load_unsafe_extensions: Default False, Loads extensions that are not in the
|
| 124 |
+
sys path and in the local directories. With this option enabled,
|
| 125 |
+
this is potentially unsafe if you clone a git repository and
|
| 126 |
+
analyze it's code, because those compiled extensions will be
|
| 127 |
+
important and therefore have execution privileges.
|
| 128 |
+
:param sys_path: list of str. You can override the sys path if you
|
| 129 |
+
want. By default the ``sys.path.`` is generated by the
|
| 130 |
+
environment (virtualenvs, etc).
|
| 131 |
+
:param added_sys_path: list of str. Adds these paths at the end of the
|
| 132 |
+
sys path.
|
| 133 |
+
:param smart_sys_path: If this is enabled (default), adds paths from
|
| 134 |
+
local directories. Otherwise you will have to rely on your packages
|
| 135 |
+
being properly configured on the ``sys.path``.
|
| 136 |
+
"""
|
| 137 |
+
|
| 138 |
+
if isinstance(path, str):
|
| 139 |
+
path = Path(path).absolute()
|
| 140 |
+
self._path = path
|
| 141 |
+
|
| 142 |
+
self._environment_path = environment_path
|
| 143 |
+
if sys_path is not None:
|
| 144 |
+
# Remap potential pathlib.Path entries
|
| 145 |
+
sys_path = list(map(str, sys_path))
|
| 146 |
+
self._sys_path = sys_path
|
| 147 |
+
self._smart_sys_path = smart_sys_path
|
| 148 |
+
self._load_unsafe_extensions = load_unsafe_extensions
|
| 149 |
+
self._django = False
|
| 150 |
+
# Remap potential pathlib.Path entries
|
| 151 |
+
self.added_sys_path = list(map(str, added_sys_path))
|
| 152 |
+
"""The sys path that is going to be added at the end of the """
|
| 153 |
+
|
| 154 |
+
@property
|
| 155 |
+
def path(self):
|
| 156 |
+
"""
|
| 157 |
+
The base path for this project.
|
| 158 |
+
"""
|
| 159 |
+
return self._path
|
| 160 |
+
|
| 161 |
+
@property
|
| 162 |
+
def sys_path(self):
|
| 163 |
+
"""
|
| 164 |
+
The sys path provided to this project. This can be None and in that
|
| 165 |
+
case will be auto generated.
|
| 166 |
+
"""
|
| 167 |
+
return self._sys_path
|
| 168 |
+
|
| 169 |
+
@property
|
| 170 |
+
def smart_sys_path(self):
|
| 171 |
+
"""
|
| 172 |
+
If the sys path is going to be calculated in a smart way, where
|
| 173 |
+
additional paths are added.
|
| 174 |
+
"""
|
| 175 |
+
return self._smart_sys_path
|
| 176 |
+
|
| 177 |
+
@property
|
| 178 |
+
def load_unsafe_extensions(self):
|
| 179 |
+
"""
|
| 180 |
+
Wheter the project loads unsafe extensions.
|
| 181 |
+
"""
|
| 182 |
+
return self._load_unsafe_extensions
|
| 183 |
+
|
| 184 |
+
@inference_state_as_method_param_cache()
|
| 185 |
+
def _get_base_sys_path(self, inference_state):
|
| 186 |
+
# The sys path has not been set explicitly.
|
| 187 |
+
sys_path = list(inference_state.environment.get_sys_path())
|
| 188 |
+
try:
|
| 189 |
+
sys_path.remove('')
|
| 190 |
+
except ValueError:
|
| 191 |
+
pass
|
| 192 |
+
return sys_path
|
| 193 |
+
|
| 194 |
+
@inference_state_as_method_param_cache()
|
| 195 |
+
def _get_sys_path(self, inference_state, add_parent_paths=True, add_init_paths=False):
|
| 196 |
+
"""
|
| 197 |
+
Keep this method private for all users of jedi. However internally this
|
| 198 |
+
one is used like a public method.
|
| 199 |
+
"""
|
| 200 |
+
suffixed = list(self.added_sys_path)
|
| 201 |
+
prefixed = []
|
| 202 |
+
|
| 203 |
+
if self._sys_path is None:
|
| 204 |
+
sys_path = list(self._get_base_sys_path(inference_state))
|
| 205 |
+
else:
|
| 206 |
+
sys_path = list(self._sys_path)
|
| 207 |
+
|
| 208 |
+
if self._smart_sys_path:
|
| 209 |
+
prefixed.append(str(self._path))
|
| 210 |
+
|
| 211 |
+
if inference_state.script_path is not None:
|
| 212 |
+
suffixed += map(str, discover_buildout_paths(
|
| 213 |
+
inference_state,
|
| 214 |
+
inference_state.script_path
|
| 215 |
+
))
|
| 216 |
+
|
| 217 |
+
if add_parent_paths:
|
| 218 |
+
# Collect directories in upward search by:
|
| 219 |
+
# 1. Skipping directories with __init__.py
|
| 220 |
+
# 2. Stopping immediately when above self._path
|
| 221 |
+
traversed = []
|
| 222 |
+
for parent_path in inference_state.script_path.parents:
|
| 223 |
+
if parent_path == self._path \
|
| 224 |
+
or self._path not in parent_path.parents:
|
| 225 |
+
break
|
| 226 |
+
if not add_init_paths \
|
| 227 |
+
and parent_path.joinpath("__init__.py").is_file():
|
| 228 |
+
continue
|
| 229 |
+
traversed.append(str(parent_path))
|
| 230 |
+
|
| 231 |
+
# AFAIK some libraries have imports like `foo.foo.bar`, which
|
| 232 |
+
# leads to the conclusion to by default prefer longer paths
|
| 233 |
+
# rather than shorter ones by default.
|
| 234 |
+
suffixed += reversed(traversed)
|
| 235 |
+
|
| 236 |
+
if self._django:
|
| 237 |
+
prefixed.append(str(self._path))
|
| 238 |
+
|
| 239 |
+
path = prefixed + sys_path + suffixed
|
| 240 |
+
return list(_remove_duplicates_from_path(path))
|
| 241 |
+
|
| 242 |
+
def get_environment(self):
|
| 243 |
+
if self._environment is None:
|
| 244 |
+
if self._environment_path is not None:
|
| 245 |
+
self._environment = create_environment(self._environment_path, safe=False)
|
| 246 |
+
else:
|
| 247 |
+
self._environment = get_cached_default_environment()
|
| 248 |
+
return self._environment
|
| 249 |
+
|
| 250 |
+
def search(self, string, *, all_scopes=False):
|
| 251 |
+
"""
|
| 252 |
+
Searches a name in the whole project. If the project is very big,
|
| 253 |
+
at some point Jedi will stop searching. However it's also very much
|
| 254 |
+
recommended to not exhaust the generator. Just display the first ten
|
| 255 |
+
results to the user.
|
| 256 |
+
|
| 257 |
+
There are currently three different search patterns:
|
| 258 |
+
|
| 259 |
+
- ``foo`` to search for a definition foo in any file or a file called
|
| 260 |
+
``foo.py`` or ``foo.pyi``.
|
| 261 |
+
- ``foo.bar`` to search for the ``foo`` and then an attribute ``bar``
|
| 262 |
+
in it.
|
| 263 |
+
- ``class foo.bar.Bar`` or ``def foo.bar.baz`` to search for a specific
|
| 264 |
+
API type.
|
| 265 |
+
|
| 266 |
+
:param bool all_scopes: Default False; searches not only for
|
| 267 |
+
definitions on the top level of a module level, but also in
|
| 268 |
+
functions and classes.
|
| 269 |
+
:yields: :class:`.Name`
|
| 270 |
+
"""
|
| 271 |
+
return self._search_func(string, all_scopes=all_scopes)
|
| 272 |
+
|
| 273 |
+
def complete_search(self, string, **kwargs):
|
| 274 |
+
"""
|
| 275 |
+
Like :meth:`.Script.search`, but completes that string. An empty string
|
| 276 |
+
lists all definitions in a project, so be careful with that.
|
| 277 |
+
|
| 278 |
+
:param bool all_scopes: Default False; searches not only for
|
| 279 |
+
definitions on the top level of a module level, but also in
|
| 280 |
+
functions and classes.
|
| 281 |
+
:yields: :class:`.Completion`
|
| 282 |
+
"""
|
| 283 |
+
return self._search_func(string, complete=True, **kwargs)
|
| 284 |
+
|
| 285 |
+
@_try_to_skip_duplicates
|
| 286 |
+
def _search_func(self, string, complete=False, all_scopes=False):
|
| 287 |
+
# Using a Script is they easiest way to get an empty module context.
|
| 288 |
+
from jedi import Script
|
| 289 |
+
s = Script('', project=self)
|
| 290 |
+
inference_state = s._inference_state
|
| 291 |
+
empty_module_context = s._get_module_context()
|
| 292 |
+
|
| 293 |
+
debug.dbg('Search for string %s, complete=%s', string, complete)
|
| 294 |
+
wanted_type, wanted_names = split_search_string(string)
|
| 295 |
+
name = wanted_names[0]
|
| 296 |
+
stub_folder_name = name + '-stubs'
|
| 297 |
+
|
| 298 |
+
ios = recurse_find_python_folders_and_files(FolderIO(str(self._path)))
|
| 299 |
+
file_ios = []
|
| 300 |
+
|
| 301 |
+
# 1. Search for modules in the current project
|
| 302 |
+
for folder_io, file_io in ios:
|
| 303 |
+
if file_io is None:
|
| 304 |
+
file_name = folder_io.get_base_name()
|
| 305 |
+
if file_name == name or file_name == stub_folder_name:
|
| 306 |
+
f = folder_io.get_file_io('__init__.py')
|
| 307 |
+
try:
|
| 308 |
+
m = load_module_from_path(inference_state, f).as_context()
|
| 309 |
+
except FileNotFoundError:
|
| 310 |
+
f = folder_io.get_file_io('__init__.pyi')
|
| 311 |
+
try:
|
| 312 |
+
m = load_module_from_path(inference_state, f).as_context()
|
| 313 |
+
except FileNotFoundError:
|
| 314 |
+
m = load_namespace_from_path(inference_state, folder_io).as_context()
|
| 315 |
+
else:
|
| 316 |
+
continue
|
| 317 |
+
else:
|
| 318 |
+
file_ios.append(file_io)
|
| 319 |
+
if Path(file_io.path).name in (name + '.py', name + '.pyi'):
|
| 320 |
+
m = load_module_from_path(inference_state, file_io).as_context()
|
| 321 |
+
else:
|
| 322 |
+
continue
|
| 323 |
+
|
| 324 |
+
debug.dbg('Search of a specific module %s', m)
|
| 325 |
+
yield from search_in_module(
|
| 326 |
+
inference_state,
|
| 327 |
+
m,
|
| 328 |
+
names=[m.name],
|
| 329 |
+
wanted_type=wanted_type,
|
| 330 |
+
wanted_names=wanted_names,
|
| 331 |
+
complete=complete,
|
| 332 |
+
convert=True,
|
| 333 |
+
ignore_imports=True,
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
# 2. Search for identifiers in the project.
|
| 337 |
+
for module_context in search_in_file_ios(inference_state, file_ios,
|
| 338 |
+
name, complete=complete):
|
| 339 |
+
names = get_module_names(module_context.tree_node, all_scopes=all_scopes)
|
| 340 |
+
names = [module_context.create_name(n) for n in names]
|
| 341 |
+
names = _remove_imports(names)
|
| 342 |
+
yield from search_in_module(
|
| 343 |
+
inference_state,
|
| 344 |
+
module_context,
|
| 345 |
+
names=names,
|
| 346 |
+
wanted_type=wanted_type,
|
| 347 |
+
wanted_names=wanted_names,
|
| 348 |
+
complete=complete,
|
| 349 |
+
ignore_imports=True,
|
| 350 |
+
)
|
| 351 |
+
|
| 352 |
+
# 3. Search for modules on sys.path
|
| 353 |
+
sys_path = [
|
| 354 |
+
p for p in self._get_sys_path(inference_state)
|
| 355 |
+
# Exclude the current folder which is handled by recursing the folders.
|
| 356 |
+
if p != self._path
|
| 357 |
+
]
|
| 358 |
+
names = list(iter_module_names(inference_state, empty_module_context, sys_path))
|
| 359 |
+
yield from search_in_module(
|
| 360 |
+
inference_state,
|
| 361 |
+
empty_module_context,
|
| 362 |
+
names=names,
|
| 363 |
+
wanted_type=wanted_type,
|
| 364 |
+
wanted_names=wanted_names,
|
| 365 |
+
complete=complete,
|
| 366 |
+
convert=True,
|
| 367 |
+
)
|
| 368 |
+
|
| 369 |
+
def __repr__(self):
|
| 370 |
+
return '<%s: %s>' % (self.__class__.__name__, self._path)
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
def _is_potential_project(path):
|
| 374 |
+
for name in _CONTAINS_POTENTIAL_PROJECT:
|
| 375 |
+
try:
|
| 376 |
+
if path.joinpath(name).exists():
|
| 377 |
+
return True
|
| 378 |
+
except OSError:
|
| 379 |
+
continue
|
| 380 |
+
return False
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def _is_django_path(directory):
|
| 384 |
+
""" Detects the path of the very well known Django library (if used) """
|
| 385 |
+
try:
|
| 386 |
+
with open(directory.joinpath('manage.py'), 'rb') as f:
|
| 387 |
+
return b"DJANGO_SETTINGS_MODULE" in f.read()
|
| 388 |
+
except (FileNotFoundError, IsADirectoryError, PermissionError):
|
| 389 |
+
return False
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def get_default_project(path=None):
|
| 393 |
+
"""
|
| 394 |
+
If a project is not defined by the user, Jedi tries to define a project by
|
| 395 |
+
itself as well as possible. Jedi traverses folders until it finds one of
|
| 396 |
+
the following:
|
| 397 |
+
|
| 398 |
+
1. A ``.jedi/config.json``
|
| 399 |
+
2. One of the following files: ``setup.py``, ``.git``, ``.hg``,
|
| 400 |
+
``requirements.txt`` and ``MANIFEST.in``.
|
| 401 |
+
"""
|
| 402 |
+
if path is None:
|
| 403 |
+
path = Path.cwd()
|
| 404 |
+
elif isinstance(path, str):
|
| 405 |
+
path = Path(path)
|
| 406 |
+
|
| 407 |
+
check = path.absolute()
|
| 408 |
+
probable_path = None
|
| 409 |
+
first_no_init_file = None
|
| 410 |
+
for dir in chain([check], check.parents):
|
| 411 |
+
try:
|
| 412 |
+
return Project.load(dir)
|
| 413 |
+
except (FileNotFoundError, IsADirectoryError, PermissionError):
|
| 414 |
+
pass
|
| 415 |
+
except NotADirectoryError:
|
| 416 |
+
continue
|
| 417 |
+
|
| 418 |
+
if first_no_init_file is None:
|
| 419 |
+
if dir.joinpath('__init__.py').exists():
|
| 420 |
+
# In the case that a __init__.py exists, it's in 99% just a
|
| 421 |
+
# Python package and the project sits at least one level above.
|
| 422 |
+
continue
|
| 423 |
+
elif not dir.is_file():
|
| 424 |
+
first_no_init_file = dir
|
| 425 |
+
|
| 426 |
+
if _is_django_path(dir):
|
| 427 |
+
project = Project(dir)
|
| 428 |
+
project._django = True
|
| 429 |
+
return project
|
| 430 |
+
|
| 431 |
+
if probable_path is None and _is_potential_project(dir):
|
| 432 |
+
probable_path = dir
|
| 433 |
+
|
| 434 |
+
if probable_path is not None:
|
| 435 |
+
return Project(probable_path)
|
| 436 |
+
|
| 437 |
+
if first_no_init_file is not None:
|
| 438 |
+
return Project(first_no_init_file)
|
| 439 |
+
|
| 440 |
+
curdir = path if path.is_dir() else path.parent
|
| 441 |
+
return Project(curdir)
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
def _remove_imports(names):
|
| 445 |
+
return [
|
| 446 |
+
n for n in names
|
| 447 |
+
if n.tree_name is None or n.api_type not in ('module', 'namespace')
|
| 448 |
+
]
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/refactoring/__init__.py
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import difflib
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from typing import Dict, Iterable, Tuple
|
| 4 |
+
|
| 5 |
+
from parso import split_lines
|
| 6 |
+
|
| 7 |
+
from jedi.api.exceptions import RefactoringError
|
| 8 |
+
from jedi.inference.value.namespace import ImplicitNSName
|
| 9 |
+
|
| 10 |
+
EXPRESSION_PARTS = (
|
| 11 |
+
'or_test and_test not_test comparison '
|
| 12 |
+
'expr xor_expr and_expr shift_expr arith_expr term factor power atom_expr'
|
| 13 |
+
).split()
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class ChangedFile:
|
| 17 |
+
def __init__(self, inference_state, from_path, to_path,
|
| 18 |
+
module_node, node_to_str_map):
|
| 19 |
+
self._inference_state = inference_state
|
| 20 |
+
self._from_path = from_path
|
| 21 |
+
self._to_path = to_path
|
| 22 |
+
self._module_node = module_node
|
| 23 |
+
self._node_to_str_map = node_to_str_map
|
| 24 |
+
|
| 25 |
+
def get_diff(self):
|
| 26 |
+
old_lines = split_lines(self._module_node.get_code(), keepends=True)
|
| 27 |
+
new_lines = split_lines(self.get_new_code(), keepends=True)
|
| 28 |
+
|
| 29 |
+
# Add a newline at the end if it's missing. Otherwise the diff will be
|
| 30 |
+
# very weird. A `diff -u file1 file2` would show the string:
|
| 31 |
+
#
|
| 32 |
+
#
|
| 33 |
+
#
|
| 34 |
+
# This is not necessary IMO, because Jedi does not really play with
|
| 35 |
+
# newlines and the ending newline does not really matter in Python
|
| 36 |
+
# files. ~dave
|
| 37 |
+
if old_lines[-1] != '':
|
| 38 |
+
old_lines[-1] += '\n'
|
| 39 |
+
if new_lines[-1] != '':
|
| 40 |
+
new_lines[-1] += '\n'
|
| 41 |
+
|
| 42 |
+
project_path = self._inference_state.project.path
|
| 43 |
+
if self._from_path is None:
|
| 44 |
+
from_p = ''
|
| 45 |
+
else:
|
| 46 |
+
try:
|
| 47 |
+
from_p = self._from_path.relative_to(project_path)
|
| 48 |
+
except ValueError: # Happens it the path is not on th project_path
|
| 49 |
+
from_p = self._from_path
|
| 50 |
+
if self._to_path is None:
|
| 51 |
+
to_p = ''
|
| 52 |
+
else:
|
| 53 |
+
try:
|
| 54 |
+
to_p = self._to_path.relative_to(project_path)
|
| 55 |
+
except ValueError:
|
| 56 |
+
to_p = self._to_path
|
| 57 |
+
diff = difflib.unified_diff(
|
| 58 |
+
old_lines, new_lines,
|
| 59 |
+
fromfile=str(from_p),
|
| 60 |
+
tofile=str(to_p),
|
| 61 |
+
)
|
| 62 |
+
# Apparently there's a space at the end of the diff - for whatever
|
| 63 |
+
# reason.
|
| 64 |
+
return ''.join(diff).rstrip(' ')
|
| 65 |
+
|
| 66 |
+
def get_new_code(self):
|
| 67 |
+
return self._inference_state.grammar.refactor(self._module_node, self._node_to_str_map)
|
| 68 |
+
|
| 69 |
+
def apply(self):
|
| 70 |
+
if self._from_path is None:
|
| 71 |
+
raise RefactoringError(
|
| 72 |
+
'Cannot apply a refactoring on a Script with path=None'
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
with open(self._from_path, 'w', newline='') as f:
|
| 76 |
+
f.write(self.get_new_code())
|
| 77 |
+
|
| 78 |
+
def __repr__(self):
|
| 79 |
+
return '<%s: %s>' % (self.__class__.__name__, self._from_path)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class Refactoring:
|
| 83 |
+
def __init__(self, inference_state, file_to_node_changes, renames=()):
|
| 84 |
+
self._inference_state = inference_state
|
| 85 |
+
self._renames = renames
|
| 86 |
+
self._file_to_node_changes = file_to_node_changes
|
| 87 |
+
|
| 88 |
+
def get_changed_files(self) -> Dict[Path, ChangedFile]:
|
| 89 |
+
def calculate_to_path(p):
|
| 90 |
+
if p is None:
|
| 91 |
+
return p
|
| 92 |
+
p = str(p)
|
| 93 |
+
for from_, to in renames:
|
| 94 |
+
if p.startswith(str(from_)):
|
| 95 |
+
p = str(to) + p[len(str(from_)):]
|
| 96 |
+
return Path(p)
|
| 97 |
+
|
| 98 |
+
renames = self.get_renames()
|
| 99 |
+
return {
|
| 100 |
+
path: ChangedFile(
|
| 101 |
+
self._inference_state,
|
| 102 |
+
from_path=path,
|
| 103 |
+
to_path=calculate_to_path(path),
|
| 104 |
+
module_node=next(iter(map_)).get_root_node(),
|
| 105 |
+
node_to_str_map=map_
|
| 106 |
+
)
|
| 107 |
+
# We need to use `or`, because the path can be None
|
| 108 |
+
for path, map_ in sorted(
|
| 109 |
+
self._file_to_node_changes.items(),
|
| 110 |
+
key=lambda x: x[0] or Path("")
|
| 111 |
+
)
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
def get_renames(self) -> Iterable[Tuple[Path, Path]]:
|
| 115 |
+
"""
|
| 116 |
+
Files can be renamed in a refactoring.
|
| 117 |
+
"""
|
| 118 |
+
return sorted(self._renames)
|
| 119 |
+
|
| 120 |
+
def get_diff(self):
|
| 121 |
+
text = ''
|
| 122 |
+
project_path = self._inference_state.project.path
|
| 123 |
+
for from_, to in self.get_renames():
|
| 124 |
+
text += 'rename from %s\nrename to %s\n' \
|
| 125 |
+
% (_try_relative_to(from_, project_path), _try_relative_to(to, project_path))
|
| 126 |
+
|
| 127 |
+
return text + ''.join(f.get_diff() for f in self.get_changed_files().values())
|
| 128 |
+
|
| 129 |
+
def apply(self):
|
| 130 |
+
"""
|
| 131 |
+
Applies the whole refactoring to the files, which includes renames.
|
| 132 |
+
"""
|
| 133 |
+
for f in self.get_changed_files().values():
|
| 134 |
+
f.apply()
|
| 135 |
+
|
| 136 |
+
for old, new in self.get_renames():
|
| 137 |
+
old.rename(new)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _calculate_rename(path, new_name):
|
| 141 |
+
dir_ = path.parent
|
| 142 |
+
if path.name in ('__init__.py', '__init__.pyi'):
|
| 143 |
+
return dir_, dir_.parent.joinpath(new_name)
|
| 144 |
+
return path, dir_.joinpath(new_name + path.suffix)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def rename(inference_state, definitions, new_name):
|
| 148 |
+
file_renames = set()
|
| 149 |
+
file_tree_name_map = {}
|
| 150 |
+
|
| 151 |
+
if not definitions:
|
| 152 |
+
raise RefactoringError("There is no name under the cursor")
|
| 153 |
+
|
| 154 |
+
for d in definitions:
|
| 155 |
+
# This private access is ok in a way. It's not public to
|
| 156 |
+
# protect Jedi users from seeing it.
|
| 157 |
+
tree_name = d._name.tree_name
|
| 158 |
+
if d.type == 'module' and tree_name is None and d.module_path is not None:
|
| 159 |
+
p = Path(d.module_path)
|
| 160 |
+
file_renames.add(_calculate_rename(p, new_name))
|
| 161 |
+
elif isinstance(d._name, ImplicitNSName):
|
| 162 |
+
for p in d._name._value.py__path__():
|
| 163 |
+
file_renames.add(_calculate_rename(Path(p), new_name))
|
| 164 |
+
else:
|
| 165 |
+
if tree_name is not None:
|
| 166 |
+
fmap = file_tree_name_map.setdefault(d.module_path, {})
|
| 167 |
+
fmap[tree_name] = tree_name.prefix + new_name
|
| 168 |
+
return Refactoring(inference_state, file_tree_name_map, file_renames)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def inline(inference_state, names):
|
| 172 |
+
if not names:
|
| 173 |
+
raise RefactoringError("There is no name under the cursor")
|
| 174 |
+
if any(n.api_type in ('module', 'namespace') for n in names):
|
| 175 |
+
raise RefactoringError("Cannot inline imports, modules or namespaces")
|
| 176 |
+
if any(n.tree_name is None for n in names):
|
| 177 |
+
raise RefactoringError("Cannot inline builtins/extensions")
|
| 178 |
+
|
| 179 |
+
definitions = [n for n in names if n.tree_name.is_definition()]
|
| 180 |
+
if len(definitions) == 0:
|
| 181 |
+
raise RefactoringError("No definition found to inline")
|
| 182 |
+
if len(definitions) > 1:
|
| 183 |
+
raise RefactoringError("Cannot inline a name with multiple definitions")
|
| 184 |
+
if len(names) == 1:
|
| 185 |
+
raise RefactoringError("There are no references to this name")
|
| 186 |
+
|
| 187 |
+
tree_name = definitions[0].tree_name
|
| 188 |
+
|
| 189 |
+
expr_stmt = tree_name.get_definition()
|
| 190 |
+
if expr_stmt.type != 'expr_stmt':
|
| 191 |
+
type_ = dict(
|
| 192 |
+
funcdef='function',
|
| 193 |
+
classdef='class',
|
| 194 |
+
).get(expr_stmt.type, expr_stmt.type)
|
| 195 |
+
raise RefactoringError("Cannot inline a %s" % type_)
|
| 196 |
+
|
| 197 |
+
if len(expr_stmt.get_defined_names(include_setitem=True)) > 1:
|
| 198 |
+
raise RefactoringError("Cannot inline a statement with multiple definitions")
|
| 199 |
+
first_child = expr_stmt.children[1]
|
| 200 |
+
if first_child.type == 'annassign' and len(first_child.children) == 4:
|
| 201 |
+
first_child = first_child.children[2]
|
| 202 |
+
if first_child != '=':
|
| 203 |
+
if first_child.type == 'annassign':
|
| 204 |
+
raise RefactoringError(
|
| 205 |
+
'Cannot inline a statement that is defined by an annotation'
|
| 206 |
+
)
|
| 207 |
+
else:
|
| 208 |
+
raise RefactoringError(
|
| 209 |
+
'Cannot inline a statement with "%s"'
|
| 210 |
+
% first_child.get_code(include_prefix=False)
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
rhs = expr_stmt.get_rhs()
|
| 214 |
+
replace_code = rhs.get_code(include_prefix=False)
|
| 215 |
+
|
| 216 |
+
references = [n for n in names if not n.tree_name.is_definition()]
|
| 217 |
+
file_to_node_changes = {}
|
| 218 |
+
for name in references:
|
| 219 |
+
tree_name = name.tree_name
|
| 220 |
+
path = name.get_root_context().py__file__()
|
| 221 |
+
s = replace_code
|
| 222 |
+
if rhs.type == 'testlist_star_expr' \
|
| 223 |
+
or tree_name.parent.type in EXPRESSION_PARTS \
|
| 224 |
+
or tree_name.parent.type == 'trailer' \
|
| 225 |
+
and tree_name.parent.get_next_sibling() is not None:
|
| 226 |
+
s = '(' + replace_code + ')'
|
| 227 |
+
|
| 228 |
+
of_path = file_to_node_changes.setdefault(path, {})
|
| 229 |
+
|
| 230 |
+
n = tree_name
|
| 231 |
+
prefix = n.prefix
|
| 232 |
+
par = n.parent
|
| 233 |
+
if par.type == 'trailer' and par.children[0] == '.':
|
| 234 |
+
prefix = par.parent.children[0].prefix
|
| 235 |
+
n = par
|
| 236 |
+
for some_node in par.parent.children[:par.parent.children.index(par)]:
|
| 237 |
+
of_path[some_node] = ''
|
| 238 |
+
of_path[n] = prefix + s
|
| 239 |
+
|
| 240 |
+
path = definitions[0].get_root_context().py__file__()
|
| 241 |
+
changes = file_to_node_changes.setdefault(path, {})
|
| 242 |
+
changes[expr_stmt] = _remove_indent_of_prefix(expr_stmt.get_first_leaf().prefix)
|
| 243 |
+
next_leaf = expr_stmt.get_next_leaf()
|
| 244 |
+
|
| 245 |
+
# Most of the time we have to remove the newline at the end of the
|
| 246 |
+
# statement, but if there's a comment we might not need to.
|
| 247 |
+
if next_leaf.prefix.strip(' \t') == '' \
|
| 248 |
+
and (next_leaf.type == 'newline' or next_leaf == ';'):
|
| 249 |
+
changes[next_leaf] = ''
|
| 250 |
+
return Refactoring(inference_state, file_to_node_changes)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def _remove_indent_of_prefix(prefix):
|
| 254 |
+
r"""
|
| 255 |
+
Removes the last indentation of a prefix, e.g. " \n \n " becomes " \n \n".
|
| 256 |
+
"""
|
| 257 |
+
return ''.join(split_lines(prefix, keepends=True)[:-1])
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def _try_relative_to(path: Path, base: Path) -> Path:
|
| 261 |
+
try:
|
| 262 |
+
return path.relative_to(base)
|
| 263 |
+
except ValueError:
|
| 264 |
+
return path
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/refactoring/extract.py
ADDED
|
@@ -0,0 +1,386 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from textwrap import dedent
|
| 2 |
+
|
| 3 |
+
from parso import split_lines
|
| 4 |
+
|
| 5 |
+
from jedi import debug
|
| 6 |
+
from jedi.api.exceptions import RefactoringError
|
| 7 |
+
from jedi.api.refactoring import Refactoring, EXPRESSION_PARTS
|
| 8 |
+
from jedi.common import indent_block
|
| 9 |
+
from jedi.parser_utils import function_is_classmethod, function_is_staticmethod
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
_DEFINITION_SCOPES = ('suite', 'file_input')
|
| 13 |
+
_VARIABLE_EXCTRACTABLE = EXPRESSION_PARTS + \
|
| 14 |
+
('atom testlist_star_expr testlist test lambdef lambdef_nocond '
|
| 15 |
+
'keyword name number string fstring').split()
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def extract_variable(inference_state, path, module_node, name, pos, until_pos):
|
| 19 |
+
nodes = _find_nodes(module_node, pos, until_pos)
|
| 20 |
+
debug.dbg('Extracting nodes: %s', nodes)
|
| 21 |
+
|
| 22 |
+
is_expression, message = _is_expression_with_error(nodes)
|
| 23 |
+
if not is_expression:
|
| 24 |
+
raise RefactoringError(message)
|
| 25 |
+
|
| 26 |
+
generated_code = name + ' = ' + _expression_nodes_to_string(nodes)
|
| 27 |
+
file_to_node_changes = {path: _replace(nodes, name, generated_code, pos)}
|
| 28 |
+
return Refactoring(inference_state, file_to_node_changes)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _is_expression_with_error(nodes):
|
| 32 |
+
"""
|
| 33 |
+
Returns a tuple (is_expression, error_string).
|
| 34 |
+
"""
|
| 35 |
+
if any(node.type == 'name' and node.is_definition() for node in nodes):
|
| 36 |
+
return False, 'Cannot extract a name that defines something'
|
| 37 |
+
|
| 38 |
+
if nodes[0].type not in _VARIABLE_EXCTRACTABLE:
|
| 39 |
+
return False, 'Cannot extract a "%s"' % nodes[0].type
|
| 40 |
+
return True, ''
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _find_nodes(module_node, pos, until_pos):
|
| 44 |
+
"""
|
| 45 |
+
Looks up a module and tries to find the appropriate amount of nodes that
|
| 46 |
+
are in there.
|
| 47 |
+
"""
|
| 48 |
+
start_node = module_node.get_leaf_for_position(pos, include_prefixes=True)
|
| 49 |
+
|
| 50 |
+
if until_pos is None:
|
| 51 |
+
if start_node.type == 'operator':
|
| 52 |
+
next_leaf = start_node.get_next_leaf()
|
| 53 |
+
if next_leaf is not None and next_leaf.start_pos == pos:
|
| 54 |
+
start_node = next_leaf
|
| 55 |
+
|
| 56 |
+
if _is_not_extractable_syntax(start_node):
|
| 57 |
+
start_node = start_node.parent
|
| 58 |
+
|
| 59 |
+
if start_node.parent.type == 'trailer':
|
| 60 |
+
start_node = start_node.parent.parent
|
| 61 |
+
while start_node.parent.type in EXPRESSION_PARTS:
|
| 62 |
+
start_node = start_node.parent
|
| 63 |
+
|
| 64 |
+
nodes = [start_node]
|
| 65 |
+
else:
|
| 66 |
+
# Get the next leaf if we are at the end of a leaf
|
| 67 |
+
if start_node.end_pos == pos:
|
| 68 |
+
next_leaf = start_node.get_next_leaf()
|
| 69 |
+
if next_leaf is not None:
|
| 70 |
+
start_node = next_leaf
|
| 71 |
+
|
| 72 |
+
# Some syntax is not exactable, just use its parent
|
| 73 |
+
if _is_not_extractable_syntax(start_node):
|
| 74 |
+
start_node = start_node.parent
|
| 75 |
+
|
| 76 |
+
# Find the end
|
| 77 |
+
end_leaf = module_node.get_leaf_for_position(until_pos, include_prefixes=True)
|
| 78 |
+
if end_leaf.start_pos > until_pos:
|
| 79 |
+
end_leaf = end_leaf.get_previous_leaf()
|
| 80 |
+
if end_leaf is None:
|
| 81 |
+
raise RefactoringError('Cannot extract anything from that')
|
| 82 |
+
|
| 83 |
+
parent_node = start_node
|
| 84 |
+
while parent_node.end_pos < end_leaf.end_pos:
|
| 85 |
+
parent_node = parent_node.parent
|
| 86 |
+
|
| 87 |
+
nodes = _remove_unwanted_expression_nodes(parent_node, pos, until_pos)
|
| 88 |
+
|
| 89 |
+
# If the user marks just a return statement, we return the expression
|
| 90 |
+
# instead of the whole statement, because the user obviously wants to
|
| 91 |
+
# extract that part.
|
| 92 |
+
if len(nodes) == 1 and start_node.type in ('return_stmt', 'yield_expr'):
|
| 93 |
+
return [nodes[0].children[1]]
|
| 94 |
+
return nodes
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _replace(nodes, expression_replacement, extracted, pos,
|
| 98 |
+
insert_before_leaf=None, remaining_prefix=None):
|
| 99 |
+
# Now try to replace the nodes found with a variable and move the code
|
| 100 |
+
# before the current statement.
|
| 101 |
+
definition = _get_parent_definition(nodes[0])
|
| 102 |
+
if insert_before_leaf is None:
|
| 103 |
+
insert_before_leaf = definition.get_first_leaf()
|
| 104 |
+
first_node_leaf = nodes[0].get_first_leaf()
|
| 105 |
+
|
| 106 |
+
lines = split_lines(insert_before_leaf.prefix, keepends=True)
|
| 107 |
+
if first_node_leaf is insert_before_leaf:
|
| 108 |
+
if remaining_prefix is not None:
|
| 109 |
+
# The remaining prefix has already been calculated.
|
| 110 |
+
lines[:-1] = remaining_prefix
|
| 111 |
+
lines[-1:-1] = [indent_block(extracted, lines[-1]) + '\n']
|
| 112 |
+
extracted_prefix = ''.join(lines)
|
| 113 |
+
|
| 114 |
+
replacement_dct = {}
|
| 115 |
+
if first_node_leaf is insert_before_leaf:
|
| 116 |
+
replacement_dct[nodes[0]] = extracted_prefix + expression_replacement
|
| 117 |
+
else:
|
| 118 |
+
if remaining_prefix is None:
|
| 119 |
+
p = first_node_leaf.prefix
|
| 120 |
+
else:
|
| 121 |
+
p = remaining_prefix + _get_indentation(nodes[0])
|
| 122 |
+
replacement_dct[nodes[0]] = p + expression_replacement
|
| 123 |
+
replacement_dct[insert_before_leaf] = extracted_prefix + insert_before_leaf.value
|
| 124 |
+
|
| 125 |
+
for node in nodes[1:]:
|
| 126 |
+
replacement_dct[node] = ''
|
| 127 |
+
return replacement_dct
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def _expression_nodes_to_string(nodes):
|
| 131 |
+
return ''.join(n.get_code(include_prefix=i != 0) for i, n in enumerate(nodes))
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _suite_nodes_to_string(nodes, pos):
|
| 135 |
+
n = nodes[0]
|
| 136 |
+
prefix, part_of_code = _split_prefix_at(n.get_first_leaf(), pos[0] - 1)
|
| 137 |
+
code = part_of_code + n.get_code(include_prefix=False) \
|
| 138 |
+
+ ''.join(n.get_code() for n in nodes[1:])
|
| 139 |
+
return prefix, code
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def _split_prefix_at(leaf, until_line):
|
| 143 |
+
"""
|
| 144 |
+
Returns a tuple of the leaf's prefix, split at the until_line
|
| 145 |
+
position.
|
| 146 |
+
"""
|
| 147 |
+
# second means the second returned part
|
| 148 |
+
second_line_count = leaf.start_pos[0] - until_line
|
| 149 |
+
lines = split_lines(leaf.prefix, keepends=True)
|
| 150 |
+
return ''.join(lines[:-second_line_count]), ''.join(lines[-second_line_count:])
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def _get_indentation(node):
|
| 154 |
+
return split_lines(node.get_first_leaf().prefix)[-1]
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def _get_parent_definition(node):
|
| 158 |
+
"""
|
| 159 |
+
Returns the statement where a node is defined.
|
| 160 |
+
"""
|
| 161 |
+
while node is not None:
|
| 162 |
+
if node.parent.type in _DEFINITION_SCOPES:
|
| 163 |
+
return node
|
| 164 |
+
node = node.parent
|
| 165 |
+
raise NotImplementedError('We should never even get here')
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _remove_unwanted_expression_nodes(parent_node, pos, until_pos):
|
| 169 |
+
"""
|
| 170 |
+
This function makes it so for `1 * 2 + 3` you can extract `2 + 3`, even
|
| 171 |
+
though it is not part of the expression.
|
| 172 |
+
"""
|
| 173 |
+
typ = parent_node.type
|
| 174 |
+
is_suite_part = typ in ('suite', 'file_input')
|
| 175 |
+
if typ in EXPRESSION_PARTS or is_suite_part:
|
| 176 |
+
nodes = parent_node.children
|
| 177 |
+
for i, n in enumerate(nodes):
|
| 178 |
+
if n.end_pos > pos:
|
| 179 |
+
start_index = i
|
| 180 |
+
if n.type == 'operator':
|
| 181 |
+
start_index -= 1
|
| 182 |
+
break
|
| 183 |
+
for i, n in reversed(list(enumerate(nodes))):
|
| 184 |
+
if n.start_pos < until_pos:
|
| 185 |
+
end_index = i
|
| 186 |
+
if n.type == 'operator':
|
| 187 |
+
end_index += 1
|
| 188 |
+
|
| 189 |
+
# Something like `not foo or bar` should not be cut after not
|
| 190 |
+
for n2 in nodes[i:]:
|
| 191 |
+
if _is_not_extractable_syntax(n2):
|
| 192 |
+
end_index += 1
|
| 193 |
+
else:
|
| 194 |
+
break
|
| 195 |
+
break
|
| 196 |
+
nodes = nodes[start_index:end_index + 1]
|
| 197 |
+
if not is_suite_part:
|
| 198 |
+
nodes[0:1] = _remove_unwanted_expression_nodes(nodes[0], pos, until_pos)
|
| 199 |
+
nodes[-1:] = _remove_unwanted_expression_nodes(nodes[-1], pos, until_pos)
|
| 200 |
+
return nodes
|
| 201 |
+
return [parent_node]
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def _is_not_extractable_syntax(node):
|
| 205 |
+
return node.type == 'operator' \
|
| 206 |
+
or node.type == 'keyword' and node.value not in ('None', 'True', 'False')
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def extract_function(inference_state, path, module_context, name, pos, until_pos):
|
| 210 |
+
nodes = _find_nodes(module_context.tree_node, pos, until_pos)
|
| 211 |
+
assert len(nodes)
|
| 212 |
+
|
| 213 |
+
is_expression, _ = _is_expression_with_error(nodes)
|
| 214 |
+
context = module_context.create_context(nodes[0])
|
| 215 |
+
is_bound_method = context.is_bound_method()
|
| 216 |
+
params, return_variables = list(_find_inputs_and_outputs(module_context, context, nodes))
|
| 217 |
+
|
| 218 |
+
# Find variables
|
| 219 |
+
# Is a class method / method
|
| 220 |
+
if context.is_module():
|
| 221 |
+
insert_before_leaf = None # Leaf will be determined later
|
| 222 |
+
else:
|
| 223 |
+
node = _get_code_insertion_node(context.tree_node, is_bound_method)
|
| 224 |
+
insert_before_leaf = node.get_first_leaf()
|
| 225 |
+
if is_expression:
|
| 226 |
+
code_block = 'return ' + _expression_nodes_to_string(nodes) + '\n'
|
| 227 |
+
remaining_prefix = None
|
| 228 |
+
has_ending_return_stmt = False
|
| 229 |
+
else:
|
| 230 |
+
has_ending_return_stmt = _is_node_ending_return_stmt(nodes[-1])
|
| 231 |
+
if not has_ending_return_stmt:
|
| 232 |
+
# Find the actually used variables (of the defined ones). If none are
|
| 233 |
+
# used (e.g. if the range covers the whole function), return the last
|
| 234 |
+
# defined variable.
|
| 235 |
+
return_variables = list(_find_needed_output_variables(
|
| 236 |
+
context,
|
| 237 |
+
nodes[0].parent,
|
| 238 |
+
nodes[-1].end_pos,
|
| 239 |
+
return_variables
|
| 240 |
+
)) or [return_variables[-1]] if return_variables else []
|
| 241 |
+
|
| 242 |
+
remaining_prefix, code_block = _suite_nodes_to_string(nodes, pos)
|
| 243 |
+
after_leaf = nodes[-1].get_next_leaf()
|
| 244 |
+
first, second = _split_prefix_at(after_leaf, until_pos[0])
|
| 245 |
+
code_block += first
|
| 246 |
+
|
| 247 |
+
code_block = dedent(code_block)
|
| 248 |
+
if not has_ending_return_stmt:
|
| 249 |
+
output_var_str = ', '.join(return_variables)
|
| 250 |
+
code_block += 'return ' + output_var_str + '\n'
|
| 251 |
+
|
| 252 |
+
# Check if we have to raise RefactoringError
|
| 253 |
+
_check_for_non_extractables(nodes[:-1] if has_ending_return_stmt else nodes)
|
| 254 |
+
|
| 255 |
+
decorator = ''
|
| 256 |
+
self_param = None
|
| 257 |
+
if is_bound_method:
|
| 258 |
+
if not function_is_staticmethod(context.tree_node):
|
| 259 |
+
function_param_names = context.get_value().get_param_names()
|
| 260 |
+
if len(function_param_names):
|
| 261 |
+
self_param = function_param_names[0].string_name
|
| 262 |
+
params = [p for p in params if p != self_param]
|
| 263 |
+
|
| 264 |
+
if function_is_classmethod(context.tree_node):
|
| 265 |
+
decorator = '@classmethod\n'
|
| 266 |
+
else:
|
| 267 |
+
code_block += '\n'
|
| 268 |
+
|
| 269 |
+
function_code = '%sdef %s(%s):\n%s' % (
|
| 270 |
+
decorator,
|
| 271 |
+
name,
|
| 272 |
+
', '.join(params if self_param is None else [self_param] + params),
|
| 273 |
+
indent_block(code_block)
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
function_call = '%s(%s)' % (
|
| 277 |
+
('' if self_param is None else self_param + '.') + name,
|
| 278 |
+
', '.join(params)
|
| 279 |
+
)
|
| 280 |
+
if is_expression:
|
| 281 |
+
replacement = function_call
|
| 282 |
+
else:
|
| 283 |
+
if has_ending_return_stmt:
|
| 284 |
+
replacement = 'return ' + function_call + '\n'
|
| 285 |
+
else:
|
| 286 |
+
replacement = output_var_str + ' = ' + function_call + '\n'
|
| 287 |
+
|
| 288 |
+
replacement_dct = _replace(nodes, replacement, function_code, pos,
|
| 289 |
+
insert_before_leaf, remaining_prefix)
|
| 290 |
+
if not is_expression:
|
| 291 |
+
replacement_dct[after_leaf] = second + after_leaf.value
|
| 292 |
+
file_to_node_changes = {path: replacement_dct}
|
| 293 |
+
return Refactoring(inference_state, file_to_node_changes)
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def _check_for_non_extractables(nodes):
|
| 297 |
+
for n in nodes:
|
| 298 |
+
try:
|
| 299 |
+
children = n.children
|
| 300 |
+
except AttributeError:
|
| 301 |
+
if n.value == 'return':
|
| 302 |
+
raise RefactoringError(
|
| 303 |
+
'Can only extract return statements if they are at the end.')
|
| 304 |
+
if n.value == 'yield':
|
| 305 |
+
raise RefactoringError('Cannot extract yield statements.')
|
| 306 |
+
else:
|
| 307 |
+
_check_for_non_extractables(children)
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def _is_name_input(module_context, names, first, last):
|
| 311 |
+
for name in names:
|
| 312 |
+
if name.api_type == 'param' or not name.parent_context.is_module():
|
| 313 |
+
if name.get_root_context() is not module_context:
|
| 314 |
+
return True
|
| 315 |
+
if name.start_pos is None or not (first <= name.start_pos < last):
|
| 316 |
+
return True
|
| 317 |
+
return False
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def _find_inputs_and_outputs(module_context, context, nodes):
|
| 321 |
+
first = nodes[0].start_pos
|
| 322 |
+
last = nodes[-1].end_pos
|
| 323 |
+
|
| 324 |
+
inputs = []
|
| 325 |
+
outputs = []
|
| 326 |
+
for name in _find_non_global_names(nodes):
|
| 327 |
+
if name.is_definition():
|
| 328 |
+
if name not in outputs:
|
| 329 |
+
outputs.append(name.value)
|
| 330 |
+
else:
|
| 331 |
+
if name.value not in inputs:
|
| 332 |
+
name_definitions = context.goto(name, name.start_pos)
|
| 333 |
+
if not name_definitions \
|
| 334 |
+
or _is_name_input(module_context, name_definitions, first, last):
|
| 335 |
+
inputs.append(name.value)
|
| 336 |
+
|
| 337 |
+
# Check if outputs are really needed:
|
| 338 |
+
return inputs, outputs
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def _find_non_global_names(nodes):
|
| 342 |
+
for node in nodes:
|
| 343 |
+
try:
|
| 344 |
+
children = node.children
|
| 345 |
+
except AttributeError:
|
| 346 |
+
if node.type == 'name':
|
| 347 |
+
yield node
|
| 348 |
+
else:
|
| 349 |
+
# We only want to check foo in foo.bar
|
| 350 |
+
if node.type == 'trailer' and node.children[0] == '.':
|
| 351 |
+
continue
|
| 352 |
+
|
| 353 |
+
yield from _find_non_global_names(children)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
def _get_code_insertion_node(node, is_bound_method):
|
| 357 |
+
if not is_bound_method or function_is_staticmethod(node):
|
| 358 |
+
while node.parent.type != 'file_input':
|
| 359 |
+
node = node.parent
|
| 360 |
+
|
| 361 |
+
while node.parent.type in ('async_funcdef', 'decorated', 'async_stmt'):
|
| 362 |
+
node = node.parent
|
| 363 |
+
return node
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
def _find_needed_output_variables(context, search_node, at_least_pos, return_variables):
|
| 367 |
+
"""
|
| 368 |
+
Searches everything after at_least_pos in a node and checks if any of the
|
| 369 |
+
return_variables are used in there and returns those.
|
| 370 |
+
"""
|
| 371 |
+
for node in search_node.children:
|
| 372 |
+
if node.start_pos < at_least_pos:
|
| 373 |
+
continue
|
| 374 |
+
|
| 375 |
+
return_variables = set(return_variables)
|
| 376 |
+
for name in _find_non_global_names([node]):
|
| 377 |
+
if not name.is_definition() and name.value in return_variables:
|
| 378 |
+
return_variables.remove(name.value)
|
| 379 |
+
yield name.value
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def _is_node_ending_return_stmt(node):
|
| 383 |
+
t = node.type
|
| 384 |
+
if t == 'simple_stmt':
|
| 385 |
+
return _is_node_ending_return_stmt(node.children[0])
|
| 386 |
+
return t == 'return_stmt'
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/replstartup.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
To use Jedi completion in Python interpreter, add the following in your shell
|
| 3 |
+
setup (e.g., ``.bashrc``). This works only on Linux/Mac, because readline is
|
| 4 |
+
not available on Windows. If you still want Jedi autocompletion in your REPL,
|
| 5 |
+
just use IPython instead::
|
| 6 |
+
|
| 7 |
+
export PYTHONSTARTUP="$(python -m jedi repl)"
|
| 8 |
+
|
| 9 |
+
Then you will be able to use Jedi completer in your Python interpreter::
|
| 10 |
+
|
| 11 |
+
$ python
|
| 12 |
+
Python 3.9.2+ (default, Jul 20 2020, 22:15:08)
|
| 13 |
+
[GCC 4.6.1] on linux2
|
| 14 |
+
Type "help", "copyright", "credits" or "license" for more information.
|
| 15 |
+
>>> import os
|
| 16 |
+
>>> os.path.join('a', 'b').split().in<TAB> # doctest: +SKIP
|
| 17 |
+
..dex ..sert
|
| 18 |
+
|
| 19 |
+
"""
|
| 20 |
+
import jedi.utils
|
| 21 |
+
from jedi import __version__ as __jedi_version__
|
| 22 |
+
|
| 23 |
+
print('REPL completion using Jedi %s' % __jedi_version__)
|
| 24 |
+
jedi.utils.setup_readline(fuzzy=False)
|
| 25 |
+
|
| 26 |
+
del jedi
|
| 27 |
+
|
| 28 |
+
# Note: try not to do many things here, as it will contaminate global
|
| 29 |
+
# namespace of the interpreter.
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/api/strings.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This module is here for string completions. This means mostly stuff where
|
| 3 |
+
strings are returned, like `foo = dict(bar=3); foo["ba` would complete to
|
| 4 |
+
`"bar"]`.
|
| 5 |
+
|
| 6 |
+
It however does the same for numbers. The difference between string completions
|
| 7 |
+
and other completions is mostly that this module doesn't return defined
|
| 8 |
+
names in a module, but pretty much an arbitrary string.
|
| 9 |
+
"""
|
| 10 |
+
import re
|
| 11 |
+
|
| 12 |
+
from jedi.inference.names import AbstractArbitraryName
|
| 13 |
+
from jedi.inference.helpers import infer_call_of_leaf
|
| 14 |
+
from jedi.api.classes import Completion
|
| 15 |
+
from jedi.parser_utils import cut_value_at_position
|
| 16 |
+
|
| 17 |
+
_sentinel = object()
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class StringName(AbstractArbitraryName):
|
| 21 |
+
api_type = 'string'
|
| 22 |
+
is_value_name = False
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def complete_dict(module_context, code_lines, leaf, position, string, fuzzy):
|
| 26 |
+
bracket_leaf = leaf
|
| 27 |
+
if bracket_leaf != '[':
|
| 28 |
+
bracket_leaf = leaf.get_previous_leaf()
|
| 29 |
+
|
| 30 |
+
cut_end_quote = ''
|
| 31 |
+
if string:
|
| 32 |
+
cut_end_quote = get_quote_ending(string, code_lines, position, invert_result=True)
|
| 33 |
+
|
| 34 |
+
if bracket_leaf == '[':
|
| 35 |
+
if string is None and leaf is not bracket_leaf:
|
| 36 |
+
string = cut_value_at_position(leaf, position)
|
| 37 |
+
|
| 38 |
+
context = module_context.create_context(bracket_leaf)
|
| 39 |
+
|
| 40 |
+
before_node = before_bracket_leaf = bracket_leaf.get_previous_leaf()
|
| 41 |
+
if before_node in (')', ']', '}'):
|
| 42 |
+
before_node = before_node.parent
|
| 43 |
+
if before_node.type in ('atom', 'trailer', 'name'):
|
| 44 |
+
values = infer_call_of_leaf(context, before_bracket_leaf)
|
| 45 |
+
return list(_completions_for_dicts(
|
| 46 |
+
module_context.inference_state,
|
| 47 |
+
values,
|
| 48 |
+
'' if string is None else string,
|
| 49 |
+
cut_end_quote,
|
| 50 |
+
fuzzy=fuzzy,
|
| 51 |
+
))
|
| 52 |
+
return []
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _completions_for_dicts(inference_state, dicts, literal_string, cut_end_quote, fuzzy):
|
| 56 |
+
for dict_key in sorted(_get_python_keys(dicts), key=lambda x: repr(x)):
|
| 57 |
+
dict_key_str = _create_repr_string(literal_string, dict_key)
|
| 58 |
+
if dict_key_str.startswith(literal_string):
|
| 59 |
+
name = StringName(inference_state, dict_key_str[:-len(cut_end_quote) or None])
|
| 60 |
+
yield Completion(
|
| 61 |
+
inference_state,
|
| 62 |
+
name,
|
| 63 |
+
stack=None,
|
| 64 |
+
like_name_length=len(literal_string),
|
| 65 |
+
is_fuzzy=fuzzy
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _create_repr_string(literal_string, dict_key):
|
| 70 |
+
if not isinstance(dict_key, (str, bytes)) or not literal_string:
|
| 71 |
+
return repr(dict_key)
|
| 72 |
+
|
| 73 |
+
r = repr(dict_key)
|
| 74 |
+
prefix, quote = _get_string_prefix_and_quote(literal_string)
|
| 75 |
+
if quote is None:
|
| 76 |
+
return r
|
| 77 |
+
if quote == r[0]:
|
| 78 |
+
return prefix + r
|
| 79 |
+
return prefix + quote + r[1:-1] + quote
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _get_python_keys(dicts):
|
| 83 |
+
for dct in dicts:
|
| 84 |
+
if dct.array_type == 'dict':
|
| 85 |
+
for key in dct.get_key_values():
|
| 86 |
+
dict_key = key.get_safe_value(default=_sentinel)
|
| 87 |
+
if dict_key is not _sentinel:
|
| 88 |
+
yield dict_key
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _get_string_prefix_and_quote(string):
|
| 92 |
+
match = re.match(r'(\w*)("""|\'{3}|"|\')', string)
|
| 93 |
+
if match is None:
|
| 94 |
+
return None, None
|
| 95 |
+
return match.group(1), match.group(2)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _matches_quote_at_position(code_lines, quote, position):
|
| 99 |
+
string = code_lines[position[0] - 1][position[1]:position[1] + len(quote)]
|
| 100 |
+
return string == quote
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def get_quote_ending(string, code_lines, position, invert_result=False):
|
| 104 |
+
_, quote = _get_string_prefix_and_quote(string)
|
| 105 |
+
if quote is None:
|
| 106 |
+
return ''
|
| 107 |
+
|
| 108 |
+
# Add a quote only if it's not already there.
|
| 109 |
+
if _matches_quote_at_position(code_lines, quote, position) != invert_result:
|
| 110 |
+
return ''
|
| 111 |
+
return quote
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/__init__.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Type inference of Python code in |jedi| is based on three assumptions:
|
| 3 |
+
|
| 4 |
+
* The code uses as least side effects as possible. Jedi understands certain
|
| 5 |
+
list/tuple/set modifications, but there's no guarantee that Jedi detects
|
| 6 |
+
everything (list.append in different modules for example).
|
| 7 |
+
* No magic is being used:
|
| 8 |
+
|
| 9 |
+
- metaclasses
|
| 10 |
+
- ``setattr()`` / ``__import__()``
|
| 11 |
+
- writing to ``globals()``, ``locals()``, ``object.__dict__``
|
| 12 |
+
* The programmer is not a total dick, e.g. like `this
|
| 13 |
+
<https://github.com/davidhalter/jedi/issues/24>`_ :-)
|
| 14 |
+
|
| 15 |
+
The actual algorithm is based on a principle I call lazy type inference. That
|
| 16 |
+
said, the typical entry point for static analysis is calling
|
| 17 |
+
``infer_expr_stmt``. There's separate logic for autocompletion in the API, the
|
| 18 |
+
inference_state is all about inferring an expression.
|
| 19 |
+
|
| 20 |
+
TODO this paragraph is not what jedi does anymore, it's similar, but not the
|
| 21 |
+
same.
|
| 22 |
+
|
| 23 |
+
Now you need to understand what follows after ``infer_expr_stmt``. Let's
|
| 24 |
+
make an example::
|
| 25 |
+
|
| 26 |
+
import datetime
|
| 27 |
+
datetime.date.toda# <-- cursor here
|
| 28 |
+
|
| 29 |
+
First of all, this module doesn't care about completion. It really just cares
|
| 30 |
+
about ``datetime.date``. At the end of the procedure ``infer_expr_stmt`` will
|
| 31 |
+
return the ``date`` class.
|
| 32 |
+
|
| 33 |
+
To *visualize* this (simplified):
|
| 34 |
+
|
| 35 |
+
- ``InferenceState.infer_expr_stmt`` doesn't do much, because there's no assignment.
|
| 36 |
+
- ``Context.infer_node`` cares for resolving the dotted path
|
| 37 |
+
- ``InferenceState.find_types`` searches for global definitions of datetime, which
|
| 38 |
+
it finds in the definition of an import, by scanning the syntax tree.
|
| 39 |
+
- Using the import logic, the datetime module is found.
|
| 40 |
+
- Now ``find_types`` is called again by ``infer_node`` to find ``date``
|
| 41 |
+
inside the datetime module.
|
| 42 |
+
|
| 43 |
+
Now what would happen if we wanted ``datetime.date.foo.bar``? Two more
|
| 44 |
+
calls to ``find_types``. However the second call would be ignored, because the
|
| 45 |
+
first one would return nothing (there's no foo attribute in ``date``).
|
| 46 |
+
|
| 47 |
+
What if the import would contain another ``ExprStmt`` like this::
|
| 48 |
+
|
| 49 |
+
from foo import bar
|
| 50 |
+
Date = bar.baz
|
| 51 |
+
|
| 52 |
+
Well... You get it. Just another ``infer_expr_stmt`` recursion. It's really
|
| 53 |
+
easy. Python can obviously get way more complicated then this. To understand
|
| 54 |
+
tuple assignments, list comprehensions and everything else, a lot more code had
|
| 55 |
+
to be written.
|
| 56 |
+
|
| 57 |
+
Jedi has been tested very well, so you can just start modifying code. It's best
|
| 58 |
+
to write your own test first for your "new" feature. Don't be scared of
|
| 59 |
+
breaking stuff. As long as the tests pass, you're most likely to be fine.
|
| 60 |
+
|
| 61 |
+
I need to mention now that lazy type inference is really good because it
|
| 62 |
+
only *inferes* what needs to be *inferred*. All the statements and modules
|
| 63 |
+
that are not used are just being ignored.
|
| 64 |
+
"""
|
| 65 |
+
import parso
|
| 66 |
+
from jedi.file_io import FileIO
|
| 67 |
+
|
| 68 |
+
from jedi import debug
|
| 69 |
+
from jedi import settings
|
| 70 |
+
from jedi.inference import imports
|
| 71 |
+
from jedi.inference import recursion
|
| 72 |
+
from jedi.inference.cache import inference_state_function_cache
|
| 73 |
+
from jedi.inference import helpers
|
| 74 |
+
from jedi.inference.names import TreeNameDefinition
|
| 75 |
+
from jedi.inference.base_value import ContextualizedNode, \
|
| 76 |
+
ValueSet, iterate_values
|
| 77 |
+
from jedi.inference.value import ClassValue, FunctionValue
|
| 78 |
+
from jedi.inference.syntax_tree import infer_expr_stmt, \
|
| 79 |
+
check_tuple_assignments, tree_name_to_values
|
| 80 |
+
from jedi.inference.imports import follow_error_node_imports_if_possible
|
| 81 |
+
from jedi.plugins import plugin_manager
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class InferenceState:
|
| 85 |
+
def __init__(self, project, environment=None, script_path=None):
|
| 86 |
+
if environment is None:
|
| 87 |
+
environment = project.get_environment()
|
| 88 |
+
self.environment = environment
|
| 89 |
+
self.script_path = script_path
|
| 90 |
+
self.compiled_subprocess = environment.get_inference_state_subprocess(self)
|
| 91 |
+
self.grammar = environment.get_grammar()
|
| 92 |
+
|
| 93 |
+
self.latest_grammar = parso.load_grammar(version='3.13')
|
| 94 |
+
self.memoize_cache = {} # for memoize decorators
|
| 95 |
+
self.module_cache = imports.ModuleCache() # does the job of `sys.modules`.
|
| 96 |
+
self.stub_module_cache = {} # Dict[Tuple[str, ...], Optional[ModuleValue]]
|
| 97 |
+
self.compiled_cache = {} # see `inference.compiled.create()`
|
| 98 |
+
self.inferred_element_counts = {}
|
| 99 |
+
self.mixed_cache = {} # see `inference.compiled.mixed._create()`
|
| 100 |
+
self.analysis = []
|
| 101 |
+
self.dynamic_params_depth = 0
|
| 102 |
+
self.do_dynamic_params_search = settings.dynamic_params
|
| 103 |
+
self.is_analysis = False
|
| 104 |
+
self.project = project
|
| 105 |
+
self.access_cache = {}
|
| 106 |
+
self.allow_unsafe_executions = False
|
| 107 |
+
self.flow_analysis_enabled = True
|
| 108 |
+
|
| 109 |
+
self.reset_recursion_limitations()
|
| 110 |
+
|
| 111 |
+
def import_module(self, import_names, sys_path=None, prefer_stubs=True):
|
| 112 |
+
return imports.import_module_by_names(
|
| 113 |
+
self, import_names, sys_path, prefer_stubs=prefer_stubs)
|
| 114 |
+
|
| 115 |
+
@staticmethod
|
| 116 |
+
@plugin_manager.decorate()
|
| 117 |
+
def execute(value, arguments):
|
| 118 |
+
debug.dbg('execute: %s %s', value, arguments)
|
| 119 |
+
with debug.increase_indent_cm():
|
| 120 |
+
value_set = value.py__call__(arguments=arguments)
|
| 121 |
+
debug.dbg('execute result: %s in %s', value_set, value)
|
| 122 |
+
return value_set
|
| 123 |
+
|
| 124 |
+
# mypy doesn't suppport decorated propeties (https://github.com/python/mypy/issues/1362)
|
| 125 |
+
@property # type: ignore[misc]
|
| 126 |
+
@inference_state_function_cache()
|
| 127 |
+
def builtins_module(self):
|
| 128 |
+
module_name = 'builtins'
|
| 129 |
+
builtins_module, = self.import_module((module_name,), sys_path=[])
|
| 130 |
+
return builtins_module
|
| 131 |
+
|
| 132 |
+
@property # type: ignore[misc]
|
| 133 |
+
@inference_state_function_cache()
|
| 134 |
+
def typing_module(self):
|
| 135 |
+
typing_module, = self.import_module(('typing',))
|
| 136 |
+
return typing_module
|
| 137 |
+
|
| 138 |
+
def reset_recursion_limitations(self):
|
| 139 |
+
self.recursion_detector = recursion.RecursionDetector()
|
| 140 |
+
self.execution_recursion_detector = recursion.ExecutionRecursionDetector(self)
|
| 141 |
+
|
| 142 |
+
def get_sys_path(self, **kwargs):
|
| 143 |
+
"""Convenience function"""
|
| 144 |
+
return self.project._get_sys_path(self, **kwargs)
|
| 145 |
+
|
| 146 |
+
def infer(self, context, name):
|
| 147 |
+
def_ = name.get_definition(import_name_always=True)
|
| 148 |
+
if def_ is not None:
|
| 149 |
+
type_ = def_.type
|
| 150 |
+
is_classdef = type_ == 'classdef'
|
| 151 |
+
if is_classdef or type_ == 'funcdef':
|
| 152 |
+
if is_classdef:
|
| 153 |
+
c = ClassValue(self, context, name.parent)
|
| 154 |
+
else:
|
| 155 |
+
c = FunctionValue.from_context(context, name.parent)
|
| 156 |
+
return ValueSet([c])
|
| 157 |
+
|
| 158 |
+
if type_ == 'expr_stmt':
|
| 159 |
+
is_simple_name = name.parent.type not in ('power', 'trailer')
|
| 160 |
+
if is_simple_name:
|
| 161 |
+
return infer_expr_stmt(context, def_, name)
|
| 162 |
+
if type_ == 'for_stmt':
|
| 163 |
+
container_types = context.infer_node(def_.children[3])
|
| 164 |
+
cn = ContextualizedNode(context, def_.children[3])
|
| 165 |
+
for_types = iterate_values(container_types, cn)
|
| 166 |
+
n = TreeNameDefinition(context, name)
|
| 167 |
+
return check_tuple_assignments(n, for_types)
|
| 168 |
+
if type_ in ('import_from', 'import_name'):
|
| 169 |
+
return imports.infer_import(context, name)
|
| 170 |
+
if type_ == 'with_stmt':
|
| 171 |
+
return tree_name_to_values(self, context, name)
|
| 172 |
+
elif type_ == 'param':
|
| 173 |
+
return context.py__getattribute__(name.value, position=name.end_pos)
|
| 174 |
+
elif type_ == 'namedexpr_test':
|
| 175 |
+
return context.infer_node(def_)
|
| 176 |
+
else:
|
| 177 |
+
result = follow_error_node_imports_if_possible(context, name)
|
| 178 |
+
if result is not None:
|
| 179 |
+
return result
|
| 180 |
+
|
| 181 |
+
return helpers.infer_call_of_leaf(context, name)
|
| 182 |
+
|
| 183 |
+
def parse_and_get_code(self, code=None, path=None,
|
| 184 |
+
use_latest_grammar=False, file_io=None, **kwargs):
|
| 185 |
+
if code is None:
|
| 186 |
+
if file_io is None:
|
| 187 |
+
file_io = FileIO(path)
|
| 188 |
+
code = file_io.read()
|
| 189 |
+
# We cannot just use parso, because it doesn't use errors='replace'.
|
| 190 |
+
code = parso.python_bytes_to_unicode(code, encoding='utf-8', errors='replace')
|
| 191 |
+
|
| 192 |
+
if len(code) > settings._cropped_file_size:
|
| 193 |
+
code = code[:settings._cropped_file_size]
|
| 194 |
+
|
| 195 |
+
grammar = self.latest_grammar if use_latest_grammar else self.grammar
|
| 196 |
+
return grammar.parse(code=code, path=path, file_io=file_io, **kwargs), code
|
| 197 |
+
|
| 198 |
+
def parse(self, *args, **kwargs):
|
| 199 |
+
return self.parse_and_get_code(*args, **kwargs)[0]
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/analysis.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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_string
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
CODES = {
|
| 11 |
+
'attribute-error': (1, AttributeError, 'Potential AttributeError.'),
|
| 12 |
+
'name-error': (2, NameError, 'Potential NameError.'),
|
| 13 |
+
'import-error': (3, ImportError, 'Potential ImportError.'),
|
| 14 |
+
'type-error-too-many-arguments': (4, TypeError, None),
|
| 15 |
+
'type-error-too-few-arguments': (5, TypeError, None),
|
| 16 |
+
'type-error-keyword-argument': (6, TypeError, None),
|
| 17 |
+
'type-error-multiple-values': (7, TypeError, None),
|
| 18 |
+
'type-error-star-star': (8, TypeError, None),
|
| 19 |
+
'type-error-star': (9, TypeError, None),
|
| 20 |
+
'type-error-operation': (10, TypeError, None),
|
| 21 |
+
'type-error-not-iterable': (11, TypeError, None),
|
| 22 |
+
'type-error-isinstance': (12, TypeError, None),
|
| 23 |
+
'type-error-not-subscriptable': (13, TypeError, None),
|
| 24 |
+
'value-error-too-many-values': (14, ValueError, None),
|
| 25 |
+
'value-error-too-few-values': (15, ValueError, None),
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class Error:
|
| 30 |
+
def __init__(self, name, module_path, start_pos, message=None):
|
| 31 |
+
self.path = module_path
|
| 32 |
+
self._start_pos = start_pos
|
| 33 |
+
self.name = name
|
| 34 |
+
if message is None:
|
| 35 |
+
message = CODES[self.name][2]
|
| 36 |
+
self.message = message
|
| 37 |
+
|
| 38 |
+
@property
|
| 39 |
+
def line(self):
|
| 40 |
+
return self._start_pos[0]
|
| 41 |
+
|
| 42 |
+
@property
|
| 43 |
+
def column(self):
|
| 44 |
+
return self._start_pos[1]
|
| 45 |
+
|
| 46 |
+
@property
|
| 47 |
+
def code(self):
|
| 48 |
+
# The class name start
|
| 49 |
+
first = self.__class__.__name__[0]
|
| 50 |
+
return first + str(CODES[self.name][0])
|
| 51 |
+
|
| 52 |
+
def __str__(self):
|
| 53 |
+
return '%s:%s:%s: %s %s' % (self.path, self.line, self.column,
|
| 54 |
+
self.code, self.message)
|
| 55 |
+
|
| 56 |
+
def __eq__(self, other):
|
| 57 |
+
return (self.path == other.path and self.name == other.name
|
| 58 |
+
and self._start_pos == other._start_pos)
|
| 59 |
+
|
| 60 |
+
def __ne__(self, other):
|
| 61 |
+
return not self.__eq__(other)
|
| 62 |
+
|
| 63 |
+
def __hash__(self):
|
| 64 |
+
return hash((self.path, self._start_pos, self.name))
|
| 65 |
+
|
| 66 |
+
def __repr__(self):
|
| 67 |
+
return '<%s %s: %s@%s,%s>' % (self.__class__.__name__,
|
| 68 |
+
self.name, self.path,
|
| 69 |
+
self._start_pos[0], self._start_pos[1])
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class Warning(Error):
|
| 73 |
+
pass
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def add(node_context, error_name, node, message=None, typ=Error, payload=None):
|
| 77 |
+
exception = CODES[error_name][1]
|
| 78 |
+
if _check_for_exception_catch(node_context, node, exception, payload):
|
| 79 |
+
return
|
| 80 |
+
|
| 81 |
+
# TODO this path is probably not right
|
| 82 |
+
module_context = node_context.get_root_context()
|
| 83 |
+
module_path = module_context.py__file__()
|
| 84 |
+
issue_instance = typ(error_name, module_path, node.start_pos, message)
|
| 85 |
+
debug.warning(str(issue_instance), format=False)
|
| 86 |
+
node_context.inference_state.analysis.append(issue_instance)
|
| 87 |
+
return issue_instance
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _check_for_setattr(instance):
|
| 91 |
+
"""
|
| 92 |
+
Check if there's any setattr method inside an instance. If so, return True.
|
| 93 |
+
"""
|
| 94 |
+
module = instance.get_root_context()
|
| 95 |
+
node = module.tree_node
|
| 96 |
+
if node is None:
|
| 97 |
+
# If it's a compiled module or doesn't have a tree_node
|
| 98 |
+
return False
|
| 99 |
+
|
| 100 |
+
try:
|
| 101 |
+
stmt_names = node.get_used_names()['setattr']
|
| 102 |
+
except KeyError:
|
| 103 |
+
return False
|
| 104 |
+
|
| 105 |
+
return any(node.start_pos < n.start_pos < node.end_pos
|
| 106 |
+
# Check if it's a function called setattr.
|
| 107 |
+
and not (n.parent.type == 'funcdef' and n.parent.name == n)
|
| 108 |
+
for n in stmt_names)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def add_attribute_error(name_context, lookup_value, name):
|
| 112 |
+
message = ('AttributeError: %s has no attribute %s.' % (lookup_value, name))
|
| 113 |
+
# Check for __getattr__/__getattribute__ existance and issue a warning
|
| 114 |
+
# instead of an error, if that happens.
|
| 115 |
+
typ = Error
|
| 116 |
+
if lookup_value.is_instance() and not lookup_value.is_compiled():
|
| 117 |
+
# TODO maybe make a warning for __getattr__/__getattribute__
|
| 118 |
+
|
| 119 |
+
if _check_for_setattr(lookup_value):
|
| 120 |
+
typ = Warning
|
| 121 |
+
|
| 122 |
+
payload = lookup_value, name
|
| 123 |
+
add(name_context, 'attribute-error', name, message, typ, payload)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _check_for_exception_catch(node_context, jedi_name, exception, payload=None):
|
| 127 |
+
"""
|
| 128 |
+
Checks if a jedi object (e.g. `Statement`) sits inside a try/catch and
|
| 129 |
+
doesn't count as an error (if equal to `exception`).
|
| 130 |
+
Also checks `hasattr` for AttributeErrors and uses the `payload` to compare
|
| 131 |
+
it.
|
| 132 |
+
Returns True if the exception was catched.
|
| 133 |
+
"""
|
| 134 |
+
def check_match(cls, exception):
|
| 135 |
+
if not cls.is_class():
|
| 136 |
+
return False
|
| 137 |
+
|
| 138 |
+
for python_cls in exception.mro():
|
| 139 |
+
if cls.py__name__() == python_cls.__name__ \
|
| 140 |
+
and cls.parent_context.is_builtins_module():
|
| 141 |
+
return True
|
| 142 |
+
return False
|
| 143 |
+
|
| 144 |
+
def check_try_for_except(obj, exception):
|
| 145 |
+
# Only nodes in try
|
| 146 |
+
iterator = iter(obj.children)
|
| 147 |
+
for branch_type in iterator:
|
| 148 |
+
next(iterator) # The colon
|
| 149 |
+
suite = next(iterator)
|
| 150 |
+
if branch_type == 'try' \
|
| 151 |
+
and not (branch_type.start_pos < jedi_name.start_pos <= suite.end_pos):
|
| 152 |
+
return False
|
| 153 |
+
|
| 154 |
+
for node in obj.get_except_clause_tests():
|
| 155 |
+
if node is None:
|
| 156 |
+
return True # An exception block that catches everything.
|
| 157 |
+
else:
|
| 158 |
+
except_classes = node_context.infer_node(node)
|
| 159 |
+
for cls in except_classes:
|
| 160 |
+
from jedi.inference.value import iterable
|
| 161 |
+
if isinstance(cls, iterable.Sequence) and \
|
| 162 |
+
cls.array_type == 'tuple':
|
| 163 |
+
# multiple exceptions
|
| 164 |
+
for lazy_value in cls.py__iter__():
|
| 165 |
+
for typ in lazy_value.infer():
|
| 166 |
+
if check_match(typ, exception):
|
| 167 |
+
return True
|
| 168 |
+
else:
|
| 169 |
+
if check_match(cls, exception):
|
| 170 |
+
return True
|
| 171 |
+
|
| 172 |
+
def check_hasattr(node, suite):
|
| 173 |
+
try:
|
| 174 |
+
assert suite.start_pos <= jedi_name.start_pos < suite.end_pos
|
| 175 |
+
assert node.type in ('power', 'atom_expr')
|
| 176 |
+
base = node.children[0]
|
| 177 |
+
assert base.type == 'name' and base.value == 'hasattr'
|
| 178 |
+
trailer = node.children[1]
|
| 179 |
+
assert trailer.type == 'trailer'
|
| 180 |
+
arglist = trailer.children[1]
|
| 181 |
+
assert arglist.type == 'arglist'
|
| 182 |
+
from jedi.inference.arguments import TreeArguments
|
| 183 |
+
args = TreeArguments(node_context.inference_state, node_context, arglist)
|
| 184 |
+
unpacked_args = list(args.unpack())
|
| 185 |
+
# Arguments should be very simple
|
| 186 |
+
assert len(unpacked_args) == 2
|
| 187 |
+
|
| 188 |
+
# Check name
|
| 189 |
+
key, lazy_value = unpacked_args[1]
|
| 190 |
+
names = list(lazy_value.infer())
|
| 191 |
+
assert len(names) == 1 and is_string(names[0])
|
| 192 |
+
assert names[0].get_safe_value() == payload[1].value
|
| 193 |
+
|
| 194 |
+
# Check objects
|
| 195 |
+
key, lazy_value = unpacked_args[0]
|
| 196 |
+
objects = lazy_value.infer()
|
| 197 |
+
return payload[0] in objects
|
| 198 |
+
except AssertionError:
|
| 199 |
+
return False
|
| 200 |
+
|
| 201 |
+
obj = jedi_name
|
| 202 |
+
while obj is not None and not isinstance(obj, (tree.Function, tree.Class)):
|
| 203 |
+
if isinstance(obj, tree.Flow):
|
| 204 |
+
# try/except catch check
|
| 205 |
+
if obj.type == 'try_stmt' and check_try_for_except(obj, exception):
|
| 206 |
+
return True
|
| 207 |
+
# hasattr check
|
| 208 |
+
if exception == AttributeError and obj.type in ('if_stmt', 'while_stmt'):
|
| 209 |
+
if check_hasattr(obj.children[1], obj.children[3]):
|
| 210 |
+
return True
|
| 211 |
+
obj = obj.parent
|
| 212 |
+
|
| 213 |
+
return False
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/arguments.py
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
from itertools import zip_longest
|
| 3 |
+
|
| 4 |
+
from parso.python import tree
|
| 5 |
+
|
| 6 |
+
from jedi import debug
|
| 7 |
+
from jedi.inference.utils import PushBackIterator
|
| 8 |
+
from jedi.inference import analysis
|
| 9 |
+
from jedi.inference.lazy_value import LazyKnownValue, LazyKnownValues, \
|
| 10 |
+
LazyTreeValue, get_merged_lazy_value
|
| 11 |
+
from jedi.inference.names import ParamName, TreeNameDefinition, AnonymousParamName
|
| 12 |
+
from jedi.inference.base_value import NO_VALUES, ValueSet, ContextualizedNode
|
| 13 |
+
from jedi.inference.value import iterable
|
| 14 |
+
from jedi.inference.cache import inference_state_as_method_param_cache
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def try_iter_content(types, depth=0):
|
| 18 |
+
"""Helper method for static analysis."""
|
| 19 |
+
if depth > 10:
|
| 20 |
+
# It's possible that a loop has references on itself (especially with
|
| 21 |
+
# CompiledValue). Therefore don't loop infinitely.
|
| 22 |
+
return
|
| 23 |
+
|
| 24 |
+
for typ in types:
|
| 25 |
+
try:
|
| 26 |
+
f = typ.py__iter__
|
| 27 |
+
except AttributeError:
|
| 28 |
+
pass
|
| 29 |
+
else:
|
| 30 |
+
for lazy_value in f():
|
| 31 |
+
try_iter_content(lazy_value.infer(), depth + 1)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class ParamIssue(Exception):
|
| 35 |
+
pass
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def repack_with_argument_clinic(clinic_string):
|
| 39 |
+
"""
|
| 40 |
+
Transforms a function or method with arguments to the signature that is
|
| 41 |
+
given as an argument clinic notation.
|
| 42 |
+
|
| 43 |
+
Argument clinic is part of CPython and used for all the functions that are
|
| 44 |
+
implemented in C (Python 3.7):
|
| 45 |
+
|
| 46 |
+
str.split.__text_signature__
|
| 47 |
+
# Results in: '($self, /, sep=None, maxsplit=-1)'
|
| 48 |
+
"""
|
| 49 |
+
def decorator(func):
|
| 50 |
+
def wrapper(value, arguments):
|
| 51 |
+
try:
|
| 52 |
+
args = tuple(iterate_argument_clinic(
|
| 53 |
+
value.inference_state,
|
| 54 |
+
arguments,
|
| 55 |
+
clinic_string,
|
| 56 |
+
))
|
| 57 |
+
except ParamIssue:
|
| 58 |
+
return NO_VALUES
|
| 59 |
+
else:
|
| 60 |
+
return func(value, *args)
|
| 61 |
+
|
| 62 |
+
return wrapper
|
| 63 |
+
return decorator
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def iterate_argument_clinic(inference_state, arguments, clinic_string):
|
| 67 |
+
"""Uses a list with argument clinic information (see PEP 436)."""
|
| 68 |
+
clinic_args = list(_parse_argument_clinic(clinic_string))
|
| 69 |
+
|
| 70 |
+
iterator = PushBackIterator(arguments.unpack())
|
| 71 |
+
for i, (name, optional, allow_kwargs, stars) in enumerate(clinic_args):
|
| 72 |
+
if stars == 1:
|
| 73 |
+
lazy_values = []
|
| 74 |
+
for key, argument in iterator:
|
| 75 |
+
if key is not None:
|
| 76 |
+
iterator.push_back((key, argument))
|
| 77 |
+
break
|
| 78 |
+
|
| 79 |
+
lazy_values.append(argument)
|
| 80 |
+
yield ValueSet([iterable.FakeTuple(inference_state, lazy_values)])
|
| 81 |
+
lazy_values
|
| 82 |
+
continue
|
| 83 |
+
elif stars == 2:
|
| 84 |
+
raise NotImplementedError()
|
| 85 |
+
key, argument = next(iterator, (None, None))
|
| 86 |
+
if key is not None:
|
| 87 |
+
debug.warning('Keyword arguments in argument clinic are currently not supported.')
|
| 88 |
+
raise ParamIssue
|
| 89 |
+
if argument is None and not optional:
|
| 90 |
+
debug.warning('TypeError: %s expected at least %s arguments, got %s',
|
| 91 |
+
name, len(clinic_args), i)
|
| 92 |
+
raise ParamIssue
|
| 93 |
+
|
| 94 |
+
value_set = NO_VALUES if argument is None else argument.infer()
|
| 95 |
+
|
| 96 |
+
if not value_set and not optional:
|
| 97 |
+
# For the stdlib we always want values. If we don't get them,
|
| 98 |
+
# that's ok, maybe something is too hard to resolve, however,
|
| 99 |
+
# we will not proceed with the type inference of that function.
|
| 100 |
+
debug.warning('argument_clinic "%s" not resolvable.', name)
|
| 101 |
+
raise ParamIssue
|
| 102 |
+
yield value_set
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _parse_argument_clinic(string):
|
| 106 |
+
allow_kwargs = False
|
| 107 |
+
optional = False
|
| 108 |
+
while string:
|
| 109 |
+
# Optional arguments have to begin with a bracket. And should always be
|
| 110 |
+
# at the end of the arguments. This is therefore not a proper argument
|
| 111 |
+
# clinic implementation. `range()` for exmple allows an optional start
|
| 112 |
+
# value at the beginning.
|
| 113 |
+
match = re.match(r'(?:(?:(\[),? ?|, ?|)(\**\w+)|, ?/)\]*', string)
|
| 114 |
+
string = string[len(match.group(0)):]
|
| 115 |
+
if not match.group(2): # A slash -> allow named arguments
|
| 116 |
+
allow_kwargs = True
|
| 117 |
+
continue
|
| 118 |
+
optional = optional or bool(match.group(1))
|
| 119 |
+
word = match.group(2)
|
| 120 |
+
stars = word.count('*')
|
| 121 |
+
word = word[stars:]
|
| 122 |
+
yield (word, optional, allow_kwargs, stars)
|
| 123 |
+
if stars:
|
| 124 |
+
allow_kwargs = True
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class _AbstractArgumentsMixin:
|
| 128 |
+
def unpack(self, funcdef=None):
|
| 129 |
+
raise NotImplementedError
|
| 130 |
+
|
| 131 |
+
def get_calling_nodes(self):
|
| 132 |
+
return []
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class AbstractArguments(_AbstractArgumentsMixin):
|
| 136 |
+
context = None
|
| 137 |
+
argument_node = None
|
| 138 |
+
trailer = None
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def unpack_arglist(arglist):
|
| 142 |
+
if arglist is None:
|
| 143 |
+
return
|
| 144 |
+
|
| 145 |
+
if arglist.type != 'arglist' and not (
|
| 146 |
+
arglist.type == 'argument' and arglist.children[0] in ('*', '**')):
|
| 147 |
+
yield 0, arglist
|
| 148 |
+
return
|
| 149 |
+
|
| 150 |
+
iterator = iter(arglist.children)
|
| 151 |
+
for child in iterator:
|
| 152 |
+
if child == ',':
|
| 153 |
+
continue
|
| 154 |
+
elif child in ('*', '**'):
|
| 155 |
+
c = next(iterator, None)
|
| 156 |
+
assert c is not None
|
| 157 |
+
yield len(child.value), c
|
| 158 |
+
elif child.type == 'argument' and \
|
| 159 |
+
child.children[0] in ('*', '**'):
|
| 160 |
+
assert len(child.children) == 2
|
| 161 |
+
yield len(child.children[0].value), child.children[1]
|
| 162 |
+
else:
|
| 163 |
+
yield 0, child
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class TreeArguments(AbstractArguments):
|
| 167 |
+
def __init__(self, inference_state, context, argument_node, trailer=None):
|
| 168 |
+
"""
|
| 169 |
+
:param argument_node: May be an argument_node or a list of nodes.
|
| 170 |
+
"""
|
| 171 |
+
self.argument_node = argument_node
|
| 172 |
+
self.context = context
|
| 173 |
+
self._inference_state = inference_state
|
| 174 |
+
self.trailer = trailer # Can be None, e.g. in a class definition.
|
| 175 |
+
|
| 176 |
+
@classmethod
|
| 177 |
+
@inference_state_as_method_param_cache()
|
| 178 |
+
def create_cached(cls, *args, **kwargs):
|
| 179 |
+
return cls(*args, **kwargs)
|
| 180 |
+
|
| 181 |
+
def unpack(self, funcdef=None):
|
| 182 |
+
named_args = []
|
| 183 |
+
for star_count, el in unpack_arglist(self.argument_node):
|
| 184 |
+
if star_count == 1:
|
| 185 |
+
arrays = self.context.infer_node(el)
|
| 186 |
+
iterators = [_iterate_star_args(self.context, a, el, funcdef)
|
| 187 |
+
for a in arrays]
|
| 188 |
+
for values in list(zip_longest(*iterators)):
|
| 189 |
+
yield None, get_merged_lazy_value(
|
| 190 |
+
[v for v in values if v is not None]
|
| 191 |
+
)
|
| 192 |
+
elif star_count == 2:
|
| 193 |
+
arrays = self.context.infer_node(el)
|
| 194 |
+
for dct in arrays:
|
| 195 |
+
yield from _star_star_dict(self.context, dct, el, funcdef)
|
| 196 |
+
else:
|
| 197 |
+
if el.type == 'argument':
|
| 198 |
+
c = el.children
|
| 199 |
+
if len(c) == 3: # Keyword argument.
|
| 200 |
+
named_args.append((c[0].value, LazyTreeValue(self.context, c[2]),))
|
| 201 |
+
else: # Generator comprehension.
|
| 202 |
+
# Include the brackets with the parent.
|
| 203 |
+
sync_comp_for = el.children[1]
|
| 204 |
+
if sync_comp_for.type == 'comp_for':
|
| 205 |
+
sync_comp_for = sync_comp_for.children[1]
|
| 206 |
+
comp = iterable.GeneratorComprehension(
|
| 207 |
+
self._inference_state,
|
| 208 |
+
defining_context=self.context,
|
| 209 |
+
sync_comp_for_node=sync_comp_for,
|
| 210 |
+
entry_node=el.children[0],
|
| 211 |
+
)
|
| 212 |
+
yield None, LazyKnownValue(comp)
|
| 213 |
+
else:
|
| 214 |
+
yield None, LazyTreeValue(self.context, el)
|
| 215 |
+
|
| 216 |
+
# Reordering arguments is necessary, because star args sometimes appear
|
| 217 |
+
# after named argument, but in the actual order it's prepended.
|
| 218 |
+
yield from named_args
|
| 219 |
+
|
| 220 |
+
def _as_tree_tuple_objects(self):
|
| 221 |
+
for star_count, argument in unpack_arglist(self.argument_node):
|
| 222 |
+
default = None
|
| 223 |
+
if argument.type == 'argument':
|
| 224 |
+
if len(argument.children) == 3: # Keyword argument.
|
| 225 |
+
argument, default = argument.children[::2]
|
| 226 |
+
yield argument, default, star_count
|
| 227 |
+
|
| 228 |
+
def iter_calling_names_with_star(self):
|
| 229 |
+
for name, default, star_count in self._as_tree_tuple_objects():
|
| 230 |
+
# TODO this function is a bit strange. probably refactor?
|
| 231 |
+
if not star_count or not isinstance(name, tree.Name):
|
| 232 |
+
continue
|
| 233 |
+
|
| 234 |
+
yield TreeNameDefinition(self.context, name)
|
| 235 |
+
|
| 236 |
+
def __repr__(self):
|
| 237 |
+
return '<%s: %s>' % (self.__class__.__name__, self.argument_node)
|
| 238 |
+
|
| 239 |
+
def get_calling_nodes(self):
|
| 240 |
+
old_arguments_list = []
|
| 241 |
+
arguments = self
|
| 242 |
+
|
| 243 |
+
while arguments not in old_arguments_list:
|
| 244 |
+
if not isinstance(arguments, TreeArguments):
|
| 245 |
+
break
|
| 246 |
+
|
| 247 |
+
old_arguments_list.append(arguments)
|
| 248 |
+
for calling_name in reversed(list(arguments.iter_calling_names_with_star())):
|
| 249 |
+
names = calling_name.goto()
|
| 250 |
+
if len(names) != 1:
|
| 251 |
+
break
|
| 252 |
+
if isinstance(names[0], AnonymousParamName):
|
| 253 |
+
# Dynamic parameters should not have calling nodes, because
|
| 254 |
+
# they are dynamic and extremely random.
|
| 255 |
+
return []
|
| 256 |
+
if not isinstance(names[0], ParamName):
|
| 257 |
+
break
|
| 258 |
+
executed_param_name = names[0].get_executed_param_name()
|
| 259 |
+
arguments = executed_param_name.arguments
|
| 260 |
+
break
|
| 261 |
+
|
| 262 |
+
if arguments.argument_node is not None:
|
| 263 |
+
return [ContextualizedNode(arguments.context, arguments.argument_node)]
|
| 264 |
+
if arguments.trailer is not None:
|
| 265 |
+
return [ContextualizedNode(arguments.context, arguments.trailer)]
|
| 266 |
+
return []
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
class ValuesArguments(AbstractArguments):
|
| 270 |
+
def __init__(self, values_list):
|
| 271 |
+
self._values_list = values_list
|
| 272 |
+
|
| 273 |
+
def unpack(self, funcdef=None):
|
| 274 |
+
for values in self._values_list:
|
| 275 |
+
yield None, LazyKnownValues(values)
|
| 276 |
+
|
| 277 |
+
def __repr__(self):
|
| 278 |
+
return '<%s: %s>' % (self.__class__.__name__, self._values_list)
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
class TreeArgumentsWrapper(_AbstractArgumentsMixin):
|
| 282 |
+
def __init__(self, arguments):
|
| 283 |
+
self._wrapped_arguments = arguments
|
| 284 |
+
|
| 285 |
+
@property
|
| 286 |
+
def context(self):
|
| 287 |
+
return self._wrapped_arguments.context
|
| 288 |
+
|
| 289 |
+
@property
|
| 290 |
+
def argument_node(self):
|
| 291 |
+
return self._wrapped_arguments.argument_node
|
| 292 |
+
|
| 293 |
+
@property
|
| 294 |
+
def trailer(self):
|
| 295 |
+
return self._wrapped_arguments.trailer
|
| 296 |
+
|
| 297 |
+
def unpack(self, func=None):
|
| 298 |
+
raise NotImplementedError
|
| 299 |
+
|
| 300 |
+
def get_calling_nodes(self):
|
| 301 |
+
return self._wrapped_arguments.get_calling_nodes()
|
| 302 |
+
|
| 303 |
+
def __repr__(self):
|
| 304 |
+
return '<%s: %s>' % (self.__class__.__name__, self._wrapped_arguments)
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def _iterate_star_args(context, array, input_node, funcdef=None):
|
| 308 |
+
if not array.py__getattribute__('__iter__'):
|
| 309 |
+
if funcdef is not None:
|
| 310 |
+
# TODO this funcdef should not be needed.
|
| 311 |
+
m = "TypeError: %s() argument after * must be a sequence, not %s" \
|
| 312 |
+
% (funcdef.name.value, array)
|
| 313 |
+
analysis.add(context, 'type-error-star', input_node, message=m)
|
| 314 |
+
try:
|
| 315 |
+
iter_ = array.py__iter__
|
| 316 |
+
except AttributeError:
|
| 317 |
+
pass
|
| 318 |
+
else:
|
| 319 |
+
yield from iter_()
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def _star_star_dict(context, array, input_node, funcdef):
|
| 323 |
+
from jedi.inference.value.instance import CompiledInstance
|
| 324 |
+
if isinstance(array, CompiledInstance) and array.name.string_name == 'dict':
|
| 325 |
+
# For now ignore this case. In the future add proper iterators and just
|
| 326 |
+
# make one call without crazy isinstance checks.
|
| 327 |
+
return {}
|
| 328 |
+
elif isinstance(array, iterable.Sequence) and array.array_type == 'dict':
|
| 329 |
+
return array.exact_key_items()
|
| 330 |
+
else:
|
| 331 |
+
if funcdef is not None:
|
| 332 |
+
m = "TypeError: %s argument after ** must be a mapping, not %s" \
|
| 333 |
+
% (funcdef.name.value, array)
|
| 334 |
+
analysis.add(context, 'type-error-star-star', input_node, message=m)
|
| 335 |
+
return {}
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/base_value.py
ADDED
|
@@ -0,0 +1,558 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Values are the "values" that Python would return. However Values are at the
|
| 3 |
+
same time also the "values" that a user is currently sitting in.
|
| 4 |
+
|
| 5 |
+
A ValueSet is typically used to specify the return of a function or any other
|
| 6 |
+
static analysis operation. In jedi there are always multiple returns and not
|
| 7 |
+
just one.
|
| 8 |
+
"""
|
| 9 |
+
from functools import reduce
|
| 10 |
+
from operator import add
|
| 11 |
+
from itertools import zip_longest
|
| 12 |
+
|
| 13 |
+
from parso.python.tree import Name
|
| 14 |
+
|
| 15 |
+
from jedi import debug
|
| 16 |
+
from jedi.parser_utils import clean_scope_docstring
|
| 17 |
+
from jedi.inference.helpers import SimpleGetItemNotFound
|
| 18 |
+
from jedi.inference.utils import safe_property
|
| 19 |
+
from jedi.inference.cache import inference_state_as_method_param_cache
|
| 20 |
+
from jedi.cache import memoize_method
|
| 21 |
+
|
| 22 |
+
sentinel = object()
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class HasNoContext(Exception):
|
| 26 |
+
pass
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class HelperValueMixin:
|
| 30 |
+
def get_root_context(self):
|
| 31 |
+
value = self
|
| 32 |
+
if value.parent_context is None:
|
| 33 |
+
return value.as_context()
|
| 34 |
+
|
| 35 |
+
while True:
|
| 36 |
+
if value.parent_context is None:
|
| 37 |
+
return value
|
| 38 |
+
value = value.parent_context
|
| 39 |
+
|
| 40 |
+
def execute(self, arguments):
|
| 41 |
+
return self.inference_state.execute(self, arguments=arguments)
|
| 42 |
+
|
| 43 |
+
def execute_with_values(self, *value_list):
|
| 44 |
+
from jedi.inference.arguments import ValuesArguments
|
| 45 |
+
arguments = ValuesArguments([ValueSet([value]) for value in value_list])
|
| 46 |
+
return self.inference_state.execute(self, arguments)
|
| 47 |
+
|
| 48 |
+
def execute_annotation(self):
|
| 49 |
+
return self.execute_with_values()
|
| 50 |
+
|
| 51 |
+
def gather_annotation_classes(self):
|
| 52 |
+
return ValueSet([self])
|
| 53 |
+
|
| 54 |
+
def merge_types_of_iterate(self, contextualized_node=None, is_async=False):
|
| 55 |
+
return ValueSet.from_sets(
|
| 56 |
+
lazy_value.infer()
|
| 57 |
+
for lazy_value in self.iterate(contextualized_node, is_async)
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
def _get_value_filters(self, name_or_str):
|
| 61 |
+
origin_scope = name_or_str if isinstance(name_or_str, Name) else None
|
| 62 |
+
yield from self.get_filters(origin_scope=origin_scope)
|
| 63 |
+
# This covers the case where a stub files are incomplete.
|
| 64 |
+
if self.is_stub():
|
| 65 |
+
from jedi.inference.gradual.conversion import convert_values
|
| 66 |
+
for c in convert_values(ValueSet({self})):
|
| 67 |
+
yield from c.get_filters()
|
| 68 |
+
|
| 69 |
+
def goto(self, name_or_str, name_context=None, analysis_errors=True):
|
| 70 |
+
from jedi.inference import finder
|
| 71 |
+
filters = self._get_value_filters(name_or_str)
|
| 72 |
+
names = finder.filter_name(filters, name_or_str)
|
| 73 |
+
debug.dbg('context.goto %s in (%s): %s', name_or_str, self, names)
|
| 74 |
+
return names
|
| 75 |
+
|
| 76 |
+
def py__getattribute__(self, name_or_str, name_context=None, position=None,
|
| 77 |
+
analysis_errors=True):
|
| 78 |
+
"""
|
| 79 |
+
:param position: Position of the last statement -> tuple of line, column
|
| 80 |
+
"""
|
| 81 |
+
if name_context is None:
|
| 82 |
+
name_context = self
|
| 83 |
+
names = self.goto(name_or_str, name_context, analysis_errors)
|
| 84 |
+
values = ValueSet.from_sets(name.infer() for name in names)
|
| 85 |
+
if not values:
|
| 86 |
+
n = name_or_str.value if isinstance(name_or_str, Name) else name_or_str
|
| 87 |
+
values = self.py__getattribute__alternatives(n)
|
| 88 |
+
|
| 89 |
+
if not names and not values and analysis_errors:
|
| 90 |
+
if isinstance(name_or_str, Name):
|
| 91 |
+
from jedi.inference import analysis
|
| 92 |
+
analysis.add_attribute_error(
|
| 93 |
+
name_context, self, name_or_str)
|
| 94 |
+
debug.dbg('context.names_to_types: %s -> %s', names, values)
|
| 95 |
+
return values
|
| 96 |
+
|
| 97 |
+
def py__await__(self):
|
| 98 |
+
await_value_set = self.py__getattribute__("__await__")
|
| 99 |
+
if not await_value_set:
|
| 100 |
+
debug.warning('Tried to run __await__ on value %s', self)
|
| 101 |
+
return await_value_set.execute_with_values()
|
| 102 |
+
|
| 103 |
+
def py__name__(self):
|
| 104 |
+
return self.name.string_name
|
| 105 |
+
|
| 106 |
+
def iterate(self, contextualized_node=None, is_async=False):
|
| 107 |
+
debug.dbg('iterate %s', self)
|
| 108 |
+
if is_async:
|
| 109 |
+
from jedi.inference.lazy_value import LazyKnownValues
|
| 110 |
+
# TODO if no __aiter__ values are there, error should be:
|
| 111 |
+
# TypeError: 'async for' requires an object with __aiter__ method, got int
|
| 112 |
+
return iter([
|
| 113 |
+
LazyKnownValues(
|
| 114 |
+
self.py__getattribute__('__aiter__').execute_with_values()
|
| 115 |
+
.py__getattribute__('__anext__').execute_with_values()
|
| 116 |
+
.py__getattribute__('__await__').execute_with_values()
|
| 117 |
+
.py__stop_iteration_returns()
|
| 118 |
+
) # noqa: E124
|
| 119 |
+
])
|
| 120 |
+
return self.py__iter__(contextualized_node)
|
| 121 |
+
|
| 122 |
+
def is_sub_class_of(self, class_value):
|
| 123 |
+
with debug.increase_indent_cm('subclass matching of %s <=> %s' % (self, class_value),
|
| 124 |
+
color='BLUE'):
|
| 125 |
+
for cls in self.py__mro__():
|
| 126 |
+
if cls.is_same_class(class_value):
|
| 127 |
+
debug.dbg('matched subclass True', color='BLUE')
|
| 128 |
+
return True
|
| 129 |
+
debug.dbg('matched subclass False', color='BLUE')
|
| 130 |
+
return False
|
| 131 |
+
|
| 132 |
+
def is_same_class(self, class2):
|
| 133 |
+
# Class matching should prefer comparisons that are not this function.
|
| 134 |
+
if type(class2).is_same_class != HelperValueMixin.is_same_class:
|
| 135 |
+
return class2.is_same_class(self)
|
| 136 |
+
return self == class2
|
| 137 |
+
|
| 138 |
+
@memoize_method
|
| 139 |
+
def as_context(self, *args, **kwargs):
|
| 140 |
+
return self._as_context(*args, **kwargs)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class Value(HelperValueMixin):
|
| 144 |
+
"""
|
| 145 |
+
To be implemented by subclasses.
|
| 146 |
+
"""
|
| 147 |
+
tree_node = None
|
| 148 |
+
# Possible values: None, tuple, list, dict and set. Here to deal with these
|
| 149 |
+
# very important containers.
|
| 150 |
+
array_type = None
|
| 151 |
+
api_type = 'not_defined_please_report_bug'
|
| 152 |
+
|
| 153 |
+
def __init__(self, inference_state, parent_context=None):
|
| 154 |
+
self.inference_state = inference_state
|
| 155 |
+
self.parent_context = parent_context
|
| 156 |
+
|
| 157 |
+
def py__getitem__(self, index_value_set, contextualized_node):
|
| 158 |
+
from jedi.inference import analysis
|
| 159 |
+
# TODO this value is probably not right.
|
| 160 |
+
analysis.add(
|
| 161 |
+
contextualized_node.context,
|
| 162 |
+
'type-error-not-subscriptable',
|
| 163 |
+
contextualized_node.node,
|
| 164 |
+
message="TypeError: '%s' object is not subscriptable" % self
|
| 165 |
+
)
|
| 166 |
+
return NO_VALUES
|
| 167 |
+
|
| 168 |
+
def py__simple_getitem__(self, index):
|
| 169 |
+
raise SimpleGetItemNotFound
|
| 170 |
+
|
| 171 |
+
def py__iter__(self, contextualized_node=None):
|
| 172 |
+
if contextualized_node is not None:
|
| 173 |
+
from jedi.inference import analysis
|
| 174 |
+
analysis.add(
|
| 175 |
+
contextualized_node.context,
|
| 176 |
+
'type-error-not-iterable',
|
| 177 |
+
contextualized_node.node,
|
| 178 |
+
message="TypeError: '%s' object is not iterable" % self)
|
| 179 |
+
return iter([])
|
| 180 |
+
|
| 181 |
+
def py__next__(self, contextualized_node=None):
|
| 182 |
+
return self.py__iter__(contextualized_node)
|
| 183 |
+
|
| 184 |
+
def get_signatures(self):
|
| 185 |
+
return []
|
| 186 |
+
|
| 187 |
+
def is_class(self):
|
| 188 |
+
return False
|
| 189 |
+
|
| 190 |
+
def is_class_mixin(self):
|
| 191 |
+
return False
|
| 192 |
+
|
| 193 |
+
def is_instance(self):
|
| 194 |
+
return False
|
| 195 |
+
|
| 196 |
+
def is_function(self):
|
| 197 |
+
return False
|
| 198 |
+
|
| 199 |
+
def is_module(self):
|
| 200 |
+
return False
|
| 201 |
+
|
| 202 |
+
def is_namespace(self):
|
| 203 |
+
return False
|
| 204 |
+
|
| 205 |
+
def is_compiled(self):
|
| 206 |
+
return False
|
| 207 |
+
|
| 208 |
+
def is_bound_method(self):
|
| 209 |
+
return False
|
| 210 |
+
|
| 211 |
+
def is_builtins_module(self):
|
| 212 |
+
return False
|
| 213 |
+
|
| 214 |
+
def py__bool__(self):
|
| 215 |
+
"""
|
| 216 |
+
Since Wrapper is a super class for classes, functions and modules,
|
| 217 |
+
the return value will always be true.
|
| 218 |
+
"""
|
| 219 |
+
return True
|
| 220 |
+
|
| 221 |
+
def py__doc__(self):
|
| 222 |
+
try:
|
| 223 |
+
self.tree_node.get_doc_node
|
| 224 |
+
except AttributeError:
|
| 225 |
+
return ''
|
| 226 |
+
else:
|
| 227 |
+
return clean_scope_docstring(self.tree_node)
|
| 228 |
+
|
| 229 |
+
def get_safe_value(self, default=sentinel):
|
| 230 |
+
if default is sentinel:
|
| 231 |
+
raise ValueError("There exists no safe value for value %s" % self)
|
| 232 |
+
return default
|
| 233 |
+
|
| 234 |
+
def execute_operation(self, other, operator):
|
| 235 |
+
debug.warning("%s not possible between %s and %s", operator, self, other)
|
| 236 |
+
return NO_VALUES
|
| 237 |
+
|
| 238 |
+
def py__call__(self, arguments):
|
| 239 |
+
debug.warning("no execution possible %s", self)
|
| 240 |
+
return NO_VALUES
|
| 241 |
+
|
| 242 |
+
def py__stop_iteration_returns(self):
|
| 243 |
+
debug.warning("Not possible to return the stop iterations of %s", self)
|
| 244 |
+
return NO_VALUES
|
| 245 |
+
|
| 246 |
+
def py__getattribute__alternatives(self, name_or_str):
|
| 247 |
+
"""
|
| 248 |
+
For now a way to add values in cases like __getattr__.
|
| 249 |
+
"""
|
| 250 |
+
return NO_VALUES
|
| 251 |
+
|
| 252 |
+
def py__get__(self, instance, class_value):
|
| 253 |
+
debug.warning("No __get__ defined on %s", self)
|
| 254 |
+
return ValueSet([self])
|
| 255 |
+
|
| 256 |
+
def py__get__on_class(self, calling_instance, instance, class_value):
|
| 257 |
+
return NotImplemented
|
| 258 |
+
|
| 259 |
+
def get_qualified_names(self):
|
| 260 |
+
# Returns Optional[Tuple[str, ...]]
|
| 261 |
+
return None
|
| 262 |
+
|
| 263 |
+
def is_stub(self):
|
| 264 |
+
# The root value knows if it's a stub or not.
|
| 265 |
+
return self.parent_context.is_stub()
|
| 266 |
+
|
| 267 |
+
def _as_context(self):
|
| 268 |
+
raise HasNoContext
|
| 269 |
+
|
| 270 |
+
@property
|
| 271 |
+
def name(self):
|
| 272 |
+
raise NotImplementedError
|
| 273 |
+
|
| 274 |
+
def get_type_hint(self, add_class_info=True):
|
| 275 |
+
return None
|
| 276 |
+
|
| 277 |
+
def infer_type_vars(self, value_set):
|
| 278 |
+
"""
|
| 279 |
+
When the current instance represents a type annotation, this method
|
| 280 |
+
tries to find information about undefined type vars and returns a dict
|
| 281 |
+
from type var name to value set.
|
| 282 |
+
|
| 283 |
+
This is for example important to understand what `iter([1])` returns.
|
| 284 |
+
According to typeshed, `iter` returns an `Iterator[_T]`:
|
| 285 |
+
|
| 286 |
+
def iter(iterable: Iterable[_T]) -> Iterator[_T]: ...
|
| 287 |
+
|
| 288 |
+
This functions would generate `int` for `_T` in this case, because it
|
| 289 |
+
unpacks the `Iterable`.
|
| 290 |
+
|
| 291 |
+
Parameters
|
| 292 |
+
----------
|
| 293 |
+
|
| 294 |
+
`self`: represents the annotation of the current parameter to infer the
|
| 295 |
+
value for. In the above example, this would initially be the
|
| 296 |
+
`Iterable[_T]` of the `iterable` parameter and then, when recursing,
|
| 297 |
+
just the `_T` generic parameter.
|
| 298 |
+
|
| 299 |
+
`value_set`: represents the actual argument passed to the parameter
|
| 300 |
+
we're inferred for, or (for recursive calls) their types. In the
|
| 301 |
+
above example this would first be the representation of the list
|
| 302 |
+
`[1]` and then, when recursing, just of `1`.
|
| 303 |
+
"""
|
| 304 |
+
return {}
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def iterate_values(values, contextualized_node=None, is_async=False):
|
| 308 |
+
"""
|
| 309 |
+
Calls `iterate`, on all values but ignores the ordering and just returns
|
| 310 |
+
all values that the iterate functions yield.
|
| 311 |
+
"""
|
| 312 |
+
return ValueSet.from_sets(
|
| 313 |
+
lazy_value.infer()
|
| 314 |
+
for lazy_value in values.iterate(contextualized_node, is_async=is_async)
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
class _ValueWrapperBase(HelperValueMixin):
|
| 319 |
+
@safe_property
|
| 320 |
+
def name(self):
|
| 321 |
+
from jedi.inference.names import ValueName
|
| 322 |
+
wrapped_name = self._wrapped_value.name
|
| 323 |
+
if wrapped_name.tree_name is not None:
|
| 324 |
+
return ValueName(self, wrapped_name.tree_name)
|
| 325 |
+
else:
|
| 326 |
+
from jedi.inference.compiled import CompiledValueName
|
| 327 |
+
return CompiledValueName(self, wrapped_name.string_name)
|
| 328 |
+
|
| 329 |
+
@classmethod
|
| 330 |
+
@inference_state_as_method_param_cache()
|
| 331 |
+
def create_cached(cls, inference_state, *args, **kwargs):
|
| 332 |
+
return cls(*args, **kwargs)
|
| 333 |
+
|
| 334 |
+
def __getattr__(self, name):
|
| 335 |
+
assert name != '_wrapped_value', 'Problem with _get_wrapped_value'
|
| 336 |
+
return getattr(self._wrapped_value, name)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
class LazyValueWrapper(_ValueWrapperBase):
|
| 340 |
+
@safe_property
|
| 341 |
+
@memoize_method
|
| 342 |
+
def _wrapped_value(self):
|
| 343 |
+
with debug.increase_indent_cm('Resolve lazy value wrapper'):
|
| 344 |
+
return self._get_wrapped_value()
|
| 345 |
+
|
| 346 |
+
def __repr__(self):
|
| 347 |
+
return '<%s>' % (self.__class__.__name__)
|
| 348 |
+
|
| 349 |
+
def _get_wrapped_value(self):
|
| 350 |
+
raise NotImplementedError
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
class ValueWrapper(_ValueWrapperBase):
|
| 354 |
+
def __init__(self, wrapped_value):
|
| 355 |
+
self._wrapped_value = wrapped_value
|
| 356 |
+
|
| 357 |
+
def __repr__(self):
|
| 358 |
+
return '%s(%s)' % (self.__class__.__name__, self._wrapped_value)
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
class TreeValue(Value):
|
| 362 |
+
def __init__(self, inference_state, parent_context, tree_node):
|
| 363 |
+
super().__init__(inference_state, parent_context)
|
| 364 |
+
self.tree_node = tree_node
|
| 365 |
+
|
| 366 |
+
def __repr__(self):
|
| 367 |
+
return '<%s: %s>' % (self.__class__.__name__, self.tree_node)
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
class ContextualizedNode:
|
| 371 |
+
def __init__(self, context, node):
|
| 372 |
+
self.context = context
|
| 373 |
+
self.node = node
|
| 374 |
+
|
| 375 |
+
def get_root_context(self):
|
| 376 |
+
return self.context.get_root_context()
|
| 377 |
+
|
| 378 |
+
def infer(self):
|
| 379 |
+
return self.context.infer_node(self.node)
|
| 380 |
+
|
| 381 |
+
def __repr__(self):
|
| 382 |
+
return '<%s: %s in %s>' % (self.__class__.__name__, self.node, self.context)
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def _getitem(value, index_values, contextualized_node):
|
| 386 |
+
# The actual getitem call.
|
| 387 |
+
result = NO_VALUES
|
| 388 |
+
unused_values = set()
|
| 389 |
+
for index_value in index_values:
|
| 390 |
+
index = index_value.get_safe_value(default=None)
|
| 391 |
+
if type(index) in (float, int, str, slice, bytes):
|
| 392 |
+
try:
|
| 393 |
+
result |= value.py__simple_getitem__(index)
|
| 394 |
+
continue
|
| 395 |
+
except SimpleGetItemNotFound:
|
| 396 |
+
pass
|
| 397 |
+
|
| 398 |
+
unused_values.add(index_value)
|
| 399 |
+
|
| 400 |
+
# The index was somehow not good enough or simply a wrong type.
|
| 401 |
+
# Therefore we now iterate through all the values and just take
|
| 402 |
+
# all results.
|
| 403 |
+
if unused_values or not index_values:
|
| 404 |
+
result |= value.py__getitem__(
|
| 405 |
+
ValueSet(unused_values),
|
| 406 |
+
contextualized_node
|
| 407 |
+
)
|
| 408 |
+
debug.dbg('py__getitem__ result: %s', result)
|
| 409 |
+
return result
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
class ValueSet:
|
| 413 |
+
def __init__(self, iterable):
|
| 414 |
+
self._set = frozenset(iterable)
|
| 415 |
+
for value in iterable:
|
| 416 |
+
assert not isinstance(value, ValueSet)
|
| 417 |
+
|
| 418 |
+
@classmethod
|
| 419 |
+
def _from_frozen_set(cls, frozenset_):
|
| 420 |
+
self = cls.__new__(cls)
|
| 421 |
+
self._set = frozenset_
|
| 422 |
+
return self
|
| 423 |
+
|
| 424 |
+
@classmethod
|
| 425 |
+
def from_sets(cls, sets):
|
| 426 |
+
"""
|
| 427 |
+
Used to work with an iterable of set.
|
| 428 |
+
"""
|
| 429 |
+
aggregated = set()
|
| 430 |
+
for set_ in sets:
|
| 431 |
+
if isinstance(set_, ValueSet):
|
| 432 |
+
aggregated |= set_._set
|
| 433 |
+
else:
|
| 434 |
+
aggregated |= frozenset(set_)
|
| 435 |
+
return cls._from_frozen_set(frozenset(aggregated))
|
| 436 |
+
|
| 437 |
+
def __or__(self, other):
|
| 438 |
+
return self._from_frozen_set(self._set | other._set)
|
| 439 |
+
|
| 440 |
+
def __and__(self, other):
|
| 441 |
+
return self._from_frozen_set(self._set & other._set)
|
| 442 |
+
|
| 443 |
+
def __iter__(self):
|
| 444 |
+
return iter(self._set)
|
| 445 |
+
|
| 446 |
+
def __bool__(self):
|
| 447 |
+
return bool(self._set)
|
| 448 |
+
|
| 449 |
+
def __len__(self):
|
| 450 |
+
return len(self._set)
|
| 451 |
+
|
| 452 |
+
def __repr__(self):
|
| 453 |
+
return 'S{%s}' % (', '.join(str(s) for s in self._set))
|
| 454 |
+
|
| 455 |
+
def filter(self, filter_func):
|
| 456 |
+
return self.__class__(filter(filter_func, self._set))
|
| 457 |
+
|
| 458 |
+
def __getattr__(self, name):
|
| 459 |
+
def mapper(*args, **kwargs):
|
| 460 |
+
return self.from_sets(
|
| 461 |
+
getattr(value, name)(*args, **kwargs)
|
| 462 |
+
for value in self._set
|
| 463 |
+
)
|
| 464 |
+
return mapper
|
| 465 |
+
|
| 466 |
+
def __eq__(self, other):
|
| 467 |
+
return self._set == other._set
|
| 468 |
+
|
| 469 |
+
def __ne__(self, other):
|
| 470 |
+
return not self.__eq__(other)
|
| 471 |
+
|
| 472 |
+
def __hash__(self):
|
| 473 |
+
return hash(self._set)
|
| 474 |
+
|
| 475 |
+
def py__class__(self):
|
| 476 |
+
return ValueSet(c.py__class__() for c in self._set)
|
| 477 |
+
|
| 478 |
+
def iterate(self, contextualized_node=None, is_async=False):
|
| 479 |
+
from jedi.inference.lazy_value import get_merged_lazy_value
|
| 480 |
+
type_iters = [c.iterate(contextualized_node, is_async=is_async) for c in self._set]
|
| 481 |
+
for lazy_values in zip_longest(*type_iters):
|
| 482 |
+
yield get_merged_lazy_value(
|
| 483 |
+
[l for l in lazy_values if l is not None]
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
def execute(self, arguments):
|
| 487 |
+
return ValueSet.from_sets(c.inference_state.execute(c, arguments) for c in self._set)
|
| 488 |
+
|
| 489 |
+
def execute_with_values(self, *args, **kwargs):
|
| 490 |
+
return ValueSet.from_sets(c.execute_with_values(*args, **kwargs) for c in self._set)
|
| 491 |
+
|
| 492 |
+
def goto(self, *args, **kwargs):
|
| 493 |
+
return reduce(add, [c.goto(*args, **kwargs) for c in self._set], [])
|
| 494 |
+
|
| 495 |
+
def py__getattribute__(self, *args, **kwargs):
|
| 496 |
+
return ValueSet.from_sets(c.py__getattribute__(*args, **kwargs) for c in self._set)
|
| 497 |
+
|
| 498 |
+
def get_item(self, *args, **kwargs):
|
| 499 |
+
return ValueSet.from_sets(_getitem(c, *args, **kwargs) for c in self._set)
|
| 500 |
+
|
| 501 |
+
def try_merge(self, function_name):
|
| 502 |
+
value_set = self.__class__([])
|
| 503 |
+
for c in self._set:
|
| 504 |
+
try:
|
| 505 |
+
method = getattr(c, function_name)
|
| 506 |
+
except AttributeError:
|
| 507 |
+
pass
|
| 508 |
+
else:
|
| 509 |
+
value_set |= method()
|
| 510 |
+
return value_set
|
| 511 |
+
|
| 512 |
+
def gather_annotation_classes(self):
|
| 513 |
+
return ValueSet.from_sets([c.gather_annotation_classes() for c in self._set])
|
| 514 |
+
|
| 515 |
+
def get_signatures(self):
|
| 516 |
+
return [sig for c in self._set for sig in c.get_signatures()]
|
| 517 |
+
|
| 518 |
+
def get_type_hint(self, add_class_info=True):
|
| 519 |
+
t = [v.get_type_hint(add_class_info=add_class_info) for v in self._set]
|
| 520 |
+
type_hints = sorted(filter(None, t))
|
| 521 |
+
if len(type_hints) == 1:
|
| 522 |
+
return type_hints[0]
|
| 523 |
+
|
| 524 |
+
optional = 'None' in type_hints
|
| 525 |
+
if optional:
|
| 526 |
+
type_hints.remove('None')
|
| 527 |
+
|
| 528 |
+
if len(type_hints) == 0:
|
| 529 |
+
return None
|
| 530 |
+
elif len(type_hints) == 1:
|
| 531 |
+
s = type_hints[0]
|
| 532 |
+
else:
|
| 533 |
+
s = 'Union[%s]' % ', '.join(type_hints)
|
| 534 |
+
if optional:
|
| 535 |
+
s = 'Optional[%s]' % s
|
| 536 |
+
return s
|
| 537 |
+
|
| 538 |
+
def infer_type_vars(self, value_set):
|
| 539 |
+
# Circular
|
| 540 |
+
from jedi.inference.gradual.annotation import merge_type_var_dicts
|
| 541 |
+
|
| 542 |
+
type_var_dict = {}
|
| 543 |
+
for value in self._set:
|
| 544 |
+
merge_type_var_dicts(
|
| 545 |
+
type_var_dict,
|
| 546 |
+
value.infer_type_vars(value_set),
|
| 547 |
+
)
|
| 548 |
+
return type_var_dict
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
NO_VALUES = ValueSet([])
|
| 552 |
+
|
| 553 |
+
|
| 554 |
+
def iterator_to_value_set(func):
|
| 555 |
+
def wrapper(*args, **kwargs):
|
| 556 |
+
return ValueSet(func(*args, **kwargs))
|
| 557 |
+
|
| 558 |
+
return wrapper
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/cache.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
- the popular ``_memoize_default`` works like a typical memoize and returns the
|
| 3 |
+
default otherwise.
|
| 4 |
+
- ``CachedMetaClass`` uses ``_memoize_default`` to do the same with classes.
|
| 5 |
+
"""
|
| 6 |
+
from functools import wraps
|
| 7 |
+
|
| 8 |
+
from jedi import debug
|
| 9 |
+
|
| 10 |
+
_NO_DEFAULT = object()
|
| 11 |
+
_RECURSION_SENTINEL = object()
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _memoize_default(default=_NO_DEFAULT, inference_state_is_first_arg=False,
|
| 15 |
+
second_arg_is_inference_state=False):
|
| 16 |
+
""" This is a typical memoization decorator, BUT there is one difference:
|
| 17 |
+
To prevent recursion it sets defaults.
|
| 18 |
+
|
| 19 |
+
Preventing recursion is in this case the much bigger use than speed. I
|
| 20 |
+
don't think, that there is a big speed difference, but there are many cases
|
| 21 |
+
where recursion could happen (think about a = b; b = a).
|
| 22 |
+
"""
|
| 23 |
+
def func(function):
|
| 24 |
+
def wrapper(obj, *args, **kwargs):
|
| 25 |
+
# TODO These checks are kind of ugly and slow.
|
| 26 |
+
if inference_state_is_first_arg:
|
| 27 |
+
cache = obj.memoize_cache
|
| 28 |
+
elif second_arg_is_inference_state:
|
| 29 |
+
cache = args[0].memoize_cache # needed for meta classes
|
| 30 |
+
else:
|
| 31 |
+
cache = obj.inference_state.memoize_cache
|
| 32 |
+
|
| 33 |
+
try:
|
| 34 |
+
memo = cache[function]
|
| 35 |
+
except KeyError:
|
| 36 |
+
cache[function] = memo = {}
|
| 37 |
+
|
| 38 |
+
key = (obj, args, frozenset(kwargs.items()))
|
| 39 |
+
if key in memo:
|
| 40 |
+
return memo[key]
|
| 41 |
+
else:
|
| 42 |
+
if default is not _NO_DEFAULT:
|
| 43 |
+
memo[key] = default
|
| 44 |
+
rv = function(obj, *args, **kwargs)
|
| 45 |
+
memo[key] = rv
|
| 46 |
+
return rv
|
| 47 |
+
return wrapper
|
| 48 |
+
|
| 49 |
+
return func
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def inference_state_function_cache(default=_NO_DEFAULT):
|
| 53 |
+
def decorator(func):
|
| 54 |
+
return _memoize_default(default=default, inference_state_is_first_arg=True)(func)
|
| 55 |
+
|
| 56 |
+
return decorator
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def inference_state_method_cache(default=_NO_DEFAULT):
|
| 60 |
+
def decorator(func):
|
| 61 |
+
return _memoize_default(default=default)(func)
|
| 62 |
+
|
| 63 |
+
return decorator
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def inference_state_as_method_param_cache():
|
| 67 |
+
def decorator(call):
|
| 68 |
+
return _memoize_default(second_arg_is_inference_state=True)(call)
|
| 69 |
+
|
| 70 |
+
return decorator
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class CachedMetaClass(type):
|
| 74 |
+
"""
|
| 75 |
+
This is basically almost the same than the decorator above, it just caches
|
| 76 |
+
class initializations. Either you do it this way or with decorators, but
|
| 77 |
+
with decorators you lose class access (isinstance, etc).
|
| 78 |
+
"""
|
| 79 |
+
@inference_state_as_method_param_cache()
|
| 80 |
+
def __call__(self, *args, **kwargs):
|
| 81 |
+
return super().__call__(*args, **kwargs)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def inference_state_method_generator_cache():
|
| 85 |
+
"""
|
| 86 |
+
This is a special memoizer. It memoizes generators and also checks for
|
| 87 |
+
recursion errors and returns no further iterator elemends in that case.
|
| 88 |
+
"""
|
| 89 |
+
def func(function):
|
| 90 |
+
@wraps(function)
|
| 91 |
+
def wrapper(obj, *args, **kwargs):
|
| 92 |
+
cache = obj.inference_state.memoize_cache
|
| 93 |
+
try:
|
| 94 |
+
memo = cache[function]
|
| 95 |
+
except KeyError:
|
| 96 |
+
cache[function] = memo = {}
|
| 97 |
+
|
| 98 |
+
key = (obj, args, frozenset(kwargs.items()))
|
| 99 |
+
|
| 100 |
+
if key in memo:
|
| 101 |
+
actual_generator, cached_lst = memo[key]
|
| 102 |
+
else:
|
| 103 |
+
actual_generator = function(obj, *args, **kwargs)
|
| 104 |
+
cached_lst = []
|
| 105 |
+
memo[key] = actual_generator, cached_lst
|
| 106 |
+
|
| 107 |
+
i = 0
|
| 108 |
+
while True:
|
| 109 |
+
try:
|
| 110 |
+
next_element = cached_lst[i]
|
| 111 |
+
if next_element is _RECURSION_SENTINEL:
|
| 112 |
+
debug.warning('Found a generator recursion for %s' % obj)
|
| 113 |
+
# This means we have hit a recursion.
|
| 114 |
+
return
|
| 115 |
+
except IndexError:
|
| 116 |
+
cached_lst.append(_RECURSION_SENTINEL)
|
| 117 |
+
next_element = next(actual_generator, None)
|
| 118 |
+
if next_element is None:
|
| 119 |
+
cached_lst.pop()
|
| 120 |
+
return
|
| 121 |
+
cached_lst[-1] = next_element
|
| 122 |
+
yield next_element
|
| 123 |
+
i += 1
|
| 124 |
+
return wrapper
|
| 125 |
+
|
| 126 |
+
return func
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/context.py
ADDED
|
@@ -0,0 +1,499 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import abstractmethod
|
| 2 |
+
from contextlib import contextmanager
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Optional
|
| 5 |
+
|
| 6 |
+
from parso.tree import search_ancestor
|
| 7 |
+
from parso.python.tree import Name
|
| 8 |
+
|
| 9 |
+
from jedi.inference.filters import ParserTreeFilter, MergedFilter, \
|
| 10 |
+
GlobalNameFilter
|
| 11 |
+
from jedi.inference.names import AnonymousParamName, TreeNameDefinition
|
| 12 |
+
from jedi.inference.base_value import NO_VALUES, ValueSet
|
| 13 |
+
from jedi.parser_utils import get_parent_scope
|
| 14 |
+
from jedi import debug
|
| 15 |
+
from jedi import parser_utils
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class AbstractContext:
|
| 19 |
+
# Must be defined: inference_state and tree_node and parent_context as an attribute/property
|
| 20 |
+
|
| 21 |
+
def __init__(self, inference_state):
|
| 22 |
+
self.inference_state = inference_state
|
| 23 |
+
self.predefined_names = {}
|
| 24 |
+
|
| 25 |
+
@abstractmethod
|
| 26 |
+
def get_filters(self, until_position=None, origin_scope=None):
|
| 27 |
+
raise NotImplementedError
|
| 28 |
+
|
| 29 |
+
def goto(self, name_or_str, position):
|
| 30 |
+
from jedi.inference import finder
|
| 31 |
+
filters = _get_global_filters_for_name(
|
| 32 |
+
self, name_or_str if isinstance(name_or_str, Name) else None, position,
|
| 33 |
+
)
|
| 34 |
+
names = finder.filter_name(filters, name_or_str)
|
| 35 |
+
debug.dbg('context.goto %s in (%s): %s', name_or_str, self, names)
|
| 36 |
+
return names
|
| 37 |
+
|
| 38 |
+
def py__getattribute__(self, name_or_str, name_context=None, position=None,
|
| 39 |
+
analysis_errors=True):
|
| 40 |
+
"""
|
| 41 |
+
:param position: Position of the last statement -> tuple of line, column
|
| 42 |
+
"""
|
| 43 |
+
if name_context is None:
|
| 44 |
+
name_context = self
|
| 45 |
+
names = self.goto(name_or_str, position)
|
| 46 |
+
|
| 47 |
+
string_name = name_or_str.value if isinstance(name_or_str, Name) else name_or_str
|
| 48 |
+
|
| 49 |
+
# This paragraph is currently needed for proper branch type inference
|
| 50 |
+
# (static analysis).
|
| 51 |
+
found_predefined_types = None
|
| 52 |
+
if self.predefined_names and isinstance(name_or_str, Name):
|
| 53 |
+
node = name_or_str
|
| 54 |
+
while node is not None and not parser_utils.is_scope(node):
|
| 55 |
+
node = node.parent
|
| 56 |
+
if node.type in ("if_stmt", "for_stmt", "comp_for", 'sync_comp_for'):
|
| 57 |
+
try:
|
| 58 |
+
name_dict = self.predefined_names[node]
|
| 59 |
+
types = name_dict[string_name]
|
| 60 |
+
except KeyError:
|
| 61 |
+
continue
|
| 62 |
+
else:
|
| 63 |
+
found_predefined_types = types
|
| 64 |
+
break
|
| 65 |
+
if found_predefined_types is not None and names:
|
| 66 |
+
from jedi.inference import flow_analysis
|
| 67 |
+
check = flow_analysis.reachability_check(
|
| 68 |
+
context=self,
|
| 69 |
+
value_scope=self.tree_node,
|
| 70 |
+
node=name_or_str,
|
| 71 |
+
)
|
| 72 |
+
if check is flow_analysis.UNREACHABLE:
|
| 73 |
+
values = NO_VALUES
|
| 74 |
+
else:
|
| 75 |
+
values = found_predefined_types
|
| 76 |
+
else:
|
| 77 |
+
values = ValueSet.from_sets(name.infer() for name in names)
|
| 78 |
+
|
| 79 |
+
if not names and not values and analysis_errors:
|
| 80 |
+
if isinstance(name_or_str, Name):
|
| 81 |
+
from jedi.inference import analysis
|
| 82 |
+
message = ("NameError: name '%s' is not defined." % string_name)
|
| 83 |
+
analysis.add(name_context, 'name-error', name_or_str, message)
|
| 84 |
+
|
| 85 |
+
debug.dbg('context.names_to_types: %s -> %s', names, values)
|
| 86 |
+
if values:
|
| 87 |
+
return values
|
| 88 |
+
return self._check_for_additional_knowledge(name_or_str, name_context, position)
|
| 89 |
+
|
| 90 |
+
def _check_for_additional_knowledge(self, name_or_str, name_context, position):
|
| 91 |
+
name_context = name_context or self
|
| 92 |
+
# Add isinstance and other if/assert knowledge.
|
| 93 |
+
if isinstance(name_or_str, Name) and not name_context.is_instance():
|
| 94 |
+
flow_scope = name_or_str
|
| 95 |
+
base_nodes = [name_context.tree_node]
|
| 96 |
+
|
| 97 |
+
if any(b.type in ('comp_for', 'sync_comp_for') for b in base_nodes):
|
| 98 |
+
return NO_VALUES
|
| 99 |
+
from jedi.inference.finder import check_flow_information
|
| 100 |
+
while True:
|
| 101 |
+
flow_scope = get_parent_scope(flow_scope, include_flows=True)
|
| 102 |
+
n = check_flow_information(name_context, flow_scope,
|
| 103 |
+
name_or_str, position)
|
| 104 |
+
if n is not None:
|
| 105 |
+
return n
|
| 106 |
+
if flow_scope in base_nodes:
|
| 107 |
+
break
|
| 108 |
+
return NO_VALUES
|
| 109 |
+
|
| 110 |
+
def get_root_context(self):
|
| 111 |
+
parent_context = self.parent_context
|
| 112 |
+
if parent_context is None:
|
| 113 |
+
return self
|
| 114 |
+
return parent_context.get_root_context()
|
| 115 |
+
|
| 116 |
+
def is_module(self):
|
| 117 |
+
return False
|
| 118 |
+
|
| 119 |
+
def is_builtins_module(self):
|
| 120 |
+
return False
|
| 121 |
+
|
| 122 |
+
def is_class(self):
|
| 123 |
+
return False
|
| 124 |
+
|
| 125 |
+
def is_stub(self):
|
| 126 |
+
return False
|
| 127 |
+
|
| 128 |
+
def is_instance(self):
|
| 129 |
+
return False
|
| 130 |
+
|
| 131 |
+
def is_compiled(self):
|
| 132 |
+
return False
|
| 133 |
+
|
| 134 |
+
def is_bound_method(self):
|
| 135 |
+
return False
|
| 136 |
+
|
| 137 |
+
@abstractmethod
|
| 138 |
+
def py__name__(self):
|
| 139 |
+
raise NotImplementedError
|
| 140 |
+
|
| 141 |
+
def get_value(self):
|
| 142 |
+
raise NotImplementedError
|
| 143 |
+
|
| 144 |
+
@property
|
| 145 |
+
def name(self):
|
| 146 |
+
return None
|
| 147 |
+
|
| 148 |
+
def get_qualified_names(self):
|
| 149 |
+
return ()
|
| 150 |
+
|
| 151 |
+
def py__doc__(self):
|
| 152 |
+
return ''
|
| 153 |
+
|
| 154 |
+
@contextmanager
|
| 155 |
+
def predefine_names(self, flow_scope, dct):
|
| 156 |
+
predefined = self.predefined_names
|
| 157 |
+
predefined[flow_scope] = dct
|
| 158 |
+
try:
|
| 159 |
+
yield
|
| 160 |
+
finally:
|
| 161 |
+
del predefined[flow_scope]
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
class ValueContext(AbstractContext):
|
| 165 |
+
"""
|
| 166 |
+
Should be defined, otherwise the API returns empty types.
|
| 167 |
+
"""
|
| 168 |
+
def __init__(self, value):
|
| 169 |
+
super().__init__(value.inference_state)
|
| 170 |
+
self._value = value
|
| 171 |
+
|
| 172 |
+
@property
|
| 173 |
+
def tree_node(self):
|
| 174 |
+
return self._value.tree_node
|
| 175 |
+
|
| 176 |
+
@property
|
| 177 |
+
def parent_context(self):
|
| 178 |
+
return self._value.parent_context
|
| 179 |
+
|
| 180 |
+
def is_module(self):
|
| 181 |
+
return self._value.is_module()
|
| 182 |
+
|
| 183 |
+
def is_builtins_module(self):
|
| 184 |
+
return self._value == self.inference_state.builtins_module
|
| 185 |
+
|
| 186 |
+
def is_class(self):
|
| 187 |
+
return self._value.is_class()
|
| 188 |
+
|
| 189 |
+
def is_stub(self):
|
| 190 |
+
return self._value.is_stub()
|
| 191 |
+
|
| 192 |
+
def is_instance(self):
|
| 193 |
+
return self._value.is_instance()
|
| 194 |
+
|
| 195 |
+
def is_compiled(self):
|
| 196 |
+
return self._value.is_compiled()
|
| 197 |
+
|
| 198 |
+
def is_bound_method(self):
|
| 199 |
+
return self._value.is_bound_method()
|
| 200 |
+
|
| 201 |
+
def py__name__(self):
|
| 202 |
+
return self._value.py__name__()
|
| 203 |
+
|
| 204 |
+
@property
|
| 205 |
+
def name(self):
|
| 206 |
+
return self._value.name
|
| 207 |
+
|
| 208 |
+
def get_qualified_names(self):
|
| 209 |
+
return self._value.get_qualified_names()
|
| 210 |
+
|
| 211 |
+
def py__doc__(self):
|
| 212 |
+
return self._value.py__doc__()
|
| 213 |
+
|
| 214 |
+
def get_value(self):
|
| 215 |
+
return self._value
|
| 216 |
+
|
| 217 |
+
def __repr__(self):
|
| 218 |
+
return '%s(%s)' % (self.__class__.__name__, self._value)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
class TreeContextMixin:
|
| 222 |
+
def infer_node(self, node):
|
| 223 |
+
from jedi.inference.syntax_tree import infer_node
|
| 224 |
+
return infer_node(self, node)
|
| 225 |
+
|
| 226 |
+
def create_value(self, node):
|
| 227 |
+
from jedi.inference import value
|
| 228 |
+
|
| 229 |
+
if node == self.tree_node:
|
| 230 |
+
assert self.is_module()
|
| 231 |
+
return self.get_value()
|
| 232 |
+
|
| 233 |
+
parent_context = self.create_context(node)
|
| 234 |
+
|
| 235 |
+
if node.type in ('funcdef', 'lambdef'):
|
| 236 |
+
func = value.FunctionValue.from_context(parent_context, node)
|
| 237 |
+
if parent_context.is_class():
|
| 238 |
+
class_value = parent_context.parent_context.create_value(parent_context.tree_node)
|
| 239 |
+
instance = value.AnonymousInstance(
|
| 240 |
+
self.inference_state, parent_context.parent_context, class_value)
|
| 241 |
+
func = value.BoundMethod(
|
| 242 |
+
instance=instance,
|
| 243 |
+
class_context=class_value.as_context(),
|
| 244 |
+
function=func
|
| 245 |
+
)
|
| 246 |
+
return func
|
| 247 |
+
elif node.type == 'classdef':
|
| 248 |
+
return value.ClassValue(self.inference_state, parent_context, node)
|
| 249 |
+
else:
|
| 250 |
+
raise NotImplementedError("Probably shouldn't happen: %s" % node)
|
| 251 |
+
|
| 252 |
+
def create_context(self, node):
|
| 253 |
+
def from_scope_node(scope_node, is_nested=True):
|
| 254 |
+
if scope_node == self.tree_node:
|
| 255 |
+
return self
|
| 256 |
+
|
| 257 |
+
if scope_node.type in ('funcdef', 'lambdef', 'classdef'):
|
| 258 |
+
return self.create_value(scope_node).as_context()
|
| 259 |
+
elif scope_node.type in ('comp_for', 'sync_comp_for'):
|
| 260 |
+
parent_context = from_scope_node(parent_scope(scope_node.parent))
|
| 261 |
+
if node.start_pos >= scope_node.children[-1].start_pos:
|
| 262 |
+
return parent_context
|
| 263 |
+
return CompForContext(parent_context, scope_node)
|
| 264 |
+
raise Exception("There's a scope that was not managed: %s" % scope_node)
|
| 265 |
+
|
| 266 |
+
def parent_scope(node):
|
| 267 |
+
while True:
|
| 268 |
+
node = node.parent
|
| 269 |
+
|
| 270 |
+
if parser_utils.is_scope(node):
|
| 271 |
+
return node
|
| 272 |
+
elif node.type in ('argument', 'testlist_comp'):
|
| 273 |
+
if node.children[1].type in ('comp_for', 'sync_comp_for'):
|
| 274 |
+
return node.children[1]
|
| 275 |
+
elif node.type == 'dictorsetmaker':
|
| 276 |
+
for n in node.children[1:4]:
|
| 277 |
+
# In dictionaries it can be pretty much anything.
|
| 278 |
+
if n.type in ('comp_for', 'sync_comp_for'):
|
| 279 |
+
return n
|
| 280 |
+
|
| 281 |
+
scope_node = parent_scope(node)
|
| 282 |
+
if scope_node.type in ('funcdef', 'classdef'):
|
| 283 |
+
colon = scope_node.children[scope_node.children.index(':')]
|
| 284 |
+
if node.start_pos < colon.start_pos:
|
| 285 |
+
parent = node.parent
|
| 286 |
+
if not (parent.type == 'param' and parent.name == node):
|
| 287 |
+
scope_node = parent_scope(scope_node)
|
| 288 |
+
return from_scope_node(scope_node, is_nested=True)
|
| 289 |
+
|
| 290 |
+
def create_name(self, tree_name):
|
| 291 |
+
definition = tree_name.get_definition()
|
| 292 |
+
if definition and definition.type == 'param' and definition.name == tree_name:
|
| 293 |
+
funcdef = search_ancestor(definition, 'funcdef', 'lambdef')
|
| 294 |
+
func = self.create_value(funcdef)
|
| 295 |
+
return AnonymousParamName(func, tree_name)
|
| 296 |
+
else:
|
| 297 |
+
context = self.create_context(tree_name)
|
| 298 |
+
return TreeNameDefinition(context, tree_name)
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
class FunctionContext(TreeContextMixin, ValueContext):
|
| 302 |
+
def get_filters(self, until_position=None, origin_scope=None):
|
| 303 |
+
yield ParserTreeFilter(
|
| 304 |
+
self.inference_state,
|
| 305 |
+
parent_context=self,
|
| 306 |
+
until_position=until_position,
|
| 307 |
+
origin_scope=origin_scope
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
class ModuleContext(TreeContextMixin, ValueContext):
|
| 312 |
+
def py__file__(self) -> Optional[Path]:
|
| 313 |
+
return self._value.py__file__() # type: ignore[no-any-return]
|
| 314 |
+
|
| 315 |
+
def get_filters(self, until_position=None, origin_scope=None):
|
| 316 |
+
filters = self._value.get_filters(origin_scope)
|
| 317 |
+
# Skip the first filter and replace it.
|
| 318 |
+
next(filters, None)
|
| 319 |
+
yield MergedFilter(
|
| 320 |
+
ParserTreeFilter(
|
| 321 |
+
parent_context=self,
|
| 322 |
+
until_position=until_position,
|
| 323 |
+
origin_scope=origin_scope
|
| 324 |
+
),
|
| 325 |
+
self.get_global_filter(),
|
| 326 |
+
)
|
| 327 |
+
yield from filters
|
| 328 |
+
|
| 329 |
+
def get_global_filter(self):
|
| 330 |
+
return GlobalNameFilter(self)
|
| 331 |
+
|
| 332 |
+
@property
|
| 333 |
+
def string_names(self):
|
| 334 |
+
return self._value.string_names
|
| 335 |
+
|
| 336 |
+
@property
|
| 337 |
+
def code_lines(self):
|
| 338 |
+
return self._value.code_lines
|
| 339 |
+
|
| 340 |
+
def get_value(self):
|
| 341 |
+
"""
|
| 342 |
+
This is the only function that converts a context back to a value.
|
| 343 |
+
This is necessary for stub -> python conversion and vice versa. However
|
| 344 |
+
this method shouldn't be moved to AbstractContext.
|
| 345 |
+
"""
|
| 346 |
+
return self._value
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
class NamespaceContext(TreeContextMixin, ValueContext):
|
| 350 |
+
def get_filters(self, until_position=None, origin_scope=None):
|
| 351 |
+
return self._value.get_filters()
|
| 352 |
+
|
| 353 |
+
def get_value(self):
|
| 354 |
+
return self._value
|
| 355 |
+
|
| 356 |
+
@property
|
| 357 |
+
def string_names(self):
|
| 358 |
+
return self._value.string_names
|
| 359 |
+
|
| 360 |
+
def py__file__(self) -> Optional[Path]:
|
| 361 |
+
return self._value.py__file__() # type: ignore[no-any-return]
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
class ClassContext(TreeContextMixin, ValueContext):
|
| 365 |
+
def get_filters(self, until_position=None, origin_scope=None):
|
| 366 |
+
yield self.get_global_filter(until_position, origin_scope)
|
| 367 |
+
|
| 368 |
+
def get_global_filter(self, until_position=None, origin_scope=None):
|
| 369 |
+
return ParserTreeFilter(
|
| 370 |
+
parent_context=self,
|
| 371 |
+
until_position=until_position,
|
| 372 |
+
origin_scope=origin_scope
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
class CompForContext(TreeContextMixin, AbstractContext):
|
| 377 |
+
def __init__(self, parent_context, comp_for):
|
| 378 |
+
super().__init__(parent_context.inference_state)
|
| 379 |
+
self.tree_node = comp_for
|
| 380 |
+
self.parent_context = parent_context
|
| 381 |
+
|
| 382 |
+
def get_filters(self, until_position=None, origin_scope=None):
|
| 383 |
+
yield ParserTreeFilter(self)
|
| 384 |
+
|
| 385 |
+
def get_value(self):
|
| 386 |
+
return None
|
| 387 |
+
|
| 388 |
+
def py__name__(self):
|
| 389 |
+
return '<comprehension context>'
|
| 390 |
+
|
| 391 |
+
def __repr__(self):
|
| 392 |
+
return '%s(%s)' % (self.__class__.__name__, self.tree_node)
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
class CompiledContext(ValueContext):
|
| 396 |
+
def get_filters(self, until_position=None, origin_scope=None):
|
| 397 |
+
return self._value.get_filters()
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
class CompiledModuleContext(CompiledContext):
|
| 401 |
+
code_lines = None
|
| 402 |
+
|
| 403 |
+
def get_value(self):
|
| 404 |
+
return self._value
|
| 405 |
+
|
| 406 |
+
@property
|
| 407 |
+
def string_names(self):
|
| 408 |
+
return self._value.string_names
|
| 409 |
+
|
| 410 |
+
def py__file__(self) -> Optional[Path]:
|
| 411 |
+
return self._value.py__file__() # type: ignore[no-any-return]
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
def _get_global_filters_for_name(context, name_or_none, position):
|
| 415 |
+
# For functions and classes the defaults don't belong to the
|
| 416 |
+
# function and get inferred in the value before the function. So
|
| 417 |
+
# make sure to exclude the function/class name.
|
| 418 |
+
if name_or_none is not None:
|
| 419 |
+
ancestor = search_ancestor(name_or_none, 'funcdef', 'classdef', 'lambdef')
|
| 420 |
+
lambdef = None
|
| 421 |
+
if ancestor == 'lambdef':
|
| 422 |
+
# For lambdas it's even more complicated since parts will
|
| 423 |
+
# be inferred later.
|
| 424 |
+
lambdef = ancestor
|
| 425 |
+
ancestor = search_ancestor(name_or_none, 'funcdef', 'classdef')
|
| 426 |
+
if ancestor is not None:
|
| 427 |
+
colon = ancestor.children[-2]
|
| 428 |
+
if position is not None and position < colon.start_pos:
|
| 429 |
+
if lambdef is None or position < lambdef.children[-2].start_pos:
|
| 430 |
+
position = ancestor.start_pos
|
| 431 |
+
|
| 432 |
+
return get_global_filters(context, position, name_or_none)
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
def get_global_filters(context, until_position, origin_scope):
|
| 436 |
+
"""
|
| 437 |
+
Returns all filters in order of priority for name resolution.
|
| 438 |
+
|
| 439 |
+
For global name lookups. The filters will handle name resolution
|
| 440 |
+
themselves, but here we gather possible filters downwards.
|
| 441 |
+
|
| 442 |
+
>>> from jedi import Script
|
| 443 |
+
>>> script = Script('''
|
| 444 |
+
... x = ['a', 'b', 'c']
|
| 445 |
+
... def func():
|
| 446 |
+
... y = None
|
| 447 |
+
... ''')
|
| 448 |
+
>>> module_node = script._module_node
|
| 449 |
+
>>> scope = next(module_node.iter_funcdefs())
|
| 450 |
+
>>> scope
|
| 451 |
+
<Function: func@3-5>
|
| 452 |
+
>>> context = script._get_module_context().create_context(scope)
|
| 453 |
+
>>> filters = list(get_global_filters(context, (4, 0), None))
|
| 454 |
+
|
| 455 |
+
First we get the names from the function scope.
|
| 456 |
+
|
| 457 |
+
>>> print(filters[0]) # doctest: +ELLIPSIS
|
| 458 |
+
MergedFilter(<ParserTreeFilter: ...>, <GlobalNameFilter: ...>)
|
| 459 |
+
>>> sorted(str(n) for n in filters[0].values()) # doctest: +NORMALIZE_WHITESPACE
|
| 460 |
+
['<TreeNameDefinition: string_name=func start_pos=(3, 4)>',
|
| 461 |
+
'<TreeNameDefinition: string_name=x start_pos=(2, 0)>']
|
| 462 |
+
>>> filters[0]._filters[0]._until_position
|
| 463 |
+
(4, 0)
|
| 464 |
+
>>> filters[0]._filters[1]._until_position
|
| 465 |
+
|
| 466 |
+
Then it yields the names from one level "lower". In this example, this is
|
| 467 |
+
the module scope (including globals).
|
| 468 |
+
As a side note, you can see, that the position in the filter is None on the
|
| 469 |
+
globals filter, because there the whole module is searched.
|
| 470 |
+
|
| 471 |
+
>>> list(filters[1].values()) # package modules -> Also empty.
|
| 472 |
+
[]
|
| 473 |
+
>>> sorted(name.string_name for name in filters[2].values()) # Module attributes
|
| 474 |
+
['__doc__', '__name__', '__package__']
|
| 475 |
+
|
| 476 |
+
Finally, it yields the builtin filter, if `include_builtin` is
|
| 477 |
+
true (default).
|
| 478 |
+
|
| 479 |
+
>>> list(filters[3].values()) # doctest: +ELLIPSIS
|
| 480 |
+
[...]
|
| 481 |
+
"""
|
| 482 |
+
base_context = context
|
| 483 |
+
from jedi.inference.value.function import BaseFunctionExecutionContext
|
| 484 |
+
while context is not None:
|
| 485 |
+
# Names in methods cannot be resolved within the class.
|
| 486 |
+
yield from context.get_filters(
|
| 487 |
+
until_position=until_position,
|
| 488 |
+
origin_scope=origin_scope
|
| 489 |
+
)
|
| 490 |
+
if isinstance(context, (BaseFunctionExecutionContext, ModuleContext)):
|
| 491 |
+
# The position should be reset if the current scope is a function.
|
| 492 |
+
until_position = None
|
| 493 |
+
|
| 494 |
+
context = context.parent_context
|
| 495 |
+
|
| 496 |
+
b = next(base_context.inference_state.builtins_module.get_filters(), None)
|
| 497 |
+
assert b is not None
|
| 498 |
+
# Add builtins to the global scope.
|
| 499 |
+
yield b
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/docstring_utils.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from jedi.inference.value import ModuleValue
|
| 2 |
+
from jedi.inference.context import ModuleContext
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class DocstringModule(ModuleValue):
|
| 6 |
+
def __init__(self, in_module_context, **kwargs):
|
| 7 |
+
super().__init__(**kwargs)
|
| 8 |
+
self._in_module_context = in_module_context
|
| 9 |
+
|
| 10 |
+
def _as_context(self):
|
| 11 |
+
return DocstringModuleContext(self, self._in_module_context)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class DocstringModuleContext(ModuleContext):
|
| 15 |
+
def __init__(self, module_value, in_module_context):
|
| 16 |
+
super().__init__(module_value)
|
| 17 |
+
self._in_module_context = in_module_context
|
| 18 |
+
|
| 19 |
+
def get_filters(self, origin_scope=None, until_position=None):
|
| 20 |
+
yield from super().get_filters(until_position=until_position)
|
| 21 |
+
yield from self._in_module_context.get_filters()
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/docstrings.py
AD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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Docstrings are another source of information for functions and classes.
|
| 3 |
+
:mod:`jedi.inference.dynamic_params` tries to find all executions of functions,
|
| 4 |
+
while the docstring parsing is much easier. There are three different types of
|
| 5 |
+
docstrings that |jedi| understands:
|
| 6 |
+
|
| 7 |
+
- `Sphinx <http://sphinx-doc.org/markup/desc.html#info-field-lists>`_
|
| 8 |
+
- `Epydoc <http://epydoc.sourceforge.net/manual-fields.html>`_
|
| 9 |
+
- `Numpydoc <https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt>`_
|
| 10 |
+
|
| 11 |
+
For example, the sphinx annotation ``:type foo: str`` clearly states that the
|
| 12 |
+
type of ``foo`` is ``str``.
|
| 13 |
+
|
| 14 |
+
As an addition to parameter searching, this module also provides return
|
| 15 |
+
annotations.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import re
|
| 19 |
+
import warnings
|
| 20 |
+
|
| 21 |
+
from parso import parse, ParserSyntaxError
|
| 22 |
+
|
| 23 |
+
from jedi import debug
|
| 24 |
+
from jedi.inference.cache import inference_state_method_cache
|
| 25 |
+
from jedi.inference.base_value import iterator_to_value_set, ValueSet, \
|
| 26 |
+
NO_VALUES
|
| 27 |
+
from jedi.inference.lazy_value import LazyKnownValues
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
DOCSTRING_PARAM_PATTERNS = [
|
| 31 |
+
r'\s*:type\s+%s:\s*([^\n]+)', # Sphinx
|
| 32 |
+
r'\s*:param\s+(\w+)\s+%s:[^\n]*', # Sphinx param with type
|
| 33 |
+
r'\s*@type\s+%s:\s*([^\n]+)', # Epydoc
|
| 34 |
+
]
|
| 35 |
+
|
| 36 |
+
DOCSTRING_RETURN_PATTERNS = [
|
| 37 |
+
re.compile(r'\s*:rtype:\s*([^\n]+)', re.M), # Sphinx
|
| 38 |
+
re.compile(r'\s*@rtype:\s*([^\n]+)', re.M), # Epydoc
|
| 39 |
+
]
|
| 40 |
+
|
| 41 |
+
REST_ROLE_PATTERN = re.compile(r':[^`]+:`([^`]+)`')
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
_numpy_doc_string_cache = None
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _get_numpy_doc_string_cls():
|
| 48 |
+
global _numpy_doc_string_cache
|
| 49 |
+
if isinstance(_numpy_doc_string_cache, (ImportError, SyntaxError)):
|
| 50 |
+
raise _numpy_doc_string_cache
|
| 51 |
+
from numpydoc.docscrape import NumpyDocString # type: ignore[import]
|
| 52 |
+
_numpy_doc_string_cache = NumpyDocString
|
| 53 |
+
return _numpy_doc_string_cache
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _search_param_in_numpydocstr(docstr, param_str):
|
| 57 |
+
"""Search `docstr` (in numpydoc format) for type(-s) of `param_str`."""
|
| 58 |
+
with warnings.catch_warnings():
|
| 59 |
+
warnings.simplefilter("ignore")
|
| 60 |
+
try:
|
| 61 |
+
# This is a non-public API. If it ever changes we should be
|
| 62 |
+
# prepared and return gracefully.
|
| 63 |
+
params = _get_numpy_doc_string_cls()(docstr)._parsed_data['Parameters']
|
| 64 |
+
except Exception:
|
| 65 |
+
return []
|
| 66 |
+
for p_name, p_type, p_descr in params:
|
| 67 |
+
if p_name == param_str:
|
| 68 |
+
m = re.match(r'([^,]+(,[^,]+)*?)(,[ ]*optional)?$', p_type)
|
| 69 |
+
if m:
|
| 70 |
+
p_type = m.group(1)
|
| 71 |
+
return list(_expand_typestr(p_type))
|
| 72 |
+
return []
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _search_return_in_numpydocstr(docstr):
|
| 76 |
+
"""
|
| 77 |
+
Search `docstr` (in numpydoc format) for type(-s) of function returns.
|
| 78 |
+
"""
|
| 79 |
+
with warnings.catch_warnings():
|
| 80 |
+
warnings.simplefilter("ignore")
|
| 81 |
+
try:
|
| 82 |
+
doc = _get_numpy_doc_string_cls()(docstr)
|
| 83 |
+
except Exception:
|
| 84 |
+
return
|
| 85 |
+
try:
|
| 86 |
+
# This is a non-public API. If it ever changes we should be
|
| 87 |
+
# prepared and return gracefully.
|
| 88 |
+
returns = doc._parsed_data['Returns']
|
| 89 |
+
returns += doc._parsed_data['Yields']
|
| 90 |
+
except Exception:
|
| 91 |
+
return
|
| 92 |
+
for r_name, r_type, r_descr in returns:
|
| 93 |
+
# Return names are optional and if so the type is in the name
|
| 94 |
+
if not r_type:
|
| 95 |
+
r_type = r_name
|
| 96 |
+
yield from _expand_typestr(r_type)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _expand_typestr(type_str):
|
| 100 |
+
"""
|
| 101 |
+
Attempts to interpret the possible types in `type_str`
|
| 102 |
+
"""
|
| 103 |
+
# Check if alternative types are specified with 'or'
|
| 104 |
+
if re.search(r'\bor\b', type_str):
|
| 105 |
+
for t in type_str.split('or'):
|
| 106 |
+
yield t.split('of')[0].strip()
|
| 107 |
+
# Check if like "list of `type`" and set type to list
|
| 108 |
+
elif re.search(r'\bof\b', type_str):
|
| 109 |
+
yield type_str.split('of')[0]
|
| 110 |
+
# Check if type has is a set of valid literal values eg: {'C', 'F', 'A'}
|
| 111 |
+
elif type_str.startswith('{'):
|
| 112 |
+
node = parse(type_str, version='3.7').children[0]
|
| 113 |
+
if node.type == 'atom':
|
| 114 |
+
for leaf in getattr(node.children[1], "children", []):
|
| 115 |
+
if leaf.type == 'number':
|
| 116 |
+
if '.' in leaf.value:
|
| 117 |
+
yield 'float'
|
| 118 |
+
else:
|
| 119 |
+
yield 'int'
|
| 120 |
+
elif leaf.type == 'string':
|
| 121 |
+
if 'b' in leaf.string_prefix.lower():
|
| 122 |
+
yield 'bytes'
|
| 123 |
+
else:
|
| 124 |
+
yield 'str'
|
| 125 |
+
# Ignore everything else.
|
| 126 |
+
|
| 127 |
+
# Otherwise just work with what we have.
|
| 128 |
+
else:
|
| 129 |
+
yield type_str
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _search_param_in_docstr(docstr, param_str):
|
| 133 |
+
"""
|
| 134 |
+
Search `docstr` for type(-s) of `param_str`.
|
| 135 |
+
|
| 136 |
+
>>> _search_param_in_docstr(':type param: int', 'param')
|
| 137 |
+
['int']
|
| 138 |
+
>>> _search_param_in_docstr('@type param: int', 'param')
|
| 139 |
+
['int']
|
| 140 |
+
>>> _search_param_in_docstr(
|
| 141 |
+
... ':type param: :class:`threading.Thread`', 'param')
|
| 142 |
+
['threading.Thread']
|
| 143 |
+
>>> bool(_search_param_in_docstr('no document', 'param'))
|
| 144 |
+
False
|
| 145 |
+
>>> _search_param_in_docstr(':param int param: some description', 'param')
|
| 146 |
+
['int']
|
| 147 |
+
|
| 148 |
+
"""
|
| 149 |
+
# look at #40 to see definitions of those params
|
| 150 |
+
patterns = [re.compile(p % re.escape(param_str))
|
| 151 |
+
for p in DOCSTRING_PARAM_PATTERNS]
|
| 152 |
+
for pattern in patterns:
|
| 153 |
+
match = pattern.search(docstr)
|
| 154 |
+
if match:
|
| 155 |
+
return [_strip_rst_role(match.group(1))]
|
| 156 |
+
|
| 157 |
+
return _search_param_in_numpydocstr(docstr, param_str)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def _strip_rst_role(type_str):
|
| 161 |
+
"""
|
| 162 |
+
Strip off the part looks like a ReST role in `type_str`.
|
| 163 |
+
|
| 164 |
+
>>> _strip_rst_role(':class:`ClassName`') # strip off :class:
|
| 165 |
+
'ClassName'
|
| 166 |
+
>>> _strip_rst_role(':py:obj:`module.Object`') # works with domain
|
| 167 |
+
'module.Object'
|
| 168 |
+
>>> _strip_rst_role('ClassName') # do nothing when not ReST role
|
| 169 |
+
'ClassName'
|
| 170 |
+
|
| 171 |
+
See also:
|
| 172 |
+
http://sphinx-doc.org/domains.html#cross-referencing-python-objects
|
| 173 |
+
|
| 174 |
+
"""
|
| 175 |
+
match = REST_ROLE_PATTERN.match(type_str)
|
| 176 |
+
if match:
|
| 177 |
+
return match.group(1)
|
| 178 |
+
else:
|
| 179 |
+
return type_str
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def _infer_for_statement_string(module_context, string):
|
| 183 |
+
if string is None:
|
| 184 |
+
return []
|
| 185 |
+
|
| 186 |
+
potential_imports = re.findall(r'((?:\w+\.)*\w+)\.', string)
|
| 187 |
+
# Try to import module part in dotted name.
|
| 188 |
+
# (e.g., 'threading' in 'threading.Thread').
|
| 189 |
+
imports = "\n".join(f"import {p}" for p in potential_imports)
|
| 190 |
+
string = f'{imports}\n{string}'
|
| 191 |
+
|
| 192 |
+
debug.dbg('Parse docstring code %s', string, color='BLUE')
|
| 193 |
+
grammar = module_context.inference_state.grammar
|
| 194 |
+
try:
|
| 195 |
+
module = grammar.parse(string, error_recovery=False)
|
| 196 |
+
except ParserSyntaxError:
|
| 197 |
+
return []
|
| 198 |
+
try:
|
| 199 |
+
# It's not the last item, because that's an end marker.
|
| 200 |
+
stmt = module.children[-2]
|
| 201 |
+
except (AttributeError, IndexError):
|
| 202 |
+
return []
|
| 203 |
+
|
| 204 |
+
if stmt.type not in ('name', 'atom', 'atom_expr'):
|
| 205 |
+
return []
|
| 206 |
+
|
| 207 |
+
# Here we basically use a fake module that also uses the filters in
|
| 208 |
+
# the actual module.
|
| 209 |
+
from jedi.inference.docstring_utils import DocstringModule
|
| 210 |
+
m = DocstringModule(
|
| 211 |
+
in_module_context=module_context,
|
| 212 |
+
inference_state=module_context.inference_state,
|
| 213 |
+
module_node=module,
|
| 214 |
+
code_lines=[],
|
| 215 |
+
)
|
| 216 |
+
return list(_execute_types_in_stmt(m.as_context(), stmt))
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def _execute_types_in_stmt(module_context, stmt):
|
| 220 |
+
"""
|
| 221 |
+
Executing all types or general elements that we find in a statement. This
|
| 222 |
+
doesn't include tuple, list and dict literals, because the stuff they
|
| 223 |
+
contain is executed. (Used as type information).
|
| 224 |
+
"""
|
| 225 |
+
definitions = module_context.infer_node(stmt)
|
| 226 |
+
return ValueSet.from_sets(
|
| 227 |
+
_execute_array_values(module_context.inference_state, d)
|
| 228 |
+
for d in definitions
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def _execute_array_values(inference_state, array):
|
| 233 |
+
"""
|
| 234 |
+
Tuples indicate that there's not just one return value, but the listed
|
| 235 |
+
ones. `(str, int)` means that it returns a tuple with both types.
|
| 236 |
+
"""
|
| 237 |
+
from jedi.inference.value.iterable import SequenceLiteralValue, FakeTuple, FakeList
|
| 238 |
+
if isinstance(array, SequenceLiteralValue) and array.array_type in ('tuple', 'list'):
|
| 239 |
+
values = []
|
| 240 |
+
for lazy_value in array.py__iter__():
|
| 241 |
+
objects = ValueSet.from_sets(
|
| 242 |
+
_execute_array_values(inference_state, typ)
|
| 243 |
+
for typ in lazy_value.infer()
|
| 244 |
+
)
|
| 245 |
+
values.append(LazyKnownValues(objects))
|
| 246 |
+
cls = FakeTuple if array.array_type == 'tuple' else FakeList
|
| 247 |
+
return {cls(inference_state, values)}
|
| 248 |
+
else:
|
| 249 |
+
return array.execute_annotation()
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
@inference_state_method_cache()
|
| 253 |
+
def infer_param(function_value, param):
|
| 254 |
+
def infer_docstring(docstring):
|
| 255 |
+
return ValueSet(
|
| 256 |
+
p
|
| 257 |
+
for param_str in _search_param_in_docstr(docstring, param.name.value)
|
| 258 |
+
for p in _infer_for_statement_string(module_context, param_str)
|
| 259 |
+
)
|
| 260 |
+
module_context = function_value.get_root_context()
|
| 261 |
+
func = param.get_parent_function()
|
| 262 |
+
if func.type == 'lambdef':
|
| 263 |
+
return NO_VALUES
|
| 264 |
+
|
| 265 |
+
types = infer_docstring(function_value.py__doc__())
|
| 266 |
+
if function_value.is_bound_method() \
|
| 267 |
+
and function_value.py__name__() == '__init__':
|
| 268 |
+
types |= infer_docstring(function_value.class_context.py__doc__())
|
| 269 |
+
|
| 270 |
+
debug.dbg('Found param types for docstring: %s', types, color='BLUE')
|
| 271 |
+
return types
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
@inference_state_method_cache()
|
| 275 |
+
@iterator_to_value_set
|
| 276 |
+
def infer_return_types(function_value):
|
| 277 |
+
def search_return_in_docstr(code):
|
| 278 |
+
for p in DOCSTRING_RETURN_PATTERNS:
|
| 279 |
+
match = p.search(code)
|
| 280 |
+
if match:
|
| 281 |
+
yield _strip_rst_role(match.group(1))
|
| 282 |
+
# Check for numpy style return hint
|
| 283 |
+
yield from _search_return_in_numpydocstr(code)
|
| 284 |
+
|
| 285 |
+
for type_str in search_return_in_docstr(function_value.py__doc__()):
|
| 286 |
+
yield from _infer_for_statement_string(function_value.get_root_context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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
One of the really important features of |jedi| is to have an option to
|
| 3 |
+
understand code like this::
|
| 4 |
+
|
| 5 |
+
def foo(bar):
|
| 6 |
+
bar. # completion here
|
| 7 |
+
foo(1)
|
| 8 |
+
|
| 9 |
+
There's no doubt wheter bar is an ``int`` or not, but if there's also a call
|
| 10 |
+
like ``foo('str')``, what would happen? Well, we'll just show both. Because
|
| 11 |
+
that's what a human would expect.
|
| 12 |
+
|
| 13 |
+
It works as follows:
|
| 14 |
+
|
| 15 |
+
- |Jedi| sees a param
|
| 16 |
+
- search for function calls named ``foo``
|
| 17 |
+
- execute these calls and check the input.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from jedi import settings
|
| 21 |
+
from jedi import debug
|
| 22 |
+
from jedi.parser_utils import get_parent_scope
|
| 23 |
+
from jedi.inference.cache import inference_state_method_cache
|
| 24 |
+
from jedi.inference.arguments import TreeArguments
|
| 25 |
+
from jedi.inference.param import get_executed_param_names
|
| 26 |
+
from jedi.inference.helpers import is_stdlib_path
|
| 27 |
+
from jedi.inference.utils import to_list
|
| 28 |
+
from jedi.inference.value import instance
|
| 29 |
+
from jedi.inference.base_value import ValueSet, NO_VALUES
|
| 30 |
+
from jedi.inference.references import get_module_contexts_containing_name
|
| 31 |
+
from jedi.inference import recursion
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
MAX_PARAM_SEARCHES = 20
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _avoid_recursions(func):
|
| 38 |
+
def wrapper(function_value, param_index):
|
| 39 |
+
inf = function_value.inference_state
|
| 40 |
+
with recursion.execution_allowed(inf, function_value.tree_node) as allowed:
|
| 41 |
+
# We need to catch recursions that may occur, because an
|
| 42 |
+
# anonymous functions can create an anonymous parameter that is
|
| 43 |
+
# more or less self referencing.
|
| 44 |
+
if allowed:
|
| 45 |
+
inf.dynamic_params_depth += 1
|
| 46 |
+
try:
|
| 47 |
+
return func(function_value, param_index)
|
| 48 |
+
finally:
|
| 49 |
+
inf.dynamic_params_depth -= 1
|
| 50 |
+
return NO_VALUES
|
| 51 |
+
return wrapper
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@debug.increase_indent
|
| 55 |
+
@_avoid_recursions
|
| 56 |
+
def dynamic_param_lookup(function_value, param_index):
|
| 57 |
+
"""
|
| 58 |
+
A dynamic search for param values. If you try to complete a type:
|
| 59 |
+
|
| 60 |
+
>>> def func(foo):
|
| 61 |
+
... foo
|
| 62 |
+
>>> func(1)
|
| 63 |
+
>>> func("")
|
| 64 |
+
|
| 65 |
+
It is not known what the type ``foo`` without analysing the whole code. You
|
| 66 |
+
have to look for all calls to ``func`` to find out what ``foo`` possibly
|
| 67 |
+
is.
|
| 68 |
+
"""
|
| 69 |
+
if not function_value.inference_state.do_dynamic_params_search:
|
| 70 |
+
return NO_VALUES
|
| 71 |
+
|
| 72 |
+
funcdef = function_value.tree_node
|
| 73 |
+
|
| 74 |
+
path = function_value.get_root_context().py__file__()
|
| 75 |
+
if path is not None and is_stdlib_path(path):
|
| 76 |
+
# We don't want to search for references in the stdlib. Usually people
|
| 77 |
+
# don't work with it (except if you are a core maintainer, sorry).
|
| 78 |
+
# This makes everything slower. Just disable it and run the tests,
|
| 79 |
+
# you will see the slowdown, especially in 3.6.
|
| 80 |
+
return NO_VALUES
|
| 81 |
+
|
| 82 |
+
if funcdef.type == 'lambdef':
|
| 83 |
+
string_name = _get_lambda_name(funcdef)
|
| 84 |
+
if string_name is None:
|
| 85 |
+
return NO_VALUES
|
| 86 |
+
else:
|
| 87 |
+
string_name = funcdef.name.value
|
| 88 |
+
debug.dbg('Dynamic param search in %s.', string_name, color='MAGENTA')
|
| 89 |
+
|
| 90 |
+
module_context = function_value.get_root_context()
|
| 91 |
+
arguments_list = _search_function_arguments(module_context, funcdef, string_name)
|
| 92 |
+
values = ValueSet.from_sets(
|
| 93 |
+
get_executed_param_names(
|
| 94 |
+
function_value, arguments
|
| 95 |
+
)[param_index].infer()
|
| 96 |
+
for arguments in arguments_list
|
| 97 |
+
)
|
| 98 |
+
debug.dbg('Dynamic param result finished', color='MAGENTA')
|
| 99 |
+
return values
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
@inference_state_method_cache(default=None)
|
| 103 |
+
@to_list
|
| 104 |
+
def _search_function_arguments(module_context, funcdef, string_name):
|
| 105 |
+
"""
|
| 106 |
+
Returns a list of param names.
|
| 107 |
+
"""
|
| 108 |
+
compare_node = funcdef
|
| 109 |
+
if string_name == '__init__':
|
| 110 |
+
cls = get_parent_scope(funcdef)
|
| 111 |
+
if cls.type == 'classdef':
|
| 112 |
+
string_name = cls.name.value
|
| 113 |
+
compare_node = cls
|
| 114 |
+
|
| 115 |
+
found_arguments = False
|
| 116 |
+
i = 0
|
| 117 |
+
inference_state = module_context.inference_state
|
| 118 |
+
|
| 119 |
+
if settings.dynamic_params_for_other_modules:
|
| 120 |
+
module_contexts = get_module_contexts_containing_name(
|
| 121 |
+
inference_state, [module_context], string_name,
|
| 122 |
+
# Limit the amounts of files to be opened massively.
|
| 123 |
+
limit_reduction=5,
|
| 124 |
+
)
|
| 125 |
+
else:
|
| 126 |
+
module_contexts = [module_context]
|
| 127 |
+
|
| 128 |
+
for for_mod_context in module_contexts:
|
| 129 |
+
for name, trailer in _get_potential_nodes(for_mod_context, string_name):
|
| 130 |
+
i += 1
|
| 131 |
+
|
| 132 |
+
# This is a simple way to stop Jedi's dynamic param recursion
|
| 133 |
+
# from going wild: The deeper Jedi's in the recursion, the less
|
| 134 |
+
# code should be inferred.
|
| 135 |
+
if i * inference_state.dynamic_params_depth > MAX_PARAM_SEARCHES:
|
| 136 |
+
return
|
| 137 |
+
|
| 138 |
+
random_context = for_mod_context.create_context(name)
|
| 139 |
+
for arguments in _check_name_for_execution(
|
| 140 |
+
inference_state, random_context, compare_node, name, trailer):
|
| 141 |
+
found_arguments = True
|
| 142 |
+
yield arguments
|
| 143 |
+
|
| 144 |
+
# If there are results after processing a module, we're probably
|
| 145 |
+
# good to process. This is a speed optimization.
|
| 146 |
+
if found_arguments:
|
| 147 |
+
return
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def _get_lambda_name(node):
|
| 151 |
+
stmt = node.parent
|
| 152 |
+
if stmt.type == 'expr_stmt':
|
| 153 |
+
first_operator = next(stmt.yield_operators(), None)
|
| 154 |
+
if first_operator == '=':
|
| 155 |
+
first = stmt.children[0]
|
| 156 |
+
if first.type == 'name':
|
| 157 |
+
return first.value
|
| 158 |
+
|
| 159 |
+
return None
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def _get_potential_nodes(module_value, func_string_name):
|
| 163 |
+
try:
|
| 164 |
+
names = module_value.tree_node.get_used_names()[func_string_name]
|
| 165 |
+
except KeyError:
|
| 166 |
+
return
|
| 167 |
+
|
| 168 |
+
for name in names:
|
| 169 |
+
bracket = name.get_next_leaf()
|
| 170 |
+
trailer = bracket.parent
|
| 171 |
+
if trailer.type == 'trailer' and bracket == '(':
|
| 172 |
+
yield name, trailer
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def _check_name_for_execution(inference_state, context, compare_node, name, trailer):
|
| 176 |
+
from jedi.inference.value.function import BaseFunctionExecutionContext
|
| 177 |
+
|
| 178 |
+
def create_args(value):
|
| 179 |
+
arglist = trailer.children[1]
|
| 180 |
+
if arglist == ')':
|
| 181 |
+
arglist = None
|
| 182 |
+
args = TreeArguments(inference_state, context, arglist, trailer)
|
| 183 |
+
from jedi.inference.value.instance import InstanceArguments
|
| 184 |
+
if value.tree_node.type == 'classdef':
|
| 185 |
+
created_instance = instance.TreeInstance(
|
| 186 |
+
inference_state,
|
| 187 |
+
value.parent_context,
|
| 188 |
+
value,
|
| 189 |
+
args
|
| 190 |
+
)
|
| 191 |
+
return InstanceArguments(created_instance, args)
|
| 192 |
+
else:
|
| 193 |
+
if value.is_bound_method():
|
| 194 |
+
args = InstanceArguments(value.instance, args)
|
| 195 |
+
return args
|
| 196 |
+
|
| 197 |
+
for value in inference_state.infer(context, name):
|
| 198 |
+
value_node = value.tree_node
|
| 199 |
+
if compare_node == value_node:
|
| 200 |
+
yield create_args(value)
|
| 201 |
+
elif isinstance(value.parent_context, BaseFunctionExecutionContext) \
|
| 202 |
+
and compare_node.type == 'funcdef':
|
| 203 |
+
# Here we're trying to find decorators by checking the first
|
| 204 |
+
# parameter. It's not very generic though. Should find a better
|
| 205 |
+
# solution that also applies to nested decorators.
|
| 206 |
+
param_names = value.parent_context.get_param_names()
|
| 207 |
+
if len(param_names) != 1:
|
| 208 |
+
continue
|
| 209 |
+
values = param_names[0].infer()
|
| 210 |
+
if [v.tree_node for v in values] == [compare_node]:
|
| 211 |
+
# Found a decorator.
|
| 212 |
+
module_context = context.get_root_context()
|
| 213 |
+
execution_context = value.as_context(create_args(value))
|
| 214 |
+
potential_nodes = _get_potential_nodes(module_context, param_names[0].string_name)
|
| 215 |
+
for name, trailer in potential_nodes:
|
| 216 |
+
if value_node.start_pos < name.start_pos < value_node.end_pos:
|
| 217 |
+
random_context = execution_context.create_context(name)
|
| 218 |
+
yield from _check_name_for_execution(
|
| 219 |
+
inference_state,
|
| 220 |
+
random_context,
|
| 221 |
+
compare_node,
|
| 222 |
+
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Filters are objects that you can use to filter names in different scopes. They
|
| 3 |
+
are needed for name resolution.
|
| 4 |
+
"""
|
| 5 |
+
from abc import abstractmethod
|
| 6 |
+
from typing import List, MutableMapping, Type
|
| 7 |
+
import weakref
|
| 8 |
+
|
| 9 |
+
from parso.tree import search_ancestor
|
| 10 |
+
from parso.python.tree import Name, UsedNamesMapping
|
| 11 |
+
|
| 12 |
+
from jedi.inference import flow_analysis
|
| 13 |
+
from jedi.inference.base_value import ValueSet, ValueWrapper, \
|
| 14 |
+
LazyValueWrapper
|
| 15 |
+
from jedi.parser_utils import get_cached_parent_scope, get_parso_cache_node
|
| 16 |
+
from jedi.inference.utils import to_list
|
| 17 |
+
from jedi.inference.names import TreeNameDefinition, ParamName, \
|
| 18 |
+
AnonymousParamName, AbstractNameDefinition, NameWrapper
|
| 19 |
+
|
| 20 |
+
_definition_name_cache: MutableMapping[UsedNamesMapping, List[Name]]
|
| 21 |
+
_definition_name_cache = weakref.WeakKeyDictionary()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class AbstractFilter:
|
| 25 |
+
_until_position = None
|
| 26 |
+
|
| 27 |
+
def _filter(self, names):
|
| 28 |
+
if self._until_position is not None:
|
| 29 |
+
return [n for n in names if n.start_pos < self._until_position]
|
| 30 |
+
return names
|
| 31 |
+
|
| 32 |
+
@abstractmethod
|
| 33 |
+
def get(self, name):
|
| 34 |
+
raise NotImplementedError
|
| 35 |
+
|
| 36 |
+
@abstractmethod
|
| 37 |
+
def values(self):
|
| 38 |
+
raise NotImplementedError
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class FilterWrapper:
|
| 42 |
+
name_wrapper_class: Type[NameWrapper]
|
| 43 |
+
|
| 44 |
+
def __init__(self, wrapped_filter):
|
| 45 |
+
self._wrapped_filter = wrapped_filter
|
| 46 |
+
|
| 47 |
+
def wrap_names(self, names):
|
| 48 |
+
return [self.name_wrapper_class(name) for name in names]
|
| 49 |
+
|
| 50 |
+
def get(self, name):
|
| 51 |
+
return self.wrap_names(self._wrapped_filter.get(name))
|
| 52 |
+
|
| 53 |
+
def values(self):
|
| 54 |
+
return self.wrap_names(self._wrapped_filter.values())
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _get_definition_names(parso_cache_node, used_names, name_key):
|
| 58 |
+
if parso_cache_node is None:
|
| 59 |
+
names = used_names.get(name_key, ())
|
| 60 |
+
return tuple(name for name in names if name.is_definition(include_setitem=True))
|
| 61 |
+
|
| 62 |
+
try:
|
| 63 |
+
for_module = _definition_name_cache[parso_cache_node]
|
| 64 |
+
except KeyError:
|
| 65 |
+
for_module = _definition_name_cache[parso_cache_node] = {}
|
| 66 |
+
|
| 67 |
+
try:
|
| 68 |
+
return for_module[name_key]
|
| 69 |
+
except KeyError:
|
| 70 |
+
names = used_names.get(name_key, ())
|
| 71 |
+
result = for_module[name_key] = tuple(
|
| 72 |
+
name for name in names if name.is_definition(include_setitem=True)
|
| 73 |
+
)
|
| 74 |
+
return result
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class _AbstractUsedNamesFilter(AbstractFilter):
|
| 78 |
+
name_class = TreeNameDefinition
|
| 79 |
+
|
| 80 |
+
def __init__(self, parent_context, node_context=None):
|
| 81 |
+
if node_context is None:
|
| 82 |
+
node_context = parent_context
|
| 83 |
+
self._node_context = node_context
|
| 84 |
+
self._parser_scope = node_context.tree_node
|
| 85 |
+
module_context = node_context.get_root_context()
|
| 86 |
+
# It is quite hacky that we have to use that. This is for caching
|
| 87 |
+
# certain things with a WeakKeyDictionary. However, parso intentionally
|
| 88 |
+
# uses slots (to save memory) and therefore we end up with having to
|
| 89 |
+
# have a weak reference to the object that caches the tree.
|
| 90 |
+
#
|
| 91 |
+
# Previously we have tried to solve this by using a weak reference onto
|
| 92 |
+
# used_names. However that also does not work, because it has a
|
| 93 |
+
# reference from the module, which itself is referenced by any node
|
| 94 |
+
# through parents.
|
| 95 |
+
path = module_context.py__file__()
|
| 96 |
+
if path is None:
|
| 97 |
+
# If the path is None, there is no guarantee that parso caches it.
|
| 98 |
+
self._parso_cache_node = None
|
| 99 |
+
else:
|
| 100 |
+
self._parso_cache_node = get_parso_cache_node(
|
| 101 |
+
module_context.inference_state.latest_grammar
|
| 102 |
+
if module_context.is_stub() else module_context.inference_state.grammar,
|
| 103 |
+
path
|
| 104 |
+
)
|
| 105 |
+
self._used_names = module_context.tree_node.get_used_names()
|
| 106 |
+
self.parent_context = parent_context
|
| 107 |
+
|
| 108 |
+
def get(self, name):
|
| 109 |
+
return self._convert_names(self._filter(
|
| 110 |
+
_get_definition_names(self._parso_cache_node, self._used_names, name),
|
| 111 |
+
))
|
| 112 |
+
|
| 113 |
+
def _convert_names(self, names):
|
| 114 |
+
return [self.name_class(self.parent_context, name) for name in names]
|
| 115 |
+
|
| 116 |
+
def values(self):
|
| 117 |
+
return self._convert_names(
|
| 118 |
+
name
|
| 119 |
+
for name_key in self._used_names
|
| 120 |
+
for name in self._filter(
|
| 121 |
+
_get_definition_names(self._parso_cache_node, self._used_names, name_key),
|
| 122 |
+
)
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
def __repr__(self):
|
| 126 |
+
return '<%s: %s>' % (self.__class__.__name__, self.parent_context)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class ParserTreeFilter(_AbstractUsedNamesFilter):
|
| 130 |
+
def __init__(self, parent_context, node_context=None, until_position=None,
|
| 131 |
+
origin_scope=None):
|
| 132 |
+
"""
|
| 133 |
+
node_context is an option to specify a second value for use cases
|
| 134 |
+
like the class mro where the parent class of a new name would be the
|
| 135 |
+
value, but for some type inference it's important to have a local
|
| 136 |
+
value of the other classes.
|
| 137 |
+
"""
|
| 138 |
+
super().__init__(parent_context, node_context)
|
| 139 |
+
self._origin_scope = origin_scope
|
| 140 |
+
self._until_position = until_position
|
| 141 |
+
|
| 142 |
+
def _filter(self, names):
|
| 143 |
+
names = super()._filter(names)
|
| 144 |
+
names = [n for n in names if self._is_name_reachable(n)]
|
| 145 |
+
return list(self._check_flows(names))
|
| 146 |
+
|
| 147 |
+
def _is_name_reachable(self, name):
|
| 148 |
+
parent = name.parent
|
| 149 |
+
if parent.type == 'trailer':
|
| 150 |
+
return False
|
| 151 |
+
base_node = parent if parent.type in ('classdef', 'funcdef') else name
|
| 152 |
+
return get_cached_parent_scope(self._parso_cache_node, base_node) == self._parser_scope
|
| 153 |
+
|
| 154 |
+
def _check_flows(self, names):
|
| 155 |
+
for name in sorted(names, key=lambda name: name.start_pos, reverse=True):
|
| 156 |
+
check = flow_analysis.reachability_check(
|
| 157 |
+
context=self._node_context,
|
| 158 |
+
value_scope=self._parser_scope,
|
| 159 |
+
node=name,
|
| 160 |
+
origin_scope=self._origin_scope
|
| 161 |
+
)
|
| 162 |
+
if check is not flow_analysis.UNREACHABLE:
|
| 163 |
+
yield name
|
| 164 |
+
|
| 165 |
+
if check is flow_analysis.REACHABLE:
|
| 166 |
+
break
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class _FunctionExecutionFilter(ParserTreeFilter):
|
| 170 |
+
def __init__(self, parent_context, function_value, until_position, origin_scope):
|
| 171 |
+
super().__init__(
|
| 172 |
+
parent_context,
|
| 173 |
+
until_position=until_position,
|
| 174 |
+
origin_scope=origin_scope,
|
| 175 |
+
)
|
| 176 |
+
self._function_value = function_value
|
| 177 |
+
|
| 178 |
+
def _convert_param(self, param, name):
|
| 179 |
+
raise NotImplementedError
|
| 180 |
+
|
| 181 |
+
@to_list
|
| 182 |
+
def _convert_names(self, names):
|
| 183 |
+
for name in names:
|
| 184 |
+
param = search_ancestor(name, 'param')
|
| 185 |
+
# Here we don't need to check if the param is a default/annotation,
|
| 186 |
+
# because those are not definitions and never make it to this
|
| 187 |
+
# point.
|
| 188 |
+
if param:
|
| 189 |
+
yield self._convert_param(param, name)
|
| 190 |
+
else:
|
| 191 |
+
yield TreeNameDefinition(self.parent_context, name)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
class FunctionExecutionFilter(_FunctionExecutionFilter):
|
| 195 |
+
def __init__(self, *args, arguments, **kwargs):
|
| 196 |
+
super().__init__(*args, **kwargs)
|
| 197 |
+
self._arguments = arguments
|
| 198 |
+
|
| 199 |
+
def _convert_param(self, param, name):
|
| 200 |
+
return ParamName(self._function_value, name, self._arguments)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
class AnonymousFunctionExecutionFilter(_FunctionExecutionFilter):
|
| 204 |
+
def _convert_param(self, param, name):
|
| 205 |
+
return AnonymousParamName(self._function_value, name)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
class GlobalNameFilter(_AbstractUsedNamesFilter):
|
| 209 |
+
def get(self, name):
|
| 210 |
+
try:
|
| 211 |
+
names = self._used_names[name]
|
| 212 |
+
except KeyError:
|
| 213 |
+
return []
|
| 214 |
+
return self._convert_names(self._filter(names))
|
| 215 |
+
|
| 216 |
+
@to_list
|
| 217 |
+
def _filter(self, names):
|
| 218 |
+
for name in names:
|
| 219 |
+
if name.parent.type == 'global_stmt':
|
| 220 |
+
yield name
|
| 221 |
+
|
| 222 |
+
def values(self):
|
| 223 |
+
return self._convert_names(
|
| 224 |
+
name for name_list in self._used_names.values()
|
| 225 |
+
for name in self._filter(name_list)
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
class DictFilter(AbstractFilter):
|
| 230 |
+
def __init__(self, dct):
|
| 231 |
+
self._dct = dct
|
| 232 |
+
|
| 233 |
+
def get(self, name):
|
| 234 |
+
try:
|
| 235 |
+
value = self._convert(name, self._dct[name])
|
| 236 |
+
except KeyError:
|
| 237 |
+
return []
|
| 238 |
+
else:
|
| 239 |
+
return list(self._filter([value]))
|
| 240 |
+
|
| 241 |
+
def values(self):
|
| 242 |
+
def yielder():
|
| 243 |
+
for item in self._dct.items():
|
| 244 |
+
try:
|
| 245 |
+
yield self._convert(*item)
|
| 246 |
+
except KeyError:
|
| 247 |
+
pass
|
| 248 |
+
return self._filter(yielder())
|
| 249 |
+
|
| 250 |
+
def _convert(self, name, value):
|
| 251 |
+
return value
|
| 252 |
+
|
| 253 |
+
def __repr__(self):
|
| 254 |
+
keys = ', '.join(self._dct.keys())
|
| 255 |
+
return '<%s: for {%s}>' % (self.__class__.__name__, keys)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
class MergedFilter:
|
| 259 |
+
def __init__(self, *filters):
|
| 260 |
+
self._filters = filters
|
| 261 |
+
|
| 262 |
+
def get(self, name):
|
| 263 |
+
return [n for filter in self._filters for n in filter.get(name)]
|
| 264 |
+
|
| 265 |
+
def values(self):
|
| 266 |
+
return [n for filter in self._filters for n in filter.values()]
|
| 267 |
+
|
| 268 |
+
def __repr__(self):
|
| 269 |
+
return '%s(%s)' % (self.__class__.__name__, ', '.join(str(f) for f in self._filters))
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
class _BuiltinMappedMethod(ValueWrapper):
|
| 273 |
+
"""``Generator.__next__`` ``dict.values`` methods and so on."""
|
| 274 |
+
api_type = 'function'
|
| 275 |
+
|
| 276 |
+
def __init__(self, value, method, builtin_func):
|
| 277 |
+
super().__init__(builtin_func)
|
| 278 |
+
self._value = value
|
| 279 |
+
self._method = method
|
| 280 |
+
|
| 281 |
+
def py__call__(self, arguments):
|
| 282 |
+
# TODO add TypeError if params are given/or not correct.
|
| 283 |
+
return self._method(self._value, arguments)
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
class SpecialMethodFilter(DictFilter):
|
| 287 |
+
"""
|
| 288 |
+
A filter for methods that are defined in this module on the corresponding
|
| 289 |
+
classes like Generator (for __next__, etc).
|
| 290 |
+
"""
|
| 291 |
+
class SpecialMethodName(AbstractNameDefinition):
|
| 292 |
+
api_type = 'function'
|
| 293 |
+
|
| 294 |
+
def __init__(self, parent_context, string_name, callable_, builtin_value):
|
| 295 |
+
self.parent_context = parent_context
|
| 296 |
+
self.string_name = string_name
|
| 297 |
+
self._callable = callable_
|
| 298 |
+
self._builtin_value = builtin_value
|
| 299 |
+
|
| 300 |
+
def infer(self):
|
| 301 |
+
for filter in self._builtin_value.get_filters():
|
| 302 |
+
# We can take the first index, because on builtin methods there's
|
| 303 |
+
# always only going to be one name. The same is true for the
|
| 304 |
+
# inferred values.
|
| 305 |
+
for name in filter.get(self.string_name):
|
| 306 |
+
builtin_func = next(iter(name.infer()))
|
| 307 |
+
break
|
| 308 |
+
else:
|
| 309 |
+
continue
|
| 310 |
+
break
|
| 311 |
+
return ValueSet([
|
| 312 |
+
_BuiltinMappedMethod(self.parent_context, self._callable, builtin_func)
|
| 313 |
+
])
|
| 314 |
+
|
| 315 |
+
def __init__(self, value, dct, builtin_value):
|
| 316 |
+
super().__init__(dct)
|
| 317 |
+
self.value = value
|
| 318 |
+
self._builtin_value = builtin_value
|
| 319 |
+
"""
|
| 320 |
+
This value is what will be used to introspect the name, where as the
|
| 321 |
+
other value will be used to execute the function.
|
| 322 |
+
|
| 323 |
+
We distinguish, because we have to.
|
| 324 |
+
"""
|
| 325 |
+
|
| 326 |
+
def _convert(self, name, value):
|
| 327 |
+
return self.SpecialMethodName(self.value, name, value, self._builtin_value)
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
class _OverwriteMeta(type):
|
| 331 |
+
def __init__(cls, name, bases, dct):
|
| 332 |
+
super().__init__(name, bases, dct)
|
| 333 |
+
|
| 334 |
+
base_dct = {}
|
| 335 |
+
for base_cls in reversed(cls.__bases__):
|
| 336 |
+
try:
|
| 337 |
+
base_dct.update(base_cls.overwritten_methods)
|
| 338 |
+
except AttributeError:
|
| 339 |
+
pass
|
| 340 |
+
|
| 341 |
+
for func in cls.__dict__.values():
|
| 342 |
+
try:
|
| 343 |
+
base_dct.update(func.registered_overwritten_methods)
|
| 344 |
+
except AttributeError:
|
| 345 |
+
pass
|
| 346 |
+
cls.overwritten_methods = base_dct
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
class _AttributeOverwriteMixin:
|
| 350 |
+
def get_filters(self, *args, **kwargs):
|
| 351 |
+
yield SpecialMethodFilter(self, self.overwritten_methods, self._wrapped_value)
|
| 352 |
+
yield from self._wrapped_value.get_filters(*args, **kwargs)
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
class LazyAttributeOverwrite(_AttributeOverwriteMixin, LazyValueWrapper,
|
| 356 |
+
metaclass=_OverwriteMeta):
|
| 357 |
+
def __init__(self, inference_state):
|
| 358 |
+
self.inference_state = inference_state
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
class AttributeOverwrite(_AttributeOverwriteMixin, ValueWrapper,
|
| 362 |
+
metaclass=_OverwriteMeta):
|
| 363 |
+
pass
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
def publish_method(method_name):
|
| 367 |
+
def decorator(func):
|
| 368 |
+
dct = func.__dict__.setdefault('registered_overwritten_methods', {})
|
| 369 |
+
dct[method_name] = func
|
| 370 |
+
return func
|
| 371 |
+
return decorator
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/finder.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Searching for names with given scope and name. This is very central in Jedi and
|
| 3 |
+
Python. The name resolution is quite complicated with descripter,
|
| 4 |
+
``__getattribute__``, ``__getattr__``, ``global``, etc.
|
| 5 |
+
|
| 6 |
+
If you want to understand name resolution, please read the first few chapters
|
| 7 |
+
in http://blog.ionelmc.ro/2015/02/09/understanding-python-metaclasses/.
|
| 8 |
+
|
| 9 |
+
Flow checks
|
| 10 |
+
+++++++++++
|
| 11 |
+
|
| 12 |
+
Flow checks are not really mature. There's only a check for ``isinstance``. It
|
| 13 |
+
would check whether a flow has the form of ``if isinstance(a, type_or_tuple)``.
|
| 14 |
+
Unfortunately every other thing is being ignored (e.g. a == '' would be easy to
|
| 15 |
+
check for -> a is a string). There's big potential in these checks.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from parso.tree import search_ancestor
|
| 19 |
+
from parso.python.tree import Name
|
| 20 |
+
|
| 21 |
+
from jedi import settings
|
| 22 |
+
from jedi.inference.arguments import TreeArguments
|
| 23 |
+
from jedi.inference.value import iterable
|
| 24 |
+
from jedi.inference.base_value import NO_VALUES
|
| 25 |
+
from jedi.parser_utils import is_scope
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def filter_name(filters, name_or_str):
|
| 29 |
+
"""
|
| 30 |
+
Searches names that are defined in a scope (the different
|
| 31 |
+
``filters``), until a name fits.
|
| 32 |
+
"""
|
| 33 |
+
string_name = name_or_str.value if isinstance(name_or_str, Name) else name_or_str
|
| 34 |
+
names = []
|
| 35 |
+
for filter in filters:
|
| 36 |
+
names = filter.get(string_name)
|
| 37 |
+
if names:
|
| 38 |
+
break
|
| 39 |
+
|
| 40 |
+
return list(_remove_del_stmt(names))
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _remove_del_stmt(names):
|
| 44 |
+
# Catch del statements and remove them from results.
|
| 45 |
+
for name in names:
|
| 46 |
+
if name.tree_name is not None:
|
| 47 |
+
definition = name.tree_name.get_definition()
|
| 48 |
+
if definition is not None and definition.type == 'del_stmt':
|
| 49 |
+
continue
|
| 50 |
+
yield name
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def check_flow_information(value, flow, search_name, pos):
|
| 54 |
+
""" Try to find out the type of a variable just with the information that
|
| 55 |
+
is given by the flows: e.g. It is also responsible for assert checks.::
|
| 56 |
+
|
| 57 |
+
if isinstance(k, str):
|
| 58 |
+
k. # <- completion here
|
| 59 |
+
|
| 60 |
+
ensures that `k` is a string.
|
| 61 |
+
"""
|
| 62 |
+
if not settings.dynamic_flow_information:
|
| 63 |
+
return None
|
| 64 |
+
|
| 65 |
+
result = None
|
| 66 |
+
if is_scope(flow):
|
| 67 |
+
# Check for asserts.
|
| 68 |
+
module_node = flow.get_root_node()
|
| 69 |
+
try:
|
| 70 |
+
names = module_node.get_used_names()[search_name.value]
|
| 71 |
+
except KeyError:
|
| 72 |
+
return None
|
| 73 |
+
names = reversed([
|
| 74 |
+
n for n in names
|
| 75 |
+
if flow.start_pos <= n.start_pos < (pos or flow.end_pos)
|
| 76 |
+
])
|
| 77 |
+
|
| 78 |
+
for name in names:
|
| 79 |
+
ass = search_ancestor(name, 'assert_stmt')
|
| 80 |
+
if ass is not None:
|
| 81 |
+
result = _check_isinstance_type(value, ass.assertion, search_name)
|
| 82 |
+
if result is not None:
|
| 83 |
+
return result
|
| 84 |
+
|
| 85 |
+
if flow.type in ('if_stmt', 'while_stmt'):
|
| 86 |
+
potential_ifs = [c for c in flow.children[1::4] if c != ':']
|
| 87 |
+
for if_test in reversed(potential_ifs):
|
| 88 |
+
if search_name.start_pos > if_test.end_pos:
|
| 89 |
+
return _check_isinstance_type(value, if_test, search_name)
|
| 90 |
+
return result
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _get_isinstance_trailer_arglist(node):
|
| 94 |
+
if node.type in ('power', 'atom_expr') and len(node.children) == 2:
|
| 95 |
+
# This might be removed if we analyze and, etc
|
| 96 |
+
first, trailer = node.children
|
| 97 |
+
if first.type == 'name' and first.value == 'isinstance' \
|
| 98 |
+
and trailer.type == 'trailer' and trailer.children[0] == '(':
|
| 99 |
+
return trailer
|
| 100 |
+
return None
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def _check_isinstance_type(value, node, search_name):
|
| 104 |
+
lazy_cls = None
|
| 105 |
+
trailer = _get_isinstance_trailer_arglist(node)
|
| 106 |
+
if trailer is not None and len(trailer.children) == 3:
|
| 107 |
+
arglist = trailer.children[1]
|
| 108 |
+
args = TreeArguments(value.inference_state, value, arglist, trailer)
|
| 109 |
+
param_list = list(args.unpack())
|
| 110 |
+
# Disallow keyword arguments
|
| 111 |
+
if len(param_list) == 2 and len(arglist.children) == 3:
|
| 112 |
+
(key1, _), (key2, lazy_value_cls) = param_list
|
| 113 |
+
if key1 is None and key2 is None:
|
| 114 |
+
call = _get_call_string(search_name)
|
| 115 |
+
is_instance_call = _get_call_string(arglist.children[0])
|
| 116 |
+
# Do a simple get_code comparison of the strings . They should
|
| 117 |
+
# just have the same code, and everything will be all right.
|
| 118 |
+
# There are ways that this is not correct, if some stuff is
|
| 119 |
+
# redefined in between. However here we don't care, because
|
| 120 |
+
# it's a heuristic that works pretty well.
|
| 121 |
+
if call == is_instance_call:
|
| 122 |
+
lazy_cls = lazy_value_cls
|
| 123 |
+
if lazy_cls is None:
|
| 124 |
+
return None
|
| 125 |
+
|
| 126 |
+
value_set = NO_VALUES
|
| 127 |
+
for cls_or_tup in lazy_cls.infer():
|
| 128 |
+
if isinstance(cls_or_tup, iterable.Sequence) and cls_or_tup.array_type == 'tuple':
|
| 129 |
+
for lazy_value in cls_or_tup.py__iter__():
|
| 130 |
+
value_set |= lazy_value.infer().execute_with_values()
|
| 131 |
+
else:
|
| 132 |
+
value_set |= cls_or_tup.execute_with_values()
|
| 133 |
+
return value_set
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _get_call_string(node):
|
| 137 |
+
if node.parent.type == 'atom_expr':
|
| 138 |
+
return _get_call_string(node.parent)
|
| 139 |
+
|
| 140 |
+
code = ''
|
| 141 |
+
leaf = node.get_first_leaf()
|
| 142 |
+
end = node.get_last_leaf().end_pos
|
| 143 |
+
while leaf.start_pos < end:
|
| 144 |
+
code += leaf.value
|
| 145 |
+
leaf = leaf.get_next_leaf()
|
| 146 |
+
return code
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/flow_analysis.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, Optional
|
| 2 |
+
|
| 3 |
+
from jedi.parser_utils import get_flow_branch_keyword, is_scope, get_parent_scope
|
| 4 |
+
from jedi.inference.recursion import execution_allowed
|
| 5 |
+
from jedi.inference.helpers import is_big_annoying_library
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Status:
|
| 9 |
+
lookup_table: Dict[Optional[bool], 'Status'] = {}
|
| 10 |
+
|
| 11 |
+
def __init__(self, value: Optional[bool], name: str) -> None:
|
| 12 |
+
self._value = value
|
| 13 |
+
self._name = name
|
| 14 |
+
Status.lookup_table[value] = self
|
| 15 |
+
|
| 16 |
+
def invert(self):
|
| 17 |
+
if self is REACHABLE:
|
| 18 |
+
return UNREACHABLE
|
| 19 |
+
elif self is UNREACHABLE:
|
| 20 |
+
return REACHABLE
|
| 21 |
+
else:
|
| 22 |
+
return UNSURE
|
| 23 |
+
|
| 24 |
+
def __and__(self, other):
|
| 25 |
+
if UNSURE in (self, other):
|
| 26 |
+
return UNSURE
|
| 27 |
+
else:
|
| 28 |
+
return REACHABLE if self._value and other._value else UNREACHABLE
|
| 29 |
+
|
| 30 |
+
def __repr__(self):
|
| 31 |
+
return '<%s: %s>' % (type(self).__name__, self._name)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
REACHABLE = Status(True, 'reachable')
|
| 35 |
+
UNREACHABLE = Status(False, 'unreachable')
|
| 36 |
+
UNSURE = Status(None, 'unsure')
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _get_flow_scopes(node):
|
| 40 |
+
while True:
|
| 41 |
+
node = get_parent_scope(node, include_flows=True)
|
| 42 |
+
if node is None or is_scope(node):
|
| 43 |
+
return
|
| 44 |
+
yield node
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def reachability_check(context, value_scope, node, origin_scope=None):
|
| 48 |
+
if is_big_annoying_library(context) \
|
| 49 |
+
or not context.inference_state.flow_analysis_enabled:
|
| 50 |
+
return UNSURE
|
| 51 |
+
|
| 52 |
+
first_flow_scope = get_parent_scope(node, include_flows=True)
|
| 53 |
+
if origin_scope is not None:
|
| 54 |
+
origin_flow_scopes = list(_get_flow_scopes(origin_scope))
|
| 55 |
+
node_flow_scopes = list(_get_flow_scopes(node))
|
| 56 |
+
|
| 57 |
+
branch_matches = True
|
| 58 |
+
for flow_scope in origin_flow_scopes:
|
| 59 |
+
if flow_scope in node_flow_scopes:
|
| 60 |
+
node_keyword = get_flow_branch_keyword(flow_scope, node)
|
| 61 |
+
origin_keyword = get_flow_branch_keyword(flow_scope, origin_scope)
|
| 62 |
+
branch_matches = node_keyword == origin_keyword
|
| 63 |
+
if flow_scope.type == 'if_stmt':
|
| 64 |
+
if not branch_matches:
|
| 65 |
+
return UNREACHABLE
|
| 66 |
+
elif flow_scope.type == 'try_stmt':
|
| 67 |
+
if not branch_matches and origin_keyword == 'else' \
|
| 68 |
+
and node_keyword == 'except':
|
| 69 |
+
return UNREACHABLE
|
| 70 |
+
if branch_matches:
|
| 71 |
+
break
|
| 72 |
+
|
| 73 |
+
# Direct parents get resolved, we filter scopes that are separate
|
| 74 |
+
# branches. This makes sense for autocompletion and static analysis.
|
| 75 |
+
# For actual Python it doesn't matter, because we're talking about
|
| 76 |
+
# potentially unreachable code.
|
| 77 |
+
# e.g. `if 0:` would cause all name lookup within the flow make
|
| 78 |
+
# unaccessible. This is not a "problem" in Python, because the code is
|
| 79 |
+
# never called. In Jedi though, we still want to infer types.
|
| 80 |
+
while origin_scope is not None:
|
| 81 |
+
if first_flow_scope == origin_scope and branch_matches:
|
| 82 |
+
return REACHABLE
|
| 83 |
+
origin_scope = origin_scope.parent
|
| 84 |
+
|
| 85 |
+
return _break_check(context, value_scope, first_flow_scope, node)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _break_check(context, value_scope, flow_scope, node):
|
| 89 |
+
reachable = REACHABLE
|
| 90 |
+
if flow_scope.type == 'if_stmt':
|
| 91 |
+
if flow_scope.is_node_after_else(node):
|
| 92 |
+
for check_node in flow_scope.get_test_nodes():
|
| 93 |
+
reachable = _check_if(context, check_node)
|
| 94 |
+
if reachable in (REACHABLE, UNSURE):
|
| 95 |
+
break
|
| 96 |
+
reachable = reachable.invert()
|
| 97 |
+
else:
|
| 98 |
+
flow_node = flow_scope.get_corresponding_test_node(node)
|
| 99 |
+
if flow_node is not None:
|
| 100 |
+
reachable = _check_if(context, flow_node)
|
| 101 |
+
elif flow_scope.type in ('try_stmt', 'while_stmt'):
|
| 102 |
+
return UNSURE
|
| 103 |
+
|
| 104 |
+
# Only reachable branches need to be examined further.
|
| 105 |
+
if reachable in (UNREACHABLE, UNSURE):
|
| 106 |
+
return reachable
|
| 107 |
+
|
| 108 |
+
if value_scope != flow_scope and value_scope != flow_scope.parent:
|
| 109 |
+
flow_scope = get_parent_scope(flow_scope, include_flows=True)
|
| 110 |
+
return reachable & _break_check(context, value_scope, flow_scope, node)
|
| 111 |
+
else:
|
| 112 |
+
return reachable
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _check_if(context, node):
|
| 116 |
+
with execution_allowed(context.inference_state, node) as allowed:
|
| 117 |
+
if not allowed:
|
| 118 |
+
return UNSURE
|
| 119 |
+
|
| 120 |
+
types = context.infer_node(node)
|
| 121 |
+
values = set(x.py__bool__() for x in types)
|
| 122 |
+
if len(values) == 1:
|
| 123 |
+
return Status.lookup_table[values.pop()]
|
| 124 |
+
else:
|
| 125 |
+
return UNSURE
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/helpers.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import sys
|
| 3 |
+
import re
|
| 4 |
+
import os
|
| 5 |
+
from itertools import chain
|
| 6 |
+
from contextlib import contextmanager
|
| 7 |
+
|
| 8 |
+
from parso.python import tree
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def is_stdlib_path(path):
|
| 12 |
+
# Python standard library paths look like this:
|
| 13 |
+
# /usr/lib/python3.9/...
|
| 14 |
+
# TODO The implementation below is probably incorrect and not complete.
|
| 15 |
+
parts = path.parts
|
| 16 |
+
if 'dist-packages' in parts or 'site-packages' in parts:
|
| 17 |
+
return False
|
| 18 |
+
|
| 19 |
+
base_path = os.path.join(sys.prefix, 'lib', 'python')
|
| 20 |
+
return bool(re.match(re.escape(base_path) + r'\d.\d', str(path)))
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def deep_ast_copy(obj):
|
| 24 |
+
"""
|
| 25 |
+
Much, much faster than copy.deepcopy, but just for parser tree nodes.
|
| 26 |
+
"""
|
| 27 |
+
# If it's already in the cache, just return it.
|
| 28 |
+
new_obj = copy.copy(obj)
|
| 29 |
+
|
| 30 |
+
# Copy children
|
| 31 |
+
new_children = []
|
| 32 |
+
for child in obj.children:
|
| 33 |
+
if isinstance(child, tree.Leaf):
|
| 34 |
+
new_child = copy.copy(child)
|
| 35 |
+
new_child.parent = new_obj
|
| 36 |
+
else:
|
| 37 |
+
new_child = deep_ast_copy(child)
|
| 38 |
+
new_child.parent = new_obj
|
| 39 |
+
new_children.append(new_child)
|
| 40 |
+
new_obj.children = new_children
|
| 41 |
+
|
| 42 |
+
return new_obj
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def infer_call_of_leaf(context, leaf, cut_own_trailer=False):
|
| 46 |
+
"""
|
| 47 |
+
Creates a "call" node that consist of all ``trailer`` and ``power``
|
| 48 |
+
objects. E.g. if you call it with ``append``::
|
| 49 |
+
|
| 50 |
+
list([]).append(3) or None
|
| 51 |
+
|
| 52 |
+
You would get a node with the content ``list([]).append`` back.
|
| 53 |
+
|
| 54 |
+
This generates a copy of the original ast node.
|
| 55 |
+
|
| 56 |
+
If you're using the leaf, e.g. the bracket `)` it will return ``list([])``.
|
| 57 |
+
|
| 58 |
+
We use this function for two purposes. Given an expression ``bar.foo``,
|
| 59 |
+
we may want to
|
| 60 |
+
- infer the type of ``foo`` to offer completions after foo
|
| 61 |
+
- infer the type of ``bar`` to be able to jump to the definition of foo
|
| 62 |
+
The option ``cut_own_trailer`` must be set to true for the second purpose.
|
| 63 |
+
"""
|
| 64 |
+
trailer = leaf.parent
|
| 65 |
+
if trailer.type == 'fstring':
|
| 66 |
+
from jedi.inference import compiled
|
| 67 |
+
return compiled.get_string_value_set(context.inference_state)
|
| 68 |
+
|
| 69 |
+
# The leaf may not be the last or first child, because there exist three
|
| 70 |
+
# different trailers: `( x )`, `[ x ]` and `.x`. In the first two examples
|
| 71 |
+
# we should not match anything more than x.
|
| 72 |
+
if trailer.type != 'trailer' or leaf not in (trailer.children[0], trailer.children[-1]):
|
| 73 |
+
if leaf == ':':
|
| 74 |
+
# Basically happens with foo[:] when the cursor is on the colon
|
| 75 |
+
from jedi.inference.base_value import NO_VALUES
|
| 76 |
+
return NO_VALUES
|
| 77 |
+
if trailer.type == 'atom':
|
| 78 |
+
return context.infer_node(trailer)
|
| 79 |
+
return context.infer_node(leaf)
|
| 80 |
+
|
| 81 |
+
power = trailer.parent
|
| 82 |
+
index = power.children.index(trailer)
|
| 83 |
+
if cut_own_trailer:
|
| 84 |
+
cut = index
|
| 85 |
+
else:
|
| 86 |
+
cut = index + 1
|
| 87 |
+
|
| 88 |
+
if power.type == 'error_node':
|
| 89 |
+
start = index
|
| 90 |
+
while True:
|
| 91 |
+
start -= 1
|
| 92 |
+
base = power.children[start]
|
| 93 |
+
if base.type != 'trailer':
|
| 94 |
+
break
|
| 95 |
+
trailers = power.children[start + 1:cut]
|
| 96 |
+
else:
|
| 97 |
+
base = power.children[0]
|
| 98 |
+
trailers = power.children[1:cut]
|
| 99 |
+
|
| 100 |
+
if base == 'await':
|
| 101 |
+
base = trailers[0]
|
| 102 |
+
trailers = trailers[1:]
|
| 103 |
+
|
| 104 |
+
values = context.infer_node(base)
|
| 105 |
+
from jedi.inference.syntax_tree import infer_trailer
|
| 106 |
+
for trailer in trailers:
|
| 107 |
+
values = infer_trailer(context, values, trailer)
|
| 108 |
+
return values
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def get_names_of_node(node):
|
| 112 |
+
try:
|
| 113 |
+
children = node.children
|
| 114 |
+
except AttributeError:
|
| 115 |
+
if node.type == 'name':
|
| 116 |
+
return [node]
|
| 117 |
+
else:
|
| 118 |
+
return []
|
| 119 |
+
else:
|
| 120 |
+
return list(chain.from_iterable(get_names_of_node(c) for c in children))
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def is_string(value):
|
| 124 |
+
return value.is_compiled() and isinstance(value.get_safe_value(default=None), str)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def is_literal(value):
|
| 128 |
+
return is_number(value) or is_string(value)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _get_safe_value_or_none(value, accept):
|
| 132 |
+
value = value.get_safe_value(default=None)
|
| 133 |
+
if isinstance(value, accept):
|
| 134 |
+
return value
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def get_int_or_none(value):
|
| 138 |
+
return _get_safe_value_or_none(value, int)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def get_str_or_none(value):
|
| 142 |
+
return _get_safe_value_or_none(value, str)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def is_number(value):
|
| 146 |
+
return _get_safe_value_or_none(value, (int, float)) is not None
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class SimpleGetItemNotFound(Exception):
|
| 150 |
+
pass
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
@contextmanager
|
| 154 |
+
def reraise_getitem_errors(*exception_classes):
|
| 155 |
+
try:
|
| 156 |
+
yield
|
| 157 |
+
except exception_classes as e:
|
| 158 |
+
raise SimpleGetItemNotFound(e)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def parse_dotted_names(nodes, is_import_from, until_node=None):
|
| 162 |
+
level = 0
|
| 163 |
+
names = []
|
| 164 |
+
for node in nodes[1:]:
|
| 165 |
+
if node in ('.', '...'):
|
| 166 |
+
if not names:
|
| 167 |
+
level += len(node.value)
|
| 168 |
+
elif node.type == 'dotted_name':
|
| 169 |
+
for n in node.children[::2]:
|
| 170 |
+
names.append(n)
|
| 171 |
+
if n is until_node:
|
| 172 |
+
break
|
| 173 |
+
else:
|
| 174 |
+
continue
|
| 175 |
+
break
|
| 176 |
+
elif node.type == 'name':
|
| 177 |
+
names.append(node)
|
| 178 |
+
if node is until_node:
|
| 179 |
+
break
|
| 180 |
+
elif node == ',':
|
| 181 |
+
if not is_import_from:
|
| 182 |
+
names = []
|
| 183 |
+
else:
|
| 184 |
+
# Here if the keyword `import` comes along it stops checking
|
| 185 |
+
# for names.
|
| 186 |
+
break
|
| 187 |
+
return level, names
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def values_from_qualified_names(inference_state, *names):
|
| 191 |
+
return inference_state.import_module(names[:-1]).py__getattribute__(names[-1])
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def is_big_annoying_library(context):
|
| 195 |
+
string_names = context.get_root_context().string_names
|
| 196 |
+
if string_names is None:
|
| 197 |
+
return False
|
| 198 |
+
|
| 199 |
+
# Especially pandas and tensorflow are huge complicated Python libraries
|
| 200 |
+
# that get even slower than they already are when Jedi tries to undrstand
|
| 201 |
+
# dynamic features like decorators, ifs and other stuff.
|
| 202 |
+
return string_names[0] in ('pandas', 'numpy', 'tensorflow', 'matplotlib')
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/imports.py
ADDED
|
@@ -0,0 +1,592 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
:mod:`jedi.inference.imports` is here to resolve import statements and return
|
| 3 |
+
the modules/classes/functions/whatever, which they stand for. However there's
|
| 4 |
+
not any actual importing done. This module is about finding modules in the
|
| 5 |
+
filesystem. This can be quite tricky sometimes, because Python imports are not
|
| 6 |
+
always that simple.
|
| 7 |
+
|
| 8 |
+
This module also supports import autocompletion, which means to complete
|
| 9 |
+
statements like ``from datetim`` (cursor at the end would return ``datetime``).
|
| 10 |
+
"""
|
| 11 |
+
import os
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
from parso.python import tree
|
| 15 |
+
from parso.tree import search_ancestor
|
| 16 |
+
|
| 17 |
+
from jedi import debug
|
| 18 |
+
from jedi import settings
|
| 19 |
+
from jedi.file_io import FolderIO
|
| 20 |
+
from jedi.parser_utils import get_cached_code_lines
|
| 21 |
+
from jedi.inference import sys_path
|
| 22 |
+
from jedi.inference import helpers
|
| 23 |
+
from jedi.inference import compiled
|
| 24 |
+
from jedi.inference import analysis
|
| 25 |
+
from jedi.inference.utils import unite
|
| 26 |
+
from jedi.inference.cache import inference_state_method_cache
|
| 27 |
+
from jedi.inference.names import ImportName, SubModuleName
|
| 28 |
+
from jedi.inference.base_value import ValueSet, NO_VALUES
|
| 29 |
+
from jedi.inference.gradual.typeshed import import_module_decorator, \
|
| 30 |
+
create_stub_module, parse_stub_module
|
| 31 |
+
from jedi.inference.compiled.subprocess.functions import ImplicitNSInfo
|
| 32 |
+
from jedi.plugins import plugin_manager
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class ModuleCache:
|
| 36 |
+
def __init__(self):
|
| 37 |
+
self._name_cache = {}
|
| 38 |
+
|
| 39 |
+
def add(self, string_names, value_set):
|
| 40 |
+
if string_names is not None:
|
| 41 |
+
self._name_cache[string_names] = value_set
|
| 42 |
+
|
| 43 |
+
def get(self, string_names):
|
| 44 |
+
return self._name_cache.get(string_names)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
# This memoization is needed, because otherwise we will infinitely loop on
|
| 48 |
+
# certain imports.
|
| 49 |
+
@inference_state_method_cache(default=NO_VALUES)
|
| 50 |
+
def infer_import(context, tree_name):
|
| 51 |
+
module_context = context.get_root_context()
|
| 52 |
+
from_import_name, import_path, level, values = \
|
| 53 |
+
_prepare_infer_import(module_context, tree_name)
|
| 54 |
+
if values:
|
| 55 |
+
|
| 56 |
+
if from_import_name is not None:
|
| 57 |
+
values = values.py__getattribute__(
|
| 58 |
+
from_import_name,
|
| 59 |
+
name_context=context,
|
| 60 |
+
analysis_errors=False
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
if not values:
|
| 64 |
+
path = import_path + (from_import_name,)
|
| 65 |
+
importer = Importer(context.inference_state, path, module_context, level)
|
| 66 |
+
values = importer.follow()
|
| 67 |
+
debug.dbg('after import: %s', values)
|
| 68 |
+
return values
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
@inference_state_method_cache(default=[])
|
| 72 |
+
def goto_import(context, tree_name):
|
| 73 |
+
module_context = context.get_root_context()
|
| 74 |
+
from_import_name, import_path, level, values = \
|
| 75 |
+
_prepare_infer_import(module_context, tree_name)
|
| 76 |
+
if not values:
|
| 77 |
+
return []
|
| 78 |
+
|
| 79 |
+
if from_import_name is not None:
|
| 80 |
+
names = unite([
|
| 81 |
+
c.goto(
|
| 82 |
+
from_import_name,
|
| 83 |
+
name_context=context,
|
| 84 |
+
analysis_errors=False
|
| 85 |
+
) for c in values
|
| 86 |
+
])
|
| 87 |
+
# Avoid recursion on the same names.
|
| 88 |
+
if names and not any(n.tree_name is tree_name for n in names):
|
| 89 |
+
return names
|
| 90 |
+
|
| 91 |
+
path = import_path + (from_import_name,)
|
| 92 |
+
importer = Importer(context.inference_state, path, module_context, level)
|
| 93 |
+
values = importer.follow()
|
| 94 |
+
return set(s.name for s in values)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _prepare_infer_import(module_context, tree_name):
|
| 98 |
+
import_node = search_ancestor(tree_name, 'import_name', 'import_from')
|
| 99 |
+
import_path = import_node.get_path_for_name(tree_name)
|
| 100 |
+
from_import_name = None
|
| 101 |
+
try:
|
| 102 |
+
from_names = import_node.get_from_names()
|
| 103 |
+
except AttributeError:
|
| 104 |
+
# Is an import_name
|
| 105 |
+
pass
|
| 106 |
+
else:
|
| 107 |
+
if len(from_names) + 1 == len(import_path):
|
| 108 |
+
# We have to fetch the from_names part first and then check
|
| 109 |
+
# if from_names exists in the modules.
|
| 110 |
+
from_import_name = import_path[-1]
|
| 111 |
+
import_path = from_names
|
| 112 |
+
|
| 113 |
+
importer = Importer(module_context.inference_state, tuple(import_path),
|
| 114 |
+
module_context, import_node.level)
|
| 115 |
+
|
| 116 |
+
return from_import_name, tuple(import_path), import_node.level, importer.follow()
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def _add_error(value, name, message):
|
| 120 |
+
if hasattr(name, 'parent') and value is not None:
|
| 121 |
+
analysis.add(value, 'import-error', name, message)
|
| 122 |
+
else:
|
| 123 |
+
debug.warning('ImportError without origin: ' + message)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _level_to_base_import_path(project_path, directory, level):
|
| 127 |
+
"""
|
| 128 |
+
In case the level is outside of the currently known package (something like
|
| 129 |
+
import .....foo), we can still try our best to help the user for
|
| 130 |
+
completions.
|
| 131 |
+
"""
|
| 132 |
+
for i in range(level - 1):
|
| 133 |
+
old = directory
|
| 134 |
+
directory = os.path.dirname(directory)
|
| 135 |
+
if old == directory:
|
| 136 |
+
return None, None
|
| 137 |
+
|
| 138 |
+
d = directory
|
| 139 |
+
level_import_paths = []
|
| 140 |
+
# Now that we are on the level that the user wants to be, calculate the
|
| 141 |
+
# import path for it.
|
| 142 |
+
while True:
|
| 143 |
+
if d == project_path:
|
| 144 |
+
return level_import_paths, d
|
| 145 |
+
dir_name = os.path.basename(d)
|
| 146 |
+
if dir_name:
|
| 147 |
+
level_import_paths.insert(0, dir_name)
|
| 148 |
+
d = os.path.dirname(d)
|
| 149 |
+
else:
|
| 150 |
+
return None, directory
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class Importer:
|
| 154 |
+
def __init__(self, inference_state, import_path, module_context, level=0):
|
| 155 |
+
"""
|
| 156 |
+
An implementation similar to ``__import__``. Use `follow`
|
| 157 |
+
to actually follow the imports.
|
| 158 |
+
|
| 159 |
+
*level* specifies whether to use absolute or relative imports. 0 (the
|
| 160 |
+
default) means only perform absolute imports. Positive values for level
|
| 161 |
+
indicate the number of parent directories to search relative to the
|
| 162 |
+
directory of the module calling ``__import__()`` (see PEP 328 for the
|
| 163 |
+
details).
|
| 164 |
+
|
| 165 |
+
:param import_path: List of namespaces (strings or Names).
|
| 166 |
+
"""
|
| 167 |
+
debug.speed('import %s %s' % (import_path, module_context))
|
| 168 |
+
self._inference_state = inference_state
|
| 169 |
+
self.level = level
|
| 170 |
+
self._module_context = module_context
|
| 171 |
+
|
| 172 |
+
self._fixed_sys_path = None
|
| 173 |
+
self._infer_possible = True
|
| 174 |
+
if level:
|
| 175 |
+
base = module_context.get_value().py__package__()
|
| 176 |
+
# We need to care for two cases, the first one is if it's a valid
|
| 177 |
+
# Python import. This import has a properly defined module name
|
| 178 |
+
# chain like `foo.bar.baz` and an import in baz is made for
|
| 179 |
+
# `..lala.` It can then resolve to `foo.bar.lala`.
|
| 180 |
+
# The else here is a heuristic for all other cases, if for example
|
| 181 |
+
# in `foo` you search for `...bar`, it's obviously out of scope.
|
| 182 |
+
# However since Jedi tries to just do it's best, we help the user
|
| 183 |
+
# here, because he might have specified something wrong in his
|
| 184 |
+
# project.
|
| 185 |
+
if level <= len(base):
|
| 186 |
+
# Here we basically rewrite the level to 0.
|
| 187 |
+
base = tuple(base)
|
| 188 |
+
if level > 1:
|
| 189 |
+
base = base[:-level + 1]
|
| 190 |
+
import_path = base + tuple(import_path)
|
| 191 |
+
else:
|
| 192 |
+
path = module_context.py__file__()
|
| 193 |
+
project_path = self._inference_state.project.path
|
| 194 |
+
import_path = list(import_path)
|
| 195 |
+
if path is None:
|
| 196 |
+
# If no path is defined, our best guess is that the current
|
| 197 |
+
# file is edited by a user on the current working
|
| 198 |
+
# directory. We need to add an initial path, because it
|
| 199 |
+
# will get removed as the name of the current file.
|
| 200 |
+
directory = project_path
|
| 201 |
+
else:
|
| 202 |
+
directory = os.path.dirname(path)
|
| 203 |
+
|
| 204 |
+
base_import_path, base_directory = _level_to_base_import_path(
|
| 205 |
+
project_path, directory, level,
|
| 206 |
+
)
|
| 207 |
+
if base_directory is None:
|
| 208 |
+
# Everything is lost, the relative import does point
|
| 209 |
+
# somewhere out of the filesystem.
|
| 210 |
+
self._infer_possible = False
|
| 211 |
+
else:
|
| 212 |
+
self._fixed_sys_path = [base_directory]
|
| 213 |
+
|
| 214 |
+
if base_import_path is None:
|
| 215 |
+
if import_path:
|
| 216 |
+
_add_error(
|
| 217 |
+
module_context, import_path[0],
|
| 218 |
+
message='Attempted relative import beyond top-level package.'
|
| 219 |
+
)
|
| 220 |
+
else:
|
| 221 |
+
import_path = base_import_path + import_path
|
| 222 |
+
self.import_path = import_path
|
| 223 |
+
|
| 224 |
+
@property
|
| 225 |
+
def _str_import_path(self):
|
| 226 |
+
"""Returns the import path as pure strings instead of `Name`."""
|
| 227 |
+
return tuple(
|
| 228 |
+
name.value if isinstance(name, tree.Name) else name
|
| 229 |
+
for name in self.import_path
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
def _sys_path_with_modifications(self, is_completion):
|
| 233 |
+
if self._fixed_sys_path is not None:
|
| 234 |
+
return self._fixed_sys_path
|
| 235 |
+
|
| 236 |
+
return (
|
| 237 |
+
# For import completions we don't want to see init paths, but for
|
| 238 |
+
# inference we want to show the user as much as possible.
|
| 239 |
+
# See GH #1446.
|
| 240 |
+
self._inference_state.get_sys_path(add_init_paths=not is_completion)
|
| 241 |
+
+ [
|
| 242 |
+
str(p) for p
|
| 243 |
+
in sys_path.check_sys_path_modifications(self._module_context)
|
| 244 |
+
]
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
def follow(self):
|
| 248 |
+
if not self.import_path:
|
| 249 |
+
if self._fixed_sys_path:
|
| 250 |
+
# This is a bit of a special case, that maybe should be
|
| 251 |
+
# revisited. If the project path is wrong or the user uses
|
| 252 |
+
# relative imports the wrong way, we might end up here, where
|
| 253 |
+
# the `fixed_sys_path == project.path` in that case we kind of
|
| 254 |
+
# use the project.path.parent directory as our path. This is
|
| 255 |
+
# usually not a problem, except if imports in other places are
|
| 256 |
+
# using the same names. Example:
|
| 257 |
+
#
|
| 258 |
+
# foo/ < #1
|
| 259 |
+
# - setup.py
|
| 260 |
+
# - foo/ < #2
|
| 261 |
+
# - __init__.py
|
| 262 |
+
# - foo.py < #3
|
| 263 |
+
#
|
| 264 |
+
# If the top foo is our project folder and somebody uses
|
| 265 |
+
# `from . import foo` in `setup.py`, it will resolve to foo #2,
|
| 266 |
+
# which means that the import for foo.foo is cached as
|
| 267 |
+
# `__init__.py` (#2) and not as `foo.py` (#3). This is usually
|
| 268 |
+
# not an issue, because this case is probably pretty rare, but
|
| 269 |
+
# might be an issue for some people.
|
| 270 |
+
#
|
| 271 |
+
# However for most normal cases where we work with different
|
| 272 |
+
# file names, this code path hits where we basically change the
|
| 273 |
+
# project path to an ancestor of project path.
|
| 274 |
+
from jedi.inference.value.namespace import ImplicitNamespaceValue
|
| 275 |
+
import_path = (os.path.basename(self._fixed_sys_path[0]),)
|
| 276 |
+
ns = ImplicitNamespaceValue(
|
| 277 |
+
self._inference_state,
|
| 278 |
+
string_names=import_path,
|
| 279 |
+
paths=self._fixed_sys_path,
|
| 280 |
+
)
|
| 281 |
+
return ValueSet({ns})
|
| 282 |
+
return NO_VALUES
|
| 283 |
+
if not self._infer_possible:
|
| 284 |
+
return NO_VALUES
|
| 285 |
+
|
| 286 |
+
# Check caches first
|
| 287 |
+
from_cache = self._inference_state.stub_module_cache.get(self._str_import_path)
|
| 288 |
+
if from_cache is not None:
|
| 289 |
+
return ValueSet({from_cache})
|
| 290 |
+
from_cache = self._inference_state.module_cache.get(self._str_import_path)
|
| 291 |
+
if from_cache is not None:
|
| 292 |
+
return from_cache
|
| 293 |
+
|
| 294 |
+
sys_path = self._sys_path_with_modifications(is_completion=False)
|
| 295 |
+
|
| 296 |
+
return import_module_by_names(
|
| 297 |
+
self._inference_state, self.import_path, sys_path, self._module_context
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
def _get_module_names(self, search_path=None, in_module=None):
|
| 301 |
+
"""
|
| 302 |
+
Get the names of all modules in the search_path. This means file names
|
| 303 |
+
and not names defined in the files.
|
| 304 |
+
"""
|
| 305 |
+
if search_path is None:
|
| 306 |
+
sys_path = self._sys_path_with_modifications(is_completion=True)
|
| 307 |
+
else:
|
| 308 |
+
sys_path = search_path
|
| 309 |
+
return list(iter_module_names(
|
| 310 |
+
self._inference_state, self._module_context, sys_path,
|
| 311 |
+
module_cls=ImportName if in_module is None else SubModuleName,
|
| 312 |
+
add_builtin_modules=search_path is None and in_module is None,
|
| 313 |
+
))
|
| 314 |
+
|
| 315 |
+
def completion_names(self, inference_state, only_modules=False):
|
| 316 |
+
"""
|
| 317 |
+
:param only_modules: Indicates wheter it's possible to import a
|
| 318 |
+
definition that is not defined in a module.
|
| 319 |
+
"""
|
| 320 |
+
if not self._infer_possible:
|
| 321 |
+
return []
|
| 322 |
+
|
| 323 |
+
names = []
|
| 324 |
+
if self.import_path:
|
| 325 |
+
# flask
|
| 326 |
+
if self._str_import_path == ('flask', 'ext'):
|
| 327 |
+
# List Flask extensions like ``flask_foo``
|
| 328 |
+
for mod in self._get_module_names():
|
| 329 |
+
modname = mod.string_name
|
| 330 |
+
if modname.startswith('flask_'):
|
| 331 |
+
extname = modname[len('flask_'):]
|
| 332 |
+
names.append(ImportName(self._module_context, extname))
|
| 333 |
+
# Now the old style: ``flaskext.foo``
|
| 334 |
+
for dir in self._sys_path_with_modifications(is_completion=True):
|
| 335 |
+
flaskext = os.path.join(dir, 'flaskext')
|
| 336 |
+
if os.path.isdir(flaskext):
|
| 337 |
+
names += self._get_module_names([flaskext])
|
| 338 |
+
|
| 339 |
+
values = self.follow()
|
| 340 |
+
for value in values:
|
| 341 |
+
# Non-modules are not completable.
|
| 342 |
+
if value.api_type not in ('module', 'namespace'): # not a module
|
| 343 |
+
continue
|
| 344 |
+
if not value.is_compiled():
|
| 345 |
+
# sub_modules_dict is not implemented for compiled modules.
|
| 346 |
+
names += value.sub_modules_dict().values()
|
| 347 |
+
|
| 348 |
+
if not only_modules:
|
| 349 |
+
from jedi.inference.gradual.conversion import convert_values
|
| 350 |
+
|
| 351 |
+
both_values = values | convert_values(values)
|
| 352 |
+
for c in both_values:
|
| 353 |
+
for filter in c.get_filters():
|
| 354 |
+
names += filter.values()
|
| 355 |
+
else:
|
| 356 |
+
if self.level:
|
| 357 |
+
# We only get here if the level cannot be properly calculated.
|
| 358 |
+
names += self._get_module_names(self._fixed_sys_path)
|
| 359 |
+
else:
|
| 360 |
+
# This is just the list of global imports.
|
| 361 |
+
names += self._get_module_names()
|
| 362 |
+
return names
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def import_module_by_names(inference_state, import_names, sys_path=None,
|
| 366 |
+
module_context=None, prefer_stubs=True):
|
| 367 |
+
if sys_path is None:
|
| 368 |
+
sys_path = inference_state.get_sys_path()
|
| 369 |
+
|
| 370 |
+
str_import_names = tuple(
|
| 371 |
+
i.value if isinstance(i, tree.Name) else i
|
| 372 |
+
for i in import_names
|
| 373 |
+
)
|
| 374 |
+
value_set = [None]
|
| 375 |
+
for i, name in enumerate(import_names):
|
| 376 |
+
value_set = ValueSet.from_sets([
|
| 377 |
+
import_module(
|
| 378 |
+
inference_state,
|
| 379 |
+
str_import_names[:i+1],
|
| 380 |
+
parent_module_value,
|
| 381 |
+
sys_path,
|
| 382 |
+
prefer_stubs=prefer_stubs,
|
| 383 |
+
) for parent_module_value in value_set
|
| 384 |
+
])
|
| 385 |
+
if not value_set:
|
| 386 |
+
message = 'No module named ' + '.'.join(str_import_names)
|
| 387 |
+
if module_context is not None:
|
| 388 |
+
_add_error(module_context, name, message)
|
| 389 |
+
else:
|
| 390 |
+
debug.warning(message)
|
| 391 |
+
return NO_VALUES
|
| 392 |
+
return value_set
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
@plugin_manager.decorate()
|
| 396 |
+
@import_module_decorator
|
| 397 |
+
def import_module(inference_state, import_names, parent_module_value, sys_path):
|
| 398 |
+
"""
|
| 399 |
+
This method is very similar to importlib's `_gcd_import`.
|
| 400 |
+
"""
|
| 401 |
+
if import_names[0] in settings.auto_import_modules:
|
| 402 |
+
module = _load_builtin_module(inference_state, import_names, sys_path)
|
| 403 |
+
if module is None:
|
| 404 |
+
return NO_VALUES
|
| 405 |
+
return ValueSet([module])
|
| 406 |
+
|
| 407 |
+
module_name = '.'.join(import_names)
|
| 408 |
+
if parent_module_value is None:
|
| 409 |
+
# Override the sys.path. It works only good that way.
|
| 410 |
+
# Injecting the path directly into `find_module` did not work.
|
| 411 |
+
file_io_or_ns, is_pkg = inference_state.compiled_subprocess.get_module_info(
|
| 412 |
+
string=import_names[-1],
|
| 413 |
+
full_name=module_name,
|
| 414 |
+
sys_path=sys_path,
|
| 415 |
+
is_global_search=True,
|
| 416 |
+
)
|
| 417 |
+
if is_pkg is None:
|
| 418 |
+
return NO_VALUES
|
| 419 |
+
else:
|
| 420 |
+
paths = parent_module_value.py__path__()
|
| 421 |
+
if paths is None:
|
| 422 |
+
# The module might not be a package.
|
| 423 |
+
return NO_VALUES
|
| 424 |
+
|
| 425 |
+
file_io_or_ns, is_pkg = inference_state.compiled_subprocess.get_module_info(
|
| 426 |
+
string=import_names[-1],
|
| 427 |
+
path=paths,
|
| 428 |
+
full_name=module_name,
|
| 429 |
+
is_global_search=False,
|
| 430 |
+
)
|
| 431 |
+
if is_pkg is None:
|
| 432 |
+
return NO_VALUES
|
| 433 |
+
|
| 434 |
+
if isinstance(file_io_or_ns, ImplicitNSInfo):
|
| 435 |
+
from jedi.inference.value.namespace import ImplicitNamespaceValue
|
| 436 |
+
module = ImplicitNamespaceValue(
|
| 437 |
+
inference_state,
|
| 438 |
+
string_names=tuple(file_io_or_ns.name.split('.')),
|
| 439 |
+
paths=file_io_or_ns.paths,
|
| 440 |
+
)
|
| 441 |
+
elif file_io_or_ns is None:
|
| 442 |
+
module = _load_builtin_module(inference_state, import_names, sys_path)
|
| 443 |
+
if module is None:
|
| 444 |
+
return NO_VALUES
|
| 445 |
+
else:
|
| 446 |
+
module = _load_python_module(
|
| 447 |
+
inference_state, file_io_or_ns,
|
| 448 |
+
import_names=import_names,
|
| 449 |
+
is_package=is_pkg,
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
if parent_module_value is None:
|
| 453 |
+
debug.dbg('global search_module %s: %s', import_names[-1], module)
|
| 454 |
+
else:
|
| 455 |
+
debug.dbg('search_module %s in paths %s: %s', module_name, paths, module)
|
| 456 |
+
return ValueSet([module])
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
def _load_python_module(inference_state, file_io,
|
| 460 |
+
import_names=None, is_package=False):
|
| 461 |
+
module_node = inference_state.parse(
|
| 462 |
+
file_io=file_io,
|
| 463 |
+
cache=True,
|
| 464 |
+
diff_cache=settings.fast_parser,
|
| 465 |
+
cache_path=settings.cache_directory,
|
| 466 |
+
)
|
| 467 |
+
|
| 468 |
+
from jedi.inference.value import ModuleValue
|
| 469 |
+
return ModuleValue(
|
| 470 |
+
inference_state, module_node,
|
| 471 |
+
file_io=file_io,
|
| 472 |
+
string_names=import_names,
|
| 473 |
+
code_lines=get_cached_code_lines(inference_state.grammar, file_io.path),
|
| 474 |
+
is_package=is_package,
|
| 475 |
+
)
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
def _load_builtin_module(inference_state, import_names=None, sys_path=None):
|
| 479 |
+
project = inference_state.project
|
| 480 |
+
if sys_path is None:
|
| 481 |
+
sys_path = inference_state.get_sys_path()
|
| 482 |
+
if not project._load_unsafe_extensions:
|
| 483 |
+
safe_paths = project._get_base_sys_path(inference_state)
|
| 484 |
+
sys_path = [p for p in sys_path if p in safe_paths]
|
| 485 |
+
|
| 486 |
+
dotted_name = '.'.join(import_names)
|
| 487 |
+
assert dotted_name is not None
|
| 488 |
+
module = compiled.load_module(inference_state, dotted_name=dotted_name, sys_path=sys_path)
|
| 489 |
+
if module is None:
|
| 490 |
+
# The file might raise an ImportError e.g. and therefore not be
|
| 491 |
+
# importable.
|
| 492 |
+
return None
|
| 493 |
+
return module
|
| 494 |
+
|
| 495 |
+
|
| 496 |
+
def load_module_from_path(inference_state, file_io, import_names=None, is_package=None):
|
| 497 |
+
"""
|
| 498 |
+
This should pretty much only be used for get_modules_containing_name. It's
|
| 499 |
+
here to ensure that a random path is still properly loaded into the Jedi
|
| 500 |
+
module structure.
|
| 501 |
+
"""
|
| 502 |
+
path = Path(file_io.path)
|
| 503 |
+
if import_names is None:
|
| 504 |
+
e_sys_path = inference_state.get_sys_path()
|
| 505 |
+
import_names, is_package = sys_path.transform_path_to_dotted(e_sys_path, path)
|
| 506 |
+
else:
|
| 507 |
+
assert isinstance(is_package, bool)
|
| 508 |
+
|
| 509 |
+
is_stub = path.suffix == '.pyi'
|
| 510 |
+
if is_stub:
|
| 511 |
+
folder_io = file_io.get_parent_folder()
|
| 512 |
+
if folder_io.path.endswith('-stubs'):
|
| 513 |
+
folder_io = FolderIO(folder_io.path[:-6])
|
| 514 |
+
if path.name == '__init__.pyi':
|
| 515 |
+
python_file_io = folder_io.get_file_io('__init__.py')
|
| 516 |
+
else:
|
| 517 |
+
python_file_io = folder_io.get_file_io(import_names[-1] + '.py')
|
| 518 |
+
|
| 519 |
+
try:
|
| 520 |
+
v = load_module_from_path(
|
| 521 |
+
inference_state, python_file_io,
|
| 522 |
+
import_names, is_package=is_package
|
| 523 |
+
)
|
| 524 |
+
values = ValueSet([v])
|
| 525 |
+
except FileNotFoundError:
|
| 526 |
+
values = NO_VALUES
|
| 527 |
+
|
| 528 |
+
return create_stub_module(
|
| 529 |
+
inference_state, inference_state.latest_grammar, values,
|
| 530 |
+
parse_stub_module(inference_state, file_io), file_io, import_names
|
| 531 |
+
)
|
| 532 |
+
else:
|
| 533 |
+
module = _load_python_module(
|
| 534 |
+
inference_state, file_io,
|
| 535 |
+
import_names=import_names,
|
| 536 |
+
is_package=is_package,
|
| 537 |
+
)
|
| 538 |
+
inference_state.module_cache.add(import_names, ValueSet([module]))
|
| 539 |
+
return module
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def load_namespace_from_path(inference_state, folder_io):
|
| 543 |
+
import_names, is_package = sys_path.transform_path_to_dotted(
|
| 544 |
+
inference_state.get_sys_path(),
|
| 545 |
+
Path(folder_io.path)
|
| 546 |
+
)
|
| 547 |
+
from jedi.inference.value.namespace import ImplicitNamespaceValue
|
| 548 |
+
return ImplicitNamespaceValue(inference_state, import_names, [folder_io.path])
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
def follow_error_node_imports_if_possible(context, name):
|
| 552 |
+
error_node = tree.search_ancestor(name, 'error_node')
|
| 553 |
+
if error_node is not None:
|
| 554 |
+
# Get the first command start of a started simple_stmt. The error
|
| 555 |
+
# node is sometimes a small_stmt and sometimes a simple_stmt. Check
|
| 556 |
+
# for ; leaves that start a new statements.
|
| 557 |
+
start_index = 0
|
| 558 |
+
for index, n in enumerate(error_node.children):
|
| 559 |
+
if n.start_pos > name.start_pos:
|
| 560 |
+
break
|
| 561 |
+
if n == ';':
|
| 562 |
+
start_index = index + 1
|
| 563 |
+
nodes = error_node.children[start_index:]
|
| 564 |
+
first_name = nodes[0].get_first_leaf().value
|
| 565 |
+
|
| 566 |
+
# Make it possible to infer stuff like `import foo.` or
|
| 567 |
+
# `from foo.bar`.
|
| 568 |
+
if first_name in ('from', 'import'):
|
| 569 |
+
is_import_from = first_name == 'from'
|
| 570 |
+
level, names = helpers.parse_dotted_names(
|
| 571 |
+
nodes,
|
| 572 |
+
is_import_from=is_import_from,
|
| 573 |
+
until_node=name,
|
| 574 |
+
)
|
| 575 |
+
return Importer(
|
| 576 |
+
context.inference_state, names, context.get_root_context(), level).follow()
|
| 577 |
+
return None
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
def iter_module_names(inference_state, module_context, search_path,
|
| 581 |
+
module_cls=ImportName, add_builtin_modules=True):
|
| 582 |
+
"""
|
| 583 |
+
Get the names of all modules in the search_path. This means file names
|
| 584 |
+
and not names defined in the files.
|
| 585 |
+
"""
|
| 586 |
+
# add builtin module names
|
| 587 |
+
if add_builtin_modules:
|
| 588 |
+
for name in inference_state.compiled_subprocess.get_builtin_module_names():
|
| 589 |
+
yield module_cls(module_context, name)
|
| 590 |
+
|
| 591 |
+
for name in inference_state.compiled_subprocess.iter_module_names(search_path):
|
| 592 |
+
yield module_cls(module_context, name)
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/lazy_value.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from jedi.inference.base_value import ValueSet, NO_VALUES
|
| 2 |
+
from jedi.common import monkeypatch
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class AbstractLazyValue:
|
| 6 |
+
def __init__(self, data, min=1, max=1):
|
| 7 |
+
self.data = data
|
| 8 |
+
self.min = min
|
| 9 |
+
self.max = max
|
| 10 |
+
|
| 11 |
+
def __repr__(self):
|
| 12 |
+
return '<%s: %s>' % (self.__class__.__name__, self.data)
|
| 13 |
+
|
| 14 |
+
def infer(self):
|
| 15 |
+
raise NotImplementedError
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class LazyKnownValue(AbstractLazyValue):
|
| 19 |
+
"""data is a Value."""
|
| 20 |
+
def infer(self):
|
| 21 |
+
return ValueSet([self.data])
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class LazyKnownValues(AbstractLazyValue):
|
| 25 |
+
"""data is a ValueSet."""
|
| 26 |
+
def infer(self):
|
| 27 |
+
return self.data
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class LazyUnknownValue(AbstractLazyValue):
|
| 31 |
+
def __init__(self, min=1, max=1):
|
| 32 |
+
super().__init__(None, min, max)
|
| 33 |
+
|
| 34 |
+
def infer(self):
|
| 35 |
+
return NO_VALUES
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class LazyTreeValue(AbstractLazyValue):
|
| 39 |
+
def __init__(self, context, node, min=1, max=1):
|
| 40 |
+
super().__init__(node, min, max)
|
| 41 |
+
self.context = context
|
| 42 |
+
# We need to save the predefined names. It's an unfortunate side effect
|
| 43 |
+
# that needs to be tracked otherwise results will be wrong.
|
| 44 |
+
self._predefined_names = dict(context.predefined_names)
|
| 45 |
+
|
| 46 |
+
def infer(self):
|
| 47 |
+
with monkeypatch(self.context, 'predefined_names', self._predefined_names):
|
| 48 |
+
return self.context.infer_node(self.data)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def get_merged_lazy_value(lazy_values):
|
| 52 |
+
if len(lazy_values) > 1:
|
| 53 |
+
return MergedLazyValues(lazy_values)
|
| 54 |
+
else:
|
| 55 |
+
return lazy_values[0]
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class MergedLazyValues(AbstractLazyValue):
|
| 59 |
+
"""data is a list of lazy values."""
|
| 60 |
+
def infer(self):
|
| 61 |
+
return ValueSet.from_sets(l.infer() for l in self.data)
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/names.py
ADDED
|
@@ -0,0 +1,677 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import abstractmethod
|
| 2 |
+
from inspect import Parameter
|
| 3 |
+
from typing import Optional, Tuple
|
| 4 |
+
|
| 5 |
+
from parso.tree import search_ancestor
|
| 6 |
+
|
| 7 |
+
from jedi.parser_utils import find_statement_documentation, clean_scope_docstring
|
| 8 |
+
from jedi.inference.utils import unite
|
| 9 |
+
from jedi.inference.base_value import ValueSet, NO_VALUES
|
| 10 |
+
from jedi.inference.cache import inference_state_method_cache
|
| 11 |
+
from jedi.inference import docstrings
|
| 12 |
+
from jedi.cache import memoize_method
|
| 13 |
+
from jedi.inference.helpers import deep_ast_copy, infer_call_of_leaf
|
| 14 |
+
from jedi.plugins import plugin_manager
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _merge_name_docs(names):
|
| 18 |
+
doc = ''
|
| 19 |
+
for name in names:
|
| 20 |
+
if doc:
|
| 21 |
+
# In case we have multiple values, just return all of them
|
| 22 |
+
# separated by a few dashes.
|
| 23 |
+
doc += '\n' + '-' * 30 + '\n'
|
| 24 |
+
doc += name.py__doc__()
|
| 25 |
+
return doc
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class AbstractNameDefinition:
|
| 29 |
+
start_pos: Optional[Tuple[int, int]] = None
|
| 30 |
+
string_name: str
|
| 31 |
+
parent_context = None
|
| 32 |
+
tree_name = None
|
| 33 |
+
is_value_name = True
|
| 34 |
+
"""
|
| 35 |
+
Used for the Jedi API to know if it's a keyword or an actual name.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
@abstractmethod
|
| 39 |
+
def infer(self):
|
| 40 |
+
raise NotImplementedError
|
| 41 |
+
|
| 42 |
+
@abstractmethod
|
| 43 |
+
def goto(self):
|
| 44 |
+
# Typically names are already definitions and therefore a goto on that
|
| 45 |
+
# name will always result on itself.
|
| 46 |
+
return {self}
|
| 47 |
+
|
| 48 |
+
def get_qualified_names(self, include_module_names=False):
|
| 49 |
+
qualified_names = self._get_qualified_names()
|
| 50 |
+
if qualified_names is None or not include_module_names:
|
| 51 |
+
return qualified_names
|
| 52 |
+
|
| 53 |
+
module_names = self.get_root_context().string_names
|
| 54 |
+
if module_names is None:
|
| 55 |
+
return None
|
| 56 |
+
return module_names + qualified_names
|
| 57 |
+
|
| 58 |
+
def _get_qualified_names(self):
|
| 59 |
+
# By default, a name has no qualified names.
|
| 60 |
+
return None
|
| 61 |
+
|
| 62 |
+
def get_root_context(self):
|
| 63 |
+
return self.parent_context.get_root_context()
|
| 64 |
+
|
| 65 |
+
def get_public_name(self):
|
| 66 |
+
return self.string_name
|
| 67 |
+
|
| 68 |
+
def __repr__(self):
|
| 69 |
+
if self.start_pos is None:
|
| 70 |
+
return '<%s: string_name=%s>' % (self.__class__.__name__, self.string_name)
|
| 71 |
+
return '<%s: string_name=%s start_pos=%s>' % (self.__class__.__name__,
|
| 72 |
+
self.string_name, self.start_pos)
|
| 73 |
+
|
| 74 |
+
def is_import(self):
|
| 75 |
+
return False
|
| 76 |
+
|
| 77 |
+
def py__doc__(self):
|
| 78 |
+
return ''
|
| 79 |
+
|
| 80 |
+
@property
|
| 81 |
+
def api_type(self):
|
| 82 |
+
return self.parent_context.api_type
|
| 83 |
+
|
| 84 |
+
def get_defining_qualified_value(self):
|
| 85 |
+
"""
|
| 86 |
+
Returns either None or the value that is public and qualified. Won't
|
| 87 |
+
return a function, because a name in a function is never public.
|
| 88 |
+
"""
|
| 89 |
+
return None
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class AbstractArbitraryName(AbstractNameDefinition):
|
| 93 |
+
"""
|
| 94 |
+
When you e.g. want to complete dicts keys, you probably want to complete
|
| 95 |
+
string literals, which is not really a name, but for Jedi we use this
|
| 96 |
+
concept of Name for completions as well.
|
| 97 |
+
"""
|
| 98 |
+
is_value_name = False
|
| 99 |
+
|
| 100 |
+
def __init__(self, inference_state, string):
|
| 101 |
+
self.inference_state = inference_state
|
| 102 |
+
self.string_name = string
|
| 103 |
+
self.parent_context = inference_state.builtins_module
|
| 104 |
+
|
| 105 |
+
def infer(self):
|
| 106 |
+
return NO_VALUES
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class AbstractTreeName(AbstractNameDefinition):
|
| 110 |
+
def __init__(self, parent_context, tree_name):
|
| 111 |
+
self.parent_context = parent_context
|
| 112 |
+
self.tree_name = tree_name
|
| 113 |
+
|
| 114 |
+
def get_qualified_names(self, include_module_names=False):
|
| 115 |
+
import_node = search_ancestor(self.tree_name, 'import_name', 'import_from')
|
| 116 |
+
# For import nodes we cannot just have names, because it's very unclear
|
| 117 |
+
# how they would look like. For now we just ignore them in most cases.
|
| 118 |
+
# In case of level == 1, it works always, because it's like a submodule
|
| 119 |
+
# lookup.
|
| 120 |
+
if import_node is not None and not (import_node.level == 1
|
| 121 |
+
and self.get_root_context().get_value().is_package()):
|
| 122 |
+
# TODO improve the situation for when level is present.
|
| 123 |
+
if include_module_names and not import_node.level:
|
| 124 |
+
return tuple(n.value for n in import_node.get_path_for_name(self.tree_name))
|
| 125 |
+
else:
|
| 126 |
+
return None
|
| 127 |
+
|
| 128 |
+
return super().get_qualified_names(include_module_names)
|
| 129 |
+
|
| 130 |
+
def _get_qualified_names(self):
|
| 131 |
+
parent_names = self.parent_context.get_qualified_names()
|
| 132 |
+
if parent_names is None:
|
| 133 |
+
return None
|
| 134 |
+
return parent_names + (self.tree_name.value,)
|
| 135 |
+
|
| 136 |
+
def get_defining_qualified_value(self):
|
| 137 |
+
if self.is_import():
|
| 138 |
+
raise NotImplementedError("Shouldn't really happen, please report")
|
| 139 |
+
elif self.parent_context:
|
| 140 |
+
return self.parent_context.get_value() # Might be None
|
| 141 |
+
return None
|
| 142 |
+
|
| 143 |
+
def goto(self):
|
| 144 |
+
context = self.parent_context
|
| 145 |
+
name = self.tree_name
|
| 146 |
+
definition = name.get_definition(import_name_always=True)
|
| 147 |
+
if definition is not None:
|
| 148 |
+
type_ = definition.type
|
| 149 |
+
if type_ == 'expr_stmt':
|
| 150 |
+
# Only take the parent, because if it's more complicated than just
|
| 151 |
+
# a name it's something you can "goto" again.
|
| 152 |
+
is_simple_name = name.parent.type not in ('power', 'trailer')
|
| 153 |
+
if is_simple_name:
|
| 154 |
+
return [self]
|
| 155 |
+
elif type_ in ('import_from', 'import_name'):
|
| 156 |
+
from jedi.inference.imports import goto_import
|
| 157 |
+
module_names = goto_import(context, name)
|
| 158 |
+
return module_names
|
| 159 |
+
else:
|
| 160 |
+
return [self]
|
| 161 |
+
else:
|
| 162 |
+
from jedi.inference.imports import follow_error_node_imports_if_possible
|
| 163 |
+
values = follow_error_node_imports_if_possible(context, name)
|
| 164 |
+
if values is not None:
|
| 165 |
+
return [value.name for value in values]
|
| 166 |
+
|
| 167 |
+
par = name.parent
|
| 168 |
+
node_type = par.type
|
| 169 |
+
if node_type == 'argument' and par.children[1] == '=' and par.children[0] == name:
|
| 170 |
+
# Named param goto.
|
| 171 |
+
trailer = par.parent
|
| 172 |
+
if trailer.type == 'arglist':
|
| 173 |
+
trailer = trailer.parent
|
| 174 |
+
if trailer.type != 'classdef':
|
| 175 |
+
if trailer.type == 'decorator':
|
| 176 |
+
value_set = context.infer_node(trailer.children[1])
|
| 177 |
+
else:
|
| 178 |
+
i = trailer.parent.children.index(trailer)
|
| 179 |
+
to_infer = trailer.parent.children[:i]
|
| 180 |
+
if to_infer[0] == 'await':
|
| 181 |
+
to_infer.pop(0)
|
| 182 |
+
value_set = context.infer_node(to_infer[0])
|
| 183 |
+
from jedi.inference.syntax_tree import infer_trailer
|
| 184 |
+
for trailer in to_infer[1:]:
|
| 185 |
+
value_set = infer_trailer(context, value_set, trailer)
|
| 186 |
+
param_names = []
|
| 187 |
+
for value in value_set:
|
| 188 |
+
for signature in value.get_signatures():
|
| 189 |
+
for param_name in signature.get_param_names():
|
| 190 |
+
if param_name.string_name == name.value:
|
| 191 |
+
param_names.append(param_name)
|
| 192 |
+
return param_names
|
| 193 |
+
elif node_type == 'dotted_name': # Is a decorator.
|
| 194 |
+
index = par.children.index(name)
|
| 195 |
+
if index > 0:
|
| 196 |
+
new_dotted = deep_ast_copy(par)
|
| 197 |
+
new_dotted.children[index - 1:] = []
|
| 198 |
+
values = context.infer_node(new_dotted)
|
| 199 |
+
return unite(
|
| 200 |
+
value.goto(name, name_context=context)
|
| 201 |
+
for value in values
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
if node_type == 'trailer' and par.children[0] == '.':
|
| 205 |
+
values = infer_call_of_leaf(context, name, cut_own_trailer=True)
|
| 206 |
+
return values.goto(name, name_context=context)
|
| 207 |
+
else:
|
| 208 |
+
stmt = search_ancestor(
|
| 209 |
+
name, 'expr_stmt', 'lambdef'
|
| 210 |
+
) or name
|
| 211 |
+
if stmt.type == 'lambdef':
|
| 212 |
+
stmt = name
|
| 213 |
+
return context.goto(name, position=stmt.start_pos)
|
| 214 |
+
|
| 215 |
+
def is_import(self):
|
| 216 |
+
imp = search_ancestor(self.tree_name, 'import_from', 'import_name')
|
| 217 |
+
return imp is not None
|
| 218 |
+
|
| 219 |
+
@property
|
| 220 |
+
def string_name(self):
|
| 221 |
+
return self.tree_name.value
|
| 222 |
+
|
| 223 |
+
@property
|
| 224 |
+
def start_pos(self):
|
| 225 |
+
return self.tree_name.start_pos
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
class ValueNameMixin:
|
| 229 |
+
def infer(self):
|
| 230 |
+
return ValueSet([self._value])
|
| 231 |
+
|
| 232 |
+
def py__doc__(self):
|
| 233 |
+
doc = self._value.py__doc__()
|
| 234 |
+
if not doc and self._value.is_stub():
|
| 235 |
+
from jedi.inference.gradual.conversion import convert_names
|
| 236 |
+
names = convert_names([self], prefer_stub_to_compiled=False)
|
| 237 |
+
if self not in names:
|
| 238 |
+
return _merge_name_docs(names)
|
| 239 |
+
return doc
|
| 240 |
+
|
| 241 |
+
def _get_qualified_names(self):
|
| 242 |
+
return self._value.get_qualified_names()
|
| 243 |
+
|
| 244 |
+
def get_root_context(self):
|
| 245 |
+
if self.parent_context is None: # A module
|
| 246 |
+
return self._value.as_context()
|
| 247 |
+
return super().get_root_context()
|
| 248 |
+
|
| 249 |
+
def get_defining_qualified_value(self):
|
| 250 |
+
context = self.parent_context
|
| 251 |
+
if context is not None and (context.is_module() or context.is_class()):
|
| 252 |
+
return self.parent_context.get_value() # Might be None
|
| 253 |
+
return None
|
| 254 |
+
|
| 255 |
+
@property
|
| 256 |
+
def api_type(self):
|
| 257 |
+
return self._value.api_type
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
class ValueName(ValueNameMixin, AbstractTreeName):
|
| 261 |
+
def __init__(self, value, tree_name):
|
| 262 |
+
super().__init__(value.parent_context, tree_name)
|
| 263 |
+
self._value = value
|
| 264 |
+
|
| 265 |
+
def goto(self):
|
| 266 |
+
return ValueSet([self._value.name])
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
class TreeNameDefinition(AbstractTreeName):
|
| 270 |
+
_API_TYPES = dict(
|
| 271 |
+
import_name='module',
|
| 272 |
+
import_from='module',
|
| 273 |
+
funcdef='function',
|
| 274 |
+
param='param',
|
| 275 |
+
classdef='class',
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
def infer(self):
|
| 279 |
+
# Refactor this, should probably be here.
|
| 280 |
+
from jedi.inference.syntax_tree import tree_name_to_values
|
| 281 |
+
return tree_name_to_values(
|
| 282 |
+
self.parent_context.inference_state,
|
| 283 |
+
self.parent_context,
|
| 284 |
+
self.tree_name
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
@property
|
| 288 |
+
def api_type(self):
|
| 289 |
+
definition = self.tree_name.get_definition(import_name_always=True)
|
| 290 |
+
if definition is None:
|
| 291 |
+
return 'statement'
|
| 292 |
+
return self._API_TYPES.get(definition.type, 'statement')
|
| 293 |
+
|
| 294 |
+
def assignment_indexes(self):
|
| 295 |
+
"""
|
| 296 |
+
Returns an array of tuple(int, node) of the indexes that are used in
|
| 297 |
+
tuple assignments.
|
| 298 |
+
|
| 299 |
+
For example if the name is ``y`` in the following code::
|
| 300 |
+
|
| 301 |
+
x, (y, z) = 2, ''
|
| 302 |
+
|
| 303 |
+
would result in ``[(1, xyz_node), (0, yz_node)]``.
|
| 304 |
+
|
| 305 |
+
When searching for b in the case ``a, *b, c = [...]`` it will return::
|
| 306 |
+
|
| 307 |
+
[(slice(1, -1), abc_node)]
|
| 308 |
+
"""
|
| 309 |
+
indexes = []
|
| 310 |
+
is_star_expr = False
|
| 311 |
+
node = self.tree_name.parent
|
| 312 |
+
compare = self.tree_name
|
| 313 |
+
while node is not None:
|
| 314 |
+
if node.type in ('testlist', 'testlist_comp', 'testlist_star_expr', 'exprlist'):
|
| 315 |
+
for i, child in enumerate(node.children):
|
| 316 |
+
if child == compare:
|
| 317 |
+
index = int(i / 2)
|
| 318 |
+
if is_star_expr:
|
| 319 |
+
from_end = int((len(node.children) - i) / 2)
|
| 320 |
+
index = slice(index, -from_end)
|
| 321 |
+
indexes.insert(0, (index, node))
|
| 322 |
+
break
|
| 323 |
+
else:
|
| 324 |
+
raise LookupError("Couldn't find the assignment.")
|
| 325 |
+
is_star_expr = False
|
| 326 |
+
elif node.type == 'star_expr':
|
| 327 |
+
is_star_expr = True
|
| 328 |
+
elif node.type in ('expr_stmt', 'sync_comp_for'):
|
| 329 |
+
break
|
| 330 |
+
|
| 331 |
+
compare = node
|
| 332 |
+
node = node.parent
|
| 333 |
+
return indexes
|
| 334 |
+
|
| 335 |
+
@property
|
| 336 |
+
def inference_state(self):
|
| 337 |
+
# Used by the cache function below
|
| 338 |
+
return self.parent_context.inference_state
|
| 339 |
+
|
| 340 |
+
@inference_state_method_cache(default='')
|
| 341 |
+
def py__doc__(self):
|
| 342 |
+
api_type = self.api_type
|
| 343 |
+
if api_type in ('function', 'class', 'property'):
|
| 344 |
+
if self.parent_context.get_root_context().is_stub():
|
| 345 |
+
from jedi.inference.gradual.conversion import convert_names
|
| 346 |
+
names = convert_names([self], prefer_stub_to_compiled=False)
|
| 347 |
+
if self not in names:
|
| 348 |
+
return _merge_name_docs(names)
|
| 349 |
+
|
| 350 |
+
# Make sure the names are not TreeNameDefinitions anymore.
|
| 351 |
+
return clean_scope_docstring(self.tree_name.get_definition())
|
| 352 |
+
|
| 353 |
+
if api_type == 'module':
|
| 354 |
+
names = self.goto()
|
| 355 |
+
if self not in names:
|
| 356 |
+
return _merge_name_docs(names)
|
| 357 |
+
|
| 358 |
+
if api_type == 'statement' and self.tree_name.is_definition():
|
| 359 |
+
return find_statement_documentation(self.tree_name.get_definition())
|
| 360 |
+
return ''
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
class _ParamMixin:
|
| 364 |
+
def maybe_positional_argument(self, include_star=True):
|
| 365 |
+
options = [Parameter.POSITIONAL_ONLY, Parameter.POSITIONAL_OR_KEYWORD]
|
| 366 |
+
if include_star:
|
| 367 |
+
options.append(Parameter.VAR_POSITIONAL)
|
| 368 |
+
return self.get_kind() in options
|
| 369 |
+
|
| 370 |
+
def maybe_keyword_argument(self, include_stars=True):
|
| 371 |
+
options = [Parameter.KEYWORD_ONLY, Parameter.POSITIONAL_OR_KEYWORD]
|
| 372 |
+
if include_stars:
|
| 373 |
+
options.append(Parameter.VAR_KEYWORD)
|
| 374 |
+
return self.get_kind() in options
|
| 375 |
+
|
| 376 |
+
def _kind_string(self):
|
| 377 |
+
kind = self.get_kind()
|
| 378 |
+
if kind == Parameter.VAR_POSITIONAL: # *args
|
| 379 |
+
return '*'
|
| 380 |
+
if kind == Parameter.VAR_KEYWORD: # **kwargs
|
| 381 |
+
return '**'
|
| 382 |
+
return ''
|
| 383 |
+
|
| 384 |
+
def get_qualified_names(self, include_module_names=False):
|
| 385 |
+
return None
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
class ParamNameInterface(_ParamMixin):
|
| 389 |
+
api_type = 'param'
|
| 390 |
+
|
| 391 |
+
def get_kind(self):
|
| 392 |
+
raise NotImplementedError
|
| 393 |
+
|
| 394 |
+
def to_string(self):
|
| 395 |
+
raise NotImplementedError
|
| 396 |
+
|
| 397 |
+
def get_executed_param_name(self):
|
| 398 |
+
"""
|
| 399 |
+
For dealing with type inference and working around the graph, we
|
| 400 |
+
sometimes want to have the param name of the execution. This feels a
|
| 401 |
+
bit strange and we might have to refactor at some point.
|
| 402 |
+
|
| 403 |
+
For now however it exists to avoid infering params when we don't really
|
| 404 |
+
need them (e.g. when we can just instead use annotations.
|
| 405 |
+
"""
|
| 406 |
+
return None
|
| 407 |
+
|
| 408 |
+
@property
|
| 409 |
+
def star_count(self):
|
| 410 |
+
kind = self.get_kind()
|
| 411 |
+
if kind == Parameter.VAR_POSITIONAL:
|
| 412 |
+
return 1
|
| 413 |
+
if kind == Parameter.VAR_KEYWORD:
|
| 414 |
+
return 2
|
| 415 |
+
return 0
|
| 416 |
+
|
| 417 |
+
def infer_default(self):
|
| 418 |
+
return NO_VALUES
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
class BaseTreeParamName(ParamNameInterface, AbstractTreeName):
|
| 422 |
+
annotation_node = None
|
| 423 |
+
default_node = None
|
| 424 |
+
|
| 425 |
+
def to_string(self):
|
| 426 |
+
output = self._kind_string() + self.get_public_name()
|
| 427 |
+
annotation = self.annotation_node
|
| 428 |
+
default = self.default_node
|
| 429 |
+
if annotation is not None:
|
| 430 |
+
output += ': ' + annotation.get_code(include_prefix=False)
|
| 431 |
+
if default is not None:
|
| 432 |
+
output += '=' + default.get_code(include_prefix=False)
|
| 433 |
+
return output
|
| 434 |
+
|
| 435 |
+
def get_public_name(self):
|
| 436 |
+
name = self.string_name
|
| 437 |
+
if name.startswith('__'):
|
| 438 |
+
# Params starting with __ are an equivalent to positional only
|
| 439 |
+
# variables in typeshed.
|
| 440 |
+
name = name[2:]
|
| 441 |
+
return name
|
| 442 |
+
|
| 443 |
+
def goto(self, **kwargs):
|
| 444 |
+
return [self]
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
class _ActualTreeParamName(BaseTreeParamName):
|
| 448 |
+
def __init__(self, function_value, tree_name):
|
| 449 |
+
super().__init__(
|
| 450 |
+
function_value.get_default_param_context(), tree_name)
|
| 451 |
+
self.function_value = function_value
|
| 452 |
+
|
| 453 |
+
def _get_param_node(self):
|
| 454 |
+
return search_ancestor(self.tree_name, 'param')
|
| 455 |
+
|
| 456 |
+
@property
|
| 457 |
+
def annotation_node(self):
|
| 458 |
+
return self._get_param_node().annotation
|
| 459 |
+
|
| 460 |
+
def infer_annotation(self, execute_annotation=True, ignore_stars=False):
|
| 461 |
+
from jedi.inference.gradual.annotation import infer_param
|
| 462 |
+
values = infer_param(
|
| 463 |
+
self.function_value, self._get_param_node(),
|
| 464 |
+
ignore_stars=ignore_stars)
|
| 465 |
+
if execute_annotation:
|
| 466 |
+
values = values.execute_annotation()
|
| 467 |
+
return values
|
| 468 |
+
|
| 469 |
+
def infer_default(self):
|
| 470 |
+
node = self.default_node
|
| 471 |
+
if node is None:
|
| 472 |
+
return NO_VALUES
|
| 473 |
+
return self.parent_context.infer_node(node)
|
| 474 |
+
|
| 475 |
+
@property
|
| 476 |
+
def default_node(self):
|
| 477 |
+
return self._get_param_node().default
|
| 478 |
+
|
| 479 |
+
def get_kind(self):
|
| 480 |
+
tree_param = self._get_param_node()
|
| 481 |
+
if tree_param.star_count == 1: # *args
|
| 482 |
+
return Parameter.VAR_POSITIONAL
|
| 483 |
+
if tree_param.star_count == 2: # **kwargs
|
| 484 |
+
return Parameter.VAR_KEYWORD
|
| 485 |
+
|
| 486 |
+
# Params starting with __ are an equivalent to positional only
|
| 487 |
+
# variables in typeshed.
|
| 488 |
+
if tree_param.name.value.startswith('__'):
|
| 489 |
+
return Parameter.POSITIONAL_ONLY
|
| 490 |
+
|
| 491 |
+
parent = tree_param.parent
|
| 492 |
+
param_appeared = False
|
| 493 |
+
for p in parent.children:
|
| 494 |
+
if param_appeared:
|
| 495 |
+
if p == '/':
|
| 496 |
+
return Parameter.POSITIONAL_ONLY
|
| 497 |
+
else:
|
| 498 |
+
if p == '*':
|
| 499 |
+
return Parameter.KEYWORD_ONLY
|
| 500 |
+
if p.type == 'param':
|
| 501 |
+
if p.star_count:
|
| 502 |
+
return Parameter.KEYWORD_ONLY
|
| 503 |
+
if p == tree_param:
|
| 504 |
+
param_appeared = True
|
| 505 |
+
return Parameter.POSITIONAL_OR_KEYWORD
|
| 506 |
+
|
| 507 |
+
def infer(self):
|
| 508 |
+
values = self.infer_annotation()
|
| 509 |
+
if values:
|
| 510 |
+
return values
|
| 511 |
+
|
| 512 |
+
doc_params = docstrings.infer_param(self.function_value, self._get_param_node())
|
| 513 |
+
return doc_params
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
class AnonymousParamName(_ActualTreeParamName):
|
| 517 |
+
@plugin_manager.decorate(name='goto_anonymous_param')
|
| 518 |
+
def goto(self):
|
| 519 |
+
return super().goto()
|
| 520 |
+
|
| 521 |
+
@plugin_manager.decorate(name='infer_anonymous_param')
|
| 522 |
+
def infer(self):
|
| 523 |
+
values = super().infer()
|
| 524 |
+
if values:
|
| 525 |
+
return values
|
| 526 |
+
from jedi.inference.dynamic_params import dynamic_param_lookup
|
| 527 |
+
param = self._get_param_node()
|
| 528 |
+
values = dynamic_param_lookup(self.function_value, param.position_index)
|
| 529 |
+
if values:
|
| 530 |
+
return values
|
| 531 |
+
|
| 532 |
+
if param.star_count == 1:
|
| 533 |
+
from jedi.inference.value.iterable import FakeTuple
|
| 534 |
+
value = FakeTuple(self.function_value.inference_state, [])
|
| 535 |
+
elif param.star_count == 2:
|
| 536 |
+
from jedi.inference.value.iterable import FakeDict
|
| 537 |
+
value = FakeDict(self.function_value.inference_state, {})
|
| 538 |
+
elif param.default is None:
|
| 539 |
+
return NO_VALUES
|
| 540 |
+
else:
|
| 541 |
+
return self.function_value.parent_context.infer_node(param.default)
|
| 542 |
+
return ValueSet({value})
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
class ParamName(_ActualTreeParamName):
|
| 546 |
+
def __init__(self, function_value, tree_name, arguments):
|
| 547 |
+
super().__init__(function_value, tree_name)
|
| 548 |
+
self.arguments = arguments
|
| 549 |
+
|
| 550 |
+
def infer(self):
|
| 551 |
+
values = super().infer()
|
| 552 |
+
if values:
|
| 553 |
+
return values
|
| 554 |
+
|
| 555 |
+
return self.get_executed_param_name().infer()
|
| 556 |
+
|
| 557 |
+
def get_executed_param_name(self):
|
| 558 |
+
from jedi.inference.param import get_executed_param_names
|
| 559 |
+
params_names = get_executed_param_names(self.function_value, self.arguments)
|
| 560 |
+
return params_names[self._get_param_node().position_index]
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
class ParamNameWrapper(_ParamMixin):
|
| 564 |
+
def __init__(self, param_name):
|
| 565 |
+
self._wrapped_param_name = param_name
|
| 566 |
+
|
| 567 |
+
def __getattr__(self, name):
|
| 568 |
+
return getattr(self._wrapped_param_name, name)
|
| 569 |
+
|
| 570 |
+
def __repr__(self):
|
| 571 |
+
return '<%s: %s>' % (self.__class__.__name__, self._wrapped_param_name)
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
class ImportName(AbstractNameDefinition):
|
| 575 |
+
start_pos = (1, 0)
|
| 576 |
+
_level = 0
|
| 577 |
+
|
| 578 |
+
def __init__(self, parent_context, string_name):
|
| 579 |
+
self._from_module_context = parent_context
|
| 580 |
+
self.string_name = string_name
|
| 581 |
+
|
| 582 |
+
def get_qualified_names(self, include_module_names=False):
|
| 583 |
+
if include_module_names:
|
| 584 |
+
if self._level:
|
| 585 |
+
assert self._level == 1, "Everything else is not supported for now"
|
| 586 |
+
module_names = self._from_module_context.string_names
|
| 587 |
+
if module_names is None:
|
| 588 |
+
return module_names
|
| 589 |
+
return module_names + (self.string_name,)
|
| 590 |
+
return (self.string_name,)
|
| 591 |
+
return ()
|
| 592 |
+
|
| 593 |
+
@property
|
| 594 |
+
def parent_context(self):
|
| 595 |
+
m = self._from_module_context
|
| 596 |
+
import_values = self.infer()
|
| 597 |
+
if not import_values:
|
| 598 |
+
return m
|
| 599 |
+
# It's almost always possible to find the import or to not find it. The
|
| 600 |
+
# importing returns only one value, pretty much always.
|
| 601 |
+
return next(iter(import_values)).as_context()
|
| 602 |
+
|
| 603 |
+
@memoize_method
|
| 604 |
+
def infer(self):
|
| 605 |
+
from jedi.inference.imports import Importer
|
| 606 |
+
m = self._from_module_context
|
| 607 |
+
return Importer(m.inference_state, [self.string_name], m, level=self._level).follow()
|
| 608 |
+
|
| 609 |
+
def goto(self):
|
| 610 |
+
return [m.name for m in self.infer()]
|
| 611 |
+
|
| 612 |
+
@property
|
| 613 |
+
def api_type(self):
|
| 614 |
+
return 'module'
|
| 615 |
+
|
| 616 |
+
def py__doc__(self):
|
| 617 |
+
return _merge_name_docs(self.goto())
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
class SubModuleName(ImportName):
|
| 621 |
+
_level = 1
|
| 622 |
+
|
| 623 |
+
|
| 624 |
+
class NameWrapper:
|
| 625 |
+
def __init__(self, wrapped_name):
|
| 626 |
+
self._wrapped_name = wrapped_name
|
| 627 |
+
|
| 628 |
+
def __getattr__(self, name):
|
| 629 |
+
return getattr(self._wrapped_name, name)
|
| 630 |
+
|
| 631 |
+
def __repr__(self):
|
| 632 |
+
return '%s(%s)' % (self.__class__.__name__, self._wrapped_name)
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
class StubNameMixin:
|
| 636 |
+
def py__doc__(self):
|
| 637 |
+
from jedi.inference.gradual.conversion import convert_names
|
| 638 |
+
# Stubs are not complicated and we can just follow simple statements
|
| 639 |
+
# that have an equals in them, because they typically make something
|
| 640 |
+
# else public. See e.g. stubs for `requests`.
|
| 641 |
+
names = [self]
|
| 642 |
+
if self.api_type == 'statement' and '=' in self.tree_name.get_definition().children:
|
| 643 |
+
names = [v.name for v in self.infer()]
|
| 644 |
+
|
| 645 |
+
names = convert_names(names, prefer_stub_to_compiled=False)
|
| 646 |
+
if self in names:
|
| 647 |
+
return super().py__doc__()
|
| 648 |
+
else:
|
| 649 |
+
# We have signatures ourselves in stubs, so don't use signatures
|
| 650 |
+
# from the implementation.
|
| 651 |
+
return _merge_name_docs(names)
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
# From here on down we make looking up the sys.version_info fast.
|
| 655 |
+
class StubName(StubNameMixin, TreeNameDefinition):
|
| 656 |
+
def infer(self):
|
| 657 |
+
inferred = super().infer()
|
| 658 |
+
if self.string_name == 'version_info' and self.get_root_context().py__name__() == 'sys':
|
| 659 |
+
from jedi.inference.gradual.stub_value import VersionInfo
|
| 660 |
+
return ValueSet(VersionInfo(c) for c in inferred)
|
| 661 |
+
return inferred
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
class ModuleName(ValueNameMixin, AbstractNameDefinition):
|
| 665 |
+
start_pos = 1, 0
|
| 666 |
+
|
| 667 |
+
def __init__(self, value, name):
|
| 668 |
+
self._value = value
|
| 669 |
+
self._name = name
|
| 670 |
+
|
| 671 |
+
@property
|
| 672 |
+
def string_name(self):
|
| 673 |
+
return self._name
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
class StubModuleName(StubNameMixin, ModuleName):
|
| 677 |
+
pass
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/param.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import defaultdict
|
| 2 |
+
from inspect import Parameter
|
| 3 |
+
|
| 4 |
+
from jedi import debug
|
| 5 |
+
from jedi.inference.utils import PushBackIterator
|
| 6 |
+
from jedi.inference import analysis
|
| 7 |
+
from jedi.inference.lazy_value import LazyKnownValue, \
|
| 8 |
+
LazyTreeValue, LazyUnknownValue
|
| 9 |
+
from jedi.inference.value import iterable
|
| 10 |
+
from jedi.inference.names import ParamName
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def _add_argument_issue(error_name, lazy_value, message):
|
| 14 |
+
if isinstance(lazy_value, LazyTreeValue):
|
| 15 |
+
node = lazy_value.data
|
| 16 |
+
if node.parent.type == 'argument':
|
| 17 |
+
node = node.parent
|
| 18 |
+
return analysis.add(lazy_value.context, error_name, node, message)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class ExecutedParamName(ParamName):
|
| 22 |
+
def __init__(self, function_value, arguments, param_node, lazy_value, is_default=False):
|
| 23 |
+
super().__init__(function_value, param_node.name, arguments=arguments)
|
| 24 |
+
self._lazy_value = lazy_value
|
| 25 |
+
self._is_default = is_default
|
| 26 |
+
|
| 27 |
+
def infer(self):
|
| 28 |
+
return self._lazy_value.infer()
|
| 29 |
+
|
| 30 |
+
def matches_signature(self):
|
| 31 |
+
if self._is_default:
|
| 32 |
+
return True
|
| 33 |
+
argument_values = self.infer().py__class__()
|
| 34 |
+
if self.get_kind() in (Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD):
|
| 35 |
+
return True
|
| 36 |
+
annotations = self.infer_annotation(execute_annotation=False)
|
| 37 |
+
if not annotations:
|
| 38 |
+
# If we cannot infer annotations - or there aren't any - pretend
|
| 39 |
+
# that the signature matches.
|
| 40 |
+
return True
|
| 41 |
+
matches = any(c1.is_sub_class_of(c2)
|
| 42 |
+
for c1 in argument_values
|
| 43 |
+
for c2 in annotations.gather_annotation_classes())
|
| 44 |
+
debug.dbg("param compare %s: %s <=> %s",
|
| 45 |
+
matches, argument_values, annotations, color='BLUE')
|
| 46 |
+
return matches
|
| 47 |
+
|
| 48 |
+
def __repr__(self):
|
| 49 |
+
return '<%s: %s>' % (self.__class__.__name__, self.string_name)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def get_executed_param_names_and_issues(function_value, arguments):
|
| 53 |
+
"""
|
| 54 |
+
Return a tuple of:
|
| 55 |
+
- a list of `ExecutedParamName`s corresponding to the arguments of the
|
| 56 |
+
function execution `function_value`, containing the inferred value of
|
| 57 |
+
those arguments (whether explicit or default)
|
| 58 |
+
- a list of the issues encountered while building that list
|
| 59 |
+
|
| 60 |
+
For example, given:
|
| 61 |
+
```
|
| 62 |
+
def foo(a, b, c=None, d='d'): ...
|
| 63 |
+
|
| 64 |
+
foo(42, c='c')
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
Then for the execution of `foo`, this will return a tuple containing:
|
| 68 |
+
- a list with entries for each parameter a, b, c & d; the entries for a,
|
| 69 |
+
c, & d will have their values (42, 'c' and 'd' respectively) included.
|
| 70 |
+
- a list with a single entry about the lack of a value for `b`
|
| 71 |
+
"""
|
| 72 |
+
def too_many_args(argument):
|
| 73 |
+
m = _error_argument_count(funcdef, len(unpacked_va))
|
| 74 |
+
# Just report an error for the first param that is not needed (like
|
| 75 |
+
# cPython).
|
| 76 |
+
if arguments.get_calling_nodes():
|
| 77 |
+
# There might not be a valid calling node so check for that first.
|
| 78 |
+
issues.append(
|
| 79 |
+
_add_argument_issue(
|
| 80 |
+
'type-error-too-many-arguments',
|
| 81 |
+
argument,
|
| 82 |
+
message=m
|
| 83 |
+
)
|
| 84 |
+
)
|
| 85 |
+
else:
|
| 86 |
+
issues.append(None)
|
| 87 |
+
debug.warning('non-public warning: %s', m)
|
| 88 |
+
|
| 89 |
+
issues = [] # List[Optional[analysis issue]]
|
| 90 |
+
result_params = []
|
| 91 |
+
param_dict = {}
|
| 92 |
+
funcdef = function_value.tree_node
|
| 93 |
+
# Default params are part of the value where the function was defined.
|
| 94 |
+
# This means that they might have access on class variables that the
|
| 95 |
+
# function itself doesn't have.
|
| 96 |
+
default_param_context = function_value.get_default_param_context()
|
| 97 |
+
|
| 98 |
+
for param in funcdef.get_params():
|
| 99 |
+
param_dict[param.name.value] = param
|
| 100 |
+
unpacked_va = list(arguments.unpack(funcdef))
|
| 101 |
+
var_arg_iterator = PushBackIterator(iter(unpacked_va))
|
| 102 |
+
|
| 103 |
+
non_matching_keys = defaultdict(lambda: [])
|
| 104 |
+
keys_used = {}
|
| 105 |
+
keys_only = False
|
| 106 |
+
had_multiple_value_error = False
|
| 107 |
+
for param in funcdef.get_params():
|
| 108 |
+
# The value and key can both be null. There, the defaults apply.
|
| 109 |
+
# args / kwargs will just be empty arrays / dicts, respectively.
|
| 110 |
+
# Wrong value count is just ignored. If you try to test cases that are
|
| 111 |
+
# not allowed in Python, Jedi will maybe not show any completions.
|
| 112 |
+
is_default = False
|
| 113 |
+
key, argument = next(var_arg_iterator, (None, None))
|
| 114 |
+
while key is not None:
|
| 115 |
+
keys_only = True
|
| 116 |
+
try:
|
| 117 |
+
key_param = param_dict[key]
|
| 118 |
+
except KeyError:
|
| 119 |
+
non_matching_keys[key] = argument
|
| 120 |
+
else:
|
| 121 |
+
if key in keys_used:
|
| 122 |
+
had_multiple_value_error = True
|
| 123 |
+
m = ("TypeError: %s() got multiple values for keyword argument '%s'."
|
| 124 |
+
% (funcdef.name, key))
|
| 125 |
+
for contextualized_node in arguments.get_calling_nodes():
|
| 126 |
+
issues.append(
|
| 127 |
+
analysis.add(contextualized_node.context,
|
| 128 |
+
'type-error-multiple-values',
|
| 129 |
+
contextualized_node.node, message=m)
|
| 130 |
+
)
|
| 131 |
+
else:
|
| 132 |
+
keys_used[key] = ExecutedParamName(
|
| 133 |
+
function_value, arguments, key_param, argument)
|
| 134 |
+
key, argument = next(var_arg_iterator, (None, None))
|
| 135 |
+
|
| 136 |
+
try:
|
| 137 |
+
result_params.append(keys_used[param.name.value])
|
| 138 |
+
continue
|
| 139 |
+
except KeyError:
|
| 140 |
+
pass
|
| 141 |
+
|
| 142 |
+
if param.star_count == 1:
|
| 143 |
+
# *args param
|
| 144 |
+
lazy_value_list = []
|
| 145 |
+
if argument is not None:
|
| 146 |
+
lazy_value_list.append(argument)
|
| 147 |
+
for key, argument in var_arg_iterator:
|
| 148 |
+
# Iterate until a key argument is found.
|
| 149 |
+
if key:
|
| 150 |
+
var_arg_iterator.push_back((key, argument))
|
| 151 |
+
break
|
| 152 |
+
lazy_value_list.append(argument)
|
| 153 |
+
seq = iterable.FakeTuple(function_value.inference_state, lazy_value_list)
|
| 154 |
+
result_arg = LazyKnownValue(seq)
|
| 155 |
+
elif param.star_count == 2:
|
| 156 |
+
if argument is not None:
|
| 157 |
+
too_many_args(argument)
|
| 158 |
+
# **kwargs param
|
| 159 |
+
dct = iterable.FakeDict(function_value.inference_state, dict(non_matching_keys))
|
| 160 |
+
result_arg = LazyKnownValue(dct)
|
| 161 |
+
non_matching_keys = {}
|
| 162 |
+
else:
|
| 163 |
+
# normal param
|
| 164 |
+
if argument is None:
|
| 165 |
+
# No value: Return an empty container
|
| 166 |
+
if param.default is None:
|
| 167 |
+
result_arg = LazyUnknownValue()
|
| 168 |
+
if not keys_only:
|
| 169 |
+
for contextualized_node in arguments.get_calling_nodes():
|
| 170 |
+
m = _error_argument_count(funcdef, len(unpacked_va))
|
| 171 |
+
issues.append(
|
| 172 |
+
analysis.add(
|
| 173 |
+
contextualized_node.context,
|
| 174 |
+
'type-error-too-few-arguments',
|
| 175 |
+
contextualized_node.node,
|
| 176 |
+
message=m,
|
| 177 |
+
)
|
| 178 |
+
)
|
| 179 |
+
else:
|
| 180 |
+
result_arg = LazyTreeValue(default_param_context, param.default)
|
| 181 |
+
is_default = True
|
| 182 |
+
else:
|
| 183 |
+
result_arg = argument
|
| 184 |
+
|
| 185 |
+
result_params.append(ExecutedParamName(
|
| 186 |
+
function_value, arguments, param, result_arg, is_default=is_default
|
| 187 |
+
))
|
| 188 |
+
if not isinstance(result_arg, LazyUnknownValue):
|
| 189 |
+
keys_used[param.name.value] = result_params[-1]
|
| 190 |
+
|
| 191 |
+
if keys_only:
|
| 192 |
+
# All arguments should be handed over to the next function. It's not
|
| 193 |
+
# about the values inside, it's about the names. Jedi needs to now that
|
| 194 |
+
# there's nothing to find for certain names.
|
| 195 |
+
for k in set(param_dict) - set(keys_used):
|
| 196 |
+
param = param_dict[k]
|
| 197 |
+
|
| 198 |
+
if not (non_matching_keys or had_multiple_value_error
|
| 199 |
+
or param.star_count or param.default):
|
| 200 |
+
# add a warning only if there's not another one.
|
| 201 |
+
for contextualized_node in arguments.get_calling_nodes():
|
| 202 |
+
m = _error_argument_count(funcdef, len(unpacked_va))
|
| 203 |
+
issues.append(
|
| 204 |
+
analysis.add(contextualized_node.context,
|
| 205 |
+
'type-error-too-few-arguments',
|
| 206 |
+
contextualized_node.node, message=m)
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
for key, lazy_value in non_matching_keys.items():
|
| 210 |
+
m = "TypeError: %s() got an unexpected keyword argument '%s'." \
|
| 211 |
+
% (funcdef.name, key)
|
| 212 |
+
issues.append(
|
| 213 |
+
_add_argument_issue(
|
| 214 |
+
'type-error-keyword-argument',
|
| 215 |
+
lazy_value,
|
| 216 |
+
message=m
|
| 217 |
+
)
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
remaining_arguments = list(var_arg_iterator)
|
| 221 |
+
if remaining_arguments:
|
| 222 |
+
first_key, lazy_value = remaining_arguments[0]
|
| 223 |
+
too_many_args(lazy_value)
|
| 224 |
+
return result_params, issues
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def get_executed_param_names(function_value, arguments):
|
| 228 |
+
"""
|
| 229 |
+
Return a list of `ExecutedParamName`s corresponding to the arguments of the
|
| 230 |
+
function execution `function_value`, containing the inferred value of those
|
| 231 |
+
arguments (whether explicit or default). Any issues building this list (for
|
| 232 |
+
example required arguments which are missing in the invocation) are ignored.
|
| 233 |
+
|
| 234 |
+
For example, given:
|
| 235 |
+
```
|
| 236 |
+
def foo(a, b, c=None, d='d'): ...
|
| 237 |
+
|
| 238 |
+
foo(42, c='c')
|
| 239 |
+
```
|
| 240 |
+
|
| 241 |
+
Then for the execution of `foo`, this will return a list containing entries
|
| 242 |
+
for each parameter a, b, c & d; the entries for a, c, & d will have their
|
| 243 |
+
values (42, 'c' and 'd' respectively) included.
|
| 244 |
+
"""
|
| 245 |
+
return get_executed_param_names_and_issues(function_value, arguments)[0]
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def _error_argument_count(funcdef, actual_count):
|
| 249 |
+
params = funcdef.get_params()
|
| 250 |
+
default_arguments = sum(1 for p in params if p.default or p.star_count)
|
| 251 |
+
|
| 252 |
+
if default_arguments == 0:
|
| 253 |
+
before = 'exactly '
|
| 254 |
+
else:
|
| 255 |
+
before = 'from %s to ' % (len(params) - default_arguments)
|
| 256 |
+
return ('TypeError: %s() takes %s%s arguments (%s given).'
|
| 257 |
+
% (funcdef.name, before, len(params), actual_count))
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/parser_cache.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from jedi.inference.cache import inference_state_function_cache
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
@inference_state_function_cache()
|
| 5 |
+
def get_yield_exprs(inference_state, funcdef):
|
| 6 |
+
return list(funcdef.iter_yield_exprs())
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/in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ad. Some settings are here to make |jedi| stop at
|
| 4 |
+
the right time. You can read more about them :ref:`here <settings-recursion>`.
|
| 5 |
+
|
| 6 |
+
Next to the internal ``jedi.inference.cache`` this module also makes |jedi| not
|
| 7 |
+
thread-safe, because ``execution_recursion_decorator`` uses class variables to
|
| 8 |
+
count the function calls.
|
| 9 |
+
|
| 10 |
+
.. _settings-recursion:
|
| 11 |
+
|
| 12 |
+
Settings
|
| 13 |
+
~~~~~~~~~~
|
| 14 |
+
|
| 15 |
+
Recursion settings are important if you don't want extremely
|
| 16 |
+
recursive python code to go absolutely crazy.
|
| 17 |
+
|
| 18 |
+
The default values are based on experiments while completing the |jedi| library
|
| 19 |
+
itself (inception!). But I don't think there's any other Python library that
|
| 20 |
+
uses recursion in a similarly extreme way. Completion should also be fast and
|
| 21 |
+
therefore the quality might not always be maximal.
|
| 22 |
+
|
| 23 |
+
.. autodata:: recursion_limit
|
| 24 |
+
.. autodata:: total_function_execution_limit
|
| 25 |
+
.. autodata:: per_function_execution_limit
|
| 26 |
+
.. autodata:: per_function_recursion_limit
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
from contextlib import contextmanager
|
| 30 |
+
|
| 31 |
+
from jedi import debug
|
| 32 |
+
from jedi.inference.base_value import NO_VALUES
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
recursion_limit = 15
|
| 36 |
+
"""
|
| 37 |
+
Like :func:`sys.getrecursionlimit()`, just for |jedi|.
|
| 38 |
+
"""
|
| 39 |
+
total_function_execution_limit = 200
|
| 40 |
+
"""
|
| 41 |
+
This is a hard limit of how many non-builtin functions can be executed.
|
| 42 |
+
"""
|
| 43 |
+
per_function_execution_limit = 6
|
| 44 |
+
"""
|
| 45 |
+
The maximal amount of times a specific function may be executed.
|
| 46 |
+
"""
|
| 47 |
+
per_function_recursion_limit = 2
|
| 48 |
+
"""
|
| 49 |
+
A function may not be executed more than this number of times recursively.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class RecursionDetector:
|
| 54 |
+
def __init__(self):
|
| 55 |
+
self.pushed_nodes = []
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@contextmanager
|
| 59 |
+
def execution_allowed(inference_state, node):
|
| 60 |
+
"""
|
| 61 |
+
A decorator to detect recursions in statements. In a recursion a statement
|
| 62 |
+
at the same place, in the same module may not be executed two times.
|
| 63 |
+
"""
|
| 64 |
+
pushed_nodes = inference_state.recursion_detector.pushed_nodes
|
| 65 |
+
|
| 66 |
+
if node in pushed_nodes:
|
| 67 |
+
debug.warning('catched stmt recursion: %s @%s', node,
|
| 68 |
+
getattr(node, 'start_pos', None))
|
| 69 |
+
yield False
|
| 70 |
+
else:
|
| 71 |
+
try:
|
| 72 |
+
pushed_nodes.append(node)
|
| 73 |
+
yield True
|
| 74 |
+
finally:
|
| 75 |
+
pushed_nodes.pop()
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def execution_recursion_decorator(default=NO_VALUES):
|
| 79 |
+
def decorator(func):
|
| 80 |
+
def wrapper(self, **kwargs):
|
| 81 |
+
detector = self.inference_state.execution_recursion_detector
|
| 82 |
+
limit_reached = detector.push_execution(self)
|
| 83 |
+
try:
|
| 84 |
+
if limit_reached:
|
| 85 |
+
result = default
|
| 86 |
+
else:
|
| 87 |
+
result = func(self, **kwargs)
|
| 88 |
+
finally:
|
| 89 |
+
detector.pop_execution()
|
| 90 |
+
return result
|
| 91 |
+
return wrapper
|
| 92 |
+
return decorator
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class ExecutionRecursionDetector:
|
| 96 |
+
"""
|
| 97 |
+
Catches recursions of executions.
|
| 98 |
+
"""
|
| 99 |
+
def __init__(self, inference_state):
|
| 100 |
+
self._inference_state = inference_state
|
| 101 |
+
|
| 102 |
+
self._recursion_level = 0
|
| 103 |
+
self._parent_execution_funcs = []
|
| 104 |
+
self._funcdef_execution_counts = {}
|
| 105 |
+
self._execution_count = 0
|
| 106 |
+
|
| 107 |
+
def pop_execution(self):
|
| 108 |
+
self._parent_execution_funcs.pop()
|
| 109 |
+
self._recursion_level -= 1
|
| 110 |
+
|
| 111 |
+
def push_execution(self, execution):
|
| 112 |
+
funcdef = execution.tree_node
|
| 113 |
+
|
| 114 |
+
# These two will be undone in pop_execution.
|
| 115 |
+
self._recursion_level += 1
|
| 116 |
+
self._parent_execution_funcs.append(funcdef)
|
| 117 |
+
|
| 118 |
+
module_context = execution.get_root_context()
|
| 119 |
+
|
| 120 |
+
if module_context.is_builtins_module():
|
| 121 |
+
# We have control over builtins so we know they are not recursing
|
| 122 |
+
# like crazy. Therefore we just let them execute always, because
|
| 123 |
+
# they usually just help a lot with getting good results.
|
| 124 |
+
return False
|
| 125 |
+
|
| 126 |
+
if self._recursion_level > recursion_limit:
|
| 127 |
+
debug.warning('Recursion limit (%s) reached', recursion_limit)
|
| 128 |
+
return True
|
| 129 |
+
|
| 130 |
+
if self._execution_count >= total_function_execution_limit:
|
| 131 |
+
debug.warning('Function execution limit (%s) reached', total_function_execution_limit)
|
| 132 |
+
return True
|
| 133 |
+
self._execution_count += 1
|
| 134 |
+
|
| 135 |
+
if self._funcdef_execution_counts.setdefault(funcdef, 0) >= per_function_execution_limit:
|
| 136 |
+
if module_context.py__name__() == 'typing':
|
| 137 |
+
return False
|
| 138 |
+
debug.warning(
|
| 139 |
+
'Per function execution limit (%s) reached: %s',
|
| 140 |
+
per_function_execution_limit,
|
| 141 |
+
funcdef
|
| 142 |
+
)
|
| 143 |
+
return True
|
| 144 |
+
self._funcdef_execution_counts[funcdef] += 1
|
| 145 |
+
|
| 146 |
+
if self._parent_execution_funcs.count(funcdef) > per_function_recursion_limit:
|
| 147 |
+
debug.warning(
|
| 148 |
+
'Per function recursion limit (%s) reached: %s',
|
| 149 |
+
per_function_recursion_limit,
|
| 150 |
+
funcdef
|
| 151 |
+
)
|
| 152 |
+
return True
|
| 153 |
+
return False
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/references.py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from jedi.file_io import KnownContentFileIO, FolderIO
|
| 8 |
+
from jedi.inference.names import SubModuleName
|
| 9 |
+
from jedi.inference.imports import load_module_from_path
|
| 10 |
+
from jedi.inference.filters import ParserTreeFilter
|
| 11 |
+
from jedi.inference.gradual.conversion import convert_names
|
| 12 |
+
|
| 13 |
+
_IGNORE_FOLDERS = ('.tox', '.venv', '.mypy_cache', 'venv', '__pycache__')
|
| 14 |
+
|
| 15 |
+
_OPENED_FILE_LIMIT = 2000
|
| 16 |
+
"""
|
| 17 |
+
Stats from a 2016 Lenovo Notebook running Linux:
|
| 18 |
+
With os.walk, it takes about 10s to scan 11'000 files (without filesystem
|
| 19 |
+
caching). Once cached it only takes 5s. So it is expected that reading all
|
| 20 |
+
those files might take a few seconds, but not a lot more.
|
| 21 |
+
"""
|
| 22 |
+
_PARSED_FILE_LIMIT = 30
|
| 23 |
+
"""
|
| 24 |
+
For now we keep the amount of parsed files really low, since parsing might take
|
| 25 |
+
easily 100ms for bigger files.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _resolve_names(definition_names, avoid_names=()):
|
| 30 |
+
for name in definition_names:
|
| 31 |
+
if name in avoid_names:
|
| 32 |
+
# Avoiding recursions here, because goto on a module name lands
|
| 33 |
+
# on the same module.
|
| 34 |
+
continue
|
| 35 |
+
|
| 36 |
+
if not isinstance(name, SubModuleName):
|
| 37 |
+
# SubModuleNames are not actually existing names but created
|
| 38 |
+
# names when importing something like `import foo.bar.baz`.
|
| 39 |
+
yield name
|
| 40 |
+
|
| 41 |
+
if name.api_type == 'module':
|
| 42 |
+
yield from _resolve_names(name.goto(), definition_names)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _dictionarize(names):
|
| 46 |
+
return dict(
|
| 47 |
+
(n if n.tree_name is None else n.tree_name, n)
|
| 48 |
+
for n in names
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _find_defining_names(module_context, tree_name):
|
| 53 |
+
found_names = _find_names(module_context, tree_name)
|
| 54 |
+
|
| 55 |
+
for name in list(found_names):
|
| 56 |
+
# Convert from/to stubs, because those might also be usages.
|
| 57 |
+
found_names |= set(convert_names(
|
| 58 |
+
[name],
|
| 59 |
+
only_stubs=not name.get_root_context().is_stub(),
|
| 60 |
+
prefer_stub_to_compiled=False
|
| 61 |
+
))
|
| 62 |
+
|
| 63 |
+
found_names |= set(_find_global_variables(found_names, tree_name.value))
|
| 64 |
+
for name in list(found_names):
|
| 65 |
+
if name.api_type == 'param' or name.tree_name is None \
|
| 66 |
+
or name.tree_name.parent.type == 'trailer':
|
| 67 |
+
continue
|
| 68 |
+
found_names |= set(_add_names_in_same_context(name.parent_context, name.string_name))
|
| 69 |
+
return set(_resolve_names(found_names))
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _find_names(module_context, tree_name):
|
| 73 |
+
name = module_context.create_name(tree_name)
|
| 74 |
+
found_names = set(name.goto())
|
| 75 |
+
found_names.add(name)
|
| 76 |
+
|
| 77 |
+
return set(_resolve_names(found_names))
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _add_names_in_same_context(context, string_name):
|
| 81 |
+
if context.tree_node is None:
|
| 82 |
+
return
|
| 83 |
+
|
| 84 |
+
until_position = None
|
| 85 |
+
while True:
|
| 86 |
+
filter_ = ParserTreeFilter(
|
| 87 |
+
parent_context=context,
|
| 88 |
+
until_position=until_position,
|
| 89 |
+
)
|
| 90 |
+
names = set(filter_.get(string_name))
|
| 91 |
+
if not names:
|
| 92 |
+
break
|
| 93 |
+
yield from names
|
| 94 |
+
ordered = sorted(names, key=lambda x: x.start_pos)
|
| 95 |
+
until_position = ordered[0].start_pos
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _find_global_variables(names, search_name):
|
| 99 |
+
for name in names:
|
| 100 |
+
if name.tree_name is None:
|
| 101 |
+
continue
|
| 102 |
+
module_context = name.get_root_context()
|
| 103 |
+
try:
|
| 104 |
+
method = module_context.get_global_filter
|
| 105 |
+
except AttributeError:
|
| 106 |
+
continue
|
| 107 |
+
else:
|
| 108 |
+
for global_name in method().get(search_name):
|
| 109 |
+
yield global_name
|
| 110 |
+
c = module_context.create_context(global_name.tree_name)
|
| 111 |
+
yield from _add_names_in_same_context(c, global_name.string_name)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def find_references(module_context, tree_name, only_in_module=False):
|
| 115 |
+
inf = module_context.inference_state
|
| 116 |
+
search_name = tree_name.value
|
| 117 |
+
|
| 118 |
+
# We disable flow analysis, because if we have ifs that are only true in
|
| 119 |
+
# certain cases, we want both sides.
|
| 120 |
+
try:
|
| 121 |
+
inf.flow_analysis_enabled = False
|
| 122 |
+
found_names = _find_defining_names(module_context, tree_name)
|
| 123 |
+
finally:
|
| 124 |
+
inf.flow_analysis_enabled = True
|
| 125 |
+
|
| 126 |
+
found_names_dct = _dictionarize(found_names)
|
| 127 |
+
|
| 128 |
+
module_contexts = [module_context]
|
| 129 |
+
if not only_in_module:
|
| 130 |
+
for m in set(d.get_root_context() for d in found_names):
|
| 131 |
+
if m != module_context and m.tree_node is not None \
|
| 132 |
+
and inf.project.path in m.py__file__().parents:
|
| 133 |
+
module_contexts.append(m)
|
| 134 |
+
# For param no search for other modules is necessary.
|
| 135 |
+
if only_in_module or any(n.api_type == 'param' for n in found_names):
|
| 136 |
+
potential_modules = module_contexts
|
| 137 |
+
else:
|
| 138 |
+
potential_modules = get_module_contexts_containing_name(
|
| 139 |
+
inf,
|
| 140 |
+
module_contexts,
|
| 141 |
+
search_name,
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
non_matching_reference_maps = {}
|
| 145 |
+
for module_context in potential_modules:
|
| 146 |
+
for name_leaf in module_context.tree_node.get_used_names().get(search_name, []):
|
| 147 |
+
new = _dictionarize(_find_names(module_context, name_leaf))
|
| 148 |
+
if any(tree_name in found_names_dct for tree_name in new):
|
| 149 |
+
found_names_dct.update(new)
|
| 150 |
+
for tree_name in new:
|
| 151 |
+
for dct in non_matching_reference_maps.get(tree_name, []):
|
| 152 |
+
# A reference that was previously searched for matches
|
| 153 |
+
# with a now found name. Merge.
|
| 154 |
+
found_names_dct.update(dct)
|
| 155 |
+
try:
|
| 156 |
+
del non_matching_reference_maps[tree_name]
|
| 157 |
+
except KeyError:
|
| 158 |
+
pass
|
| 159 |
+
else:
|
| 160 |
+
for name in new:
|
| 161 |
+
non_matching_reference_maps.setdefault(name, []).append(new)
|
| 162 |
+
result = found_names_dct.values()
|
| 163 |
+
if only_in_module:
|
| 164 |
+
return [n for n in result if n.get_root_context() == module_context]
|
| 165 |
+
return result
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _check_fs(inference_state, file_io, regex):
|
| 169 |
+
try:
|
| 170 |
+
code = file_io.read()
|
| 171 |
+
except FileNotFoundError:
|
| 172 |
+
return None
|
| 173 |
+
code = python_bytes_to_unicode(code, errors='replace')
|
| 174 |
+
if not regex.search(code):
|
| 175 |
+
return None
|
| 176 |
+
new_file_io = KnownContentFileIO(file_io.path, code)
|
| 177 |
+
m = load_module_from_path(inference_state, new_file_io)
|
| 178 |
+
if m.is_compiled():
|
| 179 |
+
return None
|
| 180 |
+
return m.as_context()
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def gitignored_paths(folder_io, file_io):
|
| 184 |
+
ignored_paths_abs = set()
|
| 185 |
+
ignored_paths_rel = set()
|
| 186 |
+
|
| 187 |
+
for l in file_io.read().splitlines():
|
| 188 |
+
if not l or l.startswith(b'#') or l.startswith(b'!') or b'*' in l:
|
| 189 |
+
continue
|
| 190 |
+
|
| 191 |
+
p = l.decode('utf-8', 'ignore').rstrip('/')
|
| 192 |
+
if '/' in p:
|
| 193 |
+
name = p.lstrip('/')
|
| 194 |
+
ignored_paths_abs.add(os.path.join(folder_io.path, name))
|
| 195 |
+
else:
|
| 196 |
+
name = p
|
| 197 |
+
ignored_paths_rel.add((folder_io.path, name))
|
| 198 |
+
|
| 199 |
+
return ignored_paths_abs, ignored_paths_rel
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def expand_relative_ignore_paths(folder_io, relative_paths):
|
| 203 |
+
curr_path = folder_io.path
|
| 204 |
+
return {os.path.join(curr_path, p[1]) for p in relative_paths if curr_path.startswith(p[0])}
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def recurse_find_python_folders_and_files(folder_io, except_paths=()):
|
| 208 |
+
except_paths = set(except_paths)
|
| 209 |
+
except_paths_relative = set()
|
| 210 |
+
|
| 211 |
+
for root_folder_io, folder_ios, file_ios in folder_io.walk():
|
| 212 |
+
# Delete folders that we don't want to iterate over.
|
| 213 |
+
for file_io in file_ios:
|
| 214 |
+
path = file_io.path
|
| 215 |
+
if path.suffix in ('.py', '.pyi'):
|
| 216 |
+
if path not in except_paths:
|
| 217 |
+
yield None, file_io
|
| 218 |
+
|
| 219 |
+
if path.name == '.gitignore':
|
| 220 |
+
ignored_paths_abs, ignored_paths_rel = gitignored_paths(
|
| 221 |
+
root_folder_io, file_io
|
| 222 |
+
)
|
| 223 |
+
except_paths |= ignored_paths_abs
|
| 224 |
+
except_paths_relative |= ignored_paths_rel
|
| 225 |
+
|
| 226 |
+
except_paths_relative_expanded = expand_relative_ignore_paths(
|
| 227 |
+
root_folder_io, except_paths_relative
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
folder_ios[:] = [
|
| 231 |
+
folder_io
|
| 232 |
+
for folder_io in folder_ios
|
| 233 |
+
if folder_io.path not in except_paths
|
| 234 |
+
and folder_io.path not in except_paths_relative_expanded
|
| 235 |
+
and folder_io.get_base_name() not in _IGNORE_FOLDERS
|
| 236 |
+
]
|
| 237 |
+
for folder_io in folder_ios:
|
| 238 |
+
yield folder_io, None
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def recurse_find_python_files(folder_io, except_paths=()):
|
| 242 |
+
for folder_io, file_io in recurse_find_python_folders_and_files(folder_io, except_paths):
|
| 243 |
+
if file_io is not None:
|
| 244 |
+
yield file_io
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def _find_python_files_in_sys_path(inference_state, module_contexts):
|
| 248 |
+
sys_path = inference_state.get_sys_path()
|
| 249 |
+
except_paths = set()
|
| 250 |
+
yielded_paths = [m.py__file__() for m in module_contexts]
|
| 251 |
+
for module_context in module_contexts:
|
| 252 |
+
file_io = module_context.get_value().file_io
|
| 253 |
+
if file_io is None:
|
| 254 |
+
continue
|
| 255 |
+
|
| 256 |
+
folder_io = file_io.get_parent_folder()
|
| 257 |
+
while True:
|
| 258 |
+
path = folder_io.path
|
| 259 |
+
if not any(path.startswith(p) for p in sys_path) or path in except_paths:
|
| 260 |
+
break
|
| 261 |
+
for file_io in recurse_find_python_files(folder_io, except_paths):
|
| 262 |
+
if file_io.path not in yielded_paths:
|
| 263 |
+
yield file_io
|
| 264 |
+
except_paths.add(path)
|
| 265 |
+
folder_io = folder_io.get_parent_folder()
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def _find_project_modules(inference_state, module_contexts):
|
| 269 |
+
except_ = [m.py__file__() for m in module_contexts]
|
| 270 |
+
yield from recurse_find_python_files(FolderIO(inference_state.project.path), except_)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def get_module_contexts_containing_name(inference_state, module_contexts, name,
|
| 274 |
+
limit_reduction=1):
|
| 275 |
+
"""
|
| 276 |
+
Search a name in the directories of modules.
|
| 277 |
+
|
| 278 |
+
:param limit_reduction: Divides the limits on opening/parsing files by this
|
| 279 |
+
factor.
|
| 280 |
+
"""
|
| 281 |
+
# Skip non python modules
|
| 282 |
+
for module_context in module_contexts:
|
| 283 |
+
if module_context.is_compiled():
|
| 284 |
+
continue
|
| 285 |
+
yield module_context
|
| 286 |
+
|
| 287 |
+
# Very short names are not searched in other modules for now to avoid lots
|
| 288 |
+
# of file lookups.
|
| 289 |
+
if len(name) <= 2:
|
| 290 |
+
return
|
| 291 |
+
|
| 292 |
+
# Currently not used, because there's only `scope=project` and `scope=file`
|
| 293 |
+
# At the moment there is no such thing as `scope=sys.path`.
|
| 294 |
+
# file_io_iterator = _find_python_files_in_sys_path(inference_state, module_contexts)
|
| 295 |
+
file_io_iterator = _find_project_modules(inference_state, module_contexts)
|
| 296 |
+
yield from search_in_file_ios(inference_state, file_io_iterator, name,
|
| 297 |
+
limit_reduction=limit_reduction)
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def search_in_file_ios(inference_state, file_io_iterator, name,
|
| 301 |
+
limit_reduction=1, complete=False):
|
| 302 |
+
parse_limit = _PARSED_FILE_LIMIT / limit_reduction
|
| 303 |
+
open_limit = _OPENED_FILE_LIMIT / limit_reduction
|
| 304 |
+
file_io_count = 0
|
| 305 |
+
parsed_file_count = 0
|
| 306 |
+
regex = re.compile(r'\b' + re.escape(name) + (r'' if complete else r'\b'))
|
| 307 |
+
for file_io in file_io_iterator:
|
| 308 |
+
file_io_count += 1
|
| 309 |
+
m = _check_fs(inference_state, file_io, regex)
|
| 310 |
+
if m is not None:
|
| 311 |
+
parsed_file_count += 1
|
| 312 |
+
yield m
|
| 313 |
+
if parsed_file_count >= parse_limit:
|
| 314 |
+
dbg('Hit limit of parsed files: %s', parse_limit)
|
| 315 |
+
break
|
| 316 |
+
|
| 317 |
+
if file_io_count >= open_limit:
|
| 318 |
+
dbg('Hit limit of opened files: %s', open_limit)
|
| 319 |
+
break
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/signature.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from inspect import Parameter
|
| 2 |
+
|
| 3 |
+
from jedi.cache import memoize_method
|
| 4 |
+
from jedi import debug
|
| 5 |
+
from jedi import parser_utils
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class _SignatureMixin:
|
| 9 |
+
def to_string(self):
|
| 10 |
+
def param_strings():
|
| 11 |
+
is_positional = False
|
| 12 |
+
is_kw_only = False
|
| 13 |
+
for n in self.get_param_names(resolve_stars=True):
|
| 14 |
+
kind = n.get_kind()
|
| 15 |
+
is_positional |= kind == Parameter.POSITIONAL_ONLY
|
| 16 |
+
if is_positional and kind != Parameter.POSITIONAL_ONLY:
|
| 17 |
+
yield '/'
|
| 18 |
+
is_positional = False
|
| 19 |
+
|
| 20 |
+
if kind == Parameter.VAR_POSITIONAL:
|
| 21 |
+
is_kw_only = True
|
| 22 |
+
elif kind == Parameter.KEYWORD_ONLY and not is_kw_only:
|
| 23 |
+
yield '*'
|
| 24 |
+
is_kw_only = True
|
| 25 |
+
|
| 26 |
+
yield n.to_string()
|
| 27 |
+
|
| 28 |
+
if is_positional:
|
| 29 |
+
yield '/'
|
| 30 |
+
|
| 31 |
+
s = self.name.string_name + '(' + ', '.join(param_strings()) + ')'
|
| 32 |
+
annotation = self.annotation_string
|
| 33 |
+
if annotation:
|
| 34 |
+
s += ' -> ' + annotation
|
| 35 |
+
return s
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class AbstractSignature(_SignatureMixin):
|
| 39 |
+
def __init__(self, value, is_bound=False):
|
| 40 |
+
self.value = value
|
| 41 |
+
self.is_bound = is_bound
|
| 42 |
+
|
| 43 |
+
@property
|
| 44 |
+
def name(self):
|
| 45 |
+
return self.value.name
|
| 46 |
+
|
| 47 |
+
@property
|
| 48 |
+
def annotation_string(self):
|
| 49 |
+
return ''
|
| 50 |
+
|
| 51 |
+
def get_param_names(self, resolve_stars=False):
|
| 52 |
+
param_names = self._function_value.get_param_names()
|
| 53 |
+
if self.is_bound:
|
| 54 |
+
return param_names[1:]
|
| 55 |
+
return param_names
|
| 56 |
+
|
| 57 |
+
def bind(self, value):
|
| 58 |
+
raise NotImplementedError
|
| 59 |
+
|
| 60 |
+
def matches_signature(self, arguments):
|
| 61 |
+
return True
|
| 62 |
+
|
| 63 |
+
def __repr__(self):
|
| 64 |
+
if self.value is self._function_value:
|
| 65 |
+
return '<%s: %s>' % (self.__class__.__name__, self.value)
|
| 66 |
+
return '<%s: %s, %s>' % (self.__class__.__name__, self.value, self._function_value)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class TreeSignature(AbstractSignature):
|
| 70 |
+
def __init__(self, value, function_value=None, is_bound=False):
|
| 71 |
+
super().__init__(value, is_bound)
|
| 72 |
+
self._function_value = function_value or value
|
| 73 |
+
|
| 74 |
+
def bind(self, value):
|
| 75 |
+
return TreeSignature(value, self._function_value, is_bound=True)
|
| 76 |
+
|
| 77 |
+
@property
|
| 78 |
+
def _annotation(self):
|
| 79 |
+
# Classes don't need annotations, even if __init__ has one. They always
|
| 80 |
+
# return themselves.
|
| 81 |
+
if self.value.is_class():
|
| 82 |
+
return None
|
| 83 |
+
return self._function_value.tree_node.annotation
|
| 84 |
+
|
| 85 |
+
@property
|
| 86 |
+
def annotation_string(self):
|
| 87 |
+
a = self._annotation
|
| 88 |
+
if a is None:
|
| 89 |
+
return ''
|
| 90 |
+
return a.get_code(include_prefix=False)
|
| 91 |
+
|
| 92 |
+
@memoize_method
|
| 93 |
+
def get_param_names(self, resolve_stars=False):
|
| 94 |
+
params = self._function_value.get_param_names()
|
| 95 |
+
if resolve_stars:
|
| 96 |
+
from jedi.inference.star_args import process_params
|
| 97 |
+
params = process_params(params)
|
| 98 |
+
if self.is_bound:
|
| 99 |
+
return params[1:]
|
| 100 |
+
return params
|
| 101 |
+
|
| 102 |
+
def matches_signature(self, arguments):
|
| 103 |
+
from jedi.inference.param import get_executed_param_names_and_issues
|
| 104 |
+
executed_param_names, issues = \
|
| 105 |
+
get_executed_param_names_and_issues(self._function_value, arguments)
|
| 106 |
+
if issues:
|
| 107 |
+
return False
|
| 108 |
+
|
| 109 |
+
matches = all(executed_param_name.matches_signature()
|
| 110 |
+
for executed_param_name in executed_param_names)
|
| 111 |
+
if debug.enable_notice:
|
| 112 |
+
tree_node = self._function_value.tree_node
|
| 113 |
+
signature = parser_utils.get_signature(tree_node)
|
| 114 |
+
if matches:
|
| 115 |
+
debug.dbg("Overloading match: %s@%s (%s)",
|
| 116 |
+
signature, tree_node.start_pos[0], arguments, color='BLUE')
|
| 117 |
+
else:
|
| 118 |
+
debug.dbg("Overloading no match: %s@%s (%s)",
|
| 119 |
+
signature, tree_node.start_pos[0], arguments, color='BLUE')
|
| 120 |
+
return matches
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
class BuiltinSignature(AbstractSignature):
|
| 124 |
+
def __init__(self, value, return_string, function_value=None, is_bound=False):
|
| 125 |
+
super().__init__(value, is_bound)
|
| 126 |
+
self._return_string = return_string
|
| 127 |
+
self.__function_value = function_value
|
| 128 |
+
|
| 129 |
+
@property
|
| 130 |
+
def annotation_string(self):
|
| 131 |
+
return self._return_string
|
| 132 |
+
|
| 133 |
+
@property
|
| 134 |
+
def _function_value(self):
|
| 135 |
+
if self.__function_value is None:
|
| 136 |
+
return self.value
|
| 137 |
+
return self.__function_value
|
| 138 |
+
|
| 139 |
+
def bind(self, value):
|
| 140 |
+
return BuiltinSignature(
|
| 141 |
+
value, self._return_string,
|
| 142 |
+
function_value=self.value,
|
| 143 |
+
is_bound=True
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class SignatureWrapper(_SignatureMixin):
|
| 148 |
+
def __init__(self, wrapped_signature):
|
| 149 |
+
self._wrapped_signature = wrapped_signature
|
| 150 |
+
|
| 151 |
+
def __getattr__(self, name):
|
| 152 |
+
return getattr(self._wrapped_signature, name)
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/star_args.py
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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case::
|
| 5 |
+
|
| 6 |
+
def foo(a, b, c): ...
|
| 7 |
+
|
| 8 |
+
def bar(*args):
|
| 9 |
+
return foo(1, *args)
|
| 10 |
+
|
| 11 |
+
The signature here for bar should be `bar(b, c)` instead of bar(*args).
|
| 12 |
+
"""
|
| 13 |
+
from inspect import Parameter
|
| 14 |
+
|
| 15 |
+
from parso import tree
|
| 16 |
+
|
| 17 |
+
from jedi.inference.utils import to_list
|
| 18 |
+
from jedi.inference.names import ParamNameWrapper
|
| 19 |
+
from jedi.inference.helpers import is_big_annoying_library
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _iter_nodes_for_param(param_name):
|
| 23 |
+
from parso.python.tree import search_ancestor
|
| 24 |
+
from jedi.inference.arguments import TreeArguments
|
| 25 |
+
|
| 26 |
+
execution_context = param_name.parent_context
|
| 27 |
+
# Walk up the parso tree to get the FunctionNode we want. We use the parso
|
| 28 |
+
# tree rather than going via the execution context so that we're agnostic of
|
| 29 |
+
# the specific scope we're evaluating within (i.e: module or function,
|
| 30 |
+
# etc.).
|
| 31 |
+
function_node = tree.search_ancestor(param_name.tree_name, 'funcdef', 'lambdef')
|
| 32 |
+
module_node = function_node.get_root_node()
|
| 33 |
+
start = function_node.children[-1].start_pos
|
| 34 |
+
end = function_node.children[-1].end_pos
|
| 35 |
+
for name in module_node.get_used_names().get(param_name.string_name):
|
| 36 |
+
if start <= name.start_pos < end:
|
| 37 |
+
# Is used in the function
|
| 38 |
+
argument = name.parent
|
| 39 |
+
if argument.type == 'argument' \
|
| 40 |
+
and argument.children[0] == '*' * param_name.star_count:
|
| 41 |
+
trailer = search_ancestor(argument, 'trailer')
|
| 42 |
+
if trailer is not None: # Make sure we're in a function
|
| 43 |
+
context = execution_context.create_context(trailer)
|
| 44 |
+
if _goes_to_param_name(param_name, context, name):
|
| 45 |
+
values = _to_callables(context, trailer)
|
| 46 |
+
|
| 47 |
+
args = TreeArguments.create_cached(
|
| 48 |
+
execution_context.inference_state,
|
| 49 |
+
context=context,
|
| 50 |
+
argument_node=trailer.children[1],
|
| 51 |
+
trailer=trailer,
|
| 52 |
+
)
|
| 53 |
+
for c in values:
|
| 54 |
+
yield c, args
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _goes_to_param_name(param_name, context, potential_name):
|
| 58 |
+
if potential_name.type != 'name':
|
| 59 |
+
return False
|
| 60 |
+
from jedi.inference.names import TreeNameDefinition
|
| 61 |
+
found = TreeNameDefinition(context, potential_name).goto()
|
| 62 |
+
return any(param_name.parent_context == p.parent_context
|
| 63 |
+
and param_name.start_pos == p.start_pos
|
| 64 |
+
for p in found)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _to_callables(context, trailer):
|
| 68 |
+
from jedi.inference.syntax_tree import infer_trailer
|
| 69 |
+
|
| 70 |
+
atom_expr = trailer.parent
|
| 71 |
+
index = atom_expr.children[0] == 'await'
|
| 72 |
+
# Infer atom first
|
| 73 |
+
values = context.infer_node(atom_expr.children[index])
|
| 74 |
+
for trailer2 in atom_expr.children[index + 1:]:
|
| 75 |
+
if trailer == trailer2:
|
| 76 |
+
break
|
| 77 |
+
values = infer_trailer(context, values, trailer2)
|
| 78 |
+
return values
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _remove_given_params(arguments, param_names):
|
| 82 |
+
count = 0
|
| 83 |
+
used_keys = set()
|
| 84 |
+
for key, _ in arguments.unpack():
|
| 85 |
+
if key is None:
|
| 86 |
+
count += 1
|
| 87 |
+
else:
|
| 88 |
+
used_keys.add(key)
|
| 89 |
+
|
| 90 |
+
for p in param_names:
|
| 91 |
+
if count and p.maybe_positional_argument():
|
| 92 |
+
count -= 1
|
| 93 |
+
continue
|
| 94 |
+
if p.string_name in used_keys and p.maybe_keyword_argument():
|
| 95 |
+
continue
|
| 96 |
+
yield p
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
@to_list
|
| 100 |
+
def process_params(param_names, star_count=3): # default means both * and **
|
| 101 |
+
if param_names:
|
| 102 |
+
if is_big_annoying_library(param_names[0].parent_context):
|
| 103 |
+
# At first this feature can look innocent, but it does a lot of
|
| 104 |
+
# type inference in some cases, so we just ditch it.
|
| 105 |
+
yield from param_names
|
| 106 |
+
return
|
| 107 |
+
|
| 108 |
+
used_names = set()
|
| 109 |
+
arg_callables = []
|
| 110 |
+
kwarg_callables = []
|
| 111 |
+
|
| 112 |
+
kw_only_names = []
|
| 113 |
+
kwarg_names = []
|
| 114 |
+
arg_names = []
|
| 115 |
+
original_arg_name = None
|
| 116 |
+
original_kwarg_name = None
|
| 117 |
+
for p in param_names:
|
| 118 |
+
kind = p.get_kind()
|
| 119 |
+
if kind == Parameter.VAR_POSITIONAL:
|
| 120 |
+
if star_count & 1:
|
| 121 |
+
arg_callables = _iter_nodes_for_param(p)
|
| 122 |
+
original_arg_name = p
|
| 123 |
+
elif p.get_kind() == Parameter.VAR_KEYWORD:
|
| 124 |
+
if star_count & 2:
|
| 125 |
+
kwarg_callables = list(_iter_nodes_for_param(p))
|
| 126 |
+
original_kwarg_name = p
|
| 127 |
+
elif kind == Parameter.KEYWORD_ONLY:
|
| 128 |
+
if star_count & 2:
|
| 129 |
+
kw_only_names.append(p)
|
| 130 |
+
elif kind == Parameter.POSITIONAL_ONLY:
|
| 131 |
+
if star_count & 1:
|
| 132 |
+
yield p
|
| 133 |
+
else:
|
| 134 |
+
if star_count == 1:
|
| 135 |
+
yield ParamNameFixedKind(p, Parameter.POSITIONAL_ONLY)
|
| 136 |
+
elif star_count == 2:
|
| 137 |
+
kw_only_names.append(ParamNameFixedKind(p, Parameter.KEYWORD_ONLY))
|
| 138 |
+
else:
|
| 139 |
+
used_names.add(p.string_name)
|
| 140 |
+
yield p
|
| 141 |
+
|
| 142 |
+
# First process *args
|
| 143 |
+
longest_param_names = ()
|
| 144 |
+
found_arg_signature = False
|
| 145 |
+
found_kwarg_signature = False
|
| 146 |
+
for func_and_argument in arg_callables:
|
| 147 |
+
func, arguments = func_and_argument
|
| 148 |
+
new_star_count = star_count
|
| 149 |
+
if func_and_argument in kwarg_callables:
|
| 150 |
+
kwarg_callables.remove(func_and_argument)
|
| 151 |
+
else:
|
| 152 |
+
new_star_count = 1
|
| 153 |
+
|
| 154 |
+
for signature in func.get_signatures():
|
| 155 |
+
found_arg_signature = True
|
| 156 |
+
if new_star_count == 3:
|
| 157 |
+
found_kwarg_signature = True
|
| 158 |
+
args_for_this_func = []
|
| 159 |
+
for p in process_params(
|
| 160 |
+
list(_remove_given_params(
|
| 161 |
+
arguments,
|
| 162 |
+
signature.get_param_names(resolve_stars=False)
|
| 163 |
+
)), new_star_count):
|
| 164 |
+
if p.get_kind() == Parameter.VAR_KEYWORD:
|
| 165 |
+
kwarg_names.append(p)
|
| 166 |
+
elif p.get_kind() == Parameter.VAR_POSITIONAL:
|
| 167 |
+
arg_names.append(p)
|
| 168 |
+
elif p.get_kind() == Parameter.KEYWORD_ONLY:
|
| 169 |
+
kw_only_names.append(p)
|
| 170 |
+
else:
|
| 171 |
+
args_for_this_func.append(p)
|
| 172 |
+
if len(args_for_this_func) > len(longest_param_names):
|
| 173 |
+
longest_param_names = args_for_this_func
|
| 174 |
+
|
| 175 |
+
for p in longest_param_names:
|
| 176 |
+
if star_count == 1 and p.get_kind() != Parameter.VAR_POSITIONAL:
|
| 177 |
+
yield ParamNameFixedKind(p, Parameter.POSITIONAL_ONLY)
|
| 178 |
+
else:
|
| 179 |
+
if p.get_kind() == Parameter.POSITIONAL_OR_KEYWORD:
|
| 180 |
+
used_names.add(p.string_name)
|
| 181 |
+
yield p
|
| 182 |
+
|
| 183 |
+
if not found_arg_signature and original_arg_name is not None:
|
| 184 |
+
yield original_arg_name
|
| 185 |
+
elif arg_names:
|
| 186 |
+
yield arg_names[0]
|
| 187 |
+
|
| 188 |
+
# Then process **kwargs
|
| 189 |
+
for func, arguments in kwarg_callables:
|
| 190 |
+
for signature in func.get_signatures():
|
| 191 |
+
found_kwarg_signature = True
|
| 192 |
+
for p in process_params(
|
| 193 |
+
list(_remove_given_params(
|
| 194 |
+
arguments,
|
| 195 |
+
signature.get_param_names(resolve_stars=False)
|
| 196 |
+
)), star_count=2):
|
| 197 |
+
if p.get_kind() == Parameter.VAR_KEYWORD:
|
| 198 |
+
kwarg_names.append(p)
|
| 199 |
+
elif p.get_kind() == Parameter.KEYWORD_ONLY:
|
| 200 |
+
kw_only_names.append(p)
|
| 201 |
+
|
| 202 |
+
for p in kw_only_names:
|
| 203 |
+
if p.string_name in used_names:
|
| 204 |
+
continue
|
| 205 |
+
yield p
|
| 206 |
+
used_names.add(p.string_name)
|
| 207 |
+
|
| 208 |
+
if not found_kwarg_signature and original_kwarg_name is not None:
|
| 209 |
+
yield original_kwarg_name
|
| 210 |
+
elif kwarg_names:
|
| 211 |
+
yield kwarg_names[0]
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
class ParamNameFixedKind(ParamNameWrapper):
|
| 215 |
+
def __init__(self, param_name, new_kind):
|
| 216 |
+
super().__init__(param_name)
|
| 217 |
+
self._new_kind = new_kind
|
| 218 |
+
|
| 219 |
+
def get_kind(self):
|
| 220 |
+
return self._new_kind
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/syntax_tree.py
ADDED
|
@@ -0,0 +1,903 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
+
import itertools
|
| 6 |
+
|
| 7 |
+
from parso.python import tree
|
| 8 |
+
|
| 9 |
+
from jedi import debug
|
| 10 |
+
from jedi import parser_utils
|
| 11 |
+
from jedi.inference.base_value import ValueSet, NO_VALUES, ContextualizedNode, \
|
| 12 |
+
iterator_to_value_set, iterate_values
|
| 13 |
+
from jedi.inference.lazy_value import LazyTreeValue
|
| 14 |
+
from jedi.inference import compiled
|
| 15 |
+
from jedi.inference import recursion
|
| 16 |
+
from jedi.inference import analysis
|
| 17 |
+
from jedi.inference import imports
|
| 18 |
+
from jedi.inference import arguments
|
| 19 |
+
from jedi.inference.value import ClassValue, FunctionValue
|
| 20 |
+
from jedi.inference.value import iterable
|
| 21 |
+
from jedi.inference.value.dynamic_arrays import ListModification, DictModification
|
| 22 |
+
from jedi.inference.value import TreeInstance
|
| 23 |
+
from jedi.inference.helpers import is_string, is_literal, is_number, \
|
| 24 |
+
get_names_of_node, is_big_annoying_library
|
| 25 |
+
from jedi.inference.compiled.access import COMPARISON_OPERATORS
|
| 26 |
+
from jedi.inference.cache import inference_state_method_cache
|
| 27 |
+
from jedi.inference.gradual.stub_value import VersionInfo
|
| 28 |
+
from jedi.inference.gradual import annotation
|
| 29 |
+
from jedi.inference.names import TreeNameDefinition
|
| 30 |
+
from jedi.inference.context import CompForContext
|
| 31 |
+
from jedi.inference.value.decorator import Decoratee
|
| 32 |
+
from jedi.plugins import plugin_manager
|
| 33 |
+
|
| 34 |
+
operator_to_magic_method = {
|
| 35 |
+
'+': '__add__',
|
| 36 |
+
'-': '__sub__',
|
| 37 |
+
'*': '__mul__',
|
| 38 |
+
'@': '__matmul__',
|
| 39 |
+
'/': '__truediv__',
|
| 40 |
+
'//': '__floordiv__',
|
| 41 |
+
'%': '__mod__',
|
| 42 |
+
'**': '__pow__',
|
| 43 |
+
'<<': '__lshift__',
|
| 44 |
+
'>>': '__rshift__',
|
| 45 |
+
'&': '__and__',
|
| 46 |
+
'|': '__or__',
|
| 47 |
+
'^': '__xor__',
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
reverse_operator_to_magic_method = {
|
| 51 |
+
k: '__r' + v[2:] for k, v in operator_to_magic_method.items()
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _limit_value_infers(func):
|
| 56 |
+
"""
|
| 57 |
+
This is for now the way how we limit type inference going wild. There are
|
| 58 |
+
other ways to ensure recursion limits as well. This is mostly necessary
|
| 59 |
+
because of instance (self) access that can be quite tricky to limit.
|
| 60 |
+
|
| 61 |
+
I'm still not sure this is the way to go, but it looks okay for now and we
|
| 62 |
+
can still go anther way in the future. Tests are there. ~ dave
|
| 63 |
+
"""
|
| 64 |
+
def wrapper(context, *args, **kwargs):
|
| 65 |
+
n = context.tree_node
|
| 66 |
+
inference_state = context.inference_state
|
| 67 |
+
try:
|
| 68 |
+
inference_state.inferred_element_counts[n] += 1
|
| 69 |
+
maximum = 300
|
| 70 |
+
if context.parent_context is None \
|
| 71 |
+
and context.get_value() is inference_state.builtins_module:
|
| 72 |
+
# Builtins should have a more generous inference limit.
|
| 73 |
+
# It is important that builtins can be executed, otherwise some
|
| 74 |
+
# functions that depend on certain builtins features would be
|
| 75 |
+
# broken, see e.g. GH #1432
|
| 76 |
+
maximum *= 100
|
| 77 |
+
|
| 78 |
+
if inference_state.inferred_element_counts[n] > maximum:
|
| 79 |
+
debug.warning('In value %s there were too many inferences.', n)
|
| 80 |
+
return NO_VALUES
|
| 81 |
+
except KeyError:
|
| 82 |
+
inference_state.inferred_element_counts[n] = 1
|
| 83 |
+
return func(context, *args, **kwargs)
|
| 84 |
+
|
| 85 |
+
return wrapper
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def infer_node(context, element):
|
| 89 |
+
if isinstance(context, CompForContext):
|
| 90 |
+
return _infer_node(context, element)
|
| 91 |
+
|
| 92 |
+
if_stmt = element
|
| 93 |
+
while if_stmt is not None:
|
| 94 |
+
if_stmt = if_stmt.parent
|
| 95 |
+
if if_stmt.type in ('if_stmt', 'for_stmt'):
|
| 96 |
+
break
|
| 97 |
+
if parser_utils.is_scope(if_stmt):
|
| 98 |
+
if_stmt = None
|
| 99 |
+
break
|
| 100 |
+
predefined_if_name_dict = context.predefined_names.get(if_stmt)
|
| 101 |
+
# TODO there's a lot of issues with this one. We actually should do
|
| 102 |
+
# this in a different way. Caching should only be active in certain
|
| 103 |
+
# cases and this all sucks.
|
| 104 |
+
if predefined_if_name_dict is None and if_stmt \
|
| 105 |
+
and if_stmt.type == 'if_stmt' and context.inference_state.is_analysis:
|
| 106 |
+
if_stmt_test = if_stmt.children[1]
|
| 107 |
+
name_dicts = [{}]
|
| 108 |
+
# If we already did a check, we don't want to do it again -> If
|
| 109 |
+
# value.predefined_names is filled, we stop.
|
| 110 |
+
# We don't want to check the if stmt itself, it's just about
|
| 111 |
+
# the content.
|
| 112 |
+
if element.start_pos > if_stmt_test.end_pos:
|
| 113 |
+
# Now we need to check if the names in the if_stmt match the
|
| 114 |
+
# names in the suite.
|
| 115 |
+
if_names = get_names_of_node(if_stmt_test)
|
| 116 |
+
element_names = get_names_of_node(element)
|
| 117 |
+
str_element_names = [e.value for e in element_names]
|
| 118 |
+
if any(i.value in str_element_names for i in if_names):
|
| 119 |
+
for if_name in if_names:
|
| 120 |
+
definitions = context.inference_state.infer(context, if_name)
|
| 121 |
+
# Every name that has multiple different definitions
|
| 122 |
+
# causes the complexity to rise. The complexity should
|
| 123 |
+
# never fall below 1.
|
| 124 |
+
if len(definitions) > 1:
|
| 125 |
+
if len(name_dicts) * len(definitions) > 16:
|
| 126 |
+
debug.dbg('Too many options for if branch inference %s.', if_stmt)
|
| 127 |
+
# There's only a certain amount of branches
|
| 128 |
+
# Jedi can infer, otherwise it will take to
|
| 129 |
+
# long.
|
| 130 |
+
name_dicts = [{}]
|
| 131 |
+
break
|
| 132 |
+
|
| 133 |
+
original_name_dicts = list(name_dicts)
|
| 134 |
+
name_dicts = []
|
| 135 |
+
for definition in definitions:
|
| 136 |
+
new_name_dicts = list(original_name_dicts)
|
| 137 |
+
for i, name_dict in enumerate(new_name_dicts):
|
| 138 |
+
new_name_dicts[i] = name_dict.copy()
|
| 139 |
+
new_name_dicts[i][if_name.value] = ValueSet([definition])
|
| 140 |
+
|
| 141 |
+
name_dicts += new_name_dicts
|
| 142 |
+
else:
|
| 143 |
+
for name_dict in name_dicts:
|
| 144 |
+
name_dict[if_name.value] = definitions
|
| 145 |
+
if len(name_dicts) > 1:
|
| 146 |
+
result = NO_VALUES
|
| 147 |
+
for name_dict in name_dicts:
|
| 148 |
+
with context.predefine_names(if_stmt, name_dict):
|
| 149 |
+
result |= _infer_node(context, element)
|
| 150 |
+
return result
|
| 151 |
+
else:
|
| 152 |
+
return _infer_node_if_inferred(context, element)
|
| 153 |
+
else:
|
| 154 |
+
if predefined_if_name_dict:
|
| 155 |
+
return _infer_node(context, element)
|
| 156 |
+
else:
|
| 157 |
+
return _infer_node_if_inferred(context, element)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def _infer_node_if_inferred(context, element):
|
| 161 |
+
"""
|
| 162 |
+
TODO This function is temporary: Merge with infer_node.
|
| 163 |
+
"""
|
| 164 |
+
parent = element
|
| 165 |
+
while parent is not None:
|
| 166 |
+
parent = parent.parent
|
| 167 |
+
predefined_if_name_dict = context.predefined_names.get(parent)
|
| 168 |
+
if predefined_if_name_dict is not None:
|
| 169 |
+
return _infer_node(context, element)
|
| 170 |
+
return _infer_node_cached(context, element)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
@inference_state_method_cache(default=NO_VALUES)
|
| 174 |
+
def _infer_node_cached(context, element):
|
| 175 |
+
return _infer_node(context, element)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
@debug.increase_indent
|
| 179 |
+
@_limit_value_infers
|
| 180 |
+
def _infer_node(context, element):
|
| 181 |
+
debug.dbg('infer_node %s@%s in %s', element, element.start_pos, context)
|
| 182 |
+
inference_state = context.inference_state
|
| 183 |
+
typ = element.type
|
| 184 |
+
if typ in ('name', 'number', 'string', 'atom', 'strings', 'keyword', 'fstring'):
|
| 185 |
+
return infer_atom(context, element)
|
| 186 |
+
elif typ == 'lambdef':
|
| 187 |
+
return ValueSet([FunctionValue.from_context(context, element)])
|
| 188 |
+
elif typ == 'expr_stmt':
|
| 189 |
+
return infer_expr_stmt(context, element)
|
| 190 |
+
elif typ in ('power', 'atom_expr'):
|
| 191 |
+
first_child = element.children[0]
|
| 192 |
+
children = element.children[1:]
|
| 193 |
+
had_await = False
|
| 194 |
+
if first_child.type == 'keyword' and first_child.value == 'await':
|
| 195 |
+
had_await = True
|
| 196 |
+
first_child = children.pop(0)
|
| 197 |
+
|
| 198 |
+
value_set = context.infer_node(first_child)
|
| 199 |
+
for (i, trailer) in enumerate(children):
|
| 200 |
+
if trailer == '**': # has a power operation.
|
| 201 |
+
right = context.infer_node(children[i + 1])
|
| 202 |
+
value_set = _infer_comparison(
|
| 203 |
+
context,
|
| 204 |
+
value_set,
|
| 205 |
+
trailer,
|
| 206 |
+
right
|
| 207 |
+
)
|
| 208 |
+
break
|
| 209 |
+
value_set = infer_trailer(context, value_set, trailer)
|
| 210 |
+
|
| 211 |
+
if had_await:
|
| 212 |
+
return value_set.py__await__().py__stop_iteration_returns()
|
| 213 |
+
return value_set
|
| 214 |
+
elif typ in ('testlist_star_expr', 'testlist',):
|
| 215 |
+
# The implicit tuple in statements.
|
| 216 |
+
return ValueSet([iterable.SequenceLiteralValue(inference_state, context, element)])
|
| 217 |
+
elif typ in ('not_test', 'factor'):
|
| 218 |
+
value_set = context.infer_node(element.children[-1])
|
| 219 |
+
for operator in element.children[:-1]:
|
| 220 |
+
value_set = infer_factor(value_set, operator)
|
| 221 |
+
return value_set
|
| 222 |
+
elif typ == 'test':
|
| 223 |
+
# `x if foo else y` case.
|
| 224 |
+
return (context.infer_node(element.children[0])
|
| 225 |
+
| context.infer_node(element.children[-1]))
|
| 226 |
+
elif typ == 'operator':
|
| 227 |
+
# Must be an ellipsis, other operators are not inferred.
|
| 228 |
+
if element.value != '...':
|
| 229 |
+
origin = element.parent
|
| 230 |
+
raise AssertionError("unhandled operator %s in %s " % (repr(element.value), origin))
|
| 231 |
+
return ValueSet([compiled.builtin_from_name(inference_state, 'Ellipsis')])
|
| 232 |
+
elif typ == 'dotted_name':
|
| 233 |
+
value_set = infer_atom(context, element.children[0])
|
| 234 |
+
for next_name in element.children[2::2]:
|
| 235 |
+
value_set = value_set.py__getattribute__(next_name, name_context=context)
|
| 236 |
+
return value_set
|
| 237 |
+
elif typ == 'eval_input':
|
| 238 |
+
return context.infer_node(element.children[0])
|
| 239 |
+
elif typ == 'annassign':
|
| 240 |
+
return annotation.infer_annotation(context, element.children[1]) \
|
| 241 |
+
.execute_annotation()
|
| 242 |
+
elif typ == 'yield_expr':
|
| 243 |
+
if len(element.children) and element.children[1].type == 'yield_arg':
|
| 244 |
+
# Implies that it's a yield from.
|
| 245 |
+
element = element.children[1].children[1]
|
| 246 |
+
generators = context.infer_node(element) \
|
| 247 |
+
.py__getattribute__('__iter__').execute_with_values()
|
| 248 |
+
return generators.py__stop_iteration_returns()
|
| 249 |
+
|
| 250 |
+
# Generator.send() is not implemented.
|
| 251 |
+
return NO_VALUES
|
| 252 |
+
elif typ == 'namedexpr_test':
|
| 253 |
+
return context.infer_node(element.children[2])
|
| 254 |
+
else:
|
| 255 |
+
return infer_or_test(context, element)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def infer_trailer(context, atom_values, trailer):
|
| 259 |
+
trailer_op, node = trailer.children[:2]
|
| 260 |
+
if node == ')': # `arglist` is optional.
|
| 261 |
+
node = None
|
| 262 |
+
|
| 263 |
+
if trailer_op == '[':
|
| 264 |
+
trailer_op, node, _ = trailer.children
|
| 265 |
+
return atom_values.get_item(
|
| 266 |
+
_infer_subscript_list(context, node),
|
| 267 |
+
ContextualizedNode(context, trailer)
|
| 268 |
+
)
|
| 269 |
+
else:
|
| 270 |
+
debug.dbg('infer_trailer: %s in %s', trailer, atom_values)
|
| 271 |
+
if trailer_op == '.':
|
| 272 |
+
return atom_values.py__getattribute__(
|
| 273 |
+
name_context=context,
|
| 274 |
+
name_or_str=node
|
| 275 |
+
)
|
| 276 |
+
else:
|
| 277 |
+
assert trailer_op == '(', 'trailer_op is actually %s' % trailer_op
|
| 278 |
+
args = arguments.TreeArguments(context.inference_state, context, node, trailer)
|
| 279 |
+
return atom_values.execute(args)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def infer_atom(context, atom):
|
| 283 |
+
"""
|
| 284 |
+
Basically to process ``atom`` nodes. The parser sometimes doesn't
|
| 285 |
+
generate the node (because it has just one child). In that case an atom
|
| 286 |
+
might be a name or a literal as well.
|
| 287 |
+
"""
|
| 288 |
+
state = context.inference_state
|
| 289 |
+
if atom.type == 'name':
|
| 290 |
+
# This is the first global lookup.
|
| 291 |
+
stmt = tree.search_ancestor(atom, 'expr_stmt', 'lambdef', 'if_stmt') or atom
|
| 292 |
+
if stmt.type == 'if_stmt':
|
| 293 |
+
if not any(n.start_pos <= atom.start_pos < n.end_pos for n in stmt.get_test_nodes()):
|
| 294 |
+
stmt = atom
|
| 295 |
+
elif stmt.type == 'lambdef':
|
| 296 |
+
stmt = atom
|
| 297 |
+
position = stmt.start_pos
|
| 298 |
+
if _is_annotation_name(atom):
|
| 299 |
+
# Since Python 3.7 (with from __future__ import annotations),
|
| 300 |
+
# annotations are essentially strings and can reference objects
|
| 301 |
+
# that are defined further down in code. Therefore just set the
|
| 302 |
+
# position to None, so the finder will not try to stop at a certain
|
| 303 |
+
# position in the module.
|
| 304 |
+
position = None
|
| 305 |
+
return context.py__getattribute__(atom, position=position)
|
| 306 |
+
elif atom.type == 'keyword':
|
| 307 |
+
# For False/True/None
|
| 308 |
+
if atom.value in ('False', 'True', 'None'):
|
| 309 |
+
return ValueSet([compiled.builtin_from_name(state, atom.value)])
|
| 310 |
+
elif atom.value == 'yield':
|
| 311 |
+
# Contrary to yield from, yield can just appear alone to return a
|
| 312 |
+
# value when used with `.send()`.
|
| 313 |
+
return NO_VALUES
|
| 314 |
+
assert False, 'Cannot infer the keyword %s' % atom
|
| 315 |
+
|
| 316 |
+
elif isinstance(atom, tree.Literal):
|
| 317 |
+
string = state.compiled_subprocess.safe_literal_eval(atom.value)
|
| 318 |
+
return ValueSet([compiled.create_simple_object(state, string)])
|
| 319 |
+
elif atom.type == 'strings':
|
| 320 |
+
# Will be multiple string.
|
| 321 |
+
value_set = infer_atom(context, atom.children[0])
|
| 322 |
+
for string in atom.children[1:]:
|
| 323 |
+
right = infer_atom(context, string)
|
| 324 |
+
value_set = _infer_comparison(context, value_set, '+', right)
|
| 325 |
+
return value_set
|
| 326 |
+
elif atom.type == 'fstring':
|
| 327 |
+
return compiled.get_string_value_set(state)
|
| 328 |
+
else:
|
| 329 |
+
c = atom.children
|
| 330 |
+
# Parentheses without commas are not tuples.
|
| 331 |
+
if c[0] == '(' and not len(c) == 2 \
|
| 332 |
+
and not (c[1].type == 'testlist_comp'
|
| 333 |
+
and len(c[1].children) > 1):
|
| 334 |
+
return context.infer_node(c[1])
|
| 335 |
+
|
| 336 |
+
try:
|
| 337 |
+
comp_for = c[1].children[1]
|
| 338 |
+
except (IndexError, AttributeError):
|
| 339 |
+
pass
|
| 340 |
+
else:
|
| 341 |
+
if comp_for == ':':
|
| 342 |
+
# Dict comprehensions have a colon at the 3rd index.
|
| 343 |
+
try:
|
| 344 |
+
comp_for = c[1].children[3]
|
| 345 |
+
except IndexError:
|
| 346 |
+
pass
|
| 347 |
+
|
| 348 |
+
if comp_for.type in ('comp_for', 'sync_comp_for'):
|
| 349 |
+
return ValueSet([iterable.comprehension_from_atom(
|
| 350 |
+
state, context, atom
|
| 351 |
+
)])
|
| 352 |
+
|
| 353 |
+
# It's a dict/list/tuple literal.
|
| 354 |
+
array_node = c[1]
|
| 355 |
+
try:
|
| 356 |
+
array_node_c = array_node.children
|
| 357 |
+
except AttributeError:
|
| 358 |
+
array_node_c = []
|
| 359 |
+
if c[0] == '{' and (array_node == '}' or ':' in array_node_c
|
| 360 |
+
or '**' in array_node_c):
|
| 361 |
+
new_value = iterable.DictLiteralValue(state, context, atom)
|
| 362 |
+
else:
|
| 363 |
+
new_value = iterable.SequenceLiteralValue(state, context, atom)
|
| 364 |
+
return ValueSet([new_value])
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
@_limit_value_infers
|
| 368 |
+
def infer_expr_stmt(context, stmt, seek_name=None):
|
| 369 |
+
with recursion.execution_allowed(context.inference_state, stmt) as allowed:
|
| 370 |
+
if allowed:
|
| 371 |
+
if seek_name is not None:
|
| 372 |
+
pep0484_values = \
|
| 373 |
+
annotation.find_type_from_comment_hint_assign(context, stmt, seek_name)
|
| 374 |
+
if pep0484_values:
|
| 375 |
+
return pep0484_values
|
| 376 |
+
|
| 377 |
+
return _infer_expr_stmt(context, stmt, seek_name)
|
| 378 |
+
return NO_VALUES
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
@debug.increase_indent
|
| 382 |
+
def _infer_expr_stmt(context, stmt, seek_name=None):
|
| 383 |
+
"""
|
| 384 |
+
The starting point of the completion. A statement always owns a call
|
| 385 |
+
list, which are the calls, that a statement does. In case multiple
|
| 386 |
+
names are defined in the statement, `seek_name` returns the result for
|
| 387 |
+
this name.
|
| 388 |
+
|
| 389 |
+
expr_stmt: testlist_star_expr (annassign | augassign (yield_expr|testlist) |
|
| 390 |
+
('=' (yield_expr|testlist_star_expr))*)
|
| 391 |
+
annassign: ':' test ['=' test]
|
| 392 |
+
augassign: ('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' |
|
| 393 |
+
'<<=' | '>>=' | '**=' | '//=')
|
| 394 |
+
|
| 395 |
+
:param stmt: A `tree.ExprStmt`.
|
| 396 |
+
"""
|
| 397 |
+
def check_setitem(stmt):
|
| 398 |
+
atom_expr = stmt.children[0]
|
| 399 |
+
if atom_expr.type not in ('atom_expr', 'power'):
|
| 400 |
+
return False, None
|
| 401 |
+
name = atom_expr.children[0]
|
| 402 |
+
if name.type != 'name' or len(atom_expr.children) != 2:
|
| 403 |
+
return False, None
|
| 404 |
+
trailer = atom_expr.children[-1]
|
| 405 |
+
return trailer.children[0] == '[', trailer.children[1]
|
| 406 |
+
|
| 407 |
+
debug.dbg('infer_expr_stmt %s (%s)', stmt, seek_name)
|
| 408 |
+
rhs = stmt.get_rhs()
|
| 409 |
+
|
| 410 |
+
value_set = context.infer_node(rhs)
|
| 411 |
+
|
| 412 |
+
if seek_name:
|
| 413 |
+
n = TreeNameDefinition(context, seek_name)
|
| 414 |
+
value_set = check_tuple_assignments(n, value_set)
|
| 415 |
+
|
| 416 |
+
first_operator = next(stmt.yield_operators(), None)
|
| 417 |
+
is_setitem, subscriptlist = check_setitem(stmt)
|
| 418 |
+
is_annassign = first_operator not in ('=', None) and first_operator.type == 'operator'
|
| 419 |
+
if is_annassign or is_setitem:
|
| 420 |
+
# `=` is always the last character in aug assignments -> -1
|
| 421 |
+
name = stmt.get_defined_names(include_setitem=True)[0].value
|
| 422 |
+
left_values = context.py__getattribute__(name, position=stmt.start_pos)
|
| 423 |
+
|
| 424 |
+
if is_setitem:
|
| 425 |
+
def to_mod(v):
|
| 426 |
+
c = ContextualizedSubscriptListNode(context, subscriptlist)
|
| 427 |
+
if v.array_type == 'dict':
|
| 428 |
+
return DictModification(v, value_set, c)
|
| 429 |
+
elif v.array_type == 'list':
|
| 430 |
+
return ListModification(v, value_set, c)
|
| 431 |
+
return v
|
| 432 |
+
|
| 433 |
+
value_set = ValueSet(to_mod(v) for v in left_values)
|
| 434 |
+
else:
|
| 435 |
+
operator = copy.copy(first_operator)
|
| 436 |
+
operator.value = operator.value[:-1]
|
| 437 |
+
for_stmt = tree.search_ancestor(stmt, 'for_stmt')
|
| 438 |
+
if for_stmt is not None and for_stmt.type == 'for_stmt' and value_set \
|
| 439 |
+
and parser_utils.for_stmt_defines_one_name(for_stmt):
|
| 440 |
+
# Iterate through result and add the values, that's possible
|
| 441 |
+
# only in for loops without clutter, because they are
|
| 442 |
+
# predictable. Also only do it, if the variable is not a tuple.
|
| 443 |
+
node = for_stmt.get_testlist()
|
| 444 |
+
cn = ContextualizedNode(context, node)
|
| 445 |
+
ordered = list(cn.infer().iterate(cn))
|
| 446 |
+
|
| 447 |
+
for lazy_value in ordered:
|
| 448 |
+
dct = {for_stmt.children[1].value: lazy_value.infer()}
|
| 449 |
+
with context.predefine_names(for_stmt, dct):
|
| 450 |
+
t = context.infer_node(rhs)
|
| 451 |
+
left_values = _infer_comparison(context, left_values, operator, t)
|
| 452 |
+
value_set = left_values
|
| 453 |
+
else:
|
| 454 |
+
value_set = _infer_comparison(context, left_values, operator, value_set)
|
| 455 |
+
debug.dbg('infer_expr_stmt result %s', value_set)
|
| 456 |
+
return value_set
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
def infer_or_test(context, or_test):
|
| 460 |
+
iterator = iter(or_test.children)
|
| 461 |
+
types = context.infer_node(next(iterator))
|
| 462 |
+
for operator in iterator:
|
| 463 |
+
right = next(iterator)
|
| 464 |
+
if operator.type == 'comp_op': # not in / is not
|
| 465 |
+
operator = ' '.join(c.value for c in operator.children)
|
| 466 |
+
|
| 467 |
+
# handle type inference of and/or here.
|
| 468 |
+
if operator in ('and', 'or'):
|
| 469 |
+
left_bools = set(left.py__bool__() for left in types)
|
| 470 |
+
if left_bools == {True}:
|
| 471 |
+
if operator == 'and':
|
| 472 |
+
types = context.infer_node(right)
|
| 473 |
+
elif left_bools == {False}:
|
| 474 |
+
if operator != 'and':
|
| 475 |
+
types = context.infer_node(right)
|
| 476 |
+
# Otherwise continue, because of uncertainty.
|
| 477 |
+
else:
|
| 478 |
+
types = _infer_comparison(context, types, operator,
|
| 479 |
+
context.infer_node(right))
|
| 480 |
+
debug.dbg('infer_or_test types %s', types)
|
| 481 |
+
return types
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
@iterator_to_value_set
|
| 485 |
+
def infer_factor(value_set, operator):
|
| 486 |
+
"""
|
| 487 |
+
Calculates `+`, `-`, `~` and `not` prefixes.
|
| 488 |
+
"""
|
| 489 |
+
for value in value_set:
|
| 490 |
+
if operator == '-':
|
| 491 |
+
if is_number(value):
|
| 492 |
+
yield value.negate()
|
| 493 |
+
elif operator == 'not':
|
| 494 |
+
b = value.py__bool__()
|
| 495 |
+
if b is None: # Uncertainty.
|
| 496 |
+
yield list(value.inference_state.builtins_module.py__getattribute__('bool')
|
| 497 |
+
.execute_annotation()).pop()
|
| 498 |
+
else:
|
| 499 |
+
yield compiled.create_simple_object(value.inference_state, not b)
|
| 500 |
+
else:
|
| 501 |
+
yield value
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
def _literals_to_types(inference_state, result):
|
| 505 |
+
# Changes literals ('a', 1, 1.0, etc) to its type instances (str(),
|
| 506 |
+
# int(), float(), etc).
|
| 507 |
+
new_result = NO_VALUES
|
| 508 |
+
for typ in result:
|
| 509 |
+
if is_literal(typ):
|
| 510 |
+
# Literals are only valid as long as the operations are
|
| 511 |
+
# correct. Otherwise add a value-free instance.
|
| 512 |
+
cls = compiled.builtin_from_name(inference_state, typ.name.string_name)
|
| 513 |
+
new_result |= cls.execute_with_values()
|
| 514 |
+
else:
|
| 515 |
+
new_result |= ValueSet([typ])
|
| 516 |
+
return new_result
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
def _infer_comparison(context, left_values, operator, right_values):
|
| 520 |
+
state = context.inference_state
|
| 521 |
+
if isinstance(operator, str):
|
| 522 |
+
operator_str = operator
|
| 523 |
+
else:
|
| 524 |
+
operator_str = str(operator.value)
|
| 525 |
+
if not left_values or not right_values:
|
| 526 |
+
# illegal slices e.g. cause left/right_result to be None
|
| 527 |
+
result = (left_values or NO_VALUES) | (right_values or NO_VALUES)
|
| 528 |
+
return _literals_to_types(state, result)
|
| 529 |
+
elif operator_str == "|" and all(
|
| 530 |
+
value.is_class() or value.is_compiled()
|
| 531 |
+
for value in itertools.chain(left_values, right_values)
|
| 532 |
+
):
|
| 533 |
+
# ^^^ A naive hack for PEP 604
|
| 534 |
+
return ValueSet.from_sets((left_values, right_values))
|
| 535 |
+
else:
|
| 536 |
+
# I don't think there's a reasonable chance that a string
|
| 537 |
+
# operation is still correct, once we pass something like six
|
| 538 |
+
# objects.
|
| 539 |
+
if len(left_values) * len(right_values) > 6:
|
| 540 |
+
return _literals_to_types(state, left_values | right_values)
|
| 541 |
+
else:
|
| 542 |
+
return ValueSet.from_sets(
|
| 543 |
+
_infer_comparison_part(state, context, left, operator, right)
|
| 544 |
+
for left in left_values
|
| 545 |
+
for right in right_values
|
| 546 |
+
)
|
| 547 |
+
|
| 548 |
+
|
| 549 |
+
def _is_annotation_name(name):
|
| 550 |
+
ancestor = tree.search_ancestor(name, 'param', 'funcdef', 'expr_stmt')
|
| 551 |
+
if ancestor is None:
|
| 552 |
+
return False
|
| 553 |
+
|
| 554 |
+
if ancestor.type in ('param', 'funcdef'):
|
| 555 |
+
ann = ancestor.annotation
|
| 556 |
+
if ann is not None:
|
| 557 |
+
return ann.start_pos <= name.start_pos < ann.end_pos
|
| 558 |
+
elif ancestor.type == 'expr_stmt':
|
| 559 |
+
c = ancestor.children
|
| 560 |
+
if len(c) > 1 and c[1].type == 'annassign':
|
| 561 |
+
return c[1].start_pos <= name.start_pos < c[1].end_pos
|
| 562 |
+
return False
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
def _is_list(value):
|
| 566 |
+
return value.array_type == 'list'
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
def _is_tuple(value):
|
| 570 |
+
return value.array_type == 'tuple'
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
def _bool_to_value(inference_state, bool_):
|
| 574 |
+
return compiled.builtin_from_name(inference_state, str(bool_))
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
def _get_tuple_ints(value):
|
| 578 |
+
if not isinstance(value, iterable.SequenceLiteralValue):
|
| 579 |
+
return None
|
| 580 |
+
numbers = []
|
| 581 |
+
for lazy_value in value.py__iter__():
|
| 582 |
+
if not isinstance(lazy_value, LazyTreeValue):
|
| 583 |
+
return None
|
| 584 |
+
node = lazy_value.data
|
| 585 |
+
if node.type != 'number':
|
| 586 |
+
return None
|
| 587 |
+
try:
|
| 588 |
+
numbers.append(int(node.value))
|
| 589 |
+
except ValueError:
|
| 590 |
+
return None
|
| 591 |
+
return numbers
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
def _infer_comparison_part(inference_state, context, left, operator, right):
|
| 595 |
+
l_is_num = is_number(left)
|
| 596 |
+
r_is_num = is_number(right)
|
| 597 |
+
if isinstance(operator, str):
|
| 598 |
+
str_operator = operator
|
| 599 |
+
else:
|
| 600 |
+
str_operator = str(operator.value)
|
| 601 |
+
|
| 602 |
+
if str_operator == '*':
|
| 603 |
+
# for iterables, ignore * operations
|
| 604 |
+
if isinstance(left, iterable.Sequence) or is_string(left):
|
| 605 |
+
return ValueSet([left])
|
| 606 |
+
elif isinstance(right, iterable.Sequence) or is_string(right):
|
| 607 |
+
return ValueSet([right])
|
| 608 |
+
elif str_operator == '+':
|
| 609 |
+
if l_is_num and r_is_num or is_string(left) and is_string(right):
|
| 610 |
+
return left.execute_operation(right, str_operator)
|
| 611 |
+
elif _is_list(left) and _is_list(right) or _is_tuple(left) and _is_tuple(right):
|
| 612 |
+
return ValueSet([iterable.MergedArray(inference_state, (left, right))])
|
| 613 |
+
elif str_operator == '-':
|
| 614 |
+
if l_is_num and r_is_num:
|
| 615 |
+
return left.execute_operation(right, str_operator)
|
| 616 |
+
elif str_operator == '%':
|
| 617 |
+
# With strings and numbers the left type typically remains. Except for
|
| 618 |
+
# `int() % float()`.
|
| 619 |
+
return ValueSet([left])
|
| 620 |
+
elif str_operator in COMPARISON_OPERATORS:
|
| 621 |
+
if left.is_compiled() and right.is_compiled():
|
| 622 |
+
# Possible, because the return is not an option. Just compare.
|
| 623 |
+
result = left.execute_operation(right, str_operator)
|
| 624 |
+
if result:
|
| 625 |
+
return result
|
| 626 |
+
else:
|
| 627 |
+
if str_operator in ('is', '!=', '==', 'is not'):
|
| 628 |
+
operation = COMPARISON_OPERATORS[str_operator]
|
| 629 |
+
bool_ = operation(left, right)
|
| 630 |
+
# Only if == returns True or != returns False, we can continue.
|
| 631 |
+
# There's no guarantee that they are not equal. This can help
|
| 632 |
+
# in some cases, but does not cover everything.
|
| 633 |
+
if (str_operator in ('is', '==')) == bool_:
|
| 634 |
+
return ValueSet([_bool_to_value(inference_state, bool_)])
|
| 635 |
+
|
| 636 |
+
if isinstance(left, VersionInfo):
|
| 637 |
+
version_info = _get_tuple_ints(right)
|
| 638 |
+
if version_info is not None:
|
| 639 |
+
bool_result = compiled.access.COMPARISON_OPERATORS[operator](
|
| 640 |
+
inference_state.environment.version_info,
|
| 641 |
+
tuple(version_info)
|
| 642 |
+
)
|
| 643 |
+
return ValueSet([_bool_to_value(inference_state, bool_result)])
|
| 644 |
+
|
| 645 |
+
return ValueSet([
|
| 646 |
+
_bool_to_value(inference_state, True),
|
| 647 |
+
_bool_to_value(inference_state, False)
|
| 648 |
+
])
|
| 649 |
+
elif str_operator in ('in', 'not in'):
|
| 650 |
+
return inference_state.builtins_module.py__getattribute__('bool').execute_annotation()
|
| 651 |
+
|
| 652 |
+
def check(obj):
|
| 653 |
+
"""Checks if a Jedi object is either a float or an int."""
|
| 654 |
+
return isinstance(obj, TreeInstance) and \
|
| 655 |
+
obj.name.string_name in ('int', 'float')
|
| 656 |
+
|
| 657 |
+
# Static analysis, one is a number, the other one is not.
|
| 658 |
+
if str_operator in ('+', '-') and l_is_num != r_is_num \
|
| 659 |
+
and not (check(left) or check(right)):
|
| 660 |
+
message = "TypeError: unsupported operand type(s) for +: %s and %s"
|
| 661 |
+
analysis.add(context, 'type-error-operation', operator,
|
| 662 |
+
message % (left, right))
|
| 663 |
+
|
| 664 |
+
if left.is_class() or right.is_class():
|
| 665 |
+
return NO_VALUES
|
| 666 |
+
|
| 667 |
+
method_name = operator_to_magic_method[str_operator]
|
| 668 |
+
magic_methods = left.py__getattribute__(method_name)
|
| 669 |
+
if magic_methods:
|
| 670 |
+
result = magic_methods.execute_with_values(right)
|
| 671 |
+
if result:
|
| 672 |
+
return result
|
| 673 |
+
|
| 674 |
+
if not magic_methods:
|
| 675 |
+
reverse_method_name = reverse_operator_to_magic_method[str_operator]
|
| 676 |
+
magic_methods = right.py__getattribute__(reverse_method_name)
|
| 677 |
+
|
| 678 |
+
result = magic_methods.execute_with_values(left)
|
| 679 |
+
if result:
|
| 680 |
+
return result
|
| 681 |
+
|
| 682 |
+
result = ValueSet([left, right])
|
| 683 |
+
debug.dbg('Used operator %s resulting in %s', operator, result)
|
| 684 |
+
return result
|
| 685 |
+
|
| 686 |
+
|
| 687 |
+
@plugin_manager.decorate()
|
| 688 |
+
def tree_name_to_values(inference_state, context, tree_name):
|
| 689 |
+
value_set = NO_VALUES
|
| 690 |
+
module_node = context.get_root_context().tree_node
|
| 691 |
+
# First check for annotations, like: `foo: int = 3`
|
| 692 |
+
if module_node is not None:
|
| 693 |
+
names = module_node.get_used_names().get(tree_name.value, [])
|
| 694 |
+
found_annotation = False
|
| 695 |
+
for name in names:
|
| 696 |
+
expr_stmt = name.parent
|
| 697 |
+
|
| 698 |
+
if expr_stmt.type == "expr_stmt" and expr_stmt.children[1].type == "annassign":
|
| 699 |
+
correct_scope = parser_utils.get_parent_scope(name) == context.tree_node
|
| 700 |
+
ann_assign = expr_stmt.children[1]
|
| 701 |
+
if correct_scope:
|
| 702 |
+
found_annotation = True
|
| 703 |
+
if (
|
| 704 |
+
(ann_assign.children[1].type == 'name')
|
| 705 |
+
and (ann_assign.children[1].value == tree_name.value)
|
| 706 |
+
and context.parent_context
|
| 707 |
+
):
|
| 708 |
+
context = context.parent_context
|
| 709 |
+
value_set |= annotation.infer_annotation(
|
| 710 |
+
context, expr_stmt.children[1].children[1]
|
| 711 |
+
).execute_annotation()
|
| 712 |
+
if found_annotation:
|
| 713 |
+
return value_set
|
| 714 |
+
|
| 715 |
+
types = []
|
| 716 |
+
node = tree_name.get_definition(import_name_always=True, include_setitem=True)
|
| 717 |
+
if node is None:
|
| 718 |
+
node = tree_name.parent
|
| 719 |
+
if node.type == 'global_stmt':
|
| 720 |
+
c = context.create_context(tree_name)
|
| 721 |
+
if c.is_module():
|
| 722 |
+
# In case we are already part of the module, there is no point
|
| 723 |
+
# in looking up the global statement anymore, because it's not
|
| 724 |
+
# valid at that point anyway.
|
| 725 |
+
return NO_VALUES
|
| 726 |
+
# For global_stmt lookups, we only need the first possible scope,
|
| 727 |
+
# which means the function itself.
|
| 728 |
+
filter = next(c.get_filters())
|
| 729 |
+
names = filter.get(tree_name.value)
|
| 730 |
+
return ValueSet.from_sets(name.infer() for name in names)
|
| 731 |
+
elif node.type not in ('import_from', 'import_name'):
|
| 732 |
+
c = context.create_context(tree_name)
|
| 733 |
+
return infer_atom(c, tree_name)
|
| 734 |
+
|
| 735 |
+
typ = node.type
|
| 736 |
+
if typ == 'for_stmt':
|
| 737 |
+
types = annotation.find_type_from_comment_hint_for(context, node, tree_name)
|
| 738 |
+
if types:
|
| 739 |
+
return types
|
| 740 |
+
if typ == 'with_stmt':
|
| 741 |
+
types = annotation.find_type_from_comment_hint_with(context, node, tree_name)
|
| 742 |
+
if types:
|
| 743 |
+
return types
|
| 744 |
+
|
| 745 |
+
if typ in ('for_stmt', 'comp_for', 'sync_comp_for'):
|
| 746 |
+
try:
|
| 747 |
+
types = context.predefined_names[node][tree_name.value]
|
| 748 |
+
except KeyError:
|
| 749 |
+
cn = ContextualizedNode(context, node.children[3])
|
| 750 |
+
for_types = iterate_values(
|
| 751 |
+
cn.infer(),
|
| 752 |
+
contextualized_node=cn,
|
| 753 |
+
is_async=node.parent.type == 'async_stmt',
|
| 754 |
+
)
|
| 755 |
+
n = TreeNameDefinition(context, tree_name)
|
| 756 |
+
types = check_tuple_assignments(n, for_types)
|
| 757 |
+
elif typ == 'expr_stmt':
|
| 758 |
+
types = infer_expr_stmt(context, node, tree_name)
|
| 759 |
+
elif typ == 'with_stmt':
|
| 760 |
+
value_managers = context.infer_node(node.get_test_node_from_name(tree_name))
|
| 761 |
+
if node.parent.type == 'async_stmt':
|
| 762 |
+
# In the case of `async with` statements, we need to
|
| 763 |
+
# first get the coroutine from the `__aenter__` method,
|
| 764 |
+
# then "unwrap" via the `__await__` method
|
| 765 |
+
enter_methods = value_managers.py__getattribute__('__aenter__')
|
| 766 |
+
coro = enter_methods.execute_with_values()
|
| 767 |
+
return coro.py__await__().py__stop_iteration_returns()
|
| 768 |
+
enter_methods = value_managers.py__getattribute__('__enter__')
|
| 769 |
+
return enter_methods.execute_with_values()
|
| 770 |
+
elif typ in ('import_from', 'import_name'):
|
| 771 |
+
types = imports.infer_import(context, tree_name)
|
| 772 |
+
elif typ in ('funcdef', 'classdef'):
|
| 773 |
+
types = _apply_decorators(context, node)
|
| 774 |
+
elif typ == 'try_stmt':
|
| 775 |
+
# TODO an exception can also be a tuple. Check for those.
|
| 776 |
+
# TODO check for types that are not classes and add it to
|
| 777 |
+
# the static analysis report.
|
| 778 |
+
exceptions = context.infer_node(tree_name.get_previous_sibling().get_previous_sibling())
|
| 779 |
+
types = exceptions.execute_with_values()
|
| 780 |
+
elif typ == 'param':
|
| 781 |
+
types = NO_VALUES
|
| 782 |
+
elif typ == 'del_stmt':
|
| 783 |
+
types = NO_VALUES
|
| 784 |
+
elif typ == 'namedexpr_test':
|
| 785 |
+
types = infer_node(context, node)
|
| 786 |
+
else:
|
| 787 |
+
raise ValueError("Should not happen. type: %s" % typ)
|
| 788 |
+
return types
|
| 789 |
+
|
| 790 |
+
|
| 791 |
+
# We don't want to have functions/classes that are created by the same
|
| 792 |
+
# tree_node.
|
| 793 |
+
@inference_state_method_cache()
|
| 794 |
+
def _apply_decorators(context, node):
|
| 795 |
+
"""
|
| 796 |
+
Returns the function, that should to be executed in the end.
|
| 797 |
+
This is also the places where the decorators are processed.
|
| 798 |
+
"""
|
| 799 |
+
if node.type == 'classdef':
|
| 800 |
+
decoratee_value = ClassValue(
|
| 801 |
+
context.inference_state,
|
| 802 |
+
parent_context=context,
|
| 803 |
+
tree_node=node
|
| 804 |
+
)
|
| 805 |
+
else:
|
| 806 |
+
decoratee_value = FunctionValue.from_context(context, node)
|
| 807 |
+
initial = values = ValueSet([decoratee_value])
|
| 808 |
+
|
| 809 |
+
if is_big_annoying_library(context):
|
| 810 |
+
return values
|
| 811 |
+
|
| 812 |
+
for dec in reversed(node.get_decorators()):
|
| 813 |
+
debug.dbg('decorator: %s %s', dec, values, color="MAGENTA")
|
| 814 |
+
with debug.increase_indent_cm():
|
| 815 |
+
dec_values = context.infer_node(dec.children[1])
|
| 816 |
+
trailer_nodes = dec.children[2:-1]
|
| 817 |
+
if trailer_nodes:
|
| 818 |
+
# Create a trailer and infer it.
|
| 819 |
+
trailer = tree.PythonNode('trailer', trailer_nodes)
|
| 820 |
+
trailer.parent = dec
|
| 821 |
+
dec_values = infer_trailer(context, dec_values, trailer)
|
| 822 |
+
|
| 823 |
+
if not len(dec_values):
|
| 824 |
+
code = dec.get_code(include_prefix=False)
|
| 825 |
+
# For the short future, we don't want to hear about the runtime
|
| 826 |
+
# decorator in typing that was intentionally omitted. This is not
|
| 827 |
+
# "correct", but helps with debugging.
|
| 828 |
+
if code != '@runtime\n':
|
| 829 |
+
debug.warning('decorator not found: %s on %s', dec, node)
|
| 830 |
+
return initial
|
| 831 |
+
|
| 832 |
+
values = dec_values.execute(arguments.ValuesArguments([values]))
|
| 833 |
+
if not len(values):
|
| 834 |
+
debug.warning('not possible to resolve wrappers found %s', node)
|
| 835 |
+
return initial
|
| 836 |
+
|
| 837 |
+
debug.dbg('decorator end %s', values, color="MAGENTA")
|
| 838 |
+
if values != initial:
|
| 839 |
+
return ValueSet([Decoratee(c, decoratee_value) for c in values])
|
| 840 |
+
return values
|
| 841 |
+
|
| 842 |
+
|
| 843 |
+
def check_tuple_assignments(name, value_set):
|
| 844 |
+
"""
|
| 845 |
+
Checks if tuples are assigned.
|
| 846 |
+
"""
|
| 847 |
+
lazy_value = None
|
| 848 |
+
for index, node in name.assignment_indexes():
|
| 849 |
+
cn = ContextualizedNode(name.parent_context, node)
|
| 850 |
+
iterated = value_set.iterate(cn)
|
| 851 |
+
if isinstance(index, slice):
|
| 852 |
+
# For no star unpacking is not possible.
|
| 853 |
+
return NO_VALUES
|
| 854 |
+
i = 0
|
| 855 |
+
while i <= index:
|
| 856 |
+
try:
|
| 857 |
+
lazy_value = next(iterated)
|
| 858 |
+
except StopIteration:
|
| 859 |
+
# We could do this with the default param in next. But this
|
| 860 |
+
# would allow this loop to run for a very long time if the
|
| 861 |
+
# index number is high. Therefore break if the loop is
|
| 862 |
+
# finished.
|
| 863 |
+
return NO_VALUES
|
| 864 |
+
else:
|
| 865 |
+
i += lazy_value.max
|
| 866 |
+
value_set = lazy_value.infer()
|
| 867 |
+
return value_set
|
| 868 |
+
|
| 869 |
+
|
| 870 |
+
class ContextualizedSubscriptListNode(ContextualizedNode):
|
| 871 |
+
def infer(self):
|
| 872 |
+
return _infer_subscript_list(self.context, self.node)
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
def _infer_subscript_list(context, index):
|
| 876 |
+
"""
|
| 877 |
+
Handles slices in subscript nodes.
|
| 878 |
+
"""
|
| 879 |
+
if index == ':':
|
| 880 |
+
# Like array[:]
|
| 881 |
+
return ValueSet([iterable.Slice(context, None, None, None)])
|
| 882 |
+
|
| 883 |
+
elif index.type == 'subscript' and not index.children[0] == '.':
|
| 884 |
+
# subscript basically implies a slice operation
|
| 885 |
+
# e.g. array[:3]
|
| 886 |
+
result = []
|
| 887 |
+
for el in index.children:
|
| 888 |
+
if el == ':':
|
| 889 |
+
if not result:
|
| 890 |
+
result.append(None)
|
| 891 |
+
elif el.type == 'sliceop':
|
| 892 |
+
if len(el.children) == 2:
|
| 893 |
+
result.append(el.children[1])
|
| 894 |
+
else:
|
| 895 |
+
result.append(el)
|
| 896 |
+
result += [None] * (3 - len(result))
|
| 897 |
+
|
| 898 |
+
return ValueSet([iterable.Slice(context, *result)])
|
| 899 |
+
elif index.type == 'subscriptlist':
|
| 900 |
+
return ValueSet([iterable.SequenceLiteralValue(context.inference_state, context, index)])
|
| 901 |
+
|
| 902 |
+
# No slices
|
| 903 |
+
return context.infer_node(index)
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/sys_path.py
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from importlib.machinery import all_suffixes
|
| 5 |
+
|
| 6 |
+
from jedi.inference.cache import inference_state_method_cache
|
| 7 |
+
from jedi.inference.base_value import ContextualizedNode
|
| 8 |
+
from jedi.inference.helpers import is_string, get_str_or_none
|
| 9 |
+
from jedi.parser_utils import get_cached_code_lines
|
| 10 |
+
from jedi.file_io import FileIO
|
| 11 |
+
from jedi import settings
|
| 12 |
+
from jedi import debug
|
| 13 |
+
|
| 14 |
+
_BUILDOUT_PATH_INSERTION_LIMIT = 10
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _abs_path(module_context, str_path: str):
|
| 18 |
+
path = Path(str_path)
|
| 19 |
+
if path.is_absolute():
|
| 20 |
+
return path
|
| 21 |
+
|
| 22 |
+
module_path = module_context.py__file__()
|
| 23 |
+
if module_path is None:
|
| 24 |
+
# In this case we have no idea where we actually are in the file
|
| 25 |
+
# system.
|
| 26 |
+
return None
|
| 27 |
+
|
| 28 |
+
base_dir = module_path.parent
|
| 29 |
+
return base_dir.joinpath(path).absolute()
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _paths_from_assignment(module_context, expr_stmt):
|
| 33 |
+
"""
|
| 34 |
+
Extracts the assigned strings from an assignment that looks as follows::
|
| 35 |
+
|
| 36 |
+
sys.path[0:0] = ['module/path', 'another/module/path']
|
| 37 |
+
|
| 38 |
+
This function is in general pretty tolerant (and therefore 'buggy').
|
| 39 |
+
However, it's not a big issue usually to add more paths to Jedi's sys_path,
|
| 40 |
+
because it will only affect Jedi in very random situations and by adding
|
| 41 |
+
more paths than necessary, it usually benefits the general user.
|
| 42 |
+
"""
|
| 43 |
+
for assignee, operator in zip(expr_stmt.children[::2], expr_stmt.children[1::2]):
|
| 44 |
+
try:
|
| 45 |
+
assert operator in ['=', '+=']
|
| 46 |
+
assert assignee.type in ('power', 'atom_expr') and \
|
| 47 |
+
len(assignee.children) > 1
|
| 48 |
+
c = assignee.children
|
| 49 |
+
assert c[0].type == 'name' and c[0].value == 'sys'
|
| 50 |
+
trailer = c[1]
|
| 51 |
+
assert trailer.children[0] == '.' and trailer.children[1].value == 'path'
|
| 52 |
+
# TODO Essentially we're not checking details on sys.path
|
| 53 |
+
# manipulation. Both assigment of the sys.path and changing/adding
|
| 54 |
+
# parts of the sys.path are the same: They get added to the end of
|
| 55 |
+
# the current sys.path.
|
| 56 |
+
"""
|
| 57 |
+
execution = c[2]
|
| 58 |
+
assert execution.children[0] == '['
|
| 59 |
+
subscript = execution.children[1]
|
| 60 |
+
assert subscript.type == 'subscript'
|
| 61 |
+
assert ':' in subscript.children
|
| 62 |
+
"""
|
| 63 |
+
except AssertionError:
|
| 64 |
+
continue
|
| 65 |
+
|
| 66 |
+
cn = ContextualizedNode(module_context.create_context(expr_stmt), expr_stmt)
|
| 67 |
+
for lazy_value in cn.infer().iterate(cn):
|
| 68 |
+
for value in lazy_value.infer():
|
| 69 |
+
if is_string(value):
|
| 70 |
+
abs_path = _abs_path(module_context, value.get_safe_value())
|
| 71 |
+
if abs_path is not None:
|
| 72 |
+
yield abs_path
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _paths_from_list_modifications(module_context, trailer1, trailer2):
|
| 76 |
+
""" extract the path from either "sys.path.append" or "sys.path.insert" """
|
| 77 |
+
# Guarantee that both are trailers, the first one a name and the second one
|
| 78 |
+
# a function execution with at least one param.
|
| 79 |
+
if not (trailer1.type == 'trailer' and trailer1.children[0] == '.'
|
| 80 |
+
and trailer2.type == 'trailer' and trailer2.children[0] == '('
|
| 81 |
+
and len(trailer2.children) == 3):
|
| 82 |
+
return
|
| 83 |
+
|
| 84 |
+
name = trailer1.children[1].value
|
| 85 |
+
if name not in ['insert', 'append']:
|
| 86 |
+
return
|
| 87 |
+
arg = trailer2.children[1]
|
| 88 |
+
if name == 'insert' and len(arg.children) in (3, 4): # Possible trailing comma.
|
| 89 |
+
arg = arg.children[2]
|
| 90 |
+
|
| 91 |
+
for value in module_context.create_context(arg).infer_node(arg):
|
| 92 |
+
p = get_str_or_none(value)
|
| 93 |
+
if p is None:
|
| 94 |
+
continue
|
| 95 |
+
abs_path = _abs_path(module_context, p)
|
| 96 |
+
if abs_path is not None:
|
| 97 |
+
yield abs_path
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
@inference_state_method_cache(default=[])
|
| 101 |
+
def check_sys_path_modifications(module_context):
|
| 102 |
+
"""
|
| 103 |
+
Detect sys.path modifications within module.
|
| 104 |
+
"""
|
| 105 |
+
def get_sys_path_powers(names):
|
| 106 |
+
for name in names:
|
| 107 |
+
power = name.parent.parent
|
| 108 |
+
if power is not None and power.type in ('power', 'atom_expr'):
|
| 109 |
+
c = power.children
|
| 110 |
+
if c[0].type == 'name' and c[0].value == 'sys' \
|
| 111 |
+
and c[1].type == 'trailer':
|
| 112 |
+
n = c[1].children[1]
|
| 113 |
+
if n.type == 'name' and n.value == 'path':
|
| 114 |
+
yield name, power
|
| 115 |
+
|
| 116 |
+
if module_context.tree_node is None:
|
| 117 |
+
return []
|
| 118 |
+
|
| 119 |
+
added = []
|
| 120 |
+
try:
|
| 121 |
+
possible_names = module_context.tree_node.get_used_names()['path']
|
| 122 |
+
except KeyError:
|
| 123 |
+
pass
|
| 124 |
+
else:
|
| 125 |
+
for name, power in get_sys_path_powers(possible_names):
|
| 126 |
+
expr_stmt = power.parent
|
| 127 |
+
if len(power.children) >= 4:
|
| 128 |
+
added.extend(
|
| 129 |
+
_paths_from_list_modifications(
|
| 130 |
+
module_context, *power.children[2:4]
|
| 131 |
+
)
|
| 132 |
+
)
|
| 133 |
+
elif expr_stmt is not None and expr_stmt.type == 'expr_stmt':
|
| 134 |
+
added.extend(_paths_from_assignment(module_context, expr_stmt))
|
| 135 |
+
return added
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def discover_buildout_paths(inference_state, script_path):
|
| 139 |
+
buildout_script_paths = set()
|
| 140 |
+
|
| 141 |
+
for buildout_script_path in _get_buildout_script_paths(script_path):
|
| 142 |
+
for path in _get_paths_from_buildout_script(inference_state, buildout_script_path):
|
| 143 |
+
buildout_script_paths.add(path)
|
| 144 |
+
if len(buildout_script_paths) >= _BUILDOUT_PATH_INSERTION_LIMIT:
|
| 145 |
+
break
|
| 146 |
+
|
| 147 |
+
return buildout_script_paths
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def _get_paths_from_buildout_script(inference_state, buildout_script_path):
|
| 151 |
+
file_io = FileIO(str(buildout_script_path))
|
| 152 |
+
try:
|
| 153 |
+
module_node = inference_state.parse(
|
| 154 |
+
file_io=file_io,
|
| 155 |
+
cache=True,
|
| 156 |
+
cache_path=settings.cache_directory
|
| 157 |
+
)
|
| 158 |
+
except IOError:
|
| 159 |
+
debug.warning('Error trying to read buildout_script: %s', buildout_script_path)
|
| 160 |
+
return
|
| 161 |
+
|
| 162 |
+
from jedi.inference.value import ModuleValue
|
| 163 |
+
module_context = ModuleValue(
|
| 164 |
+
inference_state, module_node,
|
| 165 |
+
file_io=file_io,
|
| 166 |
+
string_names=None,
|
| 167 |
+
code_lines=get_cached_code_lines(inference_state.grammar, buildout_script_path),
|
| 168 |
+
).as_context()
|
| 169 |
+
yield from check_sys_path_modifications(module_context)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def _get_parent_dir_with_file(path: Path, filename):
|
| 173 |
+
for parent in path.parents:
|
| 174 |
+
try:
|
| 175 |
+
if parent.joinpath(filename).is_file():
|
| 176 |
+
return parent
|
| 177 |
+
except OSError:
|
| 178 |
+
continue
|
| 179 |
+
return None
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def _get_buildout_script_paths(search_path: Path):
|
| 183 |
+
"""
|
| 184 |
+
if there is a 'buildout.cfg' file in one of the parent directories of the
|
| 185 |
+
given module it will return a list of all files in the buildout bin
|
| 186 |
+
directory that look like python files.
|
| 187 |
+
|
| 188 |
+
:param search_path: absolute path to the module.
|
| 189 |
+
"""
|
| 190 |
+
project_root = _get_parent_dir_with_file(search_path, 'buildout.cfg')
|
| 191 |
+
if not project_root:
|
| 192 |
+
return
|
| 193 |
+
bin_path = project_root.joinpath('bin')
|
| 194 |
+
if not bin_path.exists():
|
| 195 |
+
return
|
| 196 |
+
|
| 197 |
+
for filename in os.listdir(bin_path):
|
| 198 |
+
try:
|
| 199 |
+
filepath = bin_path.joinpath(filename)
|
| 200 |
+
with open(filepath, 'r') as f:
|
| 201 |
+
firstline = f.readline()
|
| 202 |
+
if firstline.startswith('#!') and 'python' in firstline:
|
| 203 |
+
yield filepath
|
| 204 |
+
except (UnicodeDecodeError, IOError) as e:
|
| 205 |
+
# Probably a binary file; permission error or race cond. because
|
| 206 |
+
# file got deleted. Ignore it.
|
| 207 |
+
debug.warning(str(e))
|
| 208 |
+
continue
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def remove_python_path_suffix(path):
|
| 212 |
+
for suffix in all_suffixes() + ['.pyi']:
|
| 213 |
+
if path.suffix == suffix:
|
| 214 |
+
path = path.with_name(path.stem)
|
| 215 |
+
break
|
| 216 |
+
return path
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def transform_path_to_dotted(sys_path, module_path):
|
| 220 |
+
"""
|
| 221 |
+
Returns the dotted path inside a sys.path as a list of names. e.g.
|
| 222 |
+
|
| 223 |
+
>>> transform_path_to_dotted([str(Path("/foo").absolute())], Path('/foo/bar/baz.py').absolute())
|
| 224 |
+
(('bar', 'baz'), False)
|
| 225 |
+
|
| 226 |
+
Returns (None, False) if the path doesn't really resolve to anything.
|
| 227 |
+
The second return part is if it is a package.
|
| 228 |
+
"""
|
| 229 |
+
# First remove the suffix.
|
| 230 |
+
module_path = remove_python_path_suffix(module_path)
|
| 231 |
+
if module_path.name.startswith('.'):
|
| 232 |
+
return None, False
|
| 233 |
+
|
| 234 |
+
# Once the suffix was removed we are using the files as we know them. This
|
| 235 |
+
# means that if someone uses an ending like .vim for a Python file, .vim
|
| 236 |
+
# will be part of the returned dotted part.
|
| 237 |
+
|
| 238 |
+
is_package = module_path.name == '__init__'
|
| 239 |
+
if is_package:
|
| 240 |
+
module_path = module_path.parent
|
| 241 |
+
|
| 242 |
+
def iter_potential_solutions():
|
| 243 |
+
for p in sys_path:
|
| 244 |
+
if str(module_path).startswith(p):
|
| 245 |
+
# Strip the trailing slash/backslash
|
| 246 |
+
rest = str(module_path)[len(p):]
|
| 247 |
+
# On Windows a path can also use a slash.
|
| 248 |
+
if rest.startswith(os.path.sep) or rest.startswith('/'):
|
| 249 |
+
# Remove a slash in cases it's still there.
|
| 250 |
+
rest = rest[1:]
|
| 251 |
+
|
| 252 |
+
if rest:
|
| 253 |
+
split = rest.split(os.path.sep)
|
| 254 |
+
if not all(split):
|
| 255 |
+
# This means that part of the file path was empty, this
|
| 256 |
+
# is very strange and is probably a file that is called
|
| 257 |
+
# `.py`.
|
| 258 |
+
return
|
| 259 |
+
# Stub folders for foo can end with foo-stubs. Just remove
|
| 260 |
+
# it.
|
| 261 |
+
yield tuple(re.sub(r'-stubs$', '', s) for s in split)
|
| 262 |
+
|
| 263 |
+
potential_solutions = tuple(iter_potential_solutions())
|
| 264 |
+
if not potential_solutions:
|
| 265 |
+
return None, False
|
| 266 |
+
# Try to find the shortest path, this makes more sense usually, because the
|
| 267 |
+
# user usually has venvs somewhere. This means that a path like
|
| 268 |
+
# .tox/py37/lib/python3.7/os.py can be normal for a file. However in that
|
| 269 |
+
# case we definitely want to return ['os'] as a path and not a crazy
|
| 270 |
+
# ['.tox', 'py37', 'lib', 'python3.7', 'os']. Keep in mind that this is a
|
| 271 |
+
# heuristic and there's now ay to "always" do it right.
|
| 272 |
+
return sorted(potential_solutions, key=lambda p: len(p))[0], is_package
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/utils.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" A universal module with functions / classes without dependencies. """
|
| 2 |
+
import functools
|
| 3 |
+
import re
|
| 4 |
+
import os
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
_sep = os.path.sep
|
| 8 |
+
if os.path.altsep is not None:
|
| 9 |
+
_sep += os.path.altsep
|
| 10 |
+
_path_re = re.compile(r'(?:\.[^{0}]+|[{0}]__init__\.py)$'.format(re.escape(_sep)))
|
| 11 |
+
del _sep
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def to_list(func):
|
| 15 |
+
def wrapper(*args, **kwargs):
|
| 16 |
+
return list(func(*args, **kwargs))
|
| 17 |
+
return wrapper
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def to_tuple(func):
|
| 21 |
+
def wrapper(*args, **kwargs):
|
| 22 |
+
return tuple(func(*args, **kwargs))
|
| 23 |
+
return wrapper
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def unite(iterable):
|
| 27 |
+
"""Turns a two dimensional array into a one dimensional."""
|
| 28 |
+
return set(typ for types in iterable for typ in types)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class UncaughtAttributeError(Exception):
|
| 32 |
+
"""
|
| 33 |
+
Important, because `__getattr__` and `hasattr` catch AttributeErrors
|
| 34 |
+
implicitly. This is really evil (mainly because of `__getattr__`).
|
| 35 |
+
Therefore this class originally had to be derived from `BaseException`
|
| 36 |
+
instead of `Exception`. But because I removed relevant `hasattr` from
|
| 37 |
+
the code base, we can now switch back to `Exception`.
|
| 38 |
+
|
| 39 |
+
:param base: return values of sys.exc_info().
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def safe_property(func):
|
| 44 |
+
return property(reraise_uncaught(func))
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def reraise_uncaught(func):
|
| 48 |
+
"""
|
| 49 |
+
Re-throw uncaught `AttributeError`.
|
| 50 |
+
|
| 51 |
+
Usage: Put ``@rethrow_uncaught`` in front of the function
|
| 52 |
+
which does **not** suppose to raise `AttributeError`.
|
| 53 |
+
|
| 54 |
+
AttributeError is easily get caught by `hasattr` and another
|
| 55 |
+
``except AttributeError`` clause. This becomes problem when you use
|
| 56 |
+
a lot of "dynamic" attributes (e.g., using ``@property``) because you
|
| 57 |
+
can't distinguish if the property does not exist for real or some code
|
| 58 |
+
inside of the "dynamic" attribute through that error. In a well
|
| 59 |
+
written code, such error should not exist but getting there is very
|
| 60 |
+
difficult. This decorator is to help us getting there by changing
|
| 61 |
+
`AttributeError` to `UncaughtAttributeError` to avoid unexpected catch.
|
| 62 |
+
This helps us noticing bugs earlier and facilitates debugging.
|
| 63 |
+
"""
|
| 64 |
+
@functools.wraps(func)
|
| 65 |
+
def wrapper(*args, **kwds):
|
| 66 |
+
try:
|
| 67 |
+
return func(*args, **kwds)
|
| 68 |
+
except AttributeError as e:
|
| 69 |
+
raise UncaughtAttributeError(e) from e
|
| 70 |
+
return wrapper
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class PushBackIterator:
|
| 74 |
+
def __init__(self, iterator):
|
| 75 |
+
self.pushes = []
|
| 76 |
+
self.iterator = iterator
|
| 77 |
+
self.current = None
|
| 78 |
+
|
| 79 |
+
def push_back(self, value):
|
| 80 |
+
self.pushes.append(value)
|
| 81 |
+
|
| 82 |
+
def __iter__(self):
|
| 83 |
+
return self
|
| 84 |
+
|
| 85 |
+
def __next__(self):
|
| 86 |
+
if self.pushes:
|
| 87 |
+
self.current = self.pushes.pop()
|
| 88 |
+
else:
|
| 89 |
+
self.current = next(self.iterator)
|
| 90 |
+
return self.current
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/value/decorator.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'''
|
| 2 |
+
Decorators are not really values, however we need some wrappers to improve
|
| 3 |
+
docstrings and other things around decorators.
|
| 4 |
+
'''
|
| 5 |
+
|
| 6 |
+
from jedi.inference.base_value import ValueWrapper, ValueSet
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class Decoratee(ValueWrapper):
|
| 10 |
+
def __init__(self, wrapped_value, original_value):
|
| 11 |
+
super().__init__(wrapped_value)
|
| 12 |
+
self._original_value = original_value
|
| 13 |
+
|
| 14 |
+
def py__doc__(self):
|
| 15 |
+
return self._original_value.py__doc__()
|
| 16 |
+
|
| 17 |
+
def py__get__(self, instance, class_value):
|
| 18 |
+
return ValueSet(
|
| 19 |
+
Decoratee(v, self._original_value)
|
| 20 |
+
for v in self._wrapped_value.py__get__(instance, class_value)
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
def get_signatures(self):
|
| 24 |
+
signatures = self._wrapped_value.get_signatures()
|
| 25 |
+
if signatures:
|
| 26 |
+
return signatures
|
| 27 |
+
# Fallback to signatures of the original function/class if the
|
| 28 |
+
# decorator has no signature or it is not inferrable.
|
| 29 |
+
#
|
| 30 |
+
# __get__ means that it's a descriptor. In that case we don't return
|
| 31 |
+
# signatures, because they are usually properties.
|
| 32 |
+
if not self._wrapped_value.py__getattribute__('__get__'):
|
| 33 |
+
return self._original_value.get_signatures()
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A module to deal with stuff like `list.append` and `set.add`.
|
| 3 |
+
|
| 4 |
+
Array modifications
|
| 5 |
+
*******************
|
| 6 |
+
|
| 7 |
+
If the content of an array (``set``/``list``) is requested somewhere, the
|
| 8 |
+
current module will be checked for appearances of ``arr.append``,
|
| 9 |
+
``arr.insert``, etc. If the ``arr`` name points to an actual array, the
|
| 10 |
+
content will be added
|
| 11 |
+
|
| 12 |
+
This can be really cpu intensive, as you can imagine. Because |jedi| has to
|
| 13 |
+
follow **every** ``append`` and check whether it's the right array. However this
|
| 14 |
+
works pretty good, because in *slow* cases, the recursion detector and other
|
| 15 |
+
settings will stop this process.
|
| 16 |
+
|
| 17 |
+
It is important to note that:
|
| 18 |
+
|
| 19 |
+
1. Array modifications work only in the current module.
|
| 20 |
+
2. Jedi only checks Array additions; ``list.pop``, etc are ignored.
|
| 21 |
+
"""
|
| 22 |
+
from jedi import debug
|
| 23 |
+
from jedi import settings
|
| 24 |
+
from jedi.inference import recursion
|
| 25 |
+
from jedi.inference.base_value import ValueSet, NO_VALUES, HelperValueMixin, \
|
| 26 |
+
ValueWrapper
|
| 27 |
+
from jedi.inference.lazy_value import LazyKnownValues
|
| 28 |
+
from jedi.inference.helpers import infer_call_of_leaf
|
| 29 |
+
from jedi.inference.cache import inference_state_method_cache
|
| 30 |
+
|
| 31 |
+
_sentinel = object()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def check_array_additions(context, sequence):
|
| 35 |
+
""" Just a mapper function for the internal _internal_check_array_additions """
|
| 36 |
+
if sequence.array_type not in ('list', 'set'):
|
| 37 |
+
# TODO also check for dict updates
|
| 38 |
+
return NO_VALUES
|
| 39 |
+
|
| 40 |
+
return _internal_check_array_additions(context, sequence)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
@inference_state_method_cache(default=NO_VALUES)
|
| 44 |
+
@debug.increase_indent
|
| 45 |
+
def _internal_check_array_additions(context, sequence):
|
| 46 |
+
"""
|
| 47 |
+
Checks if a `Array` has "add" (append, insert, extend) statements:
|
| 48 |
+
|
| 49 |
+
>>> a = [""]
|
| 50 |
+
>>> a.append(1)
|
| 51 |
+
"""
|
| 52 |
+
from jedi.inference import arguments
|
| 53 |
+
|
| 54 |
+
debug.dbg('Dynamic array search for %s' % sequence, color='MAGENTA')
|
| 55 |
+
module_context = context.get_root_context()
|
| 56 |
+
if not settings.dynamic_array_additions or module_context.is_compiled():
|
| 57 |
+
debug.dbg('Dynamic array search aborted.', color='MAGENTA')
|
| 58 |
+
return NO_VALUES
|
| 59 |
+
|
| 60 |
+
def find_additions(context, arglist, add_name):
|
| 61 |
+
params = list(arguments.TreeArguments(context.inference_state, context, arglist).unpack())
|
| 62 |
+
result = set()
|
| 63 |
+
if add_name in ['insert']:
|
| 64 |
+
params = params[1:]
|
| 65 |
+
if add_name in ['append', 'add', 'insert']:
|
| 66 |
+
for key, lazy_value in params:
|
| 67 |
+
result.add(lazy_value)
|
| 68 |
+
elif add_name in ['extend', 'update']:
|
| 69 |
+
for key, lazy_value in params:
|
| 70 |
+
result |= set(lazy_value.infer().iterate())
|
| 71 |
+
return result
|
| 72 |
+
|
| 73 |
+
temp_param_add, settings.dynamic_params_for_other_modules = \
|
| 74 |
+
settings.dynamic_params_for_other_modules, False
|
| 75 |
+
|
| 76 |
+
is_list = sequence.name.string_name == 'list'
|
| 77 |
+
search_names = (['append', 'extend', 'insert'] if is_list else ['add', 'update'])
|
| 78 |
+
|
| 79 |
+
added_types = set()
|
| 80 |
+
for add_name in search_names:
|
| 81 |
+
try:
|
| 82 |
+
possible_names = module_context.tree_node.get_used_names()[add_name]
|
| 83 |
+
except KeyError:
|
| 84 |
+
continue
|
| 85 |
+
else:
|
| 86 |
+
for name in possible_names:
|
| 87 |
+
value_node = context.tree_node
|
| 88 |
+
if not (value_node.start_pos < name.start_pos < value_node.end_pos):
|
| 89 |
+
continue
|
| 90 |
+
trailer = name.parent
|
| 91 |
+
power = trailer.parent
|
| 92 |
+
trailer_pos = power.children.index(trailer)
|
| 93 |
+
try:
|
| 94 |
+
execution_trailer = power.children[trailer_pos + 1]
|
| 95 |
+
except IndexError:
|
| 96 |
+
continue
|
| 97 |
+
else:
|
| 98 |
+
if execution_trailer.type != 'trailer' \
|
| 99 |
+
or execution_trailer.children[0] != '(' \
|
| 100 |
+
or execution_trailer.children[1] == ')':
|
| 101 |
+
continue
|
| 102 |
+
|
| 103 |
+
random_context = context.create_context(name)
|
| 104 |
+
|
| 105 |
+
with recursion.execution_allowed(context.inference_state, power) as allowed:
|
| 106 |
+
if allowed:
|
| 107 |
+
found = infer_call_of_leaf(
|
| 108 |
+
random_context,
|
| 109 |
+
name,
|
| 110 |
+
cut_own_trailer=True
|
| 111 |
+
)
|
| 112 |
+
if sequence in found:
|
| 113 |
+
# The arrays match. Now add the results
|
| 114 |
+
added_types |= find_additions(
|
| 115 |
+
random_context,
|
| 116 |
+
execution_trailer.children[1],
|
| 117 |
+
add_name
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
# reset settings
|
| 121 |
+
settings.dynamic_params_for_other_modules = temp_param_add
|
| 122 |
+
debug.dbg('Dynamic array result %s', added_types, color='MAGENTA')
|
| 123 |
+
return added_types
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def get_dynamic_array_instance(instance, arguments):
|
| 127 |
+
"""Used for set() and list() instances."""
|
| 128 |
+
ai = _DynamicArrayAdditions(instance, arguments)
|
| 129 |
+
from jedi.inference import arguments
|
| 130 |
+
return arguments.ValuesArguments([ValueSet([ai])])
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class _DynamicArrayAdditions(HelperValueMixin):
|
| 134 |
+
"""
|
| 135 |
+
Used for the usage of set() and list().
|
| 136 |
+
This is definitely a hack, but a good one :-)
|
| 137 |
+
It makes it possible to use set/list conversions.
|
| 138 |
+
|
| 139 |
+
This is not a proper context, because it doesn't have to be. It's not used
|
| 140 |
+
in the wild, it's just used within typeshed as an argument to `__init__`
|
| 141 |
+
for set/list and never used in any other place.
|
| 142 |
+
"""
|
| 143 |
+
def __init__(self, instance, arguments):
|
| 144 |
+
self._instance = instance
|
| 145 |
+
self._arguments = arguments
|
| 146 |
+
|
| 147 |
+
def py__class__(self):
|
| 148 |
+
tuple_, = self._instance.inference_state.builtins_module.py__getattribute__('tuple')
|
| 149 |
+
return tuple_
|
| 150 |
+
|
| 151 |
+
def py__iter__(self, contextualized_node=None):
|
| 152 |
+
arguments = self._arguments
|
| 153 |
+
try:
|
| 154 |
+
_, lazy_value = next(arguments.unpack())
|
| 155 |
+
except StopIteration:
|
| 156 |
+
pass
|
| 157 |
+
else:
|
| 158 |
+
yield from lazy_value.infer().iterate()
|
| 159 |
+
|
| 160 |
+
from jedi.inference.arguments import TreeArguments
|
| 161 |
+
if isinstance(arguments, TreeArguments):
|
| 162 |
+
additions = _internal_check_array_additions(arguments.context, self._instance)
|
| 163 |
+
yield from additions
|
| 164 |
+
|
| 165 |
+
def iterate(self, contextualized_node=None, is_async=False):
|
| 166 |
+
return self.py__iter__(contextualized_node)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class _Modification(ValueWrapper):
|
| 170 |
+
def __init__(self, wrapped_value, assigned_values, contextualized_key):
|
| 171 |
+
super().__init__(wrapped_value)
|
| 172 |
+
self._assigned_values = assigned_values
|
| 173 |
+
self._contextualized_key = contextualized_key
|
| 174 |
+
|
| 175 |
+
def py__getitem__(self, *args, **kwargs):
|
| 176 |
+
return self._wrapped_value.py__getitem__(*args, **kwargs) | self._assigned_values
|
| 177 |
+
|
| 178 |
+
def py__simple_getitem__(self, index):
|
| 179 |
+
actual = [
|
| 180 |
+
v.get_safe_value(_sentinel)
|
| 181 |
+
for v in self._contextualized_key.infer()
|
| 182 |
+
]
|
| 183 |
+
if index in actual:
|
| 184 |
+
return self._assigned_values
|
| 185 |
+
return self._wrapped_value.py__simple_getitem__(index)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
class DictModification(_Modification):
|
| 189 |
+
def py__iter__(self, contextualized_node=None):
|
| 190 |
+
yield from self._wrapped_value.py__iter__(contextualized_node)
|
| 191 |
+
yield self._contextualized_key
|
| 192 |
+
|
| 193 |
+
def get_key_values(self):
|
| 194 |
+
return self._wrapped_value.get_key_values() | self._contextualized_key.infer()
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
class ListModification(_Modification):
|
| 198 |
+
def py__iter__(self, contextualized_node=None):
|
| 199 |
+
yield from self._wrapped_value.py__iter__(contextualized_node)
|
| 200 |
+
yield LazyKnownValues(self._assigned_values)
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/value/function.py
ADDED
|
@@ -0,0 +1,461 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from parso.python import tree
|
| 2 |
+
|
| 3 |
+
from jedi import debug
|
| 4 |
+
from jedi.inference.cache import inference_state_method_cache, CachedMetaClass
|
| 5 |
+
from jedi.inference import compiled
|
| 6 |
+
from jedi.inference import recursion
|
| 7 |
+
from jedi.inference import docstrings
|
| 8 |
+
from jedi.inference import flow_analysis
|
| 9 |
+
from jedi.inference.signature import TreeSignature
|
| 10 |
+
from jedi.inference.filters import ParserTreeFilter, FunctionExecutionFilter, \
|
| 11 |
+
AnonymousFunctionExecutionFilter
|
| 12 |
+
from jedi.inference.names import ValueName, AbstractNameDefinition, \
|
| 13 |
+
AnonymousParamName, ParamName, NameWrapper
|
| 14 |
+
from jedi.inference.base_value import ContextualizedNode, NO_VALUES, \
|
| 15 |
+
ValueSet, TreeValue, ValueWrapper
|
| 16 |
+
from jedi.inference.lazy_value import LazyKnownValues, LazyKnownValue, \
|
| 17 |
+
LazyTreeValue
|
| 18 |
+
from jedi.inference.context import ValueContext, TreeContextMixin
|
| 19 |
+
from jedi.inference.value import iterable
|
| 20 |
+
from jedi import parser_utils
|
| 21 |
+
from jedi.inference.parser_cache import get_yield_exprs
|
| 22 |
+
from jedi.inference.helpers import values_from_qualified_names
|
| 23 |
+
from jedi.inference.gradual.generics import TupleGenericManager
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class LambdaName(AbstractNameDefinition):
|
| 27 |
+
string_name = '<lambda>'
|
| 28 |
+
api_type = 'function'
|
| 29 |
+
|
| 30 |
+
def __init__(self, lambda_value):
|
| 31 |
+
self._lambda_value = lambda_value
|
| 32 |
+
self.parent_context = lambda_value.parent_context
|
| 33 |
+
|
| 34 |
+
@property
|
| 35 |
+
def start_pos(self):
|
| 36 |
+
return self._lambda_value.tree_node.start_pos
|
| 37 |
+
|
| 38 |
+
def infer(self):
|
| 39 |
+
return ValueSet([self._lambda_value])
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class FunctionAndClassBase(TreeValue):
|
| 43 |
+
def get_qualified_names(self):
|
| 44 |
+
if self.parent_context.is_class():
|
| 45 |
+
n = self.parent_context.get_qualified_names()
|
| 46 |
+
if n is None:
|
| 47 |
+
# This means that the parent class lives within a function.
|
| 48 |
+
return None
|
| 49 |
+
return n + (self.py__name__(),)
|
| 50 |
+
elif self.parent_context.is_module():
|
| 51 |
+
return (self.py__name__(),)
|
| 52 |
+
else:
|
| 53 |
+
return None
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class FunctionMixin:
|
| 57 |
+
api_type = 'function'
|
| 58 |
+
|
| 59 |
+
def get_filters(self, origin_scope=None):
|
| 60 |
+
cls = self.py__class__()
|
| 61 |
+
for instance in cls.execute_with_values():
|
| 62 |
+
yield from instance.get_filters(origin_scope=origin_scope)
|
| 63 |
+
|
| 64 |
+
def py__get__(self, instance, class_value):
|
| 65 |
+
from jedi.inference.value.instance import BoundMethod
|
| 66 |
+
if instance is None:
|
| 67 |
+
# Calling the Foo.bar results in the original bar function.
|
| 68 |
+
return ValueSet([self])
|
| 69 |
+
return ValueSet([BoundMethod(instance, class_value.as_context(), self)])
|
| 70 |
+
|
| 71 |
+
def get_param_names(self):
|
| 72 |
+
return [AnonymousParamName(self, param.name)
|
| 73 |
+
for param in self.tree_node.get_params()]
|
| 74 |
+
|
| 75 |
+
@property
|
| 76 |
+
def name(self):
|
| 77 |
+
if self.tree_node.type == 'lambdef':
|
| 78 |
+
return LambdaName(self)
|
| 79 |
+
return ValueName(self, self.tree_node.name)
|
| 80 |
+
|
| 81 |
+
def is_function(self):
|
| 82 |
+
return True
|
| 83 |
+
|
| 84 |
+
def py__name__(self):
|
| 85 |
+
return self.name.string_name
|
| 86 |
+
|
| 87 |
+
def get_type_hint(self, add_class_info=True):
|
| 88 |
+
return_annotation = self.tree_node.annotation
|
| 89 |
+
if return_annotation is None:
|
| 90 |
+
def param_name_to_str(n):
|
| 91 |
+
s = n.string_name
|
| 92 |
+
annotation = n.infer().get_type_hint()
|
| 93 |
+
if annotation is not None:
|
| 94 |
+
s += ': ' + annotation
|
| 95 |
+
if n.default_node is not None:
|
| 96 |
+
s += '=' + n.default_node.get_code(include_prefix=False)
|
| 97 |
+
return s
|
| 98 |
+
|
| 99 |
+
function_execution = self.as_context()
|
| 100 |
+
result = function_execution.infer()
|
| 101 |
+
return_hint = result.get_type_hint()
|
| 102 |
+
body = self.py__name__() + '(%s)' % ', '.join([
|
| 103 |
+
param_name_to_str(n)
|
| 104 |
+
for n in function_execution.get_param_names()
|
| 105 |
+
])
|
| 106 |
+
if return_hint is None:
|
| 107 |
+
return body
|
| 108 |
+
else:
|
| 109 |
+
return_hint = return_annotation.get_code(include_prefix=False)
|
| 110 |
+
body = self.py__name__() + self.tree_node.children[2].get_code(include_prefix=False)
|
| 111 |
+
|
| 112 |
+
return body + ' -> ' + return_hint
|
| 113 |
+
|
| 114 |
+
def py__call__(self, arguments):
|
| 115 |
+
function_execution = self.as_context(arguments)
|
| 116 |
+
return function_execution.infer()
|
| 117 |
+
|
| 118 |
+
def _as_context(self, arguments=None):
|
| 119 |
+
if arguments is None:
|
| 120 |
+
return AnonymousFunctionExecution(self)
|
| 121 |
+
return FunctionExecutionContext(self, arguments)
|
| 122 |
+
|
| 123 |
+
def get_signatures(self):
|
| 124 |
+
return [TreeSignature(f) for f in self.get_signature_functions()]
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class FunctionValue(FunctionMixin, FunctionAndClassBase, metaclass=CachedMetaClass):
|
| 128 |
+
@classmethod
|
| 129 |
+
def from_context(cls, context, tree_node):
|
| 130 |
+
def create(tree_node):
|
| 131 |
+
if context.is_class():
|
| 132 |
+
return MethodValue(
|
| 133 |
+
context.inference_state,
|
| 134 |
+
context,
|
| 135 |
+
parent_context=parent_context,
|
| 136 |
+
tree_node=tree_node
|
| 137 |
+
)
|
| 138 |
+
else:
|
| 139 |
+
return cls(
|
| 140 |
+
context.inference_state,
|
| 141 |
+
parent_context=parent_context,
|
| 142 |
+
tree_node=tree_node
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
overloaded_funcs = list(_find_overload_functions(context, tree_node))
|
| 146 |
+
|
| 147 |
+
parent_context = context
|
| 148 |
+
while parent_context.is_class() or parent_context.is_instance():
|
| 149 |
+
parent_context = parent_context.parent_context
|
| 150 |
+
|
| 151 |
+
function = create(tree_node)
|
| 152 |
+
|
| 153 |
+
if overloaded_funcs:
|
| 154 |
+
return OverloadedFunctionValue(
|
| 155 |
+
function,
|
| 156 |
+
# Get them into the correct order: lower line first.
|
| 157 |
+
list(reversed([create(f) for f in overloaded_funcs]))
|
| 158 |
+
)
|
| 159 |
+
return function
|
| 160 |
+
|
| 161 |
+
def py__class__(self):
|
| 162 |
+
c, = values_from_qualified_names(self.inference_state, 'types', 'FunctionType')
|
| 163 |
+
return c
|
| 164 |
+
|
| 165 |
+
def get_default_param_context(self):
|
| 166 |
+
return self.parent_context
|
| 167 |
+
|
| 168 |
+
def get_signature_functions(self):
|
| 169 |
+
return [self]
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
class FunctionNameInClass(NameWrapper):
|
| 173 |
+
def __init__(self, class_context, name):
|
| 174 |
+
super().__init__(name)
|
| 175 |
+
self._class_context = class_context
|
| 176 |
+
|
| 177 |
+
def get_defining_qualified_value(self):
|
| 178 |
+
return self._class_context.get_value() # Might be None.
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
class MethodValue(FunctionValue):
|
| 182 |
+
def __init__(self, inference_state, class_context, *args, **kwargs):
|
| 183 |
+
super().__init__(inference_state, *args, **kwargs)
|
| 184 |
+
self.class_context = class_context
|
| 185 |
+
|
| 186 |
+
def get_default_param_context(self):
|
| 187 |
+
return self.class_context
|
| 188 |
+
|
| 189 |
+
def get_qualified_names(self):
|
| 190 |
+
# Need to implement this, because the parent value of a method
|
| 191 |
+
# value is not the class value but the module.
|
| 192 |
+
names = self.class_context.get_qualified_names()
|
| 193 |
+
if names is None:
|
| 194 |
+
return None
|
| 195 |
+
return names + (self.py__name__(),)
|
| 196 |
+
|
| 197 |
+
@property
|
| 198 |
+
def name(self):
|
| 199 |
+
return FunctionNameInClass(self.class_context, super().name)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
class BaseFunctionExecutionContext(ValueContext, TreeContextMixin):
|
| 203 |
+
def infer_annotations(self):
|
| 204 |
+
raise NotImplementedError
|
| 205 |
+
|
| 206 |
+
@inference_state_method_cache(default=NO_VALUES)
|
| 207 |
+
@recursion.execution_recursion_decorator()
|
| 208 |
+
def get_return_values(self, check_yields=False):
|
| 209 |
+
funcdef = self.tree_node
|
| 210 |
+
if funcdef.type == 'lambdef':
|
| 211 |
+
return self.infer_node(funcdef.children[-1])
|
| 212 |
+
|
| 213 |
+
if check_yields:
|
| 214 |
+
value_set = NO_VALUES
|
| 215 |
+
returns = get_yield_exprs(self.inference_state, funcdef)
|
| 216 |
+
else:
|
| 217 |
+
value_set = self.infer_annotations()
|
| 218 |
+
if value_set:
|
| 219 |
+
# If there are annotations, prefer them over anything else.
|
| 220 |
+
# This will make it faster.
|
| 221 |
+
return value_set
|
| 222 |
+
value_set |= docstrings.infer_return_types(self._value)
|
| 223 |
+
returns = funcdef.iter_return_stmts()
|
| 224 |
+
|
| 225 |
+
for r in returns:
|
| 226 |
+
if check_yields:
|
| 227 |
+
value_set |= ValueSet.from_sets(
|
| 228 |
+
lazy_value.infer()
|
| 229 |
+
for lazy_value in self._get_yield_lazy_value(r)
|
| 230 |
+
)
|
| 231 |
+
else:
|
| 232 |
+
check = flow_analysis.reachability_check(self, funcdef, r)
|
| 233 |
+
if check is flow_analysis.UNREACHABLE:
|
| 234 |
+
debug.dbg('Return unreachable: %s', r)
|
| 235 |
+
else:
|
| 236 |
+
try:
|
| 237 |
+
children = r.children
|
| 238 |
+
except AttributeError:
|
| 239 |
+
ctx = compiled.builtin_from_name(self.inference_state, 'None')
|
| 240 |
+
value_set |= ValueSet([ctx])
|
| 241 |
+
else:
|
| 242 |
+
value_set |= self.infer_node(children[1])
|
| 243 |
+
if check is flow_analysis.REACHABLE:
|
| 244 |
+
debug.dbg('Return reachable: %s', r)
|
| 245 |
+
break
|
| 246 |
+
return value_set
|
| 247 |
+
|
| 248 |
+
def _get_yield_lazy_value(self, yield_expr):
|
| 249 |
+
if yield_expr.type == 'keyword':
|
| 250 |
+
# `yield` just yields None.
|
| 251 |
+
ctx = compiled.builtin_from_name(self.inference_state, 'None')
|
| 252 |
+
yield LazyKnownValue(ctx)
|
| 253 |
+
return
|
| 254 |
+
|
| 255 |
+
node = yield_expr.children[1]
|
| 256 |
+
if node.type == 'yield_arg': # It must be a yield from.
|
| 257 |
+
cn = ContextualizedNode(self, node.children[1])
|
| 258 |
+
yield from cn.infer().iterate(cn)
|
| 259 |
+
else:
|
| 260 |
+
yield LazyTreeValue(self, node)
|
| 261 |
+
|
| 262 |
+
@recursion.execution_recursion_decorator(default=iter([]))
|
| 263 |
+
def get_yield_lazy_values(self, is_async=False):
|
| 264 |
+
# TODO: if is_async, wrap yield statements in Awaitable/async_generator_asend
|
| 265 |
+
for_parents = [(y, tree.search_ancestor(y, 'for_stmt', 'funcdef',
|
| 266 |
+
'while_stmt', 'if_stmt'))
|
| 267 |
+
for y in get_yield_exprs(self.inference_state, self.tree_node)]
|
| 268 |
+
|
| 269 |
+
# Calculate if the yields are placed within the same for loop.
|
| 270 |
+
yields_order = []
|
| 271 |
+
last_for_stmt = None
|
| 272 |
+
for yield_, for_stmt in for_parents:
|
| 273 |
+
# For really simple for loops we can predict the order. Otherwise
|
| 274 |
+
# we just ignore it.
|
| 275 |
+
parent = for_stmt.parent
|
| 276 |
+
if parent.type == 'suite':
|
| 277 |
+
parent = parent.parent
|
| 278 |
+
if for_stmt.type == 'for_stmt' and parent == self.tree_node \
|
| 279 |
+
and parser_utils.for_stmt_defines_one_name(for_stmt): # Simplicity for now.
|
| 280 |
+
if for_stmt == last_for_stmt:
|
| 281 |
+
yields_order[-1][1].append(yield_)
|
| 282 |
+
else:
|
| 283 |
+
yields_order.append((for_stmt, [yield_]))
|
| 284 |
+
elif for_stmt == self.tree_node:
|
| 285 |
+
yields_order.append((None, [yield_]))
|
| 286 |
+
else:
|
| 287 |
+
types = self.get_return_values(check_yields=True)
|
| 288 |
+
if types:
|
| 289 |
+
yield LazyKnownValues(types, min=0, max=float('inf'))
|
| 290 |
+
return
|
| 291 |
+
last_for_stmt = for_stmt
|
| 292 |
+
|
| 293 |
+
for for_stmt, yields in yields_order:
|
| 294 |
+
if for_stmt is None:
|
| 295 |
+
# No for_stmt, just normal yields.
|
| 296 |
+
for yield_ in yields:
|
| 297 |
+
yield from self._get_yield_lazy_value(yield_)
|
| 298 |
+
else:
|
| 299 |
+
input_node = for_stmt.get_testlist()
|
| 300 |
+
cn = ContextualizedNode(self, input_node)
|
| 301 |
+
ordered = cn.infer().iterate(cn)
|
| 302 |
+
ordered = list(ordered)
|
| 303 |
+
for lazy_value in ordered:
|
| 304 |
+
dct = {str(for_stmt.children[1].value): lazy_value.infer()}
|
| 305 |
+
with self.predefine_names(for_stmt, dct):
|
| 306 |
+
for yield_in_same_for_stmt in yields:
|
| 307 |
+
yield from self._get_yield_lazy_value(yield_in_same_for_stmt)
|
| 308 |
+
|
| 309 |
+
def merge_yield_values(self, is_async=False):
|
| 310 |
+
return ValueSet.from_sets(
|
| 311 |
+
lazy_value.infer()
|
| 312 |
+
for lazy_value in self.get_yield_lazy_values()
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
def is_generator(self):
|
| 316 |
+
return bool(get_yield_exprs(self.inference_state, self.tree_node))
|
| 317 |
+
|
| 318 |
+
def infer(self):
|
| 319 |
+
"""
|
| 320 |
+
Created to be used by inheritance.
|
| 321 |
+
"""
|
| 322 |
+
inference_state = self.inference_state
|
| 323 |
+
is_coroutine = self.tree_node.parent.type in ('async_stmt', 'async_funcdef')
|
| 324 |
+
from jedi.inference.gradual.base import GenericClass
|
| 325 |
+
|
| 326 |
+
if is_coroutine:
|
| 327 |
+
if self.is_generator():
|
| 328 |
+
async_generator_classes = inference_state.typing_module \
|
| 329 |
+
.py__getattribute__('AsyncGenerator')
|
| 330 |
+
|
| 331 |
+
yield_values = self.merge_yield_values(is_async=True)
|
| 332 |
+
# The contravariant doesn't seem to be defined.
|
| 333 |
+
generics = (yield_values.py__class__(), NO_VALUES)
|
| 334 |
+
return ValueSet(
|
| 335 |
+
GenericClass(c, TupleGenericManager(generics))
|
| 336 |
+
for c in async_generator_classes
|
| 337 |
+
).execute_annotation()
|
| 338 |
+
else:
|
| 339 |
+
async_classes = inference_state.typing_module.py__getattribute__('Coroutine')
|
| 340 |
+
return_values = self.get_return_values()
|
| 341 |
+
# Only the first generic is relevant.
|
| 342 |
+
generics = (return_values.py__class__(), NO_VALUES, NO_VALUES)
|
| 343 |
+
return ValueSet(
|
| 344 |
+
GenericClass(c, TupleGenericManager(generics)) for c in async_classes
|
| 345 |
+
).execute_annotation()
|
| 346 |
+
else:
|
| 347 |
+
# If there are annotations, prefer them over anything else.
|
| 348 |
+
if self.is_generator() and not self.infer_annotations():
|
| 349 |
+
return ValueSet([iterable.Generator(inference_state, self)])
|
| 350 |
+
else:
|
| 351 |
+
return self.get_return_values()
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
class FunctionExecutionContext(BaseFunctionExecutionContext):
|
| 355 |
+
def __init__(self, function_value, arguments):
|
| 356 |
+
super().__init__(function_value)
|
| 357 |
+
self._arguments = arguments
|
| 358 |
+
|
| 359 |
+
def get_filters(self, until_position=None, origin_scope=None):
|
| 360 |
+
yield FunctionExecutionFilter(
|
| 361 |
+
self, self._value,
|
| 362 |
+
until_position=until_position,
|
| 363 |
+
origin_scope=origin_scope,
|
| 364 |
+
arguments=self._arguments
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
def infer_annotations(self):
|
| 368 |
+
from jedi.inference.gradual.annotation import infer_return_types
|
| 369 |
+
return infer_return_types(self._value, self._arguments)
|
| 370 |
+
|
| 371 |
+
def get_param_names(self):
|
| 372 |
+
return [
|
| 373 |
+
ParamName(self._value, param.name, self._arguments)
|
| 374 |
+
for param in self._value.tree_node.get_params()
|
| 375 |
+
]
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
class AnonymousFunctionExecution(BaseFunctionExecutionContext):
|
| 379 |
+
def infer_annotations(self):
|
| 380 |
+
# I don't think inferring anonymous executions is a big thing.
|
| 381 |
+
# Anonymous contexts are mostly there for the user to work in. ~ dave
|
| 382 |
+
return NO_VALUES
|
| 383 |
+
|
| 384 |
+
def get_filters(self, until_position=None, origin_scope=None):
|
| 385 |
+
yield AnonymousFunctionExecutionFilter(
|
| 386 |
+
self, self._value,
|
| 387 |
+
until_position=until_position,
|
| 388 |
+
origin_scope=origin_scope,
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
def get_param_names(self):
|
| 392 |
+
return self._value.get_param_names()
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
class OverloadedFunctionValue(FunctionMixin, ValueWrapper):
|
| 396 |
+
def __init__(self, function, overloaded_functions):
|
| 397 |
+
super().__init__(function)
|
| 398 |
+
self._overloaded_functions = overloaded_functions
|
| 399 |
+
|
| 400 |
+
def py__call__(self, arguments):
|
| 401 |
+
debug.dbg("Execute overloaded function %s", self._wrapped_value, color='BLUE')
|
| 402 |
+
function_executions = []
|
| 403 |
+
for signature in self.get_signatures():
|
| 404 |
+
function_execution = signature.value.as_context(arguments)
|
| 405 |
+
function_executions.append(function_execution)
|
| 406 |
+
if signature.matches_signature(arguments):
|
| 407 |
+
return function_execution.infer()
|
| 408 |
+
|
| 409 |
+
if self.inference_state.is_analysis:
|
| 410 |
+
# In this case we want precision.
|
| 411 |
+
return NO_VALUES
|
| 412 |
+
return ValueSet.from_sets(fe.infer() for fe in function_executions)
|
| 413 |
+
|
| 414 |
+
def get_signature_functions(self):
|
| 415 |
+
return self._overloaded_functions
|
| 416 |
+
|
| 417 |
+
def get_type_hint(self, add_class_info=True):
|
| 418 |
+
return 'Union[%s]' % ', '.join(f.get_type_hint() for f in self._overloaded_functions)
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
def _find_overload_functions(context, tree_node):
|
| 422 |
+
def _is_overload_decorated(funcdef):
|
| 423 |
+
if funcdef.parent.type == 'decorated':
|
| 424 |
+
decorators = funcdef.parent.children[0]
|
| 425 |
+
if decorators.type == 'decorator':
|
| 426 |
+
decorators = [decorators]
|
| 427 |
+
else:
|
| 428 |
+
decorators = decorators.children
|
| 429 |
+
for decorator in decorators:
|
| 430 |
+
dotted_name = decorator.children[1]
|
| 431 |
+
if dotted_name.type == 'name' and dotted_name.value == 'overload':
|
| 432 |
+
# TODO check with values if it's the right overload
|
| 433 |
+
return True
|
| 434 |
+
return False
|
| 435 |
+
|
| 436 |
+
if tree_node.type == 'lambdef':
|
| 437 |
+
return
|
| 438 |
+
|
| 439 |
+
if _is_overload_decorated(tree_node):
|
| 440 |
+
yield tree_node
|
| 441 |
+
|
| 442 |
+
while True:
|
| 443 |
+
filter = ParserTreeFilter(
|
| 444 |
+
context,
|
| 445 |
+
until_position=tree_node.start_pos
|
| 446 |
+
)
|
| 447 |
+
names = filter.get(tree_node.name.value)
|
| 448 |
+
assert isinstance(names, list)
|
| 449 |
+
if not names:
|
| 450 |
+
break
|
| 451 |
+
|
| 452 |
+
found = False
|
| 453 |
+
for name in names:
|
| 454 |
+
funcdef = name.tree_name.parent
|
| 455 |
+
if funcdef.type == 'funcdef' and _is_overload_decorated(funcdef):
|
| 456 |
+
tree_node = funcdef
|
| 457 |
+
found = True
|
| 458 |
+
yield funcdef
|
| 459 |
+
|
| 460 |
+
if not found:
|
| 461 |
+
break
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/value/instance.py
ADDED
|
@@ -0,0 +1,610 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import abstractproperty
|
| 2 |
+
|
| 3 |
+
from parso.tree import search_ancestor
|
| 4 |
+
|
| 5 |
+
from jedi import debug
|
| 6 |
+
from jedi import settings
|
| 7 |
+
from jedi.inference import compiled
|
| 8 |
+
from jedi.inference.compiled.value import CompiledValueFilter
|
| 9 |
+
from jedi.inference.helpers import values_from_qualified_names, is_big_annoying_library
|
| 10 |
+
from jedi.inference.filters import AbstractFilter, AnonymousFunctionExecutionFilter
|
| 11 |
+
from jedi.inference.names import ValueName, TreeNameDefinition, ParamName, \
|
| 12 |
+
NameWrapper
|
| 13 |
+
from jedi.inference.base_value import Value, NO_VALUES, ValueSet, \
|
| 14 |
+
iterator_to_value_set, ValueWrapper
|
| 15 |
+
from jedi.inference.lazy_value import LazyKnownValue, LazyKnownValues
|
| 16 |
+
from jedi.inference.cache import inference_state_method_cache
|
| 17 |
+
from jedi.inference.arguments import ValuesArguments, TreeArgumentsWrapper
|
| 18 |
+
from jedi.inference.value.function import \
|
| 19 |
+
FunctionValue, FunctionMixin, OverloadedFunctionValue, \
|
| 20 |
+
BaseFunctionExecutionContext, FunctionExecutionContext, FunctionNameInClass
|
| 21 |
+
from jedi.inference.value.klass import ClassFilter
|
| 22 |
+
from jedi.inference.value.dynamic_arrays import get_dynamic_array_instance
|
| 23 |
+
from jedi.parser_utils import function_is_staticmethod, function_is_classmethod
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class InstanceExecutedParamName(ParamName):
|
| 27 |
+
def __init__(self, instance, function_value, tree_name):
|
| 28 |
+
super().__init__(
|
| 29 |
+
function_value, tree_name, arguments=None)
|
| 30 |
+
self._instance = instance
|
| 31 |
+
|
| 32 |
+
def infer(self):
|
| 33 |
+
return ValueSet([self._instance])
|
| 34 |
+
|
| 35 |
+
def matches_signature(self):
|
| 36 |
+
return True
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class AnonymousMethodExecutionFilter(AnonymousFunctionExecutionFilter):
|
| 40 |
+
def __init__(self, instance, *args, **kwargs):
|
| 41 |
+
super().__init__(*args, **kwargs)
|
| 42 |
+
self._instance = instance
|
| 43 |
+
|
| 44 |
+
def _convert_param(self, param, name):
|
| 45 |
+
if param.position_index == 0:
|
| 46 |
+
if function_is_classmethod(self._function_value.tree_node):
|
| 47 |
+
return InstanceExecutedParamName(
|
| 48 |
+
self._instance.py__class__(),
|
| 49 |
+
self._function_value,
|
| 50 |
+
name
|
| 51 |
+
)
|
| 52 |
+
elif not function_is_staticmethod(self._function_value.tree_node):
|
| 53 |
+
return InstanceExecutedParamName(
|
| 54 |
+
self._instance,
|
| 55 |
+
self._function_value,
|
| 56 |
+
name
|
| 57 |
+
)
|
| 58 |
+
return super()._convert_param(param, name)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class AnonymousMethodExecutionContext(BaseFunctionExecutionContext):
|
| 62 |
+
def __init__(self, instance, value):
|
| 63 |
+
super().__init__(value)
|
| 64 |
+
self.instance = instance
|
| 65 |
+
|
| 66 |
+
def get_filters(self, until_position=None, origin_scope=None):
|
| 67 |
+
yield AnonymousMethodExecutionFilter(
|
| 68 |
+
self.instance, self, self._value,
|
| 69 |
+
until_position=until_position,
|
| 70 |
+
origin_scope=origin_scope,
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
def get_param_names(self):
|
| 74 |
+
param_names = list(self._value.get_param_names())
|
| 75 |
+
# set the self name
|
| 76 |
+
param_names[0] = InstanceExecutedParamName(
|
| 77 |
+
self.instance,
|
| 78 |
+
self._value,
|
| 79 |
+
param_names[0].tree_name
|
| 80 |
+
)
|
| 81 |
+
return param_names
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class MethodExecutionContext(FunctionExecutionContext):
|
| 85 |
+
def __init__(self, instance, *args, **kwargs):
|
| 86 |
+
super().__init__(*args, **kwargs)
|
| 87 |
+
self.instance = instance
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class AbstractInstanceValue(Value):
|
| 91 |
+
api_type = 'instance'
|
| 92 |
+
|
| 93 |
+
def __init__(self, inference_state, parent_context, class_value):
|
| 94 |
+
super().__init__(inference_state, parent_context)
|
| 95 |
+
# Generated instances are classes that are just generated by self
|
| 96 |
+
# (No arguments) used.
|
| 97 |
+
self.class_value = class_value
|
| 98 |
+
|
| 99 |
+
def is_instance(self):
|
| 100 |
+
return True
|
| 101 |
+
|
| 102 |
+
def get_qualified_names(self):
|
| 103 |
+
return self.class_value.get_qualified_names()
|
| 104 |
+
|
| 105 |
+
def get_annotated_class_object(self):
|
| 106 |
+
return self.class_value # This is the default.
|
| 107 |
+
|
| 108 |
+
def py__class__(self):
|
| 109 |
+
return self.class_value
|
| 110 |
+
|
| 111 |
+
def py__bool__(self):
|
| 112 |
+
# Signalize that we don't know about the bool type.
|
| 113 |
+
return None
|
| 114 |
+
|
| 115 |
+
@abstractproperty
|
| 116 |
+
def name(self):
|
| 117 |
+
raise NotImplementedError
|
| 118 |
+
|
| 119 |
+
def get_signatures(self):
|
| 120 |
+
call_funcs = self.py__getattribute__('__call__').py__get__(self, self.class_value)
|
| 121 |
+
return [s.bind(self) for s in call_funcs.get_signatures()]
|
| 122 |
+
|
| 123 |
+
def get_function_slot_names(self, name):
|
| 124 |
+
# Python classes don't look at the dictionary of the instance when
|
| 125 |
+
# looking up `__call__`. This is something that has to do with Python's
|
| 126 |
+
# internal slot system (note: not __slots__, but C slots).
|
| 127 |
+
for filter in self.get_filters(include_self_names=False):
|
| 128 |
+
names = filter.get(name)
|
| 129 |
+
if names:
|
| 130 |
+
return names
|
| 131 |
+
return []
|
| 132 |
+
|
| 133 |
+
def execute_function_slots(self, names, *inferred_args):
|
| 134 |
+
return ValueSet.from_sets(
|
| 135 |
+
name.infer().execute_with_values(*inferred_args)
|
| 136 |
+
for name in names
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
def get_type_hint(self, add_class_info=True):
|
| 140 |
+
return self.py__name__()
|
| 141 |
+
|
| 142 |
+
def py__getitem__(self, index_value_set, contextualized_node):
|
| 143 |
+
names = self.get_function_slot_names('__getitem__')
|
| 144 |
+
if not names:
|
| 145 |
+
return super().py__getitem__(
|
| 146 |
+
index_value_set,
|
| 147 |
+
contextualized_node,
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
args = ValuesArguments([index_value_set])
|
| 151 |
+
return ValueSet.from_sets(name.infer().execute(args) for name in names)
|
| 152 |
+
|
| 153 |
+
def py__iter__(self, contextualized_node=None):
|
| 154 |
+
iter_slot_names = self.get_function_slot_names('__iter__')
|
| 155 |
+
if not iter_slot_names:
|
| 156 |
+
return super().py__iter__(contextualized_node)
|
| 157 |
+
|
| 158 |
+
def iterate():
|
| 159 |
+
for generator in self.execute_function_slots(iter_slot_names):
|
| 160 |
+
yield from generator.py__next__(contextualized_node)
|
| 161 |
+
return iterate()
|
| 162 |
+
|
| 163 |
+
def __repr__(self):
|
| 164 |
+
return "<%s of %s>" % (self.__class__.__name__, self.class_value)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
class CompiledInstance(AbstractInstanceValue):
|
| 168 |
+
# This is not really a compiled class, it's just an instance from a
|
| 169 |
+
# compiled class.
|
| 170 |
+
def __init__(self, inference_state, parent_context, class_value, arguments):
|
| 171 |
+
super().__init__(inference_state, parent_context, class_value)
|
| 172 |
+
self._arguments = arguments
|
| 173 |
+
|
| 174 |
+
def get_filters(self, origin_scope=None, include_self_names=True):
|
| 175 |
+
class_value = self.get_annotated_class_object()
|
| 176 |
+
class_filters = class_value.get_filters(
|
| 177 |
+
origin_scope=origin_scope,
|
| 178 |
+
is_instance=True,
|
| 179 |
+
)
|
| 180 |
+
for f in class_filters:
|
| 181 |
+
yield CompiledInstanceClassFilter(self, f)
|
| 182 |
+
|
| 183 |
+
@property
|
| 184 |
+
def name(self):
|
| 185 |
+
return compiled.CompiledValueName(self, self.class_value.name.string_name)
|
| 186 |
+
|
| 187 |
+
def is_stub(self):
|
| 188 |
+
return False
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
class _BaseTreeInstance(AbstractInstanceValue):
|
| 192 |
+
@property
|
| 193 |
+
def array_type(self):
|
| 194 |
+
name = self.class_value.py__name__()
|
| 195 |
+
if name in ['list', 'set', 'dict'] \
|
| 196 |
+
and self.parent_context.get_root_context().is_builtins_module():
|
| 197 |
+
return name
|
| 198 |
+
return None
|
| 199 |
+
|
| 200 |
+
@property
|
| 201 |
+
def name(self):
|
| 202 |
+
return ValueName(self, self.class_value.name.tree_name)
|
| 203 |
+
|
| 204 |
+
def get_filters(self, origin_scope=None, include_self_names=True):
|
| 205 |
+
class_value = self.get_annotated_class_object()
|
| 206 |
+
if include_self_names:
|
| 207 |
+
for cls in class_value.py__mro__():
|
| 208 |
+
if not cls.is_compiled():
|
| 209 |
+
# In this case we're excluding compiled objects that are
|
| 210 |
+
# not fake objects. It doesn't make sense for normal
|
| 211 |
+
# compiled objects to search for self variables.
|
| 212 |
+
yield SelfAttributeFilter(self, class_value, cls.as_context(), origin_scope)
|
| 213 |
+
|
| 214 |
+
class_filters = class_value.get_filters(
|
| 215 |
+
origin_scope=origin_scope,
|
| 216 |
+
is_instance=True,
|
| 217 |
+
)
|
| 218 |
+
for f in class_filters:
|
| 219 |
+
if isinstance(f, ClassFilter):
|
| 220 |
+
yield InstanceClassFilter(self, f)
|
| 221 |
+
elif isinstance(f, CompiledValueFilter):
|
| 222 |
+
yield CompiledInstanceClassFilter(self, f)
|
| 223 |
+
else:
|
| 224 |
+
# Propably from the metaclass.
|
| 225 |
+
yield f
|
| 226 |
+
|
| 227 |
+
@inference_state_method_cache()
|
| 228 |
+
def create_instance_context(self, class_context, node):
|
| 229 |
+
new = node
|
| 230 |
+
while True:
|
| 231 |
+
func_node = new
|
| 232 |
+
new = search_ancestor(new, 'funcdef', 'classdef')
|
| 233 |
+
if class_context.tree_node is new:
|
| 234 |
+
func = FunctionValue.from_context(class_context, func_node)
|
| 235 |
+
bound_method = BoundMethod(self, class_context, func)
|
| 236 |
+
if func_node.name.value == '__init__':
|
| 237 |
+
context = bound_method.as_context(self._arguments)
|
| 238 |
+
else:
|
| 239 |
+
context = bound_method.as_context()
|
| 240 |
+
break
|
| 241 |
+
return context.create_context(node)
|
| 242 |
+
|
| 243 |
+
def py__getattribute__alternatives(self, string_name):
|
| 244 |
+
'''
|
| 245 |
+
Since nothing was inferred, now check the __getattr__ and
|
| 246 |
+
__getattribute__ methods. Stubs don't need to be checked, because
|
| 247 |
+
they don't contain any logic.
|
| 248 |
+
'''
|
| 249 |
+
if self.is_stub():
|
| 250 |
+
return NO_VALUES
|
| 251 |
+
|
| 252 |
+
name = compiled.create_simple_object(self.inference_state, string_name)
|
| 253 |
+
|
| 254 |
+
# This is a little bit special. `__getattribute__` is in Python
|
| 255 |
+
# executed before `__getattr__`. But: I know no use case, where
|
| 256 |
+
# this could be practical and where Jedi would return wrong types.
|
| 257 |
+
# If you ever find something, let me know!
|
| 258 |
+
# We are inversing this, because a hand-crafted `__getattribute__`
|
| 259 |
+
# could still call another hand-crafted `__getattr__`, but not the
|
| 260 |
+
# other way around.
|
| 261 |
+
if is_big_annoying_library(self.parent_context):
|
| 262 |
+
return NO_VALUES
|
| 263 |
+
names = (self.get_function_slot_names('__getattr__')
|
| 264 |
+
or self.get_function_slot_names('__getattribute__'))
|
| 265 |
+
return self.execute_function_slots(names, name)
|
| 266 |
+
|
| 267 |
+
def py__next__(self, contextualized_node=None):
|
| 268 |
+
name = u'__next__'
|
| 269 |
+
next_slot_names = self.get_function_slot_names(name)
|
| 270 |
+
if next_slot_names:
|
| 271 |
+
yield LazyKnownValues(
|
| 272 |
+
self.execute_function_slots(next_slot_names)
|
| 273 |
+
)
|
| 274 |
+
else:
|
| 275 |
+
debug.warning('Instance has no __next__ function in %s.', self)
|
| 276 |
+
|
| 277 |
+
def py__call__(self, arguments):
|
| 278 |
+
names = self.get_function_slot_names('__call__')
|
| 279 |
+
if not names:
|
| 280 |
+
# Means the Instance is not callable.
|
| 281 |
+
return super().py__call__(arguments)
|
| 282 |
+
|
| 283 |
+
return ValueSet.from_sets(name.infer().execute(arguments) for name in names)
|
| 284 |
+
|
| 285 |
+
def py__get__(self, instance, class_value):
|
| 286 |
+
"""
|
| 287 |
+
obj may be None.
|
| 288 |
+
"""
|
| 289 |
+
# Arguments in __get__ descriptors are obj, class.
|
| 290 |
+
# `method` is the new parent of the array, don't know if that's good.
|
| 291 |
+
for cls in self.class_value.py__mro__():
|
| 292 |
+
result = cls.py__get__on_class(self, instance, class_value)
|
| 293 |
+
if result is not NotImplemented:
|
| 294 |
+
return result
|
| 295 |
+
|
| 296 |
+
names = self.get_function_slot_names('__get__')
|
| 297 |
+
if names:
|
| 298 |
+
if instance is None:
|
| 299 |
+
instance = compiled.builtin_from_name(self.inference_state, 'None')
|
| 300 |
+
return self.execute_function_slots(names, instance, class_value)
|
| 301 |
+
else:
|
| 302 |
+
return ValueSet([self])
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
class TreeInstance(_BaseTreeInstance):
|
| 306 |
+
def __init__(self, inference_state, parent_context, class_value, arguments):
|
| 307 |
+
# I don't think that dynamic append lookups should happen here. That
|
| 308 |
+
# sounds more like something that should go to py__iter__.
|
| 309 |
+
if class_value.py__name__() in ['list', 'set'] \
|
| 310 |
+
and parent_context.get_root_context().is_builtins_module():
|
| 311 |
+
# compare the module path with the builtin name.
|
| 312 |
+
if settings.dynamic_array_additions:
|
| 313 |
+
arguments = get_dynamic_array_instance(self, arguments)
|
| 314 |
+
|
| 315 |
+
super().__init__(inference_state, parent_context, class_value)
|
| 316 |
+
self._arguments = arguments
|
| 317 |
+
self.tree_node = class_value.tree_node
|
| 318 |
+
|
| 319 |
+
# This can recurse, if the initialization of the class includes a reference
|
| 320 |
+
# to itself.
|
| 321 |
+
@inference_state_method_cache(default=None)
|
| 322 |
+
def _get_annotated_class_object(self):
|
| 323 |
+
from jedi.inference.gradual.annotation import py__annotations__, \
|
| 324 |
+
infer_type_vars_for_execution
|
| 325 |
+
|
| 326 |
+
args = InstanceArguments(self, self._arguments)
|
| 327 |
+
for signature in self.class_value.py__getattribute__('__init__').get_signatures():
|
| 328 |
+
# Just take the first result, it should always be one, because we
|
| 329 |
+
# control the typeshed code.
|
| 330 |
+
funcdef = signature.value.tree_node
|
| 331 |
+
if funcdef is None or funcdef.type != 'funcdef' \
|
| 332 |
+
or not signature.matches_signature(args):
|
| 333 |
+
# First check if the signature even matches, if not we don't
|
| 334 |
+
# need to infer anything.
|
| 335 |
+
continue
|
| 336 |
+
bound_method = BoundMethod(self, self.class_value.as_context(), signature.value)
|
| 337 |
+
all_annotations = py__annotations__(funcdef)
|
| 338 |
+
type_var_dict = infer_type_vars_for_execution(bound_method, args, all_annotations)
|
| 339 |
+
if type_var_dict:
|
| 340 |
+
defined, = self.class_value.define_generics(
|
| 341 |
+
infer_type_vars_for_execution(signature.value, args, all_annotations),
|
| 342 |
+
)
|
| 343 |
+
debug.dbg('Inferred instance value as %s', defined, color='BLUE')
|
| 344 |
+
return defined
|
| 345 |
+
return None
|
| 346 |
+
|
| 347 |
+
def get_annotated_class_object(self):
|
| 348 |
+
return self._get_annotated_class_object() or self.class_value
|
| 349 |
+
|
| 350 |
+
def get_key_values(self):
|
| 351 |
+
values = NO_VALUES
|
| 352 |
+
if self.array_type == 'dict':
|
| 353 |
+
for i, (key, instance) in enumerate(self._arguments.unpack()):
|
| 354 |
+
if key is None and i == 0:
|
| 355 |
+
values |= ValueSet.from_sets(
|
| 356 |
+
v.get_key_values()
|
| 357 |
+
for v in instance.infer()
|
| 358 |
+
if v.array_type == 'dict'
|
| 359 |
+
)
|
| 360 |
+
if key:
|
| 361 |
+
values |= ValueSet([compiled.create_simple_object(
|
| 362 |
+
self.inference_state,
|
| 363 |
+
key,
|
| 364 |
+
)])
|
| 365 |
+
|
| 366 |
+
return values
|
| 367 |
+
|
| 368 |
+
def py__simple_getitem__(self, index):
|
| 369 |
+
if self.array_type == 'dict':
|
| 370 |
+
# Logic for dict({'foo': bar}) and dict(foo=bar)
|
| 371 |
+
# reversed, because:
|
| 372 |
+
# >>> dict({'a': 1}, a=3)
|
| 373 |
+
# {'a': 3}
|
| 374 |
+
# TODO tuple initializations
|
| 375 |
+
# >>> dict([('a', 4)])
|
| 376 |
+
# {'a': 4}
|
| 377 |
+
for key, lazy_context in reversed(list(self._arguments.unpack())):
|
| 378 |
+
if key is None:
|
| 379 |
+
values = ValueSet.from_sets(
|
| 380 |
+
dct_value.py__simple_getitem__(index)
|
| 381 |
+
for dct_value in lazy_context.infer()
|
| 382 |
+
if dct_value.array_type == 'dict'
|
| 383 |
+
)
|
| 384 |
+
if values:
|
| 385 |
+
return values
|
| 386 |
+
else:
|
| 387 |
+
if key == index:
|
| 388 |
+
return lazy_context.infer()
|
| 389 |
+
return super().py__simple_getitem__(index)
|
| 390 |
+
|
| 391 |
+
def __repr__(self):
|
| 392 |
+
return "<%s of %s(%s)>" % (self.__class__.__name__, self.class_value,
|
| 393 |
+
self._arguments)
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
class AnonymousInstance(_BaseTreeInstance):
|
| 397 |
+
_arguments = None
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
class CompiledInstanceName(NameWrapper):
|
| 401 |
+
@iterator_to_value_set
|
| 402 |
+
def infer(self):
|
| 403 |
+
for result_value in self._wrapped_name.infer():
|
| 404 |
+
if result_value.api_type == 'function':
|
| 405 |
+
yield CompiledBoundMethod(result_value)
|
| 406 |
+
else:
|
| 407 |
+
yield result_value
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
class CompiledInstanceClassFilter(AbstractFilter):
|
| 411 |
+
def __init__(self, instance, f):
|
| 412 |
+
self._instance = instance
|
| 413 |
+
self._class_filter = f
|
| 414 |
+
|
| 415 |
+
def get(self, name):
|
| 416 |
+
return self._convert(self._class_filter.get(name))
|
| 417 |
+
|
| 418 |
+
def values(self):
|
| 419 |
+
return self._convert(self._class_filter.values())
|
| 420 |
+
|
| 421 |
+
def _convert(self, names):
|
| 422 |
+
return [CompiledInstanceName(n) for n in names]
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
class BoundMethod(FunctionMixin, ValueWrapper):
|
| 426 |
+
def __init__(self, instance, class_context, function):
|
| 427 |
+
super().__init__(function)
|
| 428 |
+
self.instance = instance
|
| 429 |
+
self._class_context = class_context
|
| 430 |
+
|
| 431 |
+
def is_bound_method(self):
|
| 432 |
+
return True
|
| 433 |
+
|
| 434 |
+
@property
|
| 435 |
+
def name(self):
|
| 436 |
+
return FunctionNameInClass(
|
| 437 |
+
self._class_context,
|
| 438 |
+
super().name
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
def py__class__(self):
|
| 442 |
+
c, = values_from_qualified_names(self.inference_state, 'types', 'MethodType')
|
| 443 |
+
return c
|
| 444 |
+
|
| 445 |
+
def _get_arguments(self, arguments):
|
| 446 |
+
assert arguments is not None
|
| 447 |
+
return InstanceArguments(self.instance, arguments)
|
| 448 |
+
|
| 449 |
+
def _as_context(self, arguments=None):
|
| 450 |
+
if arguments is None:
|
| 451 |
+
return AnonymousMethodExecutionContext(self.instance, self)
|
| 452 |
+
|
| 453 |
+
arguments = self._get_arguments(arguments)
|
| 454 |
+
return MethodExecutionContext(self.instance, self, arguments)
|
| 455 |
+
|
| 456 |
+
def py__call__(self, arguments):
|
| 457 |
+
if isinstance(self._wrapped_value, OverloadedFunctionValue):
|
| 458 |
+
return self._wrapped_value.py__call__(self._get_arguments(arguments))
|
| 459 |
+
|
| 460 |
+
function_execution = self.as_context(arguments)
|
| 461 |
+
return function_execution.infer()
|
| 462 |
+
|
| 463 |
+
def get_signature_functions(self):
|
| 464 |
+
return [
|
| 465 |
+
BoundMethod(self.instance, self._class_context, f)
|
| 466 |
+
for f in self._wrapped_value.get_signature_functions()
|
| 467 |
+
]
|
| 468 |
+
|
| 469 |
+
def get_signatures(self):
|
| 470 |
+
return [sig.bind(self) for sig in super().get_signatures()]
|
| 471 |
+
|
| 472 |
+
def __repr__(self):
|
| 473 |
+
return '<%s: %s>' % (self.__class__.__name__, self._wrapped_value)
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
class CompiledBoundMethod(ValueWrapper):
|
| 477 |
+
def is_bound_method(self):
|
| 478 |
+
return True
|
| 479 |
+
|
| 480 |
+
def get_signatures(self):
|
| 481 |
+
return [sig.bind(self) for sig in self._wrapped_value.get_signatures()]
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
class SelfName(TreeNameDefinition):
|
| 485 |
+
"""
|
| 486 |
+
This name calculates the parent_context lazily.
|
| 487 |
+
"""
|
| 488 |
+
def __init__(self, instance, class_context, tree_name):
|
| 489 |
+
self._instance = instance
|
| 490 |
+
self.class_context = class_context
|
| 491 |
+
self.tree_name = tree_name
|
| 492 |
+
|
| 493 |
+
@property
|
| 494 |
+
def parent_context(self):
|
| 495 |
+
return self._instance.create_instance_context(self.class_context, self.tree_name)
|
| 496 |
+
|
| 497 |
+
def get_defining_qualified_value(self):
|
| 498 |
+
return self._instance
|
| 499 |
+
|
| 500 |
+
def infer(self):
|
| 501 |
+
stmt = search_ancestor(self.tree_name, 'expr_stmt')
|
| 502 |
+
if stmt is not None:
|
| 503 |
+
if stmt.children[1].type == "annassign":
|
| 504 |
+
from jedi.inference.gradual.annotation import infer_annotation
|
| 505 |
+
values = infer_annotation(
|
| 506 |
+
self.parent_context, stmt.children[1].children[1]
|
| 507 |
+
).execute_annotation()
|
| 508 |
+
if values:
|
| 509 |
+
return values
|
| 510 |
+
return super().infer()
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
class LazyInstanceClassName(NameWrapper):
|
| 514 |
+
def __init__(self, instance, class_member_name):
|
| 515 |
+
super().__init__(class_member_name)
|
| 516 |
+
self._instance = instance
|
| 517 |
+
|
| 518 |
+
@iterator_to_value_set
|
| 519 |
+
def infer(self):
|
| 520 |
+
for result_value in self._wrapped_name.infer():
|
| 521 |
+
yield from result_value.py__get__(self._instance, self._instance.py__class__())
|
| 522 |
+
|
| 523 |
+
def get_signatures(self):
|
| 524 |
+
return self.infer().get_signatures()
|
| 525 |
+
|
| 526 |
+
def get_defining_qualified_value(self):
|
| 527 |
+
return self._instance
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
class InstanceClassFilter(AbstractFilter):
|
| 531 |
+
"""
|
| 532 |
+
This filter is special in that it uses the class filter and wraps the
|
| 533 |
+
resulting names in LazyInstanceClassName. The idea is that the class name
|
| 534 |
+
filtering can be very flexible and always be reflected in instances.
|
| 535 |
+
"""
|
| 536 |
+
def __init__(self, instance, class_filter):
|
| 537 |
+
self._instance = instance
|
| 538 |
+
self._class_filter = class_filter
|
| 539 |
+
|
| 540 |
+
def get(self, name):
|
| 541 |
+
return self._convert(self._class_filter.get(name))
|
| 542 |
+
|
| 543 |
+
def values(self):
|
| 544 |
+
return self._convert(self._class_filter.values())
|
| 545 |
+
|
| 546 |
+
def _convert(self, names):
|
| 547 |
+
return [
|
| 548 |
+
LazyInstanceClassName(self._instance, n)
|
| 549 |
+
for n in names
|
| 550 |
+
]
|
| 551 |
+
|
| 552 |
+
def __repr__(self):
|
| 553 |
+
return '<%s for %s>' % (self.__class__.__name__, self._class_filter)
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
class SelfAttributeFilter(ClassFilter):
|
| 557 |
+
"""
|
| 558 |
+
This class basically filters all the use cases where `self.*` was assigned.
|
| 559 |
+
"""
|
| 560 |
+
def __init__(self, instance, instance_class, node_context, origin_scope):
|
| 561 |
+
super().__init__(
|
| 562 |
+
class_value=instance_class,
|
| 563 |
+
node_context=node_context,
|
| 564 |
+
origin_scope=origin_scope,
|
| 565 |
+
is_instance=True,
|
| 566 |
+
)
|
| 567 |
+
self._instance = instance
|
| 568 |
+
|
| 569 |
+
def _filter(self, names):
|
| 570 |
+
start, end = self._parser_scope.start_pos, self._parser_scope.end_pos
|
| 571 |
+
names = [n for n in names if start < n.start_pos < end]
|
| 572 |
+
return self._filter_self_names(names)
|
| 573 |
+
|
| 574 |
+
def _filter_self_names(self, names):
|
| 575 |
+
for name in names:
|
| 576 |
+
trailer = name.parent
|
| 577 |
+
if trailer.type == 'trailer' \
|
| 578 |
+
and len(trailer.parent.children) == 2 \
|
| 579 |
+
and trailer.children[0] == '.':
|
| 580 |
+
if name.is_definition() and self._access_possible(name):
|
| 581 |
+
# TODO filter non-self assignments instead of this bad
|
| 582 |
+
# filter.
|
| 583 |
+
if self._is_in_right_scope(trailer.parent.children[0], name):
|
| 584 |
+
yield name
|
| 585 |
+
|
| 586 |
+
def _is_in_right_scope(self, self_name, name):
|
| 587 |
+
self_context = self._node_context.create_context(self_name)
|
| 588 |
+
names = self_context.goto(self_name, position=self_name.start_pos)
|
| 589 |
+
return any(
|
| 590 |
+
n.api_type == 'param'
|
| 591 |
+
and n.tree_name.get_definition().position_index == 0
|
| 592 |
+
and n.parent_context.tree_node is self._parser_scope
|
| 593 |
+
for n in names
|
| 594 |
+
)
|
| 595 |
+
|
| 596 |
+
def _convert_names(self, names):
|
| 597 |
+
return [SelfName(self._instance, self._node_context, name) for name in names]
|
| 598 |
+
|
| 599 |
+
def _check_flows(self, names):
|
| 600 |
+
return names
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
class InstanceArguments(TreeArgumentsWrapper):
|
| 604 |
+
def __init__(self, instance, arguments):
|
| 605 |
+
super().__init__(arguments)
|
| 606 |
+
self.instance = instance
|
| 607 |
+
|
| 608 |
+
def unpack(self, func=None):
|
| 609 |
+
yield None, LazyKnownValue(self.instance)
|
| 610 |
+
yield from self._wrapped_arguments.unpack(func)
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/value/iterable.py
ADDED
|
@@ -0,0 +1,647 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Contains all classes and functions to deal with lists, dicts, generators and
|
| 3 |
+
iterators in general.
|
| 4 |
+
"""
|
| 5 |
+
from jedi.inference import compiled
|
| 6 |
+
from jedi.inference import analysis
|
| 7 |
+
from jedi.inference.lazy_value import LazyKnownValue, LazyKnownValues, \
|
| 8 |
+
LazyTreeValue
|
| 9 |
+
from jedi.inference.helpers import get_int_or_none, is_string, \
|
| 10 |
+
reraise_getitem_errors, SimpleGetItemNotFound
|
| 11 |
+
from jedi.inference.utils import safe_property, to_list
|
| 12 |
+
from jedi.inference.cache import inference_state_method_cache
|
| 13 |
+
from jedi.inference.filters import LazyAttributeOverwrite, publish_method
|
| 14 |
+
from jedi.inference.base_value import ValueSet, Value, NO_VALUES, \
|
| 15 |
+
ContextualizedNode, iterate_values, sentinel, \
|
| 16 |
+
LazyValueWrapper
|
| 17 |
+
from jedi.parser_utils import get_sync_comp_fors
|
| 18 |
+
from jedi.inference.context import CompForContext
|
| 19 |
+
from jedi.inference.value.dynamic_arrays import check_array_additions
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class IterableMixin:
|
| 23 |
+
def py__next__(self, contextualized_node=None):
|
| 24 |
+
return self.py__iter__(contextualized_node)
|
| 25 |
+
|
| 26 |
+
def py__stop_iteration_returns(self):
|
| 27 |
+
return ValueSet([compiled.builtin_from_name(self.inference_state, 'None')])
|
| 28 |
+
|
| 29 |
+
# At the moment, safe values are simple values like "foo", 1 and not
|
| 30 |
+
# lists/dicts. Therefore as a small speed optimization we can just do the
|
| 31 |
+
# default instead of resolving the lazy wrapped values, that are just
|
| 32 |
+
# doing this in the end as well.
|
| 33 |
+
# This mostly speeds up patterns like `sys.version_info >= (3, 0)` in
|
| 34 |
+
# typeshed.
|
| 35 |
+
get_safe_value = Value.get_safe_value
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class GeneratorBase(LazyAttributeOverwrite, IterableMixin):
|
| 39 |
+
array_type = None
|
| 40 |
+
|
| 41 |
+
def _get_wrapped_value(self):
|
| 42 |
+
instance, = self._get_cls().execute_annotation()
|
| 43 |
+
return instance
|
| 44 |
+
|
| 45 |
+
def _get_cls(self):
|
| 46 |
+
generator, = self.inference_state.typing_module.py__getattribute__('Generator')
|
| 47 |
+
return generator
|
| 48 |
+
|
| 49 |
+
def py__bool__(self):
|
| 50 |
+
return True
|
| 51 |
+
|
| 52 |
+
@publish_method('__iter__')
|
| 53 |
+
def _iter(self, arguments):
|
| 54 |
+
return ValueSet([self])
|
| 55 |
+
|
| 56 |
+
@publish_method('send')
|
| 57 |
+
@publish_method('__next__')
|
| 58 |
+
def _next(self, arguments):
|
| 59 |
+
return ValueSet.from_sets(lazy_value.infer() for lazy_value in self.py__iter__())
|
| 60 |
+
|
| 61 |
+
def py__stop_iteration_returns(self):
|
| 62 |
+
return ValueSet([compiled.builtin_from_name(self.inference_state, 'None')])
|
| 63 |
+
|
| 64 |
+
@property
|
| 65 |
+
def name(self):
|
| 66 |
+
return compiled.CompiledValueName(self, 'Generator')
|
| 67 |
+
|
| 68 |
+
def get_annotated_class_object(self):
|
| 69 |
+
from jedi.inference.gradual.generics import TupleGenericManager
|
| 70 |
+
gen_values = self.merge_types_of_iterate().py__class__()
|
| 71 |
+
gm = TupleGenericManager((gen_values, NO_VALUES, NO_VALUES))
|
| 72 |
+
return self._get_cls().with_generics(gm)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class Generator(GeneratorBase):
|
| 76 |
+
"""Handling of `yield` functions."""
|
| 77 |
+
def __init__(self, inference_state, func_execution_context):
|
| 78 |
+
super().__init__(inference_state)
|
| 79 |
+
self._func_execution_context = func_execution_context
|
| 80 |
+
|
| 81 |
+
def py__iter__(self, contextualized_node=None):
|
| 82 |
+
iterators = self._func_execution_context.infer_annotations()
|
| 83 |
+
if iterators:
|
| 84 |
+
return iterators.iterate(contextualized_node)
|
| 85 |
+
return self._func_execution_context.get_yield_lazy_values()
|
| 86 |
+
|
| 87 |
+
def py__stop_iteration_returns(self):
|
| 88 |
+
return self._func_execution_context.get_return_values()
|
| 89 |
+
|
| 90 |
+
def __repr__(self):
|
| 91 |
+
return "<%s of %s>" % (type(self).__name__, self._func_execution_context)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def comprehension_from_atom(inference_state, value, atom):
|
| 95 |
+
bracket = atom.children[0]
|
| 96 |
+
test_list_comp = atom.children[1]
|
| 97 |
+
|
| 98 |
+
if bracket == '{':
|
| 99 |
+
if atom.children[1].children[1] == ':':
|
| 100 |
+
sync_comp_for = test_list_comp.children[3]
|
| 101 |
+
if sync_comp_for.type == 'comp_for':
|
| 102 |
+
sync_comp_for = sync_comp_for.children[1]
|
| 103 |
+
|
| 104 |
+
return DictComprehension(
|
| 105 |
+
inference_state,
|
| 106 |
+
value,
|
| 107 |
+
sync_comp_for_node=sync_comp_for,
|
| 108 |
+
key_node=test_list_comp.children[0],
|
| 109 |
+
value_node=test_list_comp.children[2],
|
| 110 |
+
)
|
| 111 |
+
else:
|
| 112 |
+
cls = SetComprehension
|
| 113 |
+
elif bracket == '(':
|
| 114 |
+
cls = GeneratorComprehension
|
| 115 |
+
elif bracket == '[':
|
| 116 |
+
cls = ListComprehension
|
| 117 |
+
|
| 118 |
+
sync_comp_for = test_list_comp.children[1]
|
| 119 |
+
if sync_comp_for.type == 'comp_for':
|
| 120 |
+
sync_comp_for = sync_comp_for.children[1]
|
| 121 |
+
|
| 122 |
+
return cls(
|
| 123 |
+
inference_state,
|
| 124 |
+
defining_context=value,
|
| 125 |
+
sync_comp_for_node=sync_comp_for,
|
| 126 |
+
entry_node=test_list_comp.children[0],
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class ComprehensionMixin:
|
| 131 |
+
@inference_state_method_cache()
|
| 132 |
+
def _get_comp_for_context(self, parent_context, comp_for):
|
| 133 |
+
return CompForContext(parent_context, comp_for)
|
| 134 |
+
|
| 135 |
+
def _nested(self, comp_fors, parent_context=None):
|
| 136 |
+
comp_for = comp_fors[0]
|
| 137 |
+
|
| 138 |
+
is_async = comp_for.parent.type == 'comp_for'
|
| 139 |
+
|
| 140 |
+
input_node = comp_for.children[3]
|
| 141 |
+
parent_context = parent_context or self._defining_context
|
| 142 |
+
input_types = parent_context.infer_node(input_node)
|
| 143 |
+
|
| 144 |
+
cn = ContextualizedNode(parent_context, input_node)
|
| 145 |
+
iterated = input_types.iterate(cn, is_async=is_async)
|
| 146 |
+
exprlist = comp_for.children[1]
|
| 147 |
+
for i, lazy_value in enumerate(iterated):
|
| 148 |
+
types = lazy_value.infer()
|
| 149 |
+
dct = unpack_tuple_to_dict(parent_context, types, exprlist)
|
| 150 |
+
context = self._get_comp_for_context(
|
| 151 |
+
parent_context,
|
| 152 |
+
comp_for,
|
| 153 |
+
)
|
| 154 |
+
with context.predefine_names(comp_for, dct):
|
| 155 |
+
try:
|
| 156 |
+
yield from self._nested(comp_fors[1:], context)
|
| 157 |
+
except IndexError:
|
| 158 |
+
iterated = context.infer_node(self._entry_node)
|
| 159 |
+
if self.array_type == 'dict':
|
| 160 |
+
yield iterated, context.infer_node(self._value_node)
|
| 161 |
+
else:
|
| 162 |
+
yield iterated
|
| 163 |
+
|
| 164 |
+
@inference_state_method_cache(default=[])
|
| 165 |
+
@to_list
|
| 166 |
+
def _iterate(self):
|
| 167 |
+
comp_fors = tuple(get_sync_comp_fors(self._sync_comp_for_node))
|
| 168 |
+
yield from self._nested(comp_fors)
|
| 169 |
+
|
| 170 |
+
def py__iter__(self, contextualized_node=None):
|
| 171 |
+
for set_ in self._iterate():
|
| 172 |
+
yield LazyKnownValues(set_)
|
| 173 |
+
|
| 174 |
+
def __repr__(self):
|
| 175 |
+
return "<%s of %s>" % (type(self).__name__, self._sync_comp_for_node)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class _DictMixin:
|
| 179 |
+
def _get_generics(self):
|
| 180 |
+
return tuple(c_set.py__class__() for c_set in self.get_mapping_item_values())
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
class Sequence(LazyAttributeOverwrite, IterableMixin):
|
| 184 |
+
api_type = 'instance'
|
| 185 |
+
|
| 186 |
+
@property
|
| 187 |
+
def name(self):
|
| 188 |
+
return compiled.CompiledValueName(self, self.array_type)
|
| 189 |
+
|
| 190 |
+
def _get_generics(self):
|
| 191 |
+
return (self.merge_types_of_iterate().py__class__(),)
|
| 192 |
+
|
| 193 |
+
@inference_state_method_cache(default=())
|
| 194 |
+
def _cached_generics(self):
|
| 195 |
+
return self._get_generics()
|
| 196 |
+
|
| 197 |
+
def _get_wrapped_value(self):
|
| 198 |
+
from jedi.inference.gradual.base import GenericClass
|
| 199 |
+
from jedi.inference.gradual.generics import TupleGenericManager
|
| 200 |
+
klass = compiled.builtin_from_name(self.inference_state, self.array_type)
|
| 201 |
+
c, = GenericClass(
|
| 202 |
+
klass,
|
| 203 |
+
TupleGenericManager(self._cached_generics())
|
| 204 |
+
).execute_annotation()
|
| 205 |
+
return c
|
| 206 |
+
|
| 207 |
+
def py__bool__(self):
|
| 208 |
+
return None # We don't know the length, because of appends.
|
| 209 |
+
|
| 210 |
+
@safe_property
|
| 211 |
+
def parent(self):
|
| 212 |
+
return self.inference_state.builtins_module
|
| 213 |
+
|
| 214 |
+
def py__getitem__(self, index_value_set, contextualized_node):
|
| 215 |
+
if self.array_type == 'dict':
|
| 216 |
+
return self._dict_values()
|
| 217 |
+
return iterate_values(ValueSet([self]))
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class _BaseComprehension(ComprehensionMixin):
|
| 221 |
+
def __init__(self, inference_state, defining_context, sync_comp_for_node, entry_node):
|
| 222 |
+
assert sync_comp_for_node.type == 'sync_comp_for'
|
| 223 |
+
super().__init__(inference_state)
|
| 224 |
+
self._defining_context = defining_context
|
| 225 |
+
self._sync_comp_for_node = sync_comp_for_node
|
| 226 |
+
self._entry_node = entry_node
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
class ListComprehension(_BaseComprehension, Sequence):
|
| 230 |
+
array_type = 'list'
|
| 231 |
+
|
| 232 |
+
def py__simple_getitem__(self, index):
|
| 233 |
+
if isinstance(index, slice):
|
| 234 |
+
return ValueSet([self])
|
| 235 |
+
|
| 236 |
+
all_types = list(self.py__iter__())
|
| 237 |
+
with reraise_getitem_errors(IndexError, TypeError):
|
| 238 |
+
lazy_value = all_types[index]
|
| 239 |
+
return lazy_value.infer()
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
class SetComprehension(_BaseComprehension, Sequence):
|
| 243 |
+
array_type = 'set'
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
class GeneratorComprehension(_BaseComprehension, GeneratorBase):
|
| 247 |
+
pass
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
class _DictKeyMixin:
|
| 251 |
+
# TODO merge with _DictMixin?
|
| 252 |
+
def get_mapping_item_values(self):
|
| 253 |
+
return self._dict_keys(), self._dict_values()
|
| 254 |
+
|
| 255 |
+
def get_key_values(self):
|
| 256 |
+
# TODO merge with _dict_keys?
|
| 257 |
+
return self._dict_keys()
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
class DictComprehension(ComprehensionMixin, Sequence, _DictKeyMixin):
|
| 261 |
+
array_type = 'dict'
|
| 262 |
+
|
| 263 |
+
def __init__(self, inference_state, defining_context, sync_comp_for_node, key_node, value_node):
|
| 264 |
+
assert sync_comp_for_node.type == 'sync_comp_for'
|
| 265 |
+
super().__init__(inference_state)
|
| 266 |
+
self._defining_context = defining_context
|
| 267 |
+
self._sync_comp_for_node = sync_comp_for_node
|
| 268 |
+
self._entry_node = key_node
|
| 269 |
+
self._value_node = value_node
|
| 270 |
+
|
| 271 |
+
def py__iter__(self, contextualized_node=None):
|
| 272 |
+
for keys, values in self._iterate():
|
| 273 |
+
yield LazyKnownValues(keys)
|
| 274 |
+
|
| 275 |
+
def py__simple_getitem__(self, index):
|
| 276 |
+
for keys, values in self._iterate():
|
| 277 |
+
for k in keys:
|
| 278 |
+
# Be careful in the future if refactoring, index could be a
|
| 279 |
+
# slice object.
|
| 280 |
+
if k.get_safe_value(default=object()) == index:
|
| 281 |
+
return values
|
| 282 |
+
raise SimpleGetItemNotFound()
|
| 283 |
+
|
| 284 |
+
def _dict_keys(self):
|
| 285 |
+
return ValueSet.from_sets(keys for keys, values in self._iterate())
|
| 286 |
+
|
| 287 |
+
def _dict_values(self):
|
| 288 |
+
return ValueSet.from_sets(values for keys, values in self._iterate())
|
| 289 |
+
|
| 290 |
+
@publish_method('values')
|
| 291 |
+
def _imitate_values(self, arguments):
|
| 292 |
+
lazy_value = LazyKnownValues(self._dict_values())
|
| 293 |
+
return ValueSet([FakeList(self.inference_state, [lazy_value])])
|
| 294 |
+
|
| 295 |
+
@publish_method('items')
|
| 296 |
+
def _imitate_items(self, arguments):
|
| 297 |
+
lazy_values = [
|
| 298 |
+
LazyKnownValue(
|
| 299 |
+
FakeTuple(
|
| 300 |
+
self.inference_state,
|
| 301 |
+
[LazyKnownValues(key),
|
| 302 |
+
LazyKnownValues(value)]
|
| 303 |
+
)
|
| 304 |
+
)
|
| 305 |
+
for key, value in self._iterate()
|
| 306 |
+
]
|
| 307 |
+
|
| 308 |
+
return ValueSet([FakeList(self.inference_state, lazy_values)])
|
| 309 |
+
|
| 310 |
+
def exact_key_items(self):
|
| 311 |
+
# NOTE: A smarter thing can probably done here to achieve better
|
| 312 |
+
# completions, but at least like this jedi doesn't crash
|
| 313 |
+
return []
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
class SequenceLiteralValue(Sequence):
|
| 317 |
+
_TUPLE_LIKE = 'testlist_star_expr', 'testlist', 'subscriptlist'
|
| 318 |
+
mapping = {'(': 'tuple',
|
| 319 |
+
'[': 'list',
|
| 320 |
+
'{': 'set'}
|
| 321 |
+
|
| 322 |
+
def __init__(self, inference_state, defining_context, atom):
|
| 323 |
+
super().__init__(inference_state)
|
| 324 |
+
self.atom = atom
|
| 325 |
+
self._defining_context = defining_context
|
| 326 |
+
|
| 327 |
+
if self.atom.type in self._TUPLE_LIKE:
|
| 328 |
+
self.array_type = 'tuple'
|
| 329 |
+
else:
|
| 330 |
+
self.array_type = SequenceLiteralValue.mapping[atom.children[0]]
|
| 331 |
+
"""The builtin name of the array (list, set, tuple or dict)."""
|
| 332 |
+
|
| 333 |
+
def _get_generics(self):
|
| 334 |
+
if self.array_type == 'tuple':
|
| 335 |
+
return tuple(x.infer().py__class__() for x in self.py__iter__())
|
| 336 |
+
return super()._get_generics()
|
| 337 |
+
|
| 338 |
+
def py__simple_getitem__(self, index):
|
| 339 |
+
"""Here the index is an int/str. Raises IndexError/KeyError."""
|
| 340 |
+
if isinstance(index, slice):
|
| 341 |
+
return ValueSet([self])
|
| 342 |
+
else:
|
| 343 |
+
with reraise_getitem_errors(TypeError, KeyError, IndexError):
|
| 344 |
+
node = self.get_tree_entries()[index]
|
| 345 |
+
if node == ':' or node.type == 'subscript':
|
| 346 |
+
return NO_VALUES
|
| 347 |
+
return self._defining_context.infer_node(node)
|
| 348 |
+
|
| 349 |
+
def py__iter__(self, contextualized_node=None):
|
| 350 |
+
"""
|
| 351 |
+
While values returns the possible values for any array field, this
|
| 352 |
+
function returns the value for a certain index.
|
| 353 |
+
"""
|
| 354 |
+
for node in self.get_tree_entries():
|
| 355 |
+
if node == ':' or node.type == 'subscript':
|
| 356 |
+
# TODO this should probably use at least part of the code
|
| 357 |
+
# of infer_subscript_list.
|
| 358 |
+
yield LazyKnownValue(Slice(self._defining_context, None, None, None))
|
| 359 |
+
else:
|
| 360 |
+
yield LazyTreeValue(self._defining_context, node)
|
| 361 |
+
yield from check_array_additions(self._defining_context, self)
|
| 362 |
+
|
| 363 |
+
def py__len__(self):
|
| 364 |
+
# This function is not really used often. It's more of a try.
|
| 365 |
+
return len(self.get_tree_entries())
|
| 366 |
+
|
| 367 |
+
def get_tree_entries(self):
|
| 368 |
+
c = self.atom.children
|
| 369 |
+
|
| 370 |
+
if self.atom.type in self._TUPLE_LIKE:
|
| 371 |
+
return c[::2]
|
| 372 |
+
|
| 373 |
+
array_node = c[1]
|
| 374 |
+
if array_node in (']', '}', ')'):
|
| 375 |
+
return [] # Direct closing bracket, doesn't contain items.
|
| 376 |
+
|
| 377 |
+
if array_node.type == 'testlist_comp':
|
| 378 |
+
# filter out (for now) pep 448 single-star unpacking
|
| 379 |
+
return [value for value in array_node.children[::2]
|
| 380 |
+
if value.type != "star_expr"]
|
| 381 |
+
elif array_node.type == 'dictorsetmaker':
|
| 382 |
+
kv = []
|
| 383 |
+
iterator = iter(array_node.children)
|
| 384 |
+
for key in iterator:
|
| 385 |
+
if key == "**":
|
| 386 |
+
# dict with pep 448 double-star unpacking
|
| 387 |
+
# for now ignoring the values imported by **
|
| 388 |
+
next(iterator)
|
| 389 |
+
next(iterator, None) # Possible comma.
|
| 390 |
+
else:
|
| 391 |
+
op = next(iterator, None)
|
| 392 |
+
if op is None or op == ',':
|
| 393 |
+
if key.type == "star_expr":
|
| 394 |
+
# pep 448 single-star unpacking
|
| 395 |
+
# for now ignoring values imported by *
|
| 396 |
+
pass
|
| 397 |
+
else:
|
| 398 |
+
kv.append(key) # A set.
|
| 399 |
+
else:
|
| 400 |
+
assert op == ':' # A dict.
|
| 401 |
+
kv.append((key, next(iterator)))
|
| 402 |
+
next(iterator, None) # Possible comma.
|
| 403 |
+
return kv
|
| 404 |
+
else:
|
| 405 |
+
if array_node.type == "star_expr":
|
| 406 |
+
# pep 448 single-star unpacking
|
| 407 |
+
# for now ignoring values imported by *
|
| 408 |
+
return []
|
| 409 |
+
else:
|
| 410 |
+
return [array_node]
|
| 411 |
+
|
| 412 |
+
def __repr__(self):
|
| 413 |
+
return "<%s of %s>" % (self.__class__.__name__, self.atom)
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
class DictLiteralValue(_DictMixin, SequenceLiteralValue, _DictKeyMixin):
|
| 417 |
+
array_type = 'dict'
|
| 418 |
+
|
| 419 |
+
def __init__(self, inference_state, defining_context, atom):
|
| 420 |
+
# Intentionally don't call the super class. This is definitely a sign
|
| 421 |
+
# that the architecture is bad and we should refactor.
|
| 422 |
+
Sequence.__init__(self, inference_state)
|
| 423 |
+
self._defining_context = defining_context
|
| 424 |
+
self.atom = atom
|
| 425 |
+
|
| 426 |
+
def py__simple_getitem__(self, index):
|
| 427 |
+
"""Here the index is an int/str. Raises IndexError/KeyError."""
|
| 428 |
+
compiled_value_index = compiled.create_simple_object(self.inference_state, index)
|
| 429 |
+
for key, value in self.get_tree_entries():
|
| 430 |
+
for k in self._defining_context.infer_node(key):
|
| 431 |
+
for key_v in k.execute_operation(compiled_value_index, '=='):
|
| 432 |
+
if key_v.get_safe_value():
|
| 433 |
+
return self._defining_context.infer_node(value)
|
| 434 |
+
raise SimpleGetItemNotFound('No key found in dictionary %s.' % self)
|
| 435 |
+
|
| 436 |
+
def py__iter__(self, contextualized_node=None):
|
| 437 |
+
"""
|
| 438 |
+
While values returns the possible values for any array field, this
|
| 439 |
+
function returns the value for a certain index.
|
| 440 |
+
"""
|
| 441 |
+
# Get keys.
|
| 442 |
+
types = NO_VALUES
|
| 443 |
+
for k, _ in self.get_tree_entries():
|
| 444 |
+
types |= self._defining_context.infer_node(k)
|
| 445 |
+
# We don't know which dict index comes first, therefore always
|
| 446 |
+
# yield all the types.
|
| 447 |
+
for _ in types:
|
| 448 |
+
yield LazyKnownValues(types)
|
| 449 |
+
|
| 450 |
+
@publish_method('values')
|
| 451 |
+
def _imitate_values(self, arguments):
|
| 452 |
+
lazy_value = LazyKnownValues(self._dict_values())
|
| 453 |
+
return ValueSet([FakeList(self.inference_state, [lazy_value])])
|
| 454 |
+
|
| 455 |
+
@publish_method('items')
|
| 456 |
+
def _imitate_items(self, arguments):
|
| 457 |
+
lazy_values = [
|
| 458 |
+
LazyKnownValue(FakeTuple(
|
| 459 |
+
self.inference_state,
|
| 460 |
+
(LazyTreeValue(self._defining_context, key_node),
|
| 461 |
+
LazyTreeValue(self._defining_context, value_node))
|
| 462 |
+
)) for key_node, value_node in self.get_tree_entries()
|
| 463 |
+
]
|
| 464 |
+
|
| 465 |
+
return ValueSet([FakeList(self.inference_state, lazy_values)])
|
| 466 |
+
|
| 467 |
+
def exact_key_items(self):
|
| 468 |
+
"""
|
| 469 |
+
Returns a generator of tuples like dict.items(), where the key is
|
| 470 |
+
resolved (as a string) and the values are still lazy values.
|
| 471 |
+
"""
|
| 472 |
+
for key_node, value in self.get_tree_entries():
|
| 473 |
+
for key in self._defining_context.infer_node(key_node):
|
| 474 |
+
if is_string(key):
|
| 475 |
+
yield key.get_safe_value(), LazyTreeValue(self._defining_context, value)
|
| 476 |
+
|
| 477 |
+
def _dict_values(self):
|
| 478 |
+
return ValueSet.from_sets(
|
| 479 |
+
self._defining_context.infer_node(v)
|
| 480 |
+
for k, v in self.get_tree_entries()
|
| 481 |
+
)
|
| 482 |
+
|
| 483 |
+
def _dict_keys(self):
|
| 484 |
+
return ValueSet.from_sets(
|
| 485 |
+
self._defining_context.infer_node(k)
|
| 486 |
+
for k, v in self.get_tree_entries()
|
| 487 |
+
)
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
class _FakeSequence(Sequence):
|
| 491 |
+
def __init__(self, inference_state, lazy_value_list):
|
| 492 |
+
"""
|
| 493 |
+
type should be one of "tuple", "list"
|
| 494 |
+
"""
|
| 495 |
+
super().__init__(inference_state)
|
| 496 |
+
self._lazy_value_list = lazy_value_list
|
| 497 |
+
|
| 498 |
+
def py__simple_getitem__(self, index):
|
| 499 |
+
if isinstance(index, slice):
|
| 500 |
+
return ValueSet([self])
|
| 501 |
+
|
| 502 |
+
with reraise_getitem_errors(IndexError, TypeError):
|
| 503 |
+
lazy_value = self._lazy_value_list[index]
|
| 504 |
+
return lazy_value.infer()
|
| 505 |
+
|
| 506 |
+
def py__iter__(self, contextualized_node=None):
|
| 507 |
+
return self._lazy_value_list
|
| 508 |
+
|
| 509 |
+
def py__bool__(self):
|
| 510 |
+
return bool(len(self._lazy_value_list))
|
| 511 |
+
|
| 512 |
+
def __repr__(self):
|
| 513 |
+
return "<%s of %s>" % (type(self).__name__, self._lazy_value_list)
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
class FakeTuple(_FakeSequence):
|
| 517 |
+
array_type = 'tuple'
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
class FakeList(_FakeSequence):
|
| 521 |
+
array_type = 'tuple'
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
class FakeDict(_DictMixin, Sequence, _DictKeyMixin):
|
| 525 |
+
array_type = 'dict'
|
| 526 |
+
|
| 527 |
+
def __init__(self, inference_state, dct):
|
| 528 |
+
super().__init__(inference_state)
|
| 529 |
+
self._dct = dct
|
| 530 |
+
|
| 531 |
+
def py__iter__(self, contextualized_node=None):
|
| 532 |
+
for key in self._dct:
|
| 533 |
+
yield LazyKnownValue(compiled.create_simple_object(self.inference_state, key))
|
| 534 |
+
|
| 535 |
+
def py__simple_getitem__(self, index):
|
| 536 |
+
with reraise_getitem_errors(KeyError, TypeError):
|
| 537 |
+
lazy_value = self._dct[index]
|
| 538 |
+
return lazy_value.infer()
|
| 539 |
+
|
| 540 |
+
@publish_method('values')
|
| 541 |
+
def _values(self, arguments):
|
| 542 |
+
return ValueSet([FakeTuple(
|
| 543 |
+
self.inference_state,
|
| 544 |
+
[LazyKnownValues(self._dict_values())]
|
| 545 |
+
)])
|
| 546 |
+
|
| 547 |
+
def _dict_values(self):
|
| 548 |
+
return ValueSet.from_sets(lazy_value.infer() for lazy_value in self._dct.values())
|
| 549 |
+
|
| 550 |
+
def _dict_keys(self):
|
| 551 |
+
return ValueSet.from_sets(lazy_value.infer() for lazy_value in self.py__iter__())
|
| 552 |
+
|
| 553 |
+
def exact_key_items(self):
|
| 554 |
+
return self._dct.items()
|
| 555 |
+
|
| 556 |
+
def __repr__(self):
|
| 557 |
+
return '<%s: %s>' % (self.__class__.__name__, self._dct)
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
class MergedArray(Sequence):
|
| 561 |
+
def __init__(self, inference_state, arrays):
|
| 562 |
+
super().__init__(inference_state)
|
| 563 |
+
self.array_type = arrays[-1].array_type
|
| 564 |
+
self._arrays = arrays
|
| 565 |
+
|
| 566 |
+
def py__iter__(self, contextualized_node=None):
|
| 567 |
+
for array in self._arrays:
|
| 568 |
+
yield from array.py__iter__()
|
| 569 |
+
|
| 570 |
+
def py__simple_getitem__(self, index):
|
| 571 |
+
return ValueSet.from_sets(lazy_value.infer() for lazy_value in self.py__iter__())
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
def unpack_tuple_to_dict(context, types, exprlist):
|
| 575 |
+
"""
|
| 576 |
+
Unpacking tuple assignments in for statements and expr_stmts.
|
| 577 |
+
"""
|
| 578 |
+
if exprlist.type == 'name':
|
| 579 |
+
return {exprlist.value: types}
|
| 580 |
+
elif exprlist.type == 'atom' and exprlist.children[0] in ('(', '['):
|
| 581 |
+
return unpack_tuple_to_dict(context, types, exprlist.children[1])
|
| 582 |
+
elif exprlist.type in ('testlist', 'testlist_comp', 'exprlist',
|
| 583 |
+
'testlist_star_expr'):
|
| 584 |
+
dct = {}
|
| 585 |
+
parts = iter(exprlist.children[::2])
|
| 586 |
+
n = 0
|
| 587 |
+
for lazy_value in types.iterate(ContextualizedNode(context, exprlist)):
|
| 588 |
+
n += 1
|
| 589 |
+
try:
|
| 590 |
+
part = next(parts)
|
| 591 |
+
except StopIteration:
|
| 592 |
+
analysis.add(context, 'value-error-too-many-values', part,
|
| 593 |
+
message="ValueError: too many values to unpack (expected %s)" % n)
|
| 594 |
+
else:
|
| 595 |
+
dct.update(unpack_tuple_to_dict(context, lazy_value.infer(), part))
|
| 596 |
+
has_parts = next(parts, None)
|
| 597 |
+
if types and has_parts is not None:
|
| 598 |
+
analysis.add(context, 'value-error-too-few-values', has_parts,
|
| 599 |
+
message="ValueError: need more than %s values to unpack" % n)
|
| 600 |
+
return dct
|
| 601 |
+
elif exprlist.type == 'power' or exprlist.type == 'atom_expr':
|
| 602 |
+
# Something like ``arr[x], var = ...``.
|
| 603 |
+
# This is something that is not yet supported, would also be difficult
|
| 604 |
+
# to write into a dict.
|
| 605 |
+
return {}
|
| 606 |
+
elif exprlist.type == 'star_expr': # `a, *b, c = x` type unpackings
|
| 607 |
+
# Currently we're not supporting them.
|
| 608 |
+
return {}
|
| 609 |
+
raise NotImplementedError
|
| 610 |
+
|
| 611 |
+
|
| 612 |
+
class Slice(LazyValueWrapper):
|
| 613 |
+
def __init__(self, python_context, start, stop, step):
|
| 614 |
+
self.inference_state = python_context.inference_state
|
| 615 |
+
self._context = python_context
|
| 616 |
+
# All of them are either a Precedence or None.
|
| 617 |
+
self._start = start
|
| 618 |
+
self._stop = stop
|
| 619 |
+
self._step = step
|
| 620 |
+
|
| 621 |
+
def _get_wrapped_value(self):
|
| 622 |
+
value = compiled.builtin_from_name(self._context.inference_state, 'slice')
|
| 623 |
+
slice_value, = value.execute_with_values()
|
| 624 |
+
return slice_value
|
| 625 |
+
|
| 626 |
+
def get_safe_value(self, default=sentinel):
|
| 627 |
+
"""
|
| 628 |
+
Imitate CompiledValue.obj behavior and return a ``builtin.slice()``
|
| 629 |
+
object.
|
| 630 |
+
"""
|
| 631 |
+
def get(element):
|
| 632 |
+
if element is None:
|
| 633 |
+
return None
|
| 634 |
+
|
| 635 |
+
result = self._context.infer_node(element)
|
| 636 |
+
if len(result) != 1:
|
| 637 |
+
# For simplicity, we want slices to be clear defined with just
|
| 638 |
+
# one type. Otherwise we will return an empty slice object.
|
| 639 |
+
raise IndexError
|
| 640 |
+
|
| 641 |
+
value, = result
|
| 642 |
+
return get_int_or_none(value)
|
| 643 |
+
|
| 644 |
+
try:
|
| 645 |
+
return slice(get(self._start), get(self._stop), get(self._step))
|
| 646 |
+
except IndexError:
|
| 647 |
+
return slice(None, None, None)
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/value/module.py
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
from jedi.inference.cache import inference_state_method_cache
|
| 6 |
+
from jedi.inference.names import AbstractNameDefinition, ModuleName
|
| 7 |
+
from jedi.inference.filters import GlobalNameFilter, ParserTreeFilter, DictFilter, MergedFilter
|
| 8 |
+
from jedi.inference import compiled
|
| 9 |
+
from jedi.inference.base_value import TreeValue
|
| 10 |
+
from jedi.inference.names import SubModuleName
|
| 11 |
+
from jedi.inference.helpers import values_from_qualified_names
|
| 12 |
+
from jedi.inference.compiled import create_simple_object
|
| 13 |
+
from jedi.inference.base_value import ValueSet
|
| 14 |
+
from jedi.inference.context import ModuleContext
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class _ModuleAttributeName(AbstractNameDefinition):
|
| 18 |
+
"""
|
| 19 |
+
For module attributes like __file__, __str__ and so on.
|
| 20 |
+
"""
|
| 21 |
+
api_type = 'instance'
|
| 22 |
+
|
| 23 |
+
def __init__(self, parent_module, string_name, string_value=None):
|
| 24 |
+
self.parent_context = parent_module
|
| 25 |
+
self.string_name = string_name
|
| 26 |
+
self._string_value = string_value
|
| 27 |
+
|
| 28 |
+
def infer(self):
|
| 29 |
+
if self._string_value is not None:
|
| 30 |
+
s = self._string_value
|
| 31 |
+
return ValueSet([
|
| 32 |
+
create_simple_object(self.parent_context.inference_state, s)
|
| 33 |
+
])
|
| 34 |
+
return compiled.get_string_value_set(self.parent_context.inference_state)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class SubModuleDictMixin:
|
| 38 |
+
@inference_state_method_cache()
|
| 39 |
+
def sub_modules_dict(self):
|
| 40 |
+
"""
|
| 41 |
+
Lists modules in the directory of this module (if this module is a
|
| 42 |
+
package).
|
| 43 |
+
"""
|
| 44 |
+
names = {}
|
| 45 |
+
if self.is_package():
|
| 46 |
+
mods = self.inference_state.compiled_subprocess.iter_module_names(
|
| 47 |
+
self.py__path__()
|
| 48 |
+
)
|
| 49 |
+
for name in mods:
|
| 50 |
+
# It's obviously a relative import to the current module.
|
| 51 |
+
names[name] = SubModuleName(self.as_context(), name)
|
| 52 |
+
|
| 53 |
+
# In the case of an import like `from x.` we don't need to
|
| 54 |
+
# add all the variables, this is only about submodules.
|
| 55 |
+
return names
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class ModuleMixin(SubModuleDictMixin):
|
| 59 |
+
_module_name_class = ModuleName
|
| 60 |
+
|
| 61 |
+
def get_filters(self, origin_scope=None):
|
| 62 |
+
yield MergedFilter(
|
| 63 |
+
ParserTreeFilter(
|
| 64 |
+
parent_context=self.as_context(),
|
| 65 |
+
origin_scope=origin_scope
|
| 66 |
+
),
|
| 67 |
+
GlobalNameFilter(self.as_context()),
|
| 68 |
+
)
|
| 69 |
+
yield DictFilter(self.sub_modules_dict())
|
| 70 |
+
yield DictFilter(self._module_attributes_dict())
|
| 71 |
+
yield from self.iter_star_filters()
|
| 72 |
+
|
| 73 |
+
def py__class__(self):
|
| 74 |
+
c, = values_from_qualified_names(self.inference_state, 'types', 'ModuleType')
|
| 75 |
+
return c
|
| 76 |
+
|
| 77 |
+
def is_module(self):
|
| 78 |
+
return True
|
| 79 |
+
|
| 80 |
+
def is_stub(self):
|
| 81 |
+
return False
|
| 82 |
+
|
| 83 |
+
@property # type: ignore[misc]
|
| 84 |
+
@inference_state_method_cache()
|
| 85 |
+
def name(self):
|
| 86 |
+
return self._module_name_class(self, self.string_names[-1])
|
| 87 |
+
|
| 88 |
+
@inference_state_method_cache()
|
| 89 |
+
def _module_attributes_dict(self):
|
| 90 |
+
names = ['__package__', '__doc__', '__name__']
|
| 91 |
+
# All the additional module attributes are strings.
|
| 92 |
+
dct = dict((n, _ModuleAttributeName(self, n)) for n in names)
|
| 93 |
+
path = self.py__file__()
|
| 94 |
+
if path is not None:
|
| 95 |
+
dct['__file__'] = _ModuleAttributeName(self, '__file__', str(path))
|
| 96 |
+
return dct
|
| 97 |
+
|
| 98 |
+
def iter_star_filters(self):
|
| 99 |
+
for star_module in self.star_imports():
|
| 100 |
+
f = next(star_module.get_filters(), None)
|
| 101 |
+
assert f is not None
|
| 102 |
+
yield f
|
| 103 |
+
|
| 104 |
+
# I'm not sure if the star import cache is really that effective anymore
|
| 105 |
+
# with all the other really fast import caches. Recheck. Also we would need
|
| 106 |
+
# to push the star imports into InferenceState.module_cache, if we reenable this.
|
| 107 |
+
@inference_state_method_cache([])
|
| 108 |
+
def star_imports(self):
|
| 109 |
+
from jedi.inference.imports import Importer
|
| 110 |
+
|
| 111 |
+
modules = []
|
| 112 |
+
module_context = self.as_context()
|
| 113 |
+
for i in self.tree_node.iter_imports():
|
| 114 |
+
if i.is_star_import():
|
| 115 |
+
new = Importer(
|
| 116 |
+
self.inference_state,
|
| 117 |
+
import_path=i.get_paths()[-1],
|
| 118 |
+
module_context=module_context,
|
| 119 |
+
level=i.level
|
| 120 |
+
).follow()
|
| 121 |
+
|
| 122 |
+
for module in new:
|
| 123 |
+
if isinstance(module, ModuleValue):
|
| 124 |
+
modules += module.star_imports()
|
| 125 |
+
modules += new
|
| 126 |
+
return modules
|
| 127 |
+
|
| 128 |
+
def get_qualified_names(self):
|
| 129 |
+
"""
|
| 130 |
+
A module doesn't have a qualified name, but it's important to note that
|
| 131 |
+
it's reachable and not `None`. With this information we can add
|
| 132 |
+
qualified names on top for all value children.
|
| 133 |
+
"""
|
| 134 |
+
return ()
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class ModuleValue(ModuleMixin, TreeValue):
|
| 138 |
+
api_type = 'module'
|
| 139 |
+
|
| 140 |
+
def __init__(self, inference_state, module_node, code_lines, file_io=None,
|
| 141 |
+
string_names=None, is_package=False):
|
| 142 |
+
super().__init__(
|
| 143 |
+
inference_state,
|
| 144 |
+
parent_context=None,
|
| 145 |
+
tree_node=module_node
|
| 146 |
+
)
|
| 147 |
+
self.file_io = file_io
|
| 148 |
+
if file_io is None:
|
| 149 |
+
self._path: Optional[Path] = None
|
| 150 |
+
else:
|
| 151 |
+
self._path = file_io.path
|
| 152 |
+
self.string_names = string_names # Optional[Tuple[str, ...]]
|
| 153 |
+
self.code_lines = code_lines
|
| 154 |
+
self._is_package = is_package
|
| 155 |
+
|
| 156 |
+
def is_stub(self):
|
| 157 |
+
if self._path is not None and self._path.suffix == '.pyi':
|
| 158 |
+
# Currently this is the way how we identify stubs when e.g. goto is
|
| 159 |
+
# used in them. This could be changed if stubs would be identified
|
| 160 |
+
# sooner and used as StubModuleValue.
|
| 161 |
+
return True
|
| 162 |
+
return super().is_stub()
|
| 163 |
+
|
| 164 |
+
def py__name__(self):
|
| 165 |
+
if self.string_names is None:
|
| 166 |
+
return None
|
| 167 |
+
return '.'.join(self.string_names)
|
| 168 |
+
|
| 169 |
+
def py__file__(self) -> Optional[Path]:
|
| 170 |
+
"""
|
| 171 |
+
In contrast to Python's __file__ can be None.
|
| 172 |
+
"""
|
| 173 |
+
if self._path is None:
|
| 174 |
+
return None
|
| 175 |
+
|
| 176 |
+
return self._path.absolute()
|
| 177 |
+
|
| 178 |
+
def is_package(self):
|
| 179 |
+
return self._is_package
|
| 180 |
+
|
| 181 |
+
def py__package__(self):
|
| 182 |
+
if self.string_names is None:
|
| 183 |
+
return []
|
| 184 |
+
|
| 185 |
+
if self._is_package:
|
| 186 |
+
return self.string_names
|
| 187 |
+
return self.string_names[:-1]
|
| 188 |
+
|
| 189 |
+
def py__path__(self):
|
| 190 |
+
"""
|
| 191 |
+
In case of a package, this returns Python's __path__ attribute, which
|
| 192 |
+
is a list of paths (strings).
|
| 193 |
+
Returns None if the module is not a package.
|
| 194 |
+
"""
|
| 195 |
+
if not self._is_package:
|
| 196 |
+
return None
|
| 197 |
+
|
| 198 |
+
# A namespace package is typically auto generated and ~10 lines long.
|
| 199 |
+
first_few_lines = ''.join(self.code_lines[:50])
|
| 200 |
+
# these are strings that need to be used for namespace packages,
|
| 201 |
+
# the first one is ``pkgutil``, the second ``pkg_resources``.
|
| 202 |
+
options = ('declare_namespace(__name__)', 'extend_path(__path__')
|
| 203 |
+
if options[0] in first_few_lines or options[1] in first_few_lines:
|
| 204 |
+
# It is a namespace, now try to find the rest of the
|
| 205 |
+
# modules on sys_path or whatever the search_path is.
|
| 206 |
+
paths = set()
|
| 207 |
+
for s in self.inference_state.get_sys_path():
|
| 208 |
+
other = os.path.join(s, self.name.string_name)
|
| 209 |
+
if os.path.isdir(other):
|
| 210 |
+
paths.add(other)
|
| 211 |
+
if paths:
|
| 212 |
+
return list(paths)
|
| 213 |
+
# Nested namespace packages will not be supported. Nobody ever
|
| 214 |
+
# asked for it and in Python 3 they are there without using all the
|
| 215 |
+
# crap above.
|
| 216 |
+
|
| 217 |
+
# Default to the of this file.
|
| 218 |
+
file = self.py__file__()
|
| 219 |
+
assert file is not None # Shouldn't be a package in the first place.
|
| 220 |
+
return [os.path.dirname(file)]
|
| 221 |
+
|
| 222 |
+
def _as_context(self):
|
| 223 |
+
return ModuleContext(self)
|
| 224 |
+
|
| 225 |
+
def __repr__(self):
|
| 226 |
+
return "<%s: %s@%s-%s is_stub=%s>" % (
|
| 227 |
+
self.__class__.__name__, self.py__name__(),
|
| 228 |
+
self.tree_node.start_pos[0], self.tree_node.end_pos[0],
|
| 229 |
+
self.is_stub()
|
| 230 |
+
)
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/inference/value/namespace.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
from typing import Optional
|
| 3 |
+
|
| 4 |
+
from jedi.inference.cache import inference_state_method_cache
|
| 5 |
+
from jedi.inference.filters import DictFilter
|
| 6 |
+
from jedi.inference.names import ValueNameMixin, AbstractNameDefinition
|
| 7 |
+
from jedi.inference.base_value import Value
|
| 8 |
+
from jedi.inference.value.module import SubModuleDictMixin
|
| 9 |
+
from jedi.inference.context import NamespaceContext
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class ImplicitNSName(ValueNameMixin, AbstractNameDefinition):
|
| 13 |
+
"""
|
| 14 |
+
Accessing names for implicit namespace packages should infer to nothing.
|
| 15 |
+
This object will prevent Jedi from raising exceptions
|
| 16 |
+
"""
|
| 17 |
+
def __init__(self, implicit_ns_value, string_name):
|
| 18 |
+
self._value = implicit_ns_value
|
| 19 |
+
self.string_name = string_name
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class ImplicitNamespaceValue(Value, SubModuleDictMixin):
|
| 23 |
+
"""
|
| 24 |
+
Provides support for implicit namespace packages
|
| 25 |
+
"""
|
| 26 |
+
api_type = 'namespace'
|
| 27 |
+
parent_context = None
|
| 28 |
+
|
| 29 |
+
def __init__(self, inference_state, string_names, paths):
|
| 30 |
+
super().__init__(inference_state, parent_context=None)
|
| 31 |
+
self.inference_state = inference_state
|
| 32 |
+
self.string_names = string_names
|
| 33 |
+
self._paths = paths
|
| 34 |
+
|
| 35 |
+
def get_filters(self, origin_scope=None):
|
| 36 |
+
yield DictFilter(self.sub_modules_dict())
|
| 37 |
+
|
| 38 |
+
def get_qualified_names(self):
|
| 39 |
+
return ()
|
| 40 |
+
|
| 41 |
+
@property # type: ignore[misc]
|
| 42 |
+
@inference_state_method_cache()
|
| 43 |
+
def name(self):
|
| 44 |
+
string_name = self.py__package__()[-1]
|
| 45 |
+
return ImplicitNSName(self, string_name)
|
| 46 |
+
|
| 47 |
+
def py__file__(self) -> Optional[Path]:
|
| 48 |
+
return None
|
| 49 |
+
|
| 50 |
+
def py__package__(self):
|
| 51 |
+
"""Return the fullname
|
| 52 |
+
"""
|
| 53 |
+
return self.string_names
|
| 54 |
+
|
| 55 |
+
def py__path__(self):
|
| 56 |
+
return self._paths
|
| 57 |
+
|
| 58 |
+
def py__name__(self):
|
| 59 |
+
return '.'.join(self.string_names)
|
| 60 |
+
|
| 61 |
+
def is_namespace(self):
|
| 62 |
+
return True
|
| 63 |
+
|
| 64 |
+
def is_stub(self):
|
| 65 |
+
return False
|
| 66 |
+
|
| 67 |
+
def is_package(self):
|
| 68 |
+
return True
|
| 69 |
+
|
| 70 |
+
def as_context(self):
|
| 71 |
+
return NamespaceContext(self)
|
| 72 |
+
|
| 73 |
+
def __repr__(self):
|
| 74 |
+
return '<%s: %s>' % (self.__class__.__name__, self.py__name__())
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/plugins/__init__.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import wraps
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class _PluginManager:
|
| 5 |
+
def __init__(self):
|
| 6 |
+
self._registered_plugins = []
|
| 7 |
+
self._cached_base_callbacks = {}
|
| 8 |
+
self._built_functions = {}
|
| 9 |
+
|
| 10 |
+
def register(self, *plugins):
|
| 11 |
+
"""
|
| 12 |
+
Makes it possible to register your plugin.
|
| 13 |
+
"""
|
| 14 |
+
self._registered_plugins.extend(plugins)
|
| 15 |
+
self._build_functions()
|
| 16 |
+
|
| 17 |
+
def decorate(self, name=None):
|
| 18 |
+
def decorator(callback):
|
| 19 |
+
@wraps(callback)
|
| 20 |
+
def wrapper(*args, **kwargs):
|
| 21 |
+
return built_functions[public_name](*args, **kwargs)
|
| 22 |
+
|
| 23 |
+
public_name = name or callback.__name__
|
| 24 |
+
|
| 25 |
+
assert public_name not in self._built_functions
|
| 26 |
+
built_functions = self._built_functions
|
| 27 |
+
built_functions[public_name] = callback
|
| 28 |
+
self._cached_base_callbacks[public_name] = callback
|
| 29 |
+
|
| 30 |
+
return wrapper
|
| 31 |
+
|
| 32 |
+
return decorator
|
| 33 |
+
|
| 34 |
+
def _build_functions(self):
|
| 35 |
+
for name, callback in self._cached_base_callbacks.items():
|
| 36 |
+
for plugin in reversed(self._registered_plugins):
|
| 37 |
+
# Need to reverse so the first plugin is run first.
|
| 38 |
+
try:
|
| 39 |
+
func = getattr(plugin, name)
|
| 40 |
+
except AttributeError:
|
| 41 |
+
pass
|
| 42 |
+
else:
|
| 43 |
+
callback = func(callback)
|
| 44 |
+
self._built_functions[name] = callback
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
plugin_manager = _PluginManager()
|
home/.vscode-server/extensions/ms-python.python-2026.4.0-linux-x64/python_files/lib/jedilsp/jedi/plugins/pytest.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from typing import List
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
from parso.tree import search_ancestor
|
| 6 |
+
from jedi.inference.cache import inference_state_method_cache
|
| 7 |
+
from jedi.inference.imports import goto_import, load_module_from_path
|
| 8 |
+
from jedi.inference.filters import ParserTreeFilter
|
| 9 |
+
from jedi.inference.base_value import NO_VALUES, ValueSet
|
| 10 |
+
from jedi.inference.helpers import infer_call_of_leaf
|
| 11 |
+
|
| 12 |
+
_PYTEST_FIXTURE_MODULES = [
|
| 13 |
+
('_pytest', 'monkeypatch'),
|
| 14 |
+
('_pytest', 'capture'),
|
| 15 |
+
('_pytest', 'logging'),
|
| 16 |
+
('_pytest', 'tmpdir'),
|
| 17 |
+
('_pytest', 'pytester'),
|
| 18 |
+
]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def execute(callback):
|
| 22 |
+
def wrapper(value, arguments):
|
| 23 |
+
# This might not be necessary anymore in pytest 4/5, definitely needed
|
| 24 |
+
# for pytest 3.
|
| 25 |
+
if value.py__name__() == 'fixture' \
|
| 26 |
+
and value.parent_context.py__name__() == '_pytest.fixtures':
|
| 27 |
+
return NO_VALUES
|
| 28 |
+
|
| 29 |
+
return callback(value, arguments)
|
| 30 |
+
return wrapper
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def infer_anonymous_param(func):
|
| 34 |
+
def get_returns(value):
|
| 35 |
+
if value.tree_node.annotation is not None:
|
| 36 |
+
result = value.execute_with_values()
|
| 37 |
+
if any(v.name.get_qualified_names(include_module_names=True)
|
| 38 |
+
== ('typing', 'Generator')
|
| 39 |
+
for v in result):
|
| 40 |
+
return ValueSet.from_sets(
|
| 41 |
+
v.py__getattribute__('__next__').execute_annotation()
|
| 42 |
+
for v in result
|
| 43 |
+
)
|
| 44 |
+
return result
|
| 45 |
+
|
| 46 |
+
# In pytest we need to differentiate between generators and normal
|
| 47 |
+
# returns.
|
| 48 |
+
# Parameters still need to be anonymous, .as_context() ensures that.
|
| 49 |
+
function_context = value.as_context()
|
| 50 |
+
if function_context.is_generator():
|
| 51 |
+
return function_context.merge_yield_values()
|
| 52 |
+
else:
|
| 53 |
+
return function_context.get_return_values()
|
| 54 |
+
|
| 55 |
+
def wrapper(param_name):
|
| 56 |
+
# parameters with an annotation do not need special handling
|
| 57 |
+
if param_name.annotation_node:
|
| 58 |
+
return func(param_name)
|
| 59 |
+
is_pytest_param, param_name_is_function_name = \
|
| 60 |
+
_is_a_pytest_param_and_inherited(param_name)
|
| 61 |
+
if is_pytest_param:
|
| 62 |
+
module = param_name.get_root_context()
|
| 63 |
+
fixtures = _goto_pytest_fixture(
|
| 64 |
+
module,
|
| 65 |
+
param_name.string_name,
|
| 66 |
+
# This skips the current module, because we are basically
|
| 67 |
+
# inheriting a fixture from somewhere else.
|
| 68 |
+
skip_own_module=param_name_is_function_name,
|
| 69 |
+
)
|
| 70 |
+
if fixtures:
|
| 71 |
+
return ValueSet.from_sets(
|
| 72 |
+
get_returns(value)
|
| 73 |
+
for fixture in fixtures
|
| 74 |
+
for value in fixture.infer()
|
| 75 |
+
)
|
| 76 |
+
return func(param_name)
|
| 77 |
+
return wrapper
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def goto_anonymous_param(func):
|
| 81 |
+
def wrapper(param_name):
|
| 82 |
+
is_pytest_param, param_name_is_function_name = \
|
| 83 |
+
_is_a_pytest_param_and_inherited(param_name)
|
| 84 |
+
if is_pytest_param:
|
| 85 |
+
names = _goto_pytest_fixture(
|
| 86 |
+
param_name.get_root_context(),
|
| 87 |
+
param_name.string_name,
|
| 88 |
+
skip_own_module=param_name_is_function_name,
|
| 89 |
+
)
|
| 90 |
+
if names:
|
| 91 |
+
return names
|
| 92 |
+
return func(param_name)
|
| 93 |
+
return wrapper
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def complete_param_names(func):
|
| 97 |
+
def wrapper(context, func_name, decorator_nodes):
|
| 98 |
+
module_context = context.get_root_context()
|
| 99 |
+
if _is_pytest_func(func_name, decorator_nodes):
|
| 100 |
+
names = []
|
| 101 |
+
for module_context in _iter_pytest_modules(module_context):
|
| 102 |
+
names += FixtureFilter(module_context).values()
|
| 103 |
+
if names:
|
| 104 |
+
return names
|
| 105 |
+
return func(context, func_name, decorator_nodes)
|
| 106 |
+
return wrapper
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _goto_pytest_fixture(module_context, name, skip_own_module):
|
| 110 |
+
for module_context in _iter_pytest_modules(module_context, skip_own_module=skip_own_module):
|
| 111 |
+
names = FixtureFilter(module_context).get(name)
|
| 112 |
+
if names:
|
| 113 |
+
return names
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _is_a_pytest_param_and_inherited(param_name):
|
| 117 |
+
"""
|
| 118 |
+
Pytest params are either in a `test_*` function or have a pytest fixture
|
| 119 |
+
with the decorator @pytest.fixture.
|
| 120 |
+
|
| 121 |
+
This is a heuristic and will work in most cases.
|
| 122 |
+
"""
|
| 123 |
+
funcdef = search_ancestor(param_name.tree_name, 'funcdef')
|
| 124 |
+
if funcdef is None: # A lambda
|
| 125 |
+
return False, False
|
| 126 |
+
decorators = funcdef.get_decorators()
|
| 127 |
+
return _is_pytest_func(funcdef.name.value, decorators), \
|
| 128 |
+
funcdef.name.value == param_name.string_name
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _is_pytest_func(func_name, decorator_nodes):
|
| 132 |
+
return func_name.startswith('test') \
|
| 133 |
+
or any('fixture' in n.get_code() for n in decorator_nodes)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _find_pytest_plugin_modules() -> List[List[str]]:
|
| 137 |
+
"""
|
| 138 |
+
Finds pytest plugin modules hooked by setuptools entry points
|
| 139 |
+
|
| 140 |
+
See https://docs.pytest.org/en/stable/how-to/writing_plugins.html#setuptools-entry-points
|
| 141 |
+
"""
|
| 142 |
+
if sys.version_info >= (3, 8):
|
| 143 |
+
from importlib.metadata import entry_points
|
| 144 |
+
|
| 145 |
+
if sys.version_info >= (3, 10):
|
| 146 |
+
pytest_entry_points = entry_points(group="pytest11")
|
| 147 |
+
else:
|
| 148 |
+
pytest_entry_points = entry_points().get("pytest11", ())
|
| 149 |
+
|
| 150 |
+
if sys.version_info >= (3, 9):
|
| 151 |
+
return [ep.module.split(".") for ep in pytest_entry_points]
|
| 152 |
+
else:
|
| 153 |
+
# Python 3.8 doesn't have `EntryPoint.module`. Implement equivalent
|
| 154 |
+
# to what Python 3.9 does (with additional None check to placate `mypy`)
|
| 155 |
+
matches = [
|
| 156 |
+
ep.pattern.match(ep.value)
|
| 157 |
+
for ep in pytest_entry_points
|
| 158 |
+
]
|
| 159 |
+
return [x.group('module').split(".") for x in matches if x]
|
| 160 |
+
|
| 161 |
+
else:
|
| 162 |
+
from pkg_resources import iter_entry_points
|
| 163 |
+
return [ep.module_name.split(".") for ep in iter_entry_points(group="pytest11")]
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
@inference_state_method_cache()
|
| 167 |
+
def _iter_pytest_modules(module_context, skip_own_module=False):
|
| 168 |
+
if not skip_own_module:
|
| 169 |
+
yield module_context
|
| 170 |
+
|
| 171 |
+
file_io = module_context.get_value().file_io
|
| 172 |
+
if file_io is not None:
|
| 173 |
+
folder = file_io.get_parent_folder()
|
| 174 |
+
sys_path = module_context.inference_state.get_sys_path()
|
| 175 |
+
|
| 176 |
+
# prevent an infinite loop when reaching the root of the current drive
|
| 177 |
+
last_folder = None
|
| 178 |
+
|
| 179 |
+
while any(folder.path.startswith(p) for p in sys_path):
|
| 180 |
+
file_io = folder.get_file_io('conftest.py')
|
| 181 |
+
if Path(file_io.path) != module_context.py__file__():
|
| 182 |
+
try:
|
| 183 |
+
m = load_module_from_path(module_context.inference_state, file_io)
|
| 184 |
+
conftest_module = m.as_context()
|
| 185 |
+
yield conftest_module
|
| 186 |
+
|
| 187 |
+
plugins_list = m.tree_node.get_used_names().get("pytest_plugins")
|
| 188 |
+
if plugins_list:
|
| 189 |
+
name = conftest_module.create_name(plugins_list[0])
|
| 190 |
+
yield from _load_pytest_plugins(module_context, name)
|
| 191 |
+
except FileNotFoundError:
|
| 192 |
+
pass
|
| 193 |
+
folder = folder.get_parent_folder()
|
| 194 |
+
|
| 195 |
+
# prevent an infinite for loop if the same parent folder is return twice
|
| 196 |
+
if last_folder is not None and folder.path == last_folder.path:
|
| 197 |
+
break
|
| 198 |
+
last_folder = folder # keep track of the last found parent name
|
| 199 |
+
|
| 200 |
+
for names in _PYTEST_FIXTURE_MODULES + _find_pytest_plugin_modules():
|
| 201 |
+
for module_value in module_context.inference_state.import_module(names):
|
| 202 |
+
yield module_value.as_context()
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def _load_pytest_plugins(module_context, name):
|
| 206 |
+
from jedi.inference.helpers import get_str_or_none
|
| 207 |
+
|
| 208 |
+
for inferred in name.infer():
|
| 209 |
+
for seq_value in inferred.py__iter__():
|
| 210 |
+
for value in seq_value.infer():
|
| 211 |
+
fq_name = get_str_or_none(value)
|
| 212 |
+
if fq_name:
|
| 213 |
+
names = fq_name.split(".")
|
| 214 |
+
for module_value in module_context.inference_state.import_module(names):
|
| 215 |
+
yield module_value.as_context()
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
class FixtureFilter(ParserTreeFilter):
|
| 219 |
+
def _filter(self, names):
|
| 220 |
+
for name in super()._filter(names):
|
| 221 |
+
# look for fixture definitions of imported names
|
| 222 |
+
if name.parent.type == "import_from":
|
| 223 |
+
imported_names = goto_import(self.parent_context, name)
|
| 224 |
+
if any(
|
| 225 |
+
self._is_fixture(iname.parent_context, iname.tree_name)
|
| 226 |
+
for iname in imported_names
|
| 227 |
+
# discard imports of whole modules, that have no tree_name
|
| 228 |
+
if iname.tree_name
|
| 229 |
+
):
|
| 230 |
+
yield name
|
| 231 |
+
|
| 232 |
+
elif self._is_fixture(self.parent_context, name):
|
| 233 |
+
yield name
|
| 234 |
+
|
| 235 |
+
def _is_fixture(self, context, name):
|
| 236 |
+
funcdef = name.parent
|
| 237 |
+
# Class fixtures are not supported
|
| 238 |
+
if funcdef.type != "funcdef":
|
| 239 |
+
return False
|
| 240 |
+
decorated = funcdef.parent
|
| 241 |
+
if decorated.type != "decorated":
|
| 242 |
+
return False
|
| 243 |
+
decorators = decorated.children[0]
|
| 244 |
+
if decorators.type == 'decorators':
|
| 245 |
+
decorators = decorators.children
|
| 246 |
+
else:
|
| 247 |
+
decorators = [decorators]
|
| 248 |
+
for decorator in decorators:
|
| 249 |
+
dotted_name = decorator.children[1]
|
| 250 |
+
# A heuristic, this makes it faster.
|
| 251 |
+
if 'fixture' in dotted_name.get_code():
|
| 252 |
+
if dotted_name.type == 'atom_expr':
|
| 253 |
+
# Since Python3.9 a decorator does not have dotted names
|
| 254 |
+
# anymore.
|
| 255 |
+
last_trailer = dotted_name.children[-1]
|
| 256 |
+
last_leaf = last_trailer.get_last_leaf()
|
| 257 |
+
if last_leaf == ')':
|
| 258 |
+
values = infer_call_of_leaf(
|
| 259 |
+
context, last_leaf, cut_own_trailer=True
|
| 260 |
+
)
|
| 261 |
+
else:
|
| 262 |
+
values = context.infer_node(dotted_name)
|
| 263 |
+
else:
|
| 264 |
+
values = context.infer_node(dotted_name)
|
| 265 |
+
for value in values:
|
| 266 |
+
if value.name.get_qualified_names(include_module_names=True) \
|
| 267 |
+
== ('_pytest', 'fixtures', 'fixture'):
|
| 268 |
+
return True
|
| 269 |
+
return False
|