builder.py 19 KB

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