Debian Codegraph @

jedi/inference/gradual/typeshed.py

raw symbols SCIP
1 import os
2 from functools import wraps
3 from collections import namedtuple
4 from typing import Dict, Mapping, Tuple
5 from pathlib import Path
6
7 from jedi import settings
8 from jedi.file_io import FileIO
9 from jedi.parser_utils import get_cached_code_lines
10 from jedi.inference.base_value import ValueSet, NO_VALUES
11 from jedi.inference.gradual.stub_value import TypingModuleWrapper, StubModuleValue
12 from jedi.inference.value import ModuleValue
13
14 _jedi_path = Path(__file__).parent.parent.parent
15 TYPESHED_PATH = _jedi_path.joinpath('third_party', 'typeshed')
16 DJANGO_INIT_PATH = _jedi_path.joinpath('third_party', 'django-stubs',
17 'django-stubs', '__init__.pyi')
18
19 _IMPORT_MAP = dict(
20 _collections='collections',
21 _socket='socket',
22 )
23
24 PathInfo = namedtuple('PathInfo', 'path is_third_party')
25
26
27 def _merge_create_stub_map(path_infos):
28 map_ = {}
29 for directory_path_info in path_infos:
30 map_.update(_create_stub_map(directory_path_info))
31 return map_
32
33
34 def _create_stub_map(directory_path_info):
35 """
36 Create a mapping of an importable name in Python to a stub file.
37 """
38 def generate():
39 try:
40 listed = os.listdir(directory_path_info.path)
41 except (FileNotFoundError, NotADirectoryError):
42 return
43
44 for entry in listed:
45 path = os.path.join(directory_path_info.path, entry)
46 if os.path.isdir(path):
47 init = os.path.join(path, '__init__.pyi')
48 if os.path.isfile(init):
49 yield entry, PathInfo(init, directory_path_info.is_third_party)
50 elif entry.endswith('.pyi') and os.path.isfile(path):
51 name = entry[:-4]
52 if name != '__init__':
53 yield name, PathInfo(path, directory_path_info.is_third_party)
54
55 # Create a dictionary from the tuple generator.
56 return dict(generate())
57
58
59 def _get_typeshed_directories(version_info):
60 yield PathInfo(str(TYPESHED_PATH.joinpath("stdlib")), False)
61 yield PathInfo(str(TYPESHED_PATH.joinpath("stubs")), True)
62
63
64 _version_cache: Dict[Tuple[int, int], Mapping[str, PathInfo]] = {}
65
66
67 def _cache_stub_file_map(version_info):
68 """
69 Returns a map of an importable name in Python to a stub file.
70 """
71 # TODO this caches the stub files indefinitely, maybe use a time cache
72 # for that?
73 version = version_info[:2]
74 try:
75 return _version_cache[version]
76 except KeyError:
77 pass
78
79 _version_cache[version] = file_set = \
80 _merge_create_stub_map(_get_typeshed_directories(version_info))
81 return file_set
82
83
84 def import_module_decorator(func):
85 @wraps(func)
86 def wrapper(inference_state, import_names, parent_module_value, sys_path, prefer_stubs):
87 python_value_set = inference_state.module_cache.get(import_names)
88 if python_value_set is None:
89 if parent_module_value is not None and parent_module_value.is_stub():
90 parent_module_values = parent_module_value.non_stub_value_set
91 else:
92 parent_module_values = [parent_module_value]
93 if import_names == ('os', 'path'):
94 # This is a huge exception, we follow a nested import
95 # ``os.path``, because it's a very important one in Python
96 # that is being achieved by messing with ``sys.modules`` in
97 # ``os``.
98 python_value_set = ValueSet.from_sets(
99 func(inference_state, (n,), None, sys_path,)
100 for n in ['posixpath', 'ntpath', 'macpath', 'os2emxpath']
101 )
102 else:
103 python_value_set = ValueSet.from_sets(
104 func(inference_state, import_names, p, sys_path,)
105 for p in parent_module_values
106 )
107 inference_state.module_cache.add(import_names, python_value_set)
108
109 if not prefer_stubs or import_names[0] in settings.auto_import_modules:
110 return python_value_set
111
112 stub = try_to_load_stub_cached(inference_state, import_names, python_value_set,
113 parent_module_value, sys_path)
114 if stub is not None:
115 return ValueSet([stub])
116 return python_value_set
117
118 return wrapper
119
120
121 def try_to_load_stub_cached(inference_state, import_names, *args, **kwargs):
122 if import_names is None:
123 return None
124
125 try:
126 return inference_state.stub_module_cache[import_names]
127 except KeyError:
128 pass
129
130 # TODO is this needed? where are the exceptions coming from that make this
131 # necessary? Just remove this line.
132 inference_state.stub_module_cache[import_names] = None
133 inference_state.stub_module_cache[import_names] = result = \
134 _try_to_load_stub(inference_state, import_names, *args, **kwargs)
135 return result
136
137
138 def _try_to_load_stub(inference_state, import_names, python_value_set,
139 parent_module_value, sys_path):
140 """
141 Trying to load a stub for a set of import_names.
142
143 This is modelled to work like "PEP 561 -- Distributing and Packaging Type
144 Information", see https://www.python.org/dev/peps/pep-0561.
145 """
146 if parent_module_value is None and len(import_names) > 1:
147 try:
148 parent_module_value = try_to_load_stub_cached(
149 inference_state, import_names[:-1], NO_VALUES,
150 parent_module_value=None, sys_path=sys_path)
151 except KeyError:
152 pass
153
154 # 1. Try to load foo-stubs folders on path for import name foo.
155 if len(import_names) == 1:
156 # foo-stubs
157 for p in sys_path:
158 init = os.path.join(p, *import_names) + '-stubs' + os.path.sep + '__init__.pyi'
159 m = _try_to_load_stub_from_file(
160 inference_state,
161 python_value_set,
162 file_io=FileIO(init),
163 import_names=import_names,
164 )
165 if m is not None:
166 return m
167 if import_names[0] == 'django' and python_value_set:
168 return _try_to_load_stub_from_file(
169 inference_state,
170 python_value_set,
171 file_io=FileIO(str(DJANGO_INIT_PATH)),
172 import_names=import_names,
173 )
174
175 # 2. Try to load pyi files next to py files.
176 for c in python_value_set:
177 try:
178 method = c.py__file__
179 except AttributeError:
180 pass
181 else:
182 file_path = method()
183 file_paths = []
184 if c.is_namespace():
185 file_paths = [os.path.join(p, '__init__.pyi') for p in c.py__path__()]
186 elif file_path is not None and file_path.suffix == '.py':
187 file_paths = [str(file_path) + 'i']
188
189 for file_path in file_paths:
190 m = _try_to_load_stub_from_file(
191 inference_state,
192 python_value_set,
193 # The file path should end with .pyi
194 file_io=FileIO(file_path),
195 import_names=import_names,
196 )
197 if m is not None:
198 return m
199
200 # 3. Try to load typeshed
201 m = _load_from_typeshed(inference_state, python_value_set, parent_module_value, import_names)
202 if m is not None:
203 return m
204
205 # 4. Try to load pyi file somewhere if python_value_set was not defined.
206 if not python_value_set:
207 if parent_module_value is not None:
208 check_path = parent_module_value.py__path__() or []
209 # In case import_names
210 names_for_path = (import_names[-1],)
211 else:
212 check_path = sys_path
213 names_for_path = import_names
214
215 for p in check_path:
216 m = _try_to_load_stub_from_file(
217 inference_state,
218 python_value_set,
219 file_io=FileIO(os.path.join(p, *names_for_path) + '.pyi'),
220 import_names=import_names,
221 )
222 if m is not None:
223 return m
224
225 # If no stub is found, that's fine, the calling function has to deal with
226 # it.
227 return None
228
229
230 def _load_from_typeshed(inference_state, python_value_set, parent_module_value, import_names):
231 import_name = import_names[-1]
232 map_ = None
233 if len(import_names) == 1:
234 map_ = _cache_stub_file_map(inference_state.grammar.version_info)
235 import_name = _IMPORT_MAP.get(import_name, import_name)
236 elif isinstance(parent_module_value, ModuleValue):
237 if not parent_module_value.is_package():
238 # Only if it's a package (= a folder) something can be
239 # imported.
240 return None
241 paths = parent_module_value.py__path__()
242 # Once the initial package has been loaded, the sub packages will
243 # always be loaded, regardless if they are there or not. This makes
244 # sense, IMO, because stubs take preference, even if the original
245 # library doesn't provide a module (it could be dynamic). ~dave
246 map_ = _merge_create_stub_map([PathInfo(p, is_third_party=False) for p in paths])
247
248 if map_ is not None:
249 path_info = map_.get(import_name)
250 if path_info is not None and (not path_info.is_third_party or python_value_set):
251 return _try_to_load_stub_from_file(
252 inference_state,
253 python_value_set,
254 file_io=FileIO(path_info.path),
255 import_names=import_names,
256 )
257
258
259 def _try_to_load_stub_from_file(inference_state, python_value_set, file_io, import_names):
260 try:
261 stub_module_node = parse_stub_module(inference_state, file_io)
262 except OSError:
263 # The file that you're looking for doesn't exist (anymore).
264 return None
265 else:
266 return create_stub_module(
267 inference_state, inference_state.latest_grammar, python_value_set,
268 stub_module_node, file_io, import_names
269 )
270
271
272 def parse_stub_module(inference_state, file_io):
273 return inference_state.parse(
274 file_io=file_io,
275 cache=True,
276 diff_cache=settings.fast_parser,
277 cache_path=settings.cache_directory,
278 use_latest_grammar=True
279 )
280
281
282 def create_stub_module(inference_state, grammar, python_value_set,
283 stub_module_node, file_io, import_names):
284 if import_names in [('typing',), ('typing_extensions',)]:
285 module_cls = TypingModuleWrapper
286 else:
287 module_cls = StubModuleValue
288 file_name = os.path.basename(file_io.path)
289 stub_module_value = module_cls(
290 python_value_set, inference_state, stub_module_node,
291 file_io=file_io,
292 string_names=import_names,
293 # The code was loaded with latest_grammar, so use
294 # that.
295 code_lines=get_cached_code_lines(grammar, file_io.path),
296 is_package=file_name == '__init__.pyi',
297 )
298 return stub_module_value