docstrings.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. """
  2. Docstrings are another source of information for functions and classes.
  3. :mod:`jedi.inference.dynamic_params` tries to find all executions of functions,
  4. while the docstring parsing is much easier. There are three different types of
  5. docstrings that |jedi| understands:
  6. - `Sphinx <http://sphinx-doc.org/markup/desc.html#info-field-lists>`_
  7. - `Epydoc <http://epydoc.sourceforge.net/manual-fields.html>`_
  8. - `Numpydoc <https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt>`_
  9. For example, the sphinx annotation ``:type foo: str`` clearly states that the
  10. type of ``foo`` is ``str``.
  11. As an addition to parameter searching, this module also provides return
  12. annotations.
  13. """
  14. import re
  15. import warnings
  16. from parso import parse, ParserSyntaxError
  17. from jedi import debug
  18. from jedi.inference.cache import inference_state_method_cache
  19. from jedi.inference.base_value import iterator_to_value_set, ValueSet, \
  20. NO_VALUES
  21. from jedi.inference.lazy_value import LazyKnownValues
  22. DOCSTRING_PARAM_PATTERNS = [
  23. r'\s*:type\s+%s:\s*([^\n]+)', # Sphinx
  24. r'\s*:param\s+(\w+)\s+%s:[^\n]*', # Sphinx param with type
  25. r'\s*@type\s+%s:\s*([^\n]+)', # Epydoc
  26. ]
  27. DOCSTRING_RETURN_PATTERNS = [
  28. re.compile(r'\s*:rtype:\s*([^\n]+)', re.M), # Sphinx
  29. re.compile(r'\s*@rtype:\s*([^\n]+)', re.M), # Epydoc
  30. ]
  31. REST_ROLE_PATTERN = re.compile(r':[^`]+:`([^`]+)`')
  32. _numpy_doc_string_cache = None
  33. def _get_numpy_doc_string_cls():
  34. global _numpy_doc_string_cache
  35. if isinstance(_numpy_doc_string_cache, (ImportError, SyntaxError)):
  36. raise _numpy_doc_string_cache
  37. from numpydoc.docscrape import NumpyDocString # type: ignore[import]
  38. _numpy_doc_string_cache = NumpyDocString
  39. return _numpy_doc_string_cache
  40. def _search_param_in_numpydocstr(docstr, param_str):
  41. """Search `docstr` (in numpydoc format) for type(-s) of `param_str`."""
  42. with warnings.catch_warnings():
  43. warnings.simplefilter("ignore")
  44. try:
  45. # This is a non-public API. If it ever changes we should be
  46. # prepared and return gracefully.
  47. params = _get_numpy_doc_string_cls()(docstr)._parsed_data['Parameters']
  48. except Exception:
  49. return []
  50. for p_name, p_type, p_descr in params:
  51. if p_name == param_str:
  52. m = re.match(r'([^,]+(,[^,]+)*?)(,[ ]*optional)?$', p_type)
  53. if m:
  54. p_type = m.group(1)
  55. return list(_expand_typestr(p_type))
  56. return []
  57. def _search_return_in_numpydocstr(docstr):
  58. """
  59. Search `docstr` (in numpydoc format) for type(-s) of function returns.
  60. """
  61. with warnings.catch_warnings():
  62. warnings.simplefilter("ignore")
  63. try:
  64. doc = _get_numpy_doc_string_cls()(docstr)
  65. except Exception:
  66. return
  67. try:
  68. # This is a non-public API. If it ever changes we should be
  69. # prepared and return gracefully.
  70. returns = doc._parsed_data['Returns']
  71. returns += doc._parsed_data['Yields']
  72. except Exception:
  73. return
  74. for r_name, r_type, r_descr in returns:
  75. # Return names are optional and if so the type is in the name
  76. if not r_type:
  77. r_type = r_name
  78. yield from _expand_typestr(r_type)
  79. def _expand_typestr(type_str):
  80. """
  81. Attempts to interpret the possible types in `type_str`
  82. """
  83. # Check if alternative types are specified with 'or'
  84. if re.search(r'\bor\b', type_str):
  85. for t in type_str.split('or'):
  86. yield t.split('of')[0].strip()
  87. # Check if like "list of `type`" and set type to list
  88. elif re.search(r'\bof\b', type_str):
  89. yield type_str.split('of')[0]
  90. # Check if type has is a set of valid literal values eg: {'C', 'F', 'A'}
  91. elif type_str.startswith('{'):
  92. node = parse(type_str, version='3.7').children[0]
  93. if node.type == 'atom':
  94. for leaf in getattr(node.children[1], "children", []):
  95. if leaf.type == 'number':
  96. if '.' in leaf.value:
  97. yield 'float'
  98. else:
  99. yield 'int'
  100. elif leaf.type == 'string':
  101. if 'b' in leaf.string_prefix.lower():
  102. yield 'bytes'
  103. else:
  104. yield 'str'
  105. # Ignore everything else.
  106. # Otherwise just work with what we have.
  107. else:
  108. yield type_str
  109. def _search_param_in_docstr(docstr, param_str):
  110. """
  111. Search `docstr` for type(-s) of `param_str`.
  112. >>> _search_param_in_docstr(':type param: int', 'param')
  113. ['int']
  114. >>> _search_param_in_docstr('@type param: int', 'param')
  115. ['int']
  116. >>> _search_param_in_docstr(
  117. ... ':type param: :class:`threading.Thread`', 'param')
  118. ['threading.Thread']
  119. >>> bool(_search_param_in_docstr('no document', 'param'))
  120. False
  121. >>> _search_param_in_docstr(':param int param: some description', 'param')
  122. ['int']
  123. """
  124. # look at #40 to see definitions of those params
  125. patterns = [re.compile(p % re.escape(param_str))
  126. for p in DOCSTRING_PARAM_PATTERNS]
  127. for pattern in patterns:
  128. match = pattern.search(docstr)
  129. if match:
  130. return [_strip_rst_role(match.group(1))]
  131. return _search_param_in_numpydocstr(docstr, param_str)
  132. def _strip_rst_role(type_str):
  133. """
  134. Strip off the part looks like a ReST role in `type_str`.
  135. >>> _strip_rst_role(':class:`ClassName`') # strip off :class:
  136. 'ClassName'
  137. >>> _strip_rst_role(':py:obj:`module.Object`') # works with domain
  138. 'module.Object'
  139. >>> _strip_rst_role('ClassName') # do nothing when not ReST role
  140. 'ClassName'
  141. See also:
  142. http://sphinx-doc.org/domains.html#cross-referencing-python-objects
  143. """
  144. match = REST_ROLE_PATTERN.match(type_str)
  145. if match:
  146. return match.group(1)
  147. else:
  148. return type_str
  149. def _infer_for_statement_string(module_context, string):
  150. if string is None:
  151. return []
  152. potential_imports = re.findall(r'((?:\w+\.)*\w+)\.', string)
  153. # Try to import module part in dotted name.
  154. # (e.g., 'threading' in 'threading.Thread').
  155. imports = "\n".join(f"import {p}" for p in potential_imports)
  156. string = f'{imports}\n{string}'
  157. debug.dbg('Parse docstring code %s', string, color='BLUE')
  158. grammar = module_context.inference_state.grammar
  159. try:
  160. module = grammar.parse(string, error_recovery=False)
  161. except ParserSyntaxError:
  162. return []
  163. try:
  164. # It's not the last item, because that's an end marker.
  165. stmt = module.children[-2]
  166. except (AttributeError, IndexError):
  167. return []
  168. if stmt.type not in ('name', 'atom', 'atom_expr'):
  169. return []
  170. # Here we basically use a fake module that also uses the filters in
  171. # the actual module.
  172. from jedi.inference.docstring_utils import DocstringModule
  173. m = DocstringModule(
  174. in_module_context=module_context,
  175. inference_state=module_context.inference_state,
  176. module_node=module,
  177. code_lines=[],
  178. )
  179. return list(_execute_types_in_stmt(m.as_context(), stmt))
  180. def _execute_types_in_stmt(module_context, stmt):
  181. """
  182. Executing all types or general elements that we find in a statement. This
  183. doesn't include tuple, list and dict literals, because the stuff they
  184. contain is executed. (Used as type information).
  185. """
  186. definitions = module_context.infer_node(stmt)
  187. return ValueSet.from_sets(
  188. _execute_array_values(module_context.inference_state, d)
  189. for d in definitions
  190. )
  191. def _execute_array_values(inference_state, array):
  192. """
  193. Tuples indicate that there's not just one return value, but the listed
  194. ones. `(str, int)` means that it returns a tuple with both types.
  195. """
  196. from jedi.inference.value.iterable import SequenceLiteralValue, FakeTuple, FakeList
  197. if isinstance(array, SequenceLiteralValue) and array.array_type in ('tuple', 'list'):
  198. values = []
  199. for lazy_value in array.py__iter__():
  200. objects = ValueSet.from_sets(
  201. _execute_array_values(inference_state, typ)
  202. for typ in lazy_value.infer()
  203. )
  204. values.append(LazyKnownValues(objects))
  205. cls = FakeTuple if array.array_type == 'tuple' else FakeList
  206. return {cls(inference_state, values)}
  207. else:
  208. return array.execute_annotation()
  209. @inference_state_method_cache()
  210. def infer_param(function_value, param):
  211. def infer_docstring(docstring):
  212. return ValueSet(
  213. p
  214. for param_str in _search_param_in_docstr(docstring, param.name.value)
  215. for p in _infer_for_statement_string(module_context, param_str)
  216. )
  217. module_context = function_value.get_root_context()
  218. func = param.get_parent_function()
  219. if func.type == 'lambdef':
  220. return NO_VALUES
  221. types = infer_docstring(function_value.py__doc__())
  222. if function_value.is_bound_method() \
  223. and function_value.py__name__() == '__init__':
  224. types |= infer_docstring(function_value.class_context.py__doc__())
  225. debug.dbg('Found param types for docstring: %s', types, color='BLUE')
  226. return types
  227. @inference_state_method_cache()
  228. @iterator_to_value_set
  229. def infer_return_types(function_value):
  230. def search_return_in_docstr(code):
  231. for p in DOCSTRING_RETURN_PATTERNS:
  232. match = p.search(code)
  233. if match:
  234. yield _strip_rst_role(match.group(1))
  235. # Check for numpy style return hint
  236. yield from _search_return_in_numpydocstr(code)
  237. for type_str in search_return_in_docstr(function_value.py__doc__()):
  238. yield from _infer_for_statement_string(function_value.get_root_context(), type_str)