imports.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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. This module also supports import autocompletion, which means to complete
  8. statements like ``from datetim`` (cursor at the end would return ``datetime``).
  9. """
  10. import os
  11. from pathlib import Path
  12. from parso.python import tree
  13. from parso.tree import search_ancestor
  14. from jedi import debug
  15. from jedi import settings
  16. from jedi.file_io import FolderIO
  17. from jedi.parser_utils import get_cached_code_lines
  18. from jedi.inference import sys_path
  19. from jedi.inference import helpers
  20. from jedi.inference import compiled
  21. from jedi.inference import analysis
  22. from jedi.inference.utils import unite
  23. from jedi.inference.cache import inference_state_method_cache
  24. from jedi.inference.names import ImportName, SubModuleName
  25. from jedi.inference.base_value import ValueSet, NO_VALUES
  26. from jedi.inference.gradual.typeshed import import_module_decorator, \
  27. create_stub_module, parse_stub_module
  28. from jedi.inference.compiled.subprocess.functions import ImplicitNSInfo
  29. from jedi.plugins import plugin_manager
  30. class ModuleCache:
  31. def __init__(self):
  32. self._name_cache = {}
  33. def add(self, string_names, value_set):
  34. if string_names is not None:
  35. self._name_cache[string_names] = value_set
  36. def get(self, string_names):
  37. return self._name_cache.get(string_names)
  38. # This memoization is needed, because otherwise we will infinitely loop on
  39. # certain imports.
  40. @inference_state_method_cache(default=NO_VALUES)
  41. def infer_import(context, tree_name):
  42. module_context = context.get_root_context()
  43. from_import_name, import_path, level, values = \
  44. _prepare_infer_import(module_context, tree_name)
  45. if values:
  46. if from_import_name is not None:
  47. values = values.py__getattribute__(
  48. from_import_name,
  49. name_context=context,
  50. analysis_errors=False
  51. )
  52. if not values:
  53. path = import_path + (from_import_name,)
  54. importer = Importer(context.inference_state, path, module_context, level)
  55. values = importer.follow()
  56. debug.dbg('after import: %s', values)
  57. return values
  58. @inference_state_method_cache(default=[])
  59. def goto_import(context, tree_name):
  60. module_context = context.get_root_context()
  61. from_import_name, import_path, level, values = \
  62. _prepare_infer_import(module_context, tree_name)
  63. if not values:
  64. return []
  65. if from_import_name is not None:
  66. names = unite([
  67. c.goto(
  68. from_import_name,
  69. name_context=context,
  70. analysis_errors=False
  71. ) for c in values
  72. ])
  73. # Avoid recursion on the same names.
  74. if names and not any(n.tree_name is tree_name for n in names):
  75. return names
  76. path = import_path + (from_import_name,)
  77. importer = Importer(context.inference_state, path, module_context, level)
  78. values = importer.follow()
  79. return set(s.name for s in values)
  80. def _prepare_infer_import(module_context, tree_name):
  81. import_node = search_ancestor(tree_name, 'import_name', 'import_from')
  82. import_path = import_node.get_path_for_name(tree_name)
  83. from_import_name = None
  84. try:
  85. from_names = import_node.get_from_names()
  86. except AttributeError:
  87. # Is an import_name
  88. pass
  89. else:
  90. if len(from_names) + 1 == len(import_path):
  91. # We have to fetch the from_names part first and then check
  92. # if from_names exists in the modules.
  93. from_import_name = import_path[-1]
  94. import_path = from_names
  95. importer = Importer(module_context.inference_state, tuple(import_path),
  96. module_context, import_node.level)
  97. return from_import_name, tuple(import_path), import_node.level, importer.follow()
  98. def _add_error(value, name, message):
  99. if hasattr(name, 'parent') and value is not None:
  100. analysis.add(value, 'import-error', name, message)
  101. else:
  102. debug.warning('ImportError without origin: ' + message)
  103. def _level_to_base_import_path(project_path, directory, level):
  104. """
  105. In case the level is outside of the currently known package (something like
  106. import .....foo), we can still try our best to help the user for
  107. completions.
  108. """
  109. for i in range(level - 1):
  110. old = directory
  111. directory = os.path.dirname(directory)
  112. if old == directory:
  113. return None, None
  114. d = directory
  115. level_import_paths = []
  116. # Now that we are on the level that the user wants to be, calculate the
  117. # import path for it.
  118. while True:
  119. if d == project_path:
  120. return level_import_paths, d
  121. dir_name = os.path.basename(d)
  122. if dir_name:
  123. level_import_paths.insert(0, dir_name)
  124. d = os.path.dirname(d)
  125. else:
  126. return None, directory
  127. class Importer:
  128. def __init__(self, inference_state, import_path, module_context, level=0):
  129. """
  130. An implementation similar to ``__import__``. Use `follow`
  131. to actually follow the imports.
  132. *level* specifies whether to use absolute or relative imports. 0 (the
  133. default) means only perform absolute imports. Positive values for level
  134. indicate the number of parent directories to search relative to the
  135. directory of the module calling ``__import__()`` (see PEP 328 for the
  136. details).
  137. :param import_path: List of namespaces (strings or Names).
  138. """
  139. debug.speed('import %s %s' % (import_path, module_context))
  140. self._inference_state = inference_state
  141. self.level = level
  142. self._module_context = module_context
  143. self._fixed_sys_path = None
  144. self._infer_possible = True
  145. if level:
  146. base = module_context.get_value().py__package__()
  147. # We need to care for two cases, the first one is if it's a valid
  148. # Python import. This import has a properly defined module name
  149. # chain like `foo.bar.baz` and an import in baz is made for
  150. # `..lala.` It can then resolve to `foo.bar.lala`.
  151. # The else here is a heuristic for all other cases, if for example
  152. # in `foo` you search for `...bar`, it's obviously out of scope.
  153. # However since Jedi tries to just do it's best, we help the user
  154. # here, because he might have specified something wrong in his
  155. # project.
  156. if level <= len(base):
  157. # Here we basically rewrite the level to 0.
  158. base = tuple(base)
  159. if level > 1:
  160. base = base[:-level + 1]
  161. import_path = base + tuple(import_path)
  162. else:
  163. path = module_context.py__file__()
  164. project_path = self._inference_state.project.path
  165. import_path = list(import_path)
  166. if path is None:
  167. # If no path is defined, our best guess is that the current
  168. # file is edited by a user on the current working
  169. # directory. We need to add an initial path, because it
  170. # will get removed as the name of the current file.
  171. directory = project_path
  172. else:
  173. directory = os.path.dirname(path)
  174. base_import_path, base_directory = _level_to_base_import_path(
  175. project_path, directory, level,
  176. )
  177. if base_directory is None:
  178. # Everything is lost, the relative import does point
  179. # somewhere out of the filesystem.
  180. self._infer_possible = False
  181. else:
  182. self._fixed_sys_path = [base_directory]
  183. if base_import_path is None:
  184. if import_path:
  185. _add_error(
  186. module_context, import_path[0],
  187. message='Attempted relative import beyond top-level package.'
  188. )
  189. else:
  190. import_path = base_import_path + import_path
  191. self.import_path = import_path
  192. @property
  193. def _str_import_path(self):
  194. """Returns the import path as pure strings instead of `Name`."""
  195. return tuple(
  196. name.value if isinstance(name, tree.Name) else name
  197. for name in self.import_path
  198. )
  199. def _sys_path_with_modifications(self, is_completion):
  200. if self._fixed_sys_path is not None:
  201. return self._fixed_sys_path
  202. return (
  203. # For import completions we don't want to see init paths, but for
  204. # inference we want to show the user as much as possible.
  205. # See GH #1446.
  206. self._inference_state.get_sys_path(add_init_paths=not is_completion)
  207. + [
  208. str(p) for p
  209. in sys_path.check_sys_path_modifications(self._module_context)
  210. ]
  211. )
  212. def follow(self):
  213. if not self.import_path:
  214. if self._fixed_sys_path:
  215. # This is a bit of a special case, that maybe should be
  216. # revisited. If the project path is wrong or the user uses
  217. # relative imports the wrong way, we might end up here, where
  218. # the `fixed_sys_path == project.path` in that case we kind of
  219. # use the project.path.parent directory as our path. This is
  220. # usually not a problem, except if imports in other places are
  221. # using the same names. Example:
  222. #
  223. # foo/ < #1
  224. # - setup.py
  225. # - foo/ < #2
  226. # - __init__.py
  227. # - foo.py < #3
  228. #
  229. # If the top foo is our project folder and somebody uses
  230. # `from . import foo` in `setup.py`, it will resolve to foo #2,
  231. # which means that the import for foo.foo is cached as
  232. # `__init__.py` (#2) and not as `foo.py` (#3). This is usually
  233. # not an issue, because this case is probably pretty rare, but
  234. # might be an issue for some people.
  235. #
  236. # However for most normal cases where we work with different
  237. # file names, this code path hits where we basically change the
  238. # project path to an ancestor of project path.
  239. from jedi.inference.value.namespace import ImplicitNamespaceValue
  240. import_path = (os.path.basename(self._fixed_sys_path[0]),)
  241. ns = ImplicitNamespaceValue(
  242. self._inference_state,
  243. string_names=import_path,
  244. paths=self._fixed_sys_path,
  245. )
  246. return ValueSet({ns})
  247. return NO_VALUES
  248. if not self._infer_possible:
  249. return NO_VALUES
  250. # Check caches first
  251. from_cache = self._inference_state.stub_module_cache.get(self._str_import_path)
  252. if from_cache is not None:
  253. return ValueSet({from_cache})
  254. from_cache = self._inference_state.module_cache.get(self._str_import_path)
  255. if from_cache is not None:
  256. return from_cache
  257. sys_path = self._sys_path_with_modifications(is_completion=False)
  258. return import_module_by_names(
  259. self._inference_state, self.import_path, sys_path, self._module_context
  260. )
  261. def _get_module_names(self, search_path=None, in_module=None):
  262. """
  263. Get the names of all modules in the search_path. This means file names
  264. and not names defined in the files.
  265. """
  266. if search_path is None:
  267. sys_path = self._sys_path_with_modifications(is_completion=True)
  268. else:
  269. sys_path = search_path
  270. return list(iter_module_names(
  271. self._inference_state, self._module_context, sys_path,
  272. module_cls=ImportName if in_module is None else SubModuleName,
  273. add_builtin_modules=search_path is None and in_module is None,
  274. ))
  275. def completion_names(self, inference_state, only_modules=False):
  276. """
  277. :param only_modules: Indicates wheter it's possible to import a
  278. definition that is not defined in a module.
  279. """
  280. if not self._infer_possible:
  281. return []
  282. names = []
  283. if self.import_path:
  284. # flask
  285. if self._str_import_path == ('flask', 'ext'):
  286. # List Flask extensions like ``flask_foo``
  287. for mod in self._get_module_names():
  288. modname = mod.string_name
  289. if modname.startswith('flask_'):
  290. extname = modname[len('flask_'):]
  291. names.append(ImportName(self._module_context, extname))
  292. # Now the old style: ``flaskext.foo``
  293. for dir in self._sys_path_with_modifications(is_completion=True):
  294. flaskext = os.path.join(dir, 'flaskext')
  295. if os.path.isdir(flaskext):
  296. names += self._get_module_names([flaskext])
  297. values = self.follow()
  298. for value in values:
  299. # Non-modules are not completable.
  300. if value.api_type not in ('module', 'namespace'): # not a module
  301. continue
  302. if not value.is_compiled():
  303. # sub_modules_dict is not implemented for compiled modules.
  304. names += value.sub_modules_dict().values()
  305. if not only_modules:
  306. from jedi.inference.gradual.conversion import convert_values
  307. both_values = values | convert_values(values)
  308. for c in both_values:
  309. for filter in c.get_filters():
  310. names += filter.values()
  311. else:
  312. if self.level:
  313. # We only get here if the level cannot be properly calculated.
  314. names += self._get_module_names(self._fixed_sys_path)
  315. else:
  316. # This is just the list of global imports.
  317. names += self._get_module_names()
  318. return names
  319. def import_module_by_names(inference_state, import_names, sys_path=None,
  320. module_context=None, prefer_stubs=True):
  321. if sys_path is None:
  322. sys_path = inference_state.get_sys_path()
  323. str_import_names = tuple(
  324. i.value if isinstance(i, tree.Name) else i
  325. for i in import_names
  326. )
  327. value_set = [None]
  328. for i, name in enumerate(import_names):
  329. value_set = ValueSet.from_sets([
  330. import_module(
  331. inference_state,
  332. str_import_names[:i+1],
  333. parent_module_value,
  334. sys_path,
  335. prefer_stubs=prefer_stubs,
  336. ) for parent_module_value in value_set
  337. ])
  338. if not value_set:
  339. message = 'No module named ' + '.'.join(str_import_names)
  340. if module_context is not None:
  341. _add_error(module_context, name, message)
  342. else:
  343. debug.warning(message)
  344. return NO_VALUES
  345. return value_set
  346. @plugin_manager.decorate()
  347. @import_module_decorator
  348. def import_module(inference_state, import_names, parent_module_value, sys_path):
  349. """
  350. This method is very similar to importlib's `_gcd_import`.
  351. """
  352. if import_names[0] in settings.auto_import_modules:
  353. module = _load_builtin_module(inference_state, import_names, sys_path)
  354. if module is None:
  355. return NO_VALUES
  356. return ValueSet([module])
  357. module_name = '.'.join(import_names)
  358. if parent_module_value is None:
  359. # Override the sys.path. It works only good that way.
  360. # Injecting the path directly into `find_module` did not work.
  361. file_io_or_ns, is_pkg = inference_state.compiled_subprocess.get_module_info(
  362. string=import_names[-1],
  363. full_name=module_name,
  364. sys_path=sys_path,
  365. is_global_search=True,
  366. )
  367. if is_pkg is None:
  368. return NO_VALUES
  369. else:
  370. paths = parent_module_value.py__path__()
  371. if paths is None:
  372. # The module might not be a package.
  373. return NO_VALUES
  374. file_io_or_ns, is_pkg = inference_state.compiled_subprocess.get_module_info(
  375. string=import_names[-1],
  376. path=paths,
  377. full_name=module_name,
  378. is_global_search=False,
  379. )
  380. if is_pkg is None:
  381. return NO_VALUES
  382. if isinstance(file_io_or_ns, ImplicitNSInfo):
  383. from jedi.inference.value.namespace import ImplicitNamespaceValue
  384. module = ImplicitNamespaceValue(
  385. inference_state,
  386. string_names=tuple(file_io_or_ns.name.split('.')),
  387. paths=file_io_or_ns.paths,
  388. )
  389. elif file_io_or_ns is None:
  390. module = _load_builtin_module(inference_state, import_names, sys_path)
  391. if module is None:
  392. return NO_VALUES
  393. else:
  394. module = _load_python_module(
  395. inference_state, file_io_or_ns,
  396. import_names=import_names,
  397. is_package=is_pkg,
  398. )
  399. if parent_module_value is None:
  400. debug.dbg('global search_module %s: %s', import_names[-1], module)
  401. else:
  402. debug.dbg('search_module %s in paths %s: %s', module_name, paths, module)
  403. return ValueSet([module])
  404. def _load_python_module(inference_state, file_io,
  405. import_names=None, is_package=False):
  406. module_node = inference_state.parse(
  407. file_io=file_io,
  408. cache=True,
  409. diff_cache=settings.fast_parser,
  410. cache_path=settings.cache_directory,
  411. )
  412. from jedi.inference.value import ModuleValue
  413. return ModuleValue(
  414. inference_state, module_node,
  415. file_io=file_io,
  416. string_names=import_names,
  417. code_lines=get_cached_code_lines(inference_state.grammar, file_io.path),
  418. is_package=is_package,
  419. )
  420. def _load_builtin_module(inference_state, import_names=None, sys_path=None):
  421. project = inference_state.project
  422. if sys_path is None:
  423. sys_path = inference_state.get_sys_path()
  424. if not project._load_unsafe_extensions:
  425. safe_paths = project._get_base_sys_path(inference_state)
  426. sys_path = [p for p in sys_path if p in safe_paths]
  427. dotted_name = '.'.join(import_names)
  428. assert dotted_name is not None
  429. module = compiled.load_module(inference_state, dotted_name=dotted_name, sys_path=sys_path)
  430. if module is None:
  431. # The file might raise an ImportError e.g. and therefore not be
  432. # importable.
  433. return None
  434. return module
  435. def load_module_from_path(inference_state, file_io, import_names=None, is_package=None):
  436. """
  437. This should pretty much only be used for get_modules_containing_name. It's
  438. here to ensure that a random path is still properly loaded into the Jedi
  439. module structure.
  440. """
  441. path = Path(file_io.path)
  442. if import_names is None:
  443. e_sys_path = inference_state.get_sys_path()
  444. import_names, is_package = sys_path.transform_path_to_dotted(e_sys_path, path)
  445. else:
  446. assert isinstance(is_package, bool)
  447. is_stub = path.suffix == '.pyi'
  448. if is_stub:
  449. folder_io = file_io.get_parent_folder()
  450. if folder_io.path.endswith('-stubs'):
  451. folder_io = FolderIO(folder_io.path[:-6])
  452. if path.name == '__init__.pyi':
  453. python_file_io = folder_io.get_file_io('__init__.py')
  454. else:
  455. python_file_io = folder_io.get_file_io(import_names[-1] + '.py')
  456. try:
  457. v = load_module_from_path(
  458. inference_state, python_file_io,
  459. import_names, is_package=is_package
  460. )
  461. values = ValueSet([v])
  462. except FileNotFoundError:
  463. values = NO_VALUES
  464. return create_stub_module(
  465. inference_state, inference_state.latest_grammar, values,
  466. parse_stub_module(inference_state, file_io), file_io, import_names
  467. )
  468. else:
  469. module = _load_python_module(
  470. inference_state, file_io,
  471. import_names=import_names,
  472. is_package=is_package,
  473. )
  474. inference_state.module_cache.add(import_names, ValueSet([module]))
  475. return module
  476. def load_namespace_from_path(inference_state, folder_io):
  477. import_names, is_package = sys_path.transform_path_to_dotted(
  478. inference_state.get_sys_path(),
  479. Path(folder_io.path)
  480. )
  481. from jedi.inference.value.namespace import ImplicitNamespaceValue
  482. return ImplicitNamespaceValue(inference_state, import_names, [folder_io.path])
  483. def follow_error_node_imports_if_possible(context, name):
  484. error_node = tree.search_ancestor(name, 'error_node')
  485. if error_node is not None:
  486. # Get the first command start of a started simple_stmt. The error
  487. # node is sometimes a small_stmt and sometimes a simple_stmt. Check
  488. # for ; leaves that start a new statements.
  489. start_index = 0
  490. for index, n in enumerate(error_node.children):
  491. if n.start_pos > name.start_pos:
  492. break
  493. if n == ';':
  494. start_index = index + 1
  495. nodes = error_node.children[start_index:]
  496. first_name = nodes[0].get_first_leaf().value
  497. # Make it possible to infer stuff like `import foo.` or
  498. # `from foo.bar`.
  499. if first_name in ('from', 'import'):
  500. is_import_from = first_name == 'from'
  501. level, names = helpers.parse_dotted_names(
  502. nodes,
  503. is_import_from=is_import_from,
  504. until_node=name,
  505. )
  506. return Importer(
  507. context.inference_state, names, context.get_root_context(), level).follow()
  508. return None
  509. def iter_module_names(inference_state, module_context, search_path,
  510. module_cls=ImportName, add_builtin_modules=True):
  511. """
  512. Get the names of all modules in the search_path. This means file names
  513. and not names defined in the files.
  514. """
  515. # add builtin module names
  516. if add_builtin_modules:
  517. for name in inference_state.compiled_subprocess.get_builtin_module_names():
  518. yield module_cls(module_context, name)
  519. for name in inference_state.compiled_subprocess.iter_module_names(search_path):
  520. yield module_cls(module_context, name)