manager.py 18 KB

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