builder.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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. """The AstroidBuilder makes astroid from living object and / or from _ast.
  5. The builder is not thread safe and can't be used to parse different sources
  6. at the same time.
  7. """
  8. from __future__ import annotations
  9. import ast
  10. import os
  11. import textwrap
  12. import types
  13. from collections.abc import Iterator, Sequence
  14. from io import TextIOWrapper
  15. from tokenize import detect_encoding
  16. from typing import TYPE_CHECKING
  17. from astroid import bases, modutils, nodes, raw_building, rebuilder, util
  18. from astroid._ast import ParserModule, get_parser_module
  19. from astroid.exceptions import AstroidBuildingError, AstroidSyntaxError, InferenceError
  20. from astroid.manager import AstroidManager
  21. if TYPE_CHECKING:
  22. from astroid import objects
  23. else:
  24. objects = util.lazy_import("objects")
  25. # The name of the transient function that is used to
  26. # wrap expressions to be extracted when calling
  27. # extract_node.
  28. _TRANSIENT_FUNCTION = "__"
  29. # The comment used to select a statement to be extracted
  30. # when calling extract_node.
  31. _STATEMENT_SELECTOR = "#@"
  32. MISPLACED_TYPE_ANNOTATION_ERROR = "misplaced type annotation"
  33. def open_source_file(filename: str) -> tuple[TextIOWrapper, str, str]:
  34. # pylint: disable=consider-using-with
  35. with open(filename, "rb") as byte_stream:
  36. encoding = detect_encoding(byte_stream.readline)[0]
  37. stream = open(filename, newline=None, encoding=encoding)
  38. data = stream.read()
  39. return stream, encoding, data
  40. def _can_assign_attr(node: nodes.ClassDef, attrname: str | None) -> bool:
  41. try:
  42. slots = node.slots()
  43. except NotImplementedError:
  44. pass
  45. else:
  46. if slots and attrname not in {slot.value for slot in slots}:
  47. return False
  48. return node.qname() != "builtins.object"
  49. class AstroidBuilder(raw_building.InspectBuilder):
  50. """Class for building an astroid tree from source code or from a live module.
  51. The param *manager* specifies the manager class which should be used.
  52. If no manager is given, then the default one will be used. The
  53. param *apply_transforms* determines if the transforms should be
  54. applied after the tree was built from source or from a live object,
  55. by default being True.
  56. """
  57. def __init__(
  58. self, manager: AstroidManager | None = None, apply_transforms: bool = True
  59. ) -> None:
  60. super().__init__(manager)
  61. self._apply_transforms = apply_transforms
  62. def module_build(
  63. self, module: types.ModuleType, modname: str | None = None
  64. ) -> nodes.Module:
  65. """Build an astroid from a living module instance."""
  66. node = None
  67. path = getattr(module, "__file__", None)
  68. loader = getattr(module, "__loader__", None)
  69. # Prefer the loader to get the source rather than assuming we have a
  70. # filesystem to read the source file from ourselves.
  71. if loader:
  72. modname = modname or module.__name__
  73. source = loader.get_source(modname)
  74. if source:
  75. node = self.string_build(source, modname, path=path)
  76. if node is None and path is not None:
  77. path_, ext = os.path.splitext(modutils._path_from_filename(path))
  78. if ext in {".py", ".pyc", ".pyo"} and os.path.exists(path_ + ".py"):
  79. node = self.file_build(path_ + ".py", modname)
  80. if node is None:
  81. # this is a built-in module
  82. # get a partial representation by introspection
  83. node = self.inspect_build(module, modname=modname, path=path)
  84. if self._apply_transforms:
  85. # We have to handle transformation by ourselves since the
  86. # rebuilder isn't called for builtin nodes
  87. node = self._manager.visit_transforms(node)
  88. assert isinstance(node, nodes.Module)
  89. return node
  90. def file_build(self, path: str, modname: str | None = None) -> nodes.Module:
  91. """Build astroid from a source code file (i.e. from an ast).
  92. *path* is expected to be a python source file
  93. """
  94. try:
  95. stream, encoding, data = open_source_file(path)
  96. except OSError as exc:
  97. raise AstroidBuildingError(
  98. "Unable to load file {path}:\n{error}",
  99. modname=modname,
  100. path=path,
  101. error=exc,
  102. ) from exc
  103. except (SyntaxError, LookupError) as exc:
  104. raise AstroidSyntaxError(
  105. "Python 3 encoding specification error or unknown encoding:\n"
  106. "{error}",
  107. modname=modname,
  108. path=path,
  109. error=exc,
  110. ) from exc
  111. except UnicodeError as exc: # wrong encoding
  112. # detect_encoding returns utf-8 if no encoding specified
  113. raise AstroidBuildingError(
  114. "Wrong or no encoding specified for {filename}.", filename=path
  115. ) from exc
  116. with stream:
  117. # get module name if necessary
  118. if modname is None:
  119. try:
  120. modname = ".".join(modutils.modpath_from_file(path))
  121. except ImportError:
  122. modname = os.path.splitext(os.path.basename(path))[0]
  123. # build astroid representation
  124. module, builder = self._data_build(data, modname, path)
  125. return self._post_build(module, builder, encoding)
  126. def string_build(
  127. self, data: str, modname: str = "", path: str | None = None
  128. ) -> nodes.Module:
  129. """Build astroid from source code string."""
  130. module, builder = self._data_build(data, modname, path)
  131. module.file_bytes = data.encode("utf-8")
  132. return self._post_build(module, builder, "utf-8")
  133. def _post_build(
  134. self, module: nodes.Module, builder: rebuilder.TreeRebuilder, encoding: str
  135. ) -> nodes.Module:
  136. """Handles encoding and delayed nodes after a module has been built."""
  137. module.file_encoding = encoding
  138. self._manager.cache_module(module)
  139. # post tree building steps after we stored the module in the cache:
  140. for from_node in builder._import_from_nodes:
  141. if from_node.modname == "__future__":
  142. for symbol, _ in from_node.names:
  143. module.future_imports.add(symbol)
  144. self.add_from_names_to_locals(from_node)
  145. # handle delayed assattr nodes
  146. for delayed in builder._delayed_assattr:
  147. self.delayed_assattr(delayed)
  148. # Visit the transforms
  149. if self._apply_transforms:
  150. module = self._manager.visit_transforms(module)
  151. return module
  152. def _data_build(
  153. self, data: str, modname: str, path: str | None
  154. ) -> tuple[nodes.Module, rebuilder.TreeRebuilder]:
  155. """Build tree node from data and add some informations."""
  156. try:
  157. node, parser_module = _parse_string(data, type_comments=True)
  158. except (TypeError, ValueError, SyntaxError) as exc:
  159. raise AstroidSyntaxError(
  160. "Parsing Python code failed:\n{error}",
  161. source=data,
  162. modname=modname,
  163. path=path,
  164. error=exc,
  165. ) from exc
  166. if path is not None:
  167. node_file = os.path.abspath(path)
  168. else:
  169. node_file = "<?>"
  170. if modname.endswith(".__init__"):
  171. modname = modname[:-9]
  172. package = True
  173. else:
  174. package = (
  175. path is not None
  176. and os.path.splitext(os.path.basename(path))[0] == "__init__"
  177. )
  178. builder = rebuilder.TreeRebuilder(self._manager, parser_module, data)
  179. module = builder.visit_module(node, modname, node_file, package)
  180. return module, builder
  181. def add_from_names_to_locals(self, node: nodes.ImportFrom) -> None:
  182. """Store imported names to the locals.
  183. Resort the locals if coming from a delayed node
  184. """
  185. def _key_func(node: nodes.NodeNG) -> int:
  186. return node.fromlineno or 0
  187. def sort_locals(my_list: list[nodes.NodeNG]) -> None:
  188. my_list.sort(key=_key_func)
  189. assert node.parent # It should always default to the module
  190. for name, asname in node.names:
  191. if name == "*":
  192. try:
  193. imported = node.do_import_module()
  194. except AstroidBuildingError:
  195. continue
  196. for name in imported.public_names():
  197. node.parent.set_local(name, node)
  198. sort_locals(node.parent.scope().locals[name]) # type: ignore[arg-type]
  199. else:
  200. node.parent.set_local(asname or name, node)
  201. sort_locals(node.parent.scope().locals[asname or name]) # type: ignore[arg-type]
  202. def delayed_assattr(self, node: nodes.AssignAttr) -> None:
  203. """Visit a AssAttr node.
  204. This adds name to locals and handle members definition.
  205. """
  206. try:
  207. frame = node.frame(future=True)
  208. for inferred in node.expr.infer():
  209. if isinstance(inferred, util.UninferableBase):
  210. continue
  211. try:
  212. # pylint: disable=unidiomatic-typecheck # We want a narrow check on the
  213. # parent type, not all of its subclasses
  214. if (
  215. type(inferred) == bases.Instance
  216. or type(inferred) == objects.ExceptionInstance
  217. ):
  218. inferred = inferred._proxied
  219. iattrs = inferred.instance_attrs
  220. if not _can_assign_attr(inferred, node.attrname):
  221. continue
  222. elif isinstance(inferred, bases.Instance):
  223. # Const, Tuple or other containers that inherit from
  224. # `Instance`
  225. continue
  226. elif isinstance(inferred, (bases.Proxy, util.UninferableBase)):
  227. continue
  228. elif inferred.is_function:
  229. iattrs = inferred.instance_attrs
  230. else:
  231. iattrs = inferred.locals
  232. except AttributeError:
  233. # XXX log error
  234. continue
  235. values = iattrs.setdefault(node.attrname, [])
  236. if node in values:
  237. continue
  238. # get assign in __init__ first XXX useful ?
  239. if (
  240. frame.name == "__init__"
  241. and values
  242. and values[0].frame(future=True).name != "__init__"
  243. ):
  244. values.insert(0, node)
  245. else:
  246. values.append(node)
  247. except InferenceError:
  248. pass
  249. def build_namespace_package_module(name: str, path: Sequence[str]) -> nodes.Module:
  250. # TODO: Typing: Remove the cast to list and just update typing to accept Sequence
  251. return nodes.Module(name, path=list(path), package=True)
  252. def parse(
  253. code: str,
  254. module_name: str = "",
  255. path: str | None = None,
  256. apply_transforms: bool = True,
  257. ) -> nodes.Module:
  258. """Parses a source string in order to obtain an astroid AST from it.
  259. :param str code: The code for the module.
  260. :param str module_name: The name for the module, if any
  261. :param str path: The path for the module
  262. :param bool apply_transforms:
  263. Apply the transforms for the give code. Use it if you
  264. don't want the default transforms to be applied.
  265. """
  266. code = textwrap.dedent(code)
  267. builder = AstroidBuilder(
  268. manager=AstroidManager(), apply_transforms=apply_transforms
  269. )
  270. return builder.string_build(code, modname=module_name, path=path)
  271. def _extract_expressions(node: nodes.NodeNG) -> Iterator[nodes.NodeNG]:
  272. """Find expressions in a call to _TRANSIENT_FUNCTION and extract them.
  273. The function walks the AST recursively to search for expressions that
  274. are wrapped into a call to _TRANSIENT_FUNCTION. If it finds such an
  275. expression, it completely removes the function call node from the tree,
  276. replacing it by the wrapped expression inside the parent.
  277. :param node: An astroid node.
  278. :type node: astroid.bases.NodeNG
  279. :yields: The sequence of wrapped expressions on the modified tree
  280. expression can be found.
  281. """
  282. if (
  283. isinstance(node, nodes.Call)
  284. and isinstance(node.func, nodes.Name)
  285. and node.func.name == _TRANSIENT_FUNCTION
  286. ):
  287. real_expr = node.args[0]
  288. assert node.parent
  289. real_expr.parent = node.parent
  290. # Search for node in all _astng_fields (the fields checked when
  291. # get_children is called) of its parent. Some of those fields may
  292. # be lists or tuples, in which case the elements need to be checked.
  293. # When we find it, replace it by real_expr, so that the AST looks
  294. # like no call to _TRANSIENT_FUNCTION ever took place.
  295. for name in node.parent._astroid_fields:
  296. child = getattr(node.parent, name)
  297. if isinstance(child, list):
  298. for idx, compound_child in enumerate(child):
  299. if compound_child is node:
  300. child[idx] = real_expr
  301. elif child is node:
  302. setattr(node.parent, name, real_expr)
  303. yield real_expr
  304. else:
  305. for child in node.get_children():
  306. yield from _extract_expressions(child)
  307. def _find_statement_by_line(node: nodes.NodeNG, line: int) -> nodes.NodeNG | None:
  308. """Extracts the statement on a specific line from an AST.
  309. If the line number of node matches line, it will be returned;
  310. otherwise its children are iterated and the function is called
  311. recursively.
  312. :param node: An astroid node.
  313. :type node: astroid.bases.NodeNG
  314. :param line: The line number of the statement to extract.
  315. :type line: int
  316. :returns: The statement on the line, or None if no statement for the line
  317. can be found.
  318. :rtype: astroid.bases.NodeNG or None
  319. """
  320. if isinstance(node, (nodes.ClassDef, nodes.FunctionDef, nodes.MatchCase)):
  321. # This is an inaccuracy in the AST: the nodes that can be
  322. # decorated do not carry explicit information on which line
  323. # the actual definition (class/def), but .fromline seems to
  324. # be close enough.
  325. node_line = node.fromlineno
  326. else:
  327. node_line = node.lineno
  328. if node_line == line:
  329. return node
  330. for child in node.get_children():
  331. result = _find_statement_by_line(child, line)
  332. if result:
  333. return result
  334. return None
  335. def extract_node(code: str, module_name: str = "") -> nodes.NodeNG | list[nodes.NodeNG]:
  336. """Parses some Python code as a module and extracts a designated AST node.
  337. Statements:
  338. To extract one or more statement nodes, append #@ to the end of the line
  339. Examples:
  340. >>> def x():
  341. >>> def y():
  342. >>> return 1 #@
  343. The return statement will be extracted.
  344. >>> class X(object):
  345. >>> def meth(self): #@
  346. >>> pass
  347. The function object 'meth' will be extracted.
  348. Expressions:
  349. To extract arbitrary expressions, surround them with the fake
  350. function call __(...). After parsing, the surrounded expression
  351. will be returned and the whole AST (accessible via the returned
  352. node's parent attribute) will look like the function call was
  353. never there in the first place.
  354. Examples:
  355. >>> a = __(1)
  356. The const node will be extracted.
  357. >>> def x(d=__(foo.bar)): pass
  358. The node containing the default argument will be extracted.
  359. >>> def foo(a, b):
  360. >>> return 0 < __(len(a)) < b
  361. The node containing the function call 'len' will be extracted.
  362. If no statements or expressions are selected, the last toplevel
  363. statement will be returned.
  364. If the selected statement is a discard statement, (i.e. an expression
  365. turned into a statement), the wrapped expression is returned instead.
  366. For convenience, singleton lists are unpacked.
  367. :param str code: A piece of Python code that is parsed as
  368. a module. Will be passed through textwrap.dedent first.
  369. :param str module_name: The name of the module.
  370. :returns: The designated node from the parse tree, or a list of nodes.
  371. """
  372. def _extract(node: nodes.NodeNG | None) -> nodes.NodeNG | None:
  373. if isinstance(node, nodes.Expr):
  374. return node.value
  375. return node
  376. requested_lines: list[int] = []
  377. for idx, line in enumerate(code.splitlines()):
  378. if line.strip().endswith(_STATEMENT_SELECTOR):
  379. requested_lines.append(idx + 1)
  380. tree = parse(code, module_name=module_name)
  381. if not tree.body:
  382. raise ValueError("Empty tree, cannot extract from it")
  383. extracted: list[nodes.NodeNG | None] = []
  384. if requested_lines:
  385. extracted = [_find_statement_by_line(tree, line) for line in requested_lines]
  386. # Modifies the tree.
  387. extracted.extend(_extract_expressions(tree))
  388. if not extracted:
  389. extracted.append(tree.body[-1])
  390. extracted = [_extract(node) for node in extracted]
  391. extracted_without_none = [node for node in extracted if node is not None]
  392. if len(extracted_without_none) == 1:
  393. return extracted_without_none[0]
  394. return extracted_without_none
  395. def _extract_single_node(code: str, module_name: str = "") -> nodes.NodeNG:
  396. """Call extract_node while making sure that only one value is returned."""
  397. ret = extract_node(code, module_name)
  398. if isinstance(ret, list):
  399. return ret[0]
  400. return ret
  401. def _parse_string(
  402. data: str, type_comments: bool = True
  403. ) -> tuple[ast.Module, ParserModule]:
  404. parser_module = get_parser_module(type_comments=type_comments)
  405. try:
  406. parsed = parser_module.parse(data + "\n", type_comments=type_comments)
  407. except SyntaxError as exc:
  408. # If the type annotations are misplaced for some reason, we do not want
  409. # to fail the entire parsing of the file, so we need to retry the parsing without
  410. # type comment support.
  411. if exc.args[0] != MISPLACED_TYPE_ANNOTATION_ERROR or not type_comments:
  412. raise
  413. parser_module = get_parser_module(type_comments=False)
  414. parsed = parser_module.parse(data + "\n", type_comments=False)
  415. return parsed, parser_module