helpers.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. """
  2. Helpers for the API
  3. """
  4. import re
  5. from collections import namedtuple
  6. from textwrap import dedent
  7. from itertools import chain
  8. from functools import wraps
  9. from inspect import Parameter
  10. from parso.python.parser import Parser
  11. from parso.python import tree
  12. from jedi.inference.base_value import NO_VALUES
  13. from jedi.inference.syntax_tree import infer_atom
  14. from jedi.inference.helpers import infer_call_of_leaf
  15. from jedi.inference.compiled import get_string_value_set
  16. from jedi.cache import signature_time_cache, memoize_method
  17. from jedi.parser_utils import get_parent_scope
  18. CompletionParts = namedtuple('CompletionParts', ['path', 'has_dot', 'name'])
  19. def _start_match(string, like_name):
  20. return string.startswith(like_name)
  21. def _fuzzy_match(string, like_name):
  22. if len(like_name) <= 1:
  23. return like_name in string
  24. pos = string.find(like_name[0])
  25. if pos >= 0:
  26. return _fuzzy_match(string[pos + 1:], like_name[1:])
  27. return False
  28. def match(string, like_name, fuzzy=False):
  29. if fuzzy:
  30. return _fuzzy_match(string, like_name)
  31. else:
  32. return _start_match(string, like_name)
  33. def sorted_definitions(defs):
  34. # Note: `or ''` below is required because `module_path` could be
  35. return sorted(defs, key=lambda x: (str(x.module_path or ''),
  36. x.line or 0,
  37. x.column or 0,
  38. x.name))
  39. def get_on_completion_name(module_node, lines, position):
  40. leaf = module_node.get_leaf_for_position(position)
  41. if leaf is None or leaf.type in ('string', 'error_leaf'):
  42. # Completions inside strings are a bit special, we need to parse the
  43. # string. The same is true for comments and error_leafs.
  44. line = lines[position[0] - 1]
  45. # The first step of completions is to get the name
  46. return re.search(r'(?!\d)\w+$|$', line[:position[1]]).group(0)
  47. elif leaf.type not in ('name', 'keyword'):
  48. return ''
  49. return leaf.value[:position[1] - leaf.start_pos[1]]
  50. def _get_code(code_lines, start_pos, end_pos):
  51. # Get relevant lines.
  52. lines = code_lines[start_pos[0] - 1:end_pos[0]]
  53. # Remove the parts at the end of the line.
  54. lines[-1] = lines[-1][:end_pos[1]]
  55. # Remove first line indentation.
  56. lines[0] = lines[0][start_pos[1]:]
  57. return ''.join(lines)
  58. class OnErrorLeaf(Exception):
  59. @property
  60. def error_leaf(self):
  61. return self.args[0]
  62. def _get_code_for_stack(code_lines, leaf, position):
  63. # It might happen that we're on whitespace or on a comment. This means
  64. # that we would not get the right leaf.
  65. if leaf.start_pos >= position:
  66. # If we're not on a comment simply get the previous leaf and proceed.
  67. leaf = leaf.get_previous_leaf()
  68. if leaf is None:
  69. return '' # At the beginning of the file.
  70. is_after_newline = leaf.type == 'newline'
  71. while leaf.type == 'newline':
  72. leaf = leaf.get_previous_leaf()
  73. if leaf is None:
  74. return ''
  75. if leaf.type == 'error_leaf' or leaf.type == 'string':
  76. if leaf.start_pos[0] < position[0]:
  77. # On a different line, we just begin anew.
  78. return ''
  79. # Error leafs cannot be parsed, completion in strings is also
  80. # impossible.
  81. raise OnErrorLeaf(leaf)
  82. else:
  83. user_stmt = leaf
  84. while True:
  85. if user_stmt.parent.type in ('file_input', 'suite', 'simple_stmt'):
  86. break
  87. user_stmt = user_stmt.parent
  88. if is_after_newline:
  89. if user_stmt.start_pos[1] > position[1]:
  90. # This means that it's actually a dedent and that means that we
  91. # start without value (part of a suite).
  92. return ''
  93. # This is basically getting the relevant lines.
  94. return _get_code(code_lines, user_stmt.get_start_pos_of_prefix(), position)
  95. def get_stack_at_position(grammar, code_lines, leaf, pos):
  96. """
  97. Returns the possible node names (e.g. import_from, xor_test or yield_stmt).
  98. """
  99. class EndMarkerReached(Exception):
  100. pass
  101. def tokenize_without_endmarker(code):
  102. # TODO This is for now not an official parso API that exists purely
  103. # for Jedi.
  104. tokens = grammar._tokenize(code)
  105. for token in tokens:
  106. if token.string == safeword:
  107. raise EndMarkerReached()
  108. elif token.prefix.endswith(safeword):
  109. # This happens with comments.
  110. raise EndMarkerReached()
  111. elif token.string.endswith(safeword):
  112. yield token # Probably an f-string literal that was not finished.
  113. raise EndMarkerReached()
  114. else:
  115. yield token
  116. # The code might be indedented, just remove it.
  117. code = dedent(_get_code_for_stack(code_lines, leaf, pos))
  118. # We use a word to tell Jedi when we have reached the start of the
  119. # completion.
  120. # Use Z as a prefix because it's not part of a number suffix.
  121. safeword = 'ZZZ_USER_WANTS_TO_COMPLETE_HERE_WITH_JEDI'
  122. code = code + ' ' + safeword
  123. p = Parser(grammar._pgen_grammar, error_recovery=True)
  124. try:
  125. p.parse(tokens=tokenize_without_endmarker(code))
  126. except EndMarkerReached:
  127. return p.stack
  128. raise SystemError(
  129. "This really shouldn't happen. There's a bug in Jedi:\n%s"
  130. % list(tokenize_without_endmarker(code))
  131. )
  132. def infer(inference_state, context, leaf):
  133. if leaf.type == 'name':
  134. return inference_state.infer(context, leaf)
  135. parent = leaf.parent
  136. definitions = NO_VALUES
  137. if parent.type == 'atom':
  138. # e.g. `(a + b)`
  139. definitions = context.infer_node(leaf.parent)
  140. elif parent.type == 'trailer':
  141. # e.g. `a()`
  142. definitions = infer_call_of_leaf(context, leaf)
  143. elif isinstance(leaf, tree.Literal):
  144. # e.g. `"foo"` or `1.0`
  145. return infer_atom(context, leaf)
  146. elif leaf.type in ('fstring_string', 'fstring_start', 'fstring_end'):
  147. return get_string_value_set(inference_state)
  148. return definitions
  149. def filter_follow_imports(names, follow_builtin_imports=False):
  150. for name in names:
  151. if name.is_import():
  152. new_names = list(filter_follow_imports(
  153. name.goto(),
  154. follow_builtin_imports=follow_builtin_imports,
  155. ))
  156. found_builtin = False
  157. if follow_builtin_imports:
  158. for new_name in new_names:
  159. if new_name.start_pos is None:
  160. found_builtin = True
  161. if found_builtin:
  162. yield name
  163. else:
  164. yield from new_names
  165. else:
  166. yield name
  167. class CallDetails:
  168. def __init__(self, bracket_leaf, children, position):
  169. self.bracket_leaf = bracket_leaf
  170. self._children = children
  171. self._position = position
  172. @property
  173. def index(self):
  174. return _get_index_and_key(self._children, self._position)[0]
  175. @property
  176. def keyword_name_str(self):
  177. return _get_index_and_key(self._children, self._position)[1]
  178. @memoize_method
  179. def _list_arguments(self):
  180. return list(_iter_arguments(self._children, self._position))
  181. def calculate_index(self, param_names):
  182. positional_count = 0
  183. used_names = set()
  184. star_count = -1
  185. args = self._list_arguments()
  186. if not args:
  187. if param_names:
  188. return 0
  189. else:
  190. return None
  191. is_kwarg = False
  192. for i, (star_count, key_start, had_equal) in enumerate(args):
  193. is_kwarg |= had_equal | (star_count == 2)
  194. if star_count:
  195. pass # For now do nothing, we don't know what's in there here.
  196. else:
  197. if i + 1 != len(args): # Not last
  198. if had_equal:
  199. used_names.add(key_start)
  200. else:
  201. positional_count += 1
  202. for i, param_name in enumerate(param_names):
  203. kind = param_name.get_kind()
  204. if not is_kwarg:
  205. if kind == Parameter.VAR_POSITIONAL:
  206. return i
  207. if kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.POSITIONAL_ONLY):
  208. if i == positional_count:
  209. return i
  210. if key_start is not None and not star_count == 1 or star_count == 2:
  211. if param_name.string_name not in used_names \
  212. and (kind == Parameter.KEYWORD_ONLY
  213. or kind == Parameter.POSITIONAL_OR_KEYWORD
  214. and positional_count <= i):
  215. if star_count:
  216. return i
  217. if had_equal:
  218. if param_name.string_name == key_start:
  219. return i
  220. else:
  221. if param_name.string_name.startswith(key_start):
  222. return i
  223. if kind == Parameter.VAR_KEYWORD:
  224. return i
  225. return None
  226. def iter_used_keyword_arguments(self):
  227. for star_count, key_start, had_equal in list(self._list_arguments()):
  228. if had_equal and key_start:
  229. yield key_start
  230. def count_positional_arguments(self):
  231. count = 0
  232. for star_count, key_start, had_equal in self._list_arguments()[:-1]:
  233. if star_count or key_start:
  234. break
  235. count += 1
  236. return count
  237. def _iter_arguments(nodes, position):
  238. def remove_after_pos(name):
  239. if name.type != 'name':
  240. return None
  241. return name.value[:position[1] - name.start_pos[1]]
  242. # Returns Generator[Tuple[star_count, Optional[key_start: str], had_equal]]
  243. nodes_before = [c for c in nodes if c.start_pos < position]
  244. if nodes_before[-1].type == 'arglist':
  245. yield from _iter_arguments(nodes_before[-1].children, position)
  246. return
  247. previous_node_yielded = False
  248. stars_seen = 0
  249. for i, node in enumerate(nodes_before):
  250. if node.type == 'argument':
  251. previous_node_yielded = True
  252. first = node.children[0]
  253. second = node.children[1]
  254. if second == '=':
  255. if second.start_pos < position and first.type == 'name':
  256. yield 0, first.value, True
  257. else:
  258. yield 0, remove_after_pos(first), False
  259. elif first in ('*', '**'):
  260. yield len(first.value), remove_after_pos(second), False
  261. else:
  262. # Must be a Comprehension
  263. first_leaf = node.get_first_leaf()
  264. if first_leaf.type == 'name' and first_leaf.start_pos >= position:
  265. yield 0, remove_after_pos(first_leaf), False
  266. else:
  267. yield 0, None, False
  268. stars_seen = 0
  269. elif node.type == 'testlist_star_expr':
  270. for n in node.children[::2]:
  271. if n.type == 'star_expr':
  272. stars_seen = 1
  273. n = n.children[1]
  274. yield stars_seen, remove_after_pos(n), False
  275. stars_seen = 0
  276. # The count of children is even if there's a comma at the end.
  277. previous_node_yielded = bool(len(node.children) % 2)
  278. elif isinstance(node, tree.PythonLeaf) and node.value == ',':
  279. if not previous_node_yielded:
  280. yield stars_seen, '', False
  281. stars_seen = 0
  282. previous_node_yielded = False
  283. elif isinstance(node, tree.PythonLeaf) and node.value in ('*', '**'):
  284. stars_seen = len(node.value)
  285. elif node == '=' and nodes_before[-1]:
  286. previous_node_yielded = True
  287. before = nodes_before[i - 1]
  288. if before.type == 'name':
  289. yield 0, before.value, True
  290. else:
  291. yield 0, None, False
  292. # Just ignore the star that is probably a syntax error.
  293. stars_seen = 0
  294. if not previous_node_yielded:
  295. if nodes_before[-1].type == 'name':
  296. yield stars_seen, remove_after_pos(nodes_before[-1]), False
  297. else:
  298. yield stars_seen, '', False
  299. def _get_index_and_key(nodes, position):
  300. """
  301. Returns the amount of commas and the keyword argument string.
  302. """
  303. nodes_before = [c for c in nodes if c.start_pos < position]
  304. if nodes_before[-1].type == 'arglist':
  305. return _get_index_and_key(nodes_before[-1].children, position)
  306. key_str = None
  307. last = nodes_before[-1]
  308. if last.type == 'argument' and last.children[1] == '=' \
  309. and last.children[1].end_pos <= position:
  310. # Checked if the argument
  311. key_str = last.children[0].value
  312. elif last == '=':
  313. key_str = nodes_before[-2].value
  314. return nodes_before.count(','), key_str
  315. def _get_signature_details_from_error_node(node, additional_children, position):
  316. for index, element in reversed(list(enumerate(node.children))):
  317. # `index > 0` means that it's a trailer and not an atom.
  318. if element == '(' and element.end_pos <= position and index > 0:
  319. # It's an error node, we don't want to match too much, just
  320. # until the parentheses is enough.
  321. children = node.children[index:]
  322. name = element.get_previous_leaf()
  323. if name is None:
  324. continue
  325. if name.type == 'name' or name.parent.type in ('trailer', 'atom'):
  326. return CallDetails(element, children + additional_children, position)
  327. def get_signature_details(module, position):
  328. leaf = module.get_leaf_for_position(position, include_prefixes=True)
  329. # It's easier to deal with the previous token than the next one in this
  330. # case.
  331. if leaf.start_pos >= position:
  332. # Whitespace / comments after the leaf count towards the previous leaf.
  333. leaf = leaf.get_previous_leaf()
  334. if leaf is None:
  335. return None
  336. # Now that we know where we are in the syntax tree, we start to look at
  337. # parents for possible function definitions.
  338. node = leaf.parent
  339. while node is not None:
  340. if node.type in ('funcdef', 'classdef', 'decorated', 'async_stmt'):
  341. # Don't show signatures if there's stuff before it that just
  342. # makes it feel strange to have a signature.
  343. return None
  344. additional_children = []
  345. for n in reversed(node.children):
  346. if n.start_pos < position:
  347. if n.type == 'error_node':
  348. result = _get_signature_details_from_error_node(
  349. n, additional_children, position
  350. )
  351. if result is not None:
  352. return result
  353. additional_children[0:0] = n.children
  354. continue
  355. additional_children.insert(0, n)
  356. # Find a valid trailer
  357. if node.type == 'trailer' and node.children[0] == '(' \
  358. or node.type == 'decorator' and node.children[2] == '(':
  359. # Additionally we have to check that an ending parenthesis isn't
  360. # interpreted wrong. There are two cases:
  361. # 1. Cursor before paren -> The current signature is good
  362. # 2. Cursor after paren -> We need to skip the current signature
  363. if not (leaf is node.children[-1] and position >= leaf.end_pos):
  364. leaf = node.get_previous_leaf()
  365. if leaf is None:
  366. return None
  367. return CallDetails(
  368. node.children[0] if node.type == 'trailer' else node.children[2],
  369. node.children,
  370. position
  371. )
  372. node = node.parent
  373. return None
  374. @signature_time_cache("call_signatures_validity")
  375. def cache_signatures(inference_state, context, bracket_leaf, code_lines, user_pos):
  376. """This function calculates the cache key."""
  377. line_index = user_pos[0] - 1
  378. before_cursor = code_lines[line_index][:user_pos[1]]
  379. other_lines = code_lines[bracket_leaf.start_pos[0]:line_index]
  380. whole = ''.join(other_lines + [before_cursor])
  381. before_bracket = re.match(r'.*\(', whole, re.DOTALL)
  382. module_path = context.get_root_context().py__file__()
  383. if module_path is None:
  384. yield None # Don't cache!
  385. else:
  386. yield (module_path, before_bracket, bracket_leaf.start_pos)
  387. yield infer(
  388. inference_state,
  389. context,
  390. bracket_leaf.get_previous_leaf(),
  391. )
  392. def validate_line_column(func):
  393. @wraps(func)
  394. def wrapper(self, line=None, column=None, *args, **kwargs):
  395. line = max(len(self._code_lines), 1) if line is None else line
  396. if not (0 < line <= len(self._code_lines)):
  397. raise ValueError('`line` parameter is not in a valid range.')
  398. line_string = self._code_lines[line - 1]
  399. line_len = len(line_string)
  400. if line_string.endswith('\r\n'):
  401. line_len -= 2
  402. elif line_string.endswith('\n'):
  403. line_len -= 1
  404. column = line_len if column is None else column
  405. if not (0 <= column <= line_len):
  406. raise ValueError('`column` parameter (%d) is not in a valid range '
  407. '(0-%d) for line %d (%r).' % (
  408. column, line_len, line, line_string))
  409. return func(self, line, column, *args, **kwargs)
  410. return wrapper
  411. def get_module_names(module, all_scopes, definitions=True, references=False):
  412. """
  413. Returns a dictionary with name parts as keys and their call paths as
  414. values.
  415. """
  416. def def_ref_filter(name):
  417. is_def = name.is_definition()
  418. return definitions and is_def or references and not is_def
  419. names = list(chain.from_iterable(module.get_used_names().values()))
  420. if not all_scopes:
  421. # We have to filter all the names that don't have the module as a
  422. # parent_scope. There's None as a parent, because nodes in the module
  423. # node have the parent module and not suite as all the others.
  424. # Therefore it's important to catch that case.
  425. def is_module_scope_name(name):
  426. parent_scope = get_parent_scope(name)
  427. # async functions have an extra wrapper. Strip it.
  428. if parent_scope and parent_scope.type == 'async_stmt':
  429. parent_scope = parent_scope.parent
  430. return parent_scope in (module, None)
  431. names = [n for n in names if is_module_scope_name(n)]
  432. return filter(def_ref_filter, names)
  433. def split_search_string(name):
  434. type, _, dotted_names = name.rpartition(' ')
  435. if type == 'def':
  436. type = 'function'
  437. return type, dotted_names.split('.')