builder.py 18 KB

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