manager.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
  2. # For details: https://github.com/PyCQA/astroid/blob/main/LICENSE
  3. # Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt
  4. """astroid manager: avoid multiple astroid build of a same module when
  5. possible by providing a class responsible to get astroid representation
  6. from various source and using a cache of built modules)
  7. """
  8. from __future__ import annotations
  9. import collections
  10. import os
  11. import types
  12. import zipimport
  13. from collections.abc import Callable, Iterator, Sequence
  14. from importlib.util import find_spec, module_from_spec
  15. from typing import Any, ClassVar
  16. from astroid import nodes
  17. from astroid._cache import CACHE_MANAGER
  18. from astroid.const import BRAIN_MODULES_DIRECTORY
  19. from astroid.context import InferenceContext, _invalidate_cache
  20. from astroid.exceptions import AstroidBuildingError, AstroidImportError
  21. from astroid.interpreter._import import spec, util
  22. from astroid.modutils import (
  23. NoSourceFile,
  24. _cache_normalize_path_,
  25. file_info_from_modpath,
  26. get_source_file,
  27. is_module_name_part_of_extension_package_whitelist,
  28. is_python_source,
  29. is_stdlib_module,
  30. load_module_from_name,
  31. modpath_from_file,
  32. )
  33. from astroid.transforms import TransformVisitor
  34. from astroid.typing import AstroidManagerBrain, InferenceResult
  35. ZIP_IMPORT_EXTS = (".zip", ".egg", ".whl", ".pyz", ".pyzw")
  36. def safe_repr(obj: Any) -> str:
  37. try:
  38. return repr(obj)
  39. except Exception: # pylint: disable=broad-except
  40. return "???"
  41. class AstroidManager:
  42. """Responsible to build astroid from files or modules.
  43. Use the Borg (singleton) pattern.
  44. """
  45. name = "astroid loader"
  46. brain: AstroidManagerBrain = {
  47. "astroid_cache": {},
  48. "_mod_file_cache": {},
  49. "_failed_import_hooks": [],
  50. "always_load_extensions": False,
  51. "optimize_ast": False,
  52. "extension_package_whitelist": set(),
  53. "_transform": TransformVisitor(),
  54. }
  55. max_inferable_values: ClassVar[int] = 100
  56. def __init__(self) -> None:
  57. # NOTE: cache entries are added by the [re]builder
  58. self.astroid_cache = AstroidManager.brain["astroid_cache"]
  59. self._mod_file_cache = AstroidManager.brain["_mod_file_cache"]
  60. self._failed_import_hooks = AstroidManager.brain["_failed_import_hooks"]
  61. self.extension_package_whitelist = AstroidManager.brain[
  62. "extension_package_whitelist"
  63. ]
  64. self._transform = AstroidManager.brain["_transform"]
  65. @property
  66. def always_load_extensions(self) -> bool:
  67. return AstroidManager.brain["always_load_extensions"]
  68. @always_load_extensions.setter
  69. def always_load_extensions(self, value: bool) -> None:
  70. AstroidManager.brain["always_load_extensions"] = value
  71. @property
  72. def optimize_ast(self) -> bool:
  73. return AstroidManager.brain["optimize_ast"]
  74. @optimize_ast.setter
  75. def optimize_ast(self, value: bool) -> None:
  76. AstroidManager.brain["optimize_ast"] = value
  77. @property
  78. def register_transform(self):
  79. # This and unregister_transform below are exported for convenience
  80. return self._transform.register_transform
  81. @property
  82. def unregister_transform(self):
  83. return self._transform.unregister_transform
  84. @property
  85. def builtins_module(self) -> nodes.Module:
  86. return self.astroid_cache["builtins"]
  87. def visit_transforms(self, node: nodes.NodeNG) -> InferenceResult:
  88. """Visit the transforms and apply them to the given *node*."""
  89. return self._transform.visit(node)
  90. def ast_from_file(
  91. self,
  92. filepath: str,
  93. modname: str | None = None,
  94. fallback: bool = True,
  95. source: bool = False,
  96. ) -> nodes.Module:
  97. """Given a module name, return the astroid object."""
  98. try:
  99. filepath = get_source_file(filepath, include_no_ext=True)
  100. source = True
  101. except NoSourceFile:
  102. pass
  103. if modname is None:
  104. try:
  105. modname = ".".join(modpath_from_file(filepath))
  106. except ImportError:
  107. modname = filepath
  108. if (
  109. modname in self.astroid_cache
  110. and self.astroid_cache[modname].file == filepath
  111. ):
  112. return self.astroid_cache[modname]
  113. if source:
  114. # pylint: disable=import-outside-toplevel; circular import
  115. from astroid.builder import AstroidBuilder
  116. return AstroidBuilder(self).file_build(filepath, modname)
  117. if fallback and modname:
  118. return self.ast_from_module_name(modname)
  119. raise AstroidBuildingError("Unable to build an AST for {path}.", path=filepath)
  120. def ast_from_string(
  121. self, data: str, modname: str = "", filepath: str | None = None
  122. ) -> nodes.Module:
  123. """Given some source code as a string, return its corresponding astroid
  124. object.
  125. """
  126. # pylint: disable=import-outside-toplevel; circular import
  127. from astroid.builder import AstroidBuilder
  128. return AstroidBuilder(self).string_build(data, modname, filepath)
  129. def _build_stub_module(self, modname: str) -> nodes.Module:
  130. # pylint: disable=import-outside-toplevel; circular import
  131. from astroid.builder import AstroidBuilder
  132. return AstroidBuilder(self).string_build("", modname)
  133. def _build_namespace_module(
  134. self, modname: str, path: Sequence[str]
  135. ) -> nodes.Module:
  136. # pylint: disable=import-outside-toplevel; circular import
  137. from astroid.builder import build_namespace_package_module
  138. return build_namespace_package_module(modname, path)
  139. def _can_load_extension(self, modname: str) -> bool:
  140. if self.always_load_extensions:
  141. return True
  142. if is_stdlib_module(modname):
  143. return True
  144. return is_module_name_part_of_extension_package_whitelist(
  145. modname, self.extension_package_whitelist
  146. )
  147. def ast_from_module_name( # noqa: C901
  148. self,
  149. modname: str | None,
  150. context_file: str | None = None,
  151. use_cache: bool = True,
  152. ) -> nodes.Module:
  153. """Given a module name, return the astroid object."""
  154. if modname is None:
  155. raise AstroidBuildingError("No module name given.")
  156. # Sometimes we don't want to use the cache. For example, when we're
  157. # importing a module with the same name as the file that is importing
  158. # we want to fallback on the import system to make sure we get the correct
  159. # module.
  160. if modname in self.astroid_cache and use_cache:
  161. return self.astroid_cache[modname]
  162. if modname == "__main__":
  163. return self._build_stub_module(modname)
  164. if context_file:
  165. old_cwd = os.getcwd()
  166. os.chdir(os.path.dirname(context_file))
  167. try:
  168. found_spec = self.file_from_module_name(modname, context_file)
  169. if found_spec.type == spec.ModuleType.PY_ZIPMODULE:
  170. module = self.zip_import_data(found_spec.location)
  171. if module is not None:
  172. return module
  173. elif found_spec.type in (
  174. spec.ModuleType.C_BUILTIN,
  175. spec.ModuleType.C_EXTENSION,
  176. ):
  177. if (
  178. found_spec.type == spec.ModuleType.C_EXTENSION
  179. and not self._can_load_extension(modname)
  180. ):
  181. return self._build_stub_module(modname)
  182. try:
  183. named_module = load_module_from_name(modname)
  184. except Exception as e:
  185. raise AstroidImportError(
  186. "Loading {modname} failed with:\n{error}",
  187. modname=modname,
  188. path=found_spec.location,
  189. ) from e
  190. return self.ast_from_module(named_module, modname)
  191. elif found_spec.type == spec.ModuleType.PY_COMPILED:
  192. raise AstroidImportError(
  193. "Unable to load compiled module {modname}.",
  194. modname=modname,
  195. path=found_spec.location,
  196. )
  197. elif found_spec.type == spec.ModuleType.PY_NAMESPACE:
  198. return self._build_namespace_module(
  199. modname, found_spec.submodule_search_locations or []
  200. )
  201. elif found_spec.type == spec.ModuleType.PY_FROZEN:
  202. if found_spec.location is None:
  203. return self._build_stub_module(modname)
  204. # For stdlib frozen modules we can determine the location and
  205. # can therefore create a module from the source file
  206. return self.ast_from_file(found_spec.location, modname, fallback=False)
  207. if found_spec.location is None:
  208. raise AstroidImportError(
  209. "Can't find a file for module {modname}.", modname=modname
  210. )
  211. return self.ast_from_file(found_spec.location, modname, fallback=False)
  212. except AstroidBuildingError as e:
  213. for hook in self._failed_import_hooks:
  214. try:
  215. return hook(modname)
  216. except AstroidBuildingError:
  217. pass
  218. raise e
  219. finally:
  220. if context_file:
  221. os.chdir(old_cwd)
  222. def zip_import_data(self, filepath: str) -> nodes.Module | None:
  223. if zipimport is None:
  224. return None
  225. # pylint: disable=import-outside-toplevel; circular import
  226. from astroid.builder import AstroidBuilder
  227. builder = AstroidBuilder(self)
  228. for ext in ZIP_IMPORT_EXTS:
  229. try:
  230. eggpath, resource = filepath.rsplit(ext + os.path.sep, 1)
  231. except ValueError:
  232. continue
  233. try:
  234. # pylint: disable-next=no-member
  235. importer = zipimport.zipimporter(eggpath + ext)
  236. zmodname = resource.replace(os.path.sep, ".")
  237. if importer.is_package(resource):
  238. zmodname = zmodname + ".__init__"
  239. module = builder.string_build(
  240. importer.get_source(resource), zmodname, filepath
  241. )
  242. return module
  243. except Exception: # pylint: disable=broad-except
  244. continue
  245. return None
  246. def file_from_module_name(
  247. self, modname: str, contextfile: str | None
  248. ) -> spec.ModuleSpec:
  249. try:
  250. value = self._mod_file_cache[(modname, contextfile)]
  251. except KeyError:
  252. try:
  253. value = file_info_from_modpath(
  254. modname.split("."), context_file=contextfile
  255. )
  256. except ImportError as e:
  257. # pylint: disable-next=redefined-variable-type
  258. value = AstroidImportError(
  259. "Failed to import module {modname} with error:\n{error}.",
  260. modname=modname,
  261. # we remove the traceback here to save on memory usage (since these exceptions are cached)
  262. error=e.with_traceback(None),
  263. )
  264. self._mod_file_cache[(modname, contextfile)] = value
  265. if isinstance(value, AstroidBuildingError):
  266. # we remove the traceback here to save on memory usage (since these exceptions are cached)
  267. raise value.with_traceback(None) # pylint: disable=no-member
  268. return value
  269. def ast_from_module(
  270. self, module: types.ModuleType, modname: str | None = None
  271. ) -> nodes.Module:
  272. """Given an imported module, return the astroid object."""
  273. modname = modname or module.__name__
  274. if modname in self.astroid_cache:
  275. return self.astroid_cache[modname]
  276. try:
  277. # some builtin modules don't have __file__ attribute
  278. filepath = module.__file__
  279. if is_python_source(filepath):
  280. # Type is checked in is_python_source
  281. return self.ast_from_file(filepath, modname) # type: ignore[arg-type]
  282. except AttributeError:
  283. pass
  284. # pylint: disable=import-outside-toplevel; circular import
  285. from astroid.builder import AstroidBuilder
  286. return AstroidBuilder(self).module_build(module, modname)
  287. def ast_from_class(self, klass: type, modname: str | None = None) -> nodes.ClassDef:
  288. """Get astroid for the given class."""
  289. if modname is None:
  290. try:
  291. modname = klass.__module__
  292. except AttributeError as exc:
  293. raise AstroidBuildingError(
  294. "Unable to get module for class {class_name}.",
  295. cls=klass,
  296. class_repr=safe_repr(klass),
  297. modname=modname,
  298. ) from exc
  299. modastroid = self.ast_from_module_name(modname)
  300. ret = modastroid.getattr(klass.__name__)[0]
  301. assert isinstance(ret, nodes.ClassDef)
  302. return ret
  303. def infer_ast_from_something(
  304. self, obj: object, context: InferenceContext | None = None
  305. ) -> Iterator[InferenceResult]:
  306. """Infer astroid for the given class."""
  307. if hasattr(obj, "__class__") and not isinstance(obj, type):
  308. klass = obj.__class__
  309. elif isinstance(obj, type):
  310. klass = obj
  311. else:
  312. raise AstroidBuildingError( # pragma: no cover
  313. "Unable to get type for {class_repr}.",
  314. cls=None,
  315. class_repr=safe_repr(obj),
  316. )
  317. try:
  318. modname = klass.__module__
  319. except AttributeError as exc:
  320. raise AstroidBuildingError(
  321. "Unable to get module for {class_repr}.",
  322. cls=klass,
  323. class_repr=safe_repr(klass),
  324. ) from exc
  325. except Exception as exc:
  326. raise AstroidImportError(
  327. "Unexpected error while retrieving module for {class_repr}:\n"
  328. "{error}",
  329. cls=klass,
  330. class_repr=safe_repr(klass),
  331. ) from exc
  332. try:
  333. name = klass.__name__
  334. except AttributeError as exc:
  335. raise AstroidBuildingError(
  336. "Unable to get name for {class_repr}:\n",
  337. cls=klass,
  338. class_repr=safe_repr(klass),
  339. ) from exc
  340. except Exception as exc:
  341. raise AstroidImportError(
  342. "Unexpected error while retrieving name for {class_repr}:\n{error}",
  343. cls=klass,
  344. class_repr=safe_repr(klass),
  345. ) from exc
  346. # take care, on living object __module__ is regularly wrong :(
  347. modastroid = self.ast_from_module_name(modname)
  348. if klass is obj:
  349. for inferred in modastroid.igetattr(name, context):
  350. yield inferred
  351. else:
  352. for inferred in modastroid.igetattr(name, context):
  353. yield inferred.instantiate_class()
  354. def register_failed_import_hook(self, hook: Callable[[str], nodes.Module]) -> None:
  355. """Registers a hook to resolve imports that cannot be found otherwise.
  356. `hook` must be a function that accepts a single argument `modname` which
  357. contains the name of the module or package that could not be imported.
  358. If `hook` can resolve the import, must return a node of type `astroid.Module`,
  359. otherwise, it must raise `AstroidBuildingError`.
  360. """
  361. self._failed_import_hooks.append(hook)
  362. def cache_module(self, module: nodes.Module) -> None:
  363. """Cache a module if no module with the same name is known yet."""
  364. self.astroid_cache.setdefault(module.name, module)
  365. def bootstrap(self) -> None:
  366. """Bootstrap the required AST modules needed for the manager to work.
  367. The bootstrap usually involves building the AST for the builtins
  368. module, which is required by the rest of astroid to work correctly.
  369. """
  370. from astroid import raw_building # pylint: disable=import-outside-toplevel
  371. raw_building._astroid_bootstrapping()
  372. def clear_cache(self) -> None:
  373. """Clear the underlying caches, bootstrap the builtins module and
  374. re-register transforms.
  375. """
  376. # import here because of cyclic imports
  377. # pylint: disable=import-outside-toplevel
  378. from astroid.inference_tip import clear_inference_tip_cache
  379. from astroid.interpreter.objectmodel import ObjectModel
  380. from astroid.nodes.node_classes import LookupMixIn
  381. from astroid.nodes.scoped_nodes import ClassDef
  382. clear_inference_tip_cache()
  383. _invalidate_cache() # inference context cache
  384. self.astroid_cache.clear()
  385. # NB: not a new TransformVisitor()
  386. AstroidManager.brain["_transform"].transforms = collections.defaultdict(list)
  387. CACHE_MANAGER.clear_all_caches()
  388. for lru_cache in (
  389. LookupMixIn.lookup,
  390. _cache_normalize_path_,
  391. util.is_namespace,
  392. ObjectModel.attributes,
  393. ClassDef._metaclass_lookup_attribute,
  394. ):
  395. lru_cache.cache_clear() # type: ignore[attr-defined]
  396. self.bootstrap()
  397. # Reload brain plugins. During initialisation this is done in astroid.__init__.py
  398. for module in BRAIN_MODULES_DIRECTORY.iterdir():
  399. if module.suffix == ".py":
  400. module_spec = find_spec(f"astroid.brain.{module.stem}")
  401. assert module_spec
  402. module_object = module_from_spec(module_spec)
  403. assert module_spec.loader
  404. module_spec.loader.exec_module(module_object)