completion.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. import re
  2. from textwrap import dedent
  3. from inspect import Parameter
  4. from parso.python.token import PythonTokenTypes
  5. from parso.python import tree
  6. from parso.tree import search_ancestor, Leaf
  7. from parso import split_lines
  8. from jedi import debug
  9. from jedi import settings
  10. from jedi.api import classes
  11. from jedi.api import helpers
  12. from jedi.api import keywords
  13. from jedi.api.strings import complete_dict
  14. from jedi.api.file_name import complete_file_name
  15. from jedi.inference import imports
  16. from jedi.inference.base_value import ValueSet
  17. from jedi.inference.helpers import infer_call_of_leaf, parse_dotted_names
  18. from jedi.inference.context import get_global_filters
  19. from jedi.inference.value import TreeInstance
  20. from jedi.inference.docstring_utils import DocstringModule
  21. from jedi.inference.names import ParamNameWrapper, SubModuleName
  22. from jedi.inference.gradual.conversion import convert_values, convert_names
  23. from jedi.parser_utils import cut_value_at_position
  24. from jedi.plugins import plugin_manager
  25. class ParamNameWithEquals(ParamNameWrapper):
  26. def get_public_name(self):
  27. return self.string_name + '='
  28. def _get_signature_param_names(signatures, positional_count, used_kwargs):
  29. # Add named params
  30. for call_sig in signatures:
  31. for i, p in enumerate(call_sig.params):
  32. kind = p.kind
  33. if i < positional_count and kind == Parameter.POSITIONAL_OR_KEYWORD:
  34. continue
  35. if kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY) \
  36. and p.name not in used_kwargs:
  37. yield ParamNameWithEquals(p._name)
  38. def _must_be_kwarg(signatures, positional_count, used_kwargs):
  39. if used_kwargs:
  40. return True
  41. must_be_kwarg = True
  42. for signature in signatures:
  43. for i, p in enumerate(signature.params):
  44. kind = p.kind
  45. if kind is Parameter.VAR_POSITIONAL:
  46. # In case there were not already kwargs, the next param can
  47. # always be a normal argument.
  48. return False
  49. if i >= positional_count and kind in (Parameter.POSITIONAL_OR_KEYWORD,
  50. Parameter.POSITIONAL_ONLY):
  51. must_be_kwarg = False
  52. break
  53. if not must_be_kwarg:
  54. break
  55. return must_be_kwarg
  56. def filter_names(inference_state, completion_names, stack, like_name, fuzzy,
  57. imported_names, cached_name):
  58. comp_dct = set()
  59. if settings.case_insensitive_completion:
  60. like_name = like_name.lower()
  61. for name in completion_names:
  62. string = name.string_name
  63. if string in imported_names and string != like_name:
  64. continue
  65. if settings.case_insensitive_completion:
  66. string = string.lower()
  67. if helpers.match(string, like_name, fuzzy=fuzzy):
  68. new = classes.Completion(
  69. inference_state,
  70. name,
  71. stack,
  72. len(like_name),
  73. is_fuzzy=fuzzy,
  74. cached_name=cached_name,
  75. )
  76. k = (new.name, new.complete) # key
  77. if k not in comp_dct:
  78. comp_dct.add(k)
  79. tree_name = name.tree_name
  80. if tree_name is not None:
  81. definition = tree_name.get_definition()
  82. if definition is not None and definition.type == 'del_stmt':
  83. continue
  84. yield new
  85. def _remove_duplicates(completions, other_completions):
  86. names = {d.name for d in other_completions}
  87. return [c for c in completions if c.name not in names]
  88. def get_user_context(module_context, position):
  89. """
  90. Returns the scope in which the user resides. This includes flows.
  91. """
  92. leaf = module_context.tree_node.get_leaf_for_position(position, include_prefixes=True)
  93. return module_context.create_context(leaf)
  94. def get_flow_scope_node(module_node, position):
  95. node = module_node.get_leaf_for_position(position, include_prefixes=True)
  96. while not isinstance(node, (tree.Scope, tree.Flow)):
  97. node = node.parent
  98. return node
  99. @plugin_manager.decorate()
  100. def complete_param_names(context, function_name, decorator_nodes):
  101. # Basically there's no way to do param completion. The plugins are
  102. # responsible for this.
  103. return []
  104. class Completion:
  105. def __init__(self, inference_state, module_context, code_lines, position,
  106. signatures_callback, fuzzy=False):
  107. self._inference_state = inference_state
  108. self._module_context = module_context
  109. self._module_node = module_context.tree_node
  110. self._code_lines = code_lines
  111. # The first step of completions is to get the name
  112. self._like_name = helpers.get_on_completion_name(self._module_node, code_lines, position)
  113. # The actual cursor position is not what we need to calculate
  114. # everything. We want the start of the name we're on.
  115. self._original_position = position
  116. self._signatures_callback = signatures_callback
  117. self._fuzzy = fuzzy
  118. # Return list of completions in this order:
  119. # - Beginning with what user is typing
  120. # - Public (alphabet)
  121. # - Private ("_xxx")
  122. # - Dunder ("__xxx")
  123. def complete(self):
  124. leaf = self._module_node.get_leaf_for_position(
  125. self._original_position,
  126. include_prefixes=True
  127. )
  128. string, start_leaf, quote = _extract_string_while_in_string(leaf, self._original_position)
  129. prefixed_completions = complete_dict(
  130. self._module_context,
  131. self._code_lines,
  132. start_leaf or leaf,
  133. self._original_position,
  134. None if string is None else quote + string,
  135. fuzzy=self._fuzzy,
  136. )
  137. if string is not None and not prefixed_completions:
  138. prefixed_completions = list(complete_file_name(
  139. self._inference_state, self._module_context, start_leaf, quote, string,
  140. self._like_name, self._signatures_callback,
  141. self._code_lines, self._original_position,
  142. self._fuzzy
  143. ))
  144. if string is not None:
  145. if not prefixed_completions and '\n' in string:
  146. # Complete only multi line strings
  147. prefixed_completions = self._complete_in_string(start_leaf, string)
  148. return prefixed_completions
  149. cached_name, completion_names = self._complete_python(leaf)
  150. imported_names = []
  151. if leaf.parent is not None and leaf.parent.type in ['import_as_names', 'dotted_as_names']:
  152. imported_names.extend(extract_imported_names(leaf.parent))
  153. completions = list(filter_names(self._inference_state, completion_names,
  154. self.stack, self._like_name,
  155. self._fuzzy, imported_names, cached_name=cached_name))
  156. return (
  157. # Removing duplicates mostly to remove False/True/None duplicates.
  158. _remove_duplicates(prefixed_completions, completions)
  159. + sorted(completions, key=lambda x: (not x.name.startswith(self._like_name),
  160. x.name.startswith('__'),
  161. x.name.startswith('_'),
  162. x.name.lower()))
  163. )
  164. def _complete_python(self, leaf):
  165. """
  166. Analyzes the current context of a completion and decides what to
  167. return.
  168. Technically this works by generating a parser stack and analysing the
  169. current stack for possible grammar nodes.
  170. Possible enhancements:
  171. - global/nonlocal search global
  172. - yield from / raise from <- could be only exceptions/generators
  173. - In args: */**: no completion
  174. - In params (also lambda): no completion before =
  175. """
  176. grammar = self._inference_state.grammar
  177. self.stack = stack = None
  178. self._position = (
  179. self._original_position[0],
  180. self._original_position[1] - len(self._like_name)
  181. )
  182. cached_name = None
  183. try:
  184. self.stack = stack = helpers.get_stack_at_position(
  185. grammar, self._code_lines, leaf, self._position
  186. )
  187. except helpers.OnErrorLeaf as e:
  188. value = e.error_leaf.value
  189. if value == '.':
  190. # After ErrorLeaf's that are dots, we will not do any
  191. # completions since this probably just confuses the user.
  192. return cached_name, []
  193. # If we don't have a value, just use global completion.
  194. return cached_name, self._complete_global_scope()
  195. allowed_transitions = \
  196. list(stack._allowed_transition_names_and_token_types())
  197. if 'if' in allowed_transitions:
  198. leaf = self._module_node.get_leaf_for_position(self._position, include_prefixes=True)
  199. previous_leaf = leaf.get_previous_leaf()
  200. indent = self._position[1]
  201. if not (leaf.start_pos <= self._position <= leaf.end_pos):
  202. indent = leaf.start_pos[1]
  203. if previous_leaf is not None:
  204. stmt = previous_leaf
  205. while True:
  206. stmt = search_ancestor(
  207. stmt, 'if_stmt', 'for_stmt', 'while_stmt', 'try_stmt',
  208. 'error_node',
  209. )
  210. if stmt is None:
  211. break
  212. type_ = stmt.type
  213. if type_ == 'error_node':
  214. first = stmt.children[0]
  215. if isinstance(first, Leaf):
  216. type_ = first.value + '_stmt'
  217. # Compare indents
  218. if stmt.start_pos[1] == indent:
  219. if type_ == 'if_stmt':
  220. allowed_transitions += ['elif', 'else']
  221. elif type_ == 'try_stmt':
  222. allowed_transitions += ['except', 'finally', 'else']
  223. elif type_ == 'for_stmt':
  224. allowed_transitions.append('else')
  225. completion_names = []
  226. kwargs_only = False
  227. if any(t in allowed_transitions for t in (PythonTokenTypes.NAME,
  228. PythonTokenTypes.INDENT)):
  229. # This means that we actually have to do type inference.
  230. nonterminals = [stack_node.nonterminal for stack_node in stack]
  231. nodes = _gather_nodes(stack)
  232. if nodes and nodes[-1] in ('as', 'def', 'class'):
  233. # No completions for ``with x as foo`` and ``import x as foo``.
  234. # Also true for defining names as a class or function.
  235. return cached_name, list(self._complete_inherited(is_function=True))
  236. elif "import_stmt" in nonterminals:
  237. level, names = parse_dotted_names(nodes, "import_from" in nonterminals)
  238. only_modules = not ("import_from" in nonterminals and 'import' in nodes)
  239. completion_names += self._get_importer_names(
  240. names,
  241. level,
  242. only_modules=only_modules,
  243. )
  244. elif nonterminals[-1] in ('trailer', 'dotted_name') and nodes[-1] == '.':
  245. dot = self._module_node.get_leaf_for_position(self._position)
  246. if dot.type == "endmarker":
  247. # This is a bit of a weird edge case, maybe we can somehow
  248. # generalize this.
  249. dot = leaf.get_previous_leaf()
  250. cached_name, n = self._complete_trailer(dot.get_previous_leaf())
  251. completion_names += n
  252. elif self._is_parameter_completion():
  253. completion_names += self._complete_params(leaf)
  254. else:
  255. # Apparently this looks like it's good enough to filter most cases
  256. # so that signature completions don't randomly appear.
  257. # To understand why this works, three things are important:
  258. # 1. trailer with a `,` in it is either a subscript or an arglist.
  259. # 2. If there's no `,`, it's at the start and only signatures start
  260. # with `(`. Other trailers could start with `.` or `[`.
  261. # 3. Decorators are very primitive and have an optional `(` with
  262. # optional arglist in them.
  263. if nodes[-1] in ['(', ','] \
  264. and nonterminals[-1] in ('trailer', 'arglist', 'decorator'):
  265. signatures = self._signatures_callback(*self._position)
  266. if signatures:
  267. call_details = signatures[0]._call_details
  268. used_kwargs = list(call_details.iter_used_keyword_arguments())
  269. positional_count = call_details.count_positional_arguments()
  270. completion_names += _get_signature_param_names(
  271. signatures,
  272. positional_count,
  273. used_kwargs,
  274. )
  275. kwargs_only = _must_be_kwarg(signatures, positional_count, used_kwargs)
  276. if not kwargs_only:
  277. completion_names += self._complete_global_scope()
  278. completion_names += self._complete_inherited(is_function=False)
  279. if not kwargs_only:
  280. current_line = self._code_lines[self._position[0] - 1][:self._position[1]]
  281. completion_names += self._complete_keywords(
  282. allowed_transitions,
  283. only_values=not (not current_line or current_line[-1] in ' \t.;'
  284. and current_line[-3:] != '...')
  285. )
  286. return cached_name, completion_names
  287. def _is_parameter_completion(self):
  288. tos = self.stack[-1]
  289. if tos.nonterminal == 'lambdef' and len(tos.nodes) == 1:
  290. # We are at the position `lambda `, where basically the next node
  291. # is a param.
  292. return True
  293. if tos.nonterminal in 'parameters':
  294. # Basically we are at the position `foo(`, there's nothing there
  295. # yet, so we have no `typedargslist`.
  296. return True
  297. # var args is for lambdas and typed args for normal functions
  298. return tos.nonterminal in ('typedargslist', 'varargslist') and tos.nodes[-1] == ','
  299. def _complete_params(self, leaf):
  300. stack_node = self.stack[-2]
  301. if stack_node.nonterminal == 'parameters':
  302. stack_node = self.stack[-3]
  303. if stack_node.nonterminal == 'funcdef':
  304. context = get_user_context(self._module_context, self._position)
  305. node = search_ancestor(leaf, 'error_node', 'funcdef')
  306. if node is not None:
  307. if node.type == 'error_node':
  308. n = node.children[0]
  309. if n.type == 'decorators':
  310. decorators = n.children
  311. elif n.type == 'decorator':
  312. decorators = [n]
  313. else:
  314. decorators = []
  315. else:
  316. decorators = node.get_decorators()
  317. function_name = stack_node.nodes[1]
  318. return complete_param_names(context, function_name.value, decorators)
  319. return []
  320. def _complete_keywords(self, allowed_transitions, only_values):
  321. for k in allowed_transitions:
  322. if isinstance(k, str) and k.isalpha():
  323. if not only_values or k in ('True', 'False', 'None'):
  324. yield keywords.KeywordName(self._inference_state, k)
  325. def _complete_global_scope(self):
  326. context = get_user_context(self._module_context, self._position)
  327. debug.dbg('global completion scope: %s', context)
  328. flow_scope_node = get_flow_scope_node(self._module_node, self._position)
  329. filters = get_global_filters(
  330. context,
  331. self._position,
  332. flow_scope_node
  333. )
  334. completion_names = []
  335. for filter in filters:
  336. completion_names += filter.values()
  337. return completion_names
  338. def _complete_trailer(self, previous_leaf):
  339. inferred_context = self._module_context.create_context(previous_leaf)
  340. values = infer_call_of_leaf(inferred_context, previous_leaf)
  341. debug.dbg('trailer completion values: %s', values, color='MAGENTA')
  342. # The cached name simply exists to make speed optimizations for certain
  343. # modules.
  344. cached_name = None
  345. if len(values) == 1:
  346. v, = values
  347. if v.is_module():
  348. if len(v.string_names) == 1:
  349. module_name = v.string_names[0]
  350. if module_name in ('numpy', 'tensorflow', 'matplotlib', 'pandas'):
  351. cached_name = module_name
  352. return cached_name, self._complete_trailer_for_values(values)
  353. def _complete_trailer_for_values(self, values):
  354. user_context = get_user_context(self._module_context, self._position)
  355. return complete_trailer(user_context, values)
  356. def _get_importer_names(self, names, level=0, only_modules=True):
  357. names = [n.value for n in names]
  358. i = imports.Importer(self._inference_state, names, self._module_context, level)
  359. return i.completion_names(self._inference_state, only_modules=only_modules)
  360. def _complete_inherited(self, is_function=True):
  361. """
  362. Autocomplete inherited methods when overriding in child class.
  363. """
  364. leaf = self._module_node.get_leaf_for_position(self._position, include_prefixes=True)
  365. cls = tree.search_ancestor(leaf, 'classdef')
  366. if cls is None:
  367. return
  368. # Complete the methods that are defined in the super classes.
  369. class_value = self._module_context.create_value(cls)
  370. if cls.start_pos[1] >= leaf.start_pos[1]:
  371. return
  372. filters = class_value.get_filters(is_instance=True)
  373. # The first dict is the dictionary of class itself.
  374. next(filters)
  375. for filter in filters:
  376. for name in filter.values():
  377. # TODO we should probably check here for properties
  378. if (name.api_type == 'function') == is_function:
  379. yield name
  380. def _complete_in_string(self, start_leaf, string):
  381. """
  382. To make it possible for people to have completions in doctests or
  383. generally in "Python" code in docstrings, we use the following
  384. heuristic:
  385. - Having an indented block of code
  386. - Having some doctest code that starts with `>>>`
  387. - Having backticks that doesn't have whitespace inside it
  388. """
  389. def iter_relevant_lines(lines):
  390. include_next_line = False
  391. for l in code_lines:
  392. if include_next_line or l.startswith('>>>') or l.startswith(' '):
  393. yield re.sub(r'^( *>>> ?| +)', '', l)
  394. else:
  395. yield None
  396. include_next_line = bool(re.match(' *>>>', l))
  397. string = dedent(string)
  398. code_lines = split_lines(string, keepends=True)
  399. relevant_code_lines = list(iter_relevant_lines(code_lines))
  400. if relevant_code_lines[-1] is not None:
  401. # Some code lines might be None, therefore get rid of that.
  402. relevant_code_lines = ['\n' if c is None else c for c in relevant_code_lines]
  403. return self._complete_code_lines(relevant_code_lines)
  404. match = re.search(r'`([^`\s]+)', code_lines[-1])
  405. if match:
  406. return self._complete_code_lines([match.group(1)])
  407. return []
  408. def _complete_code_lines(self, code_lines):
  409. module_node = self._inference_state.grammar.parse(''.join(code_lines))
  410. module_value = DocstringModule(
  411. in_module_context=self._module_context,
  412. inference_state=self._inference_state,
  413. module_node=module_node,
  414. code_lines=code_lines,
  415. )
  416. return Completion(
  417. self._inference_state,
  418. module_value.as_context(),
  419. code_lines=code_lines,
  420. position=module_node.end_pos,
  421. signatures_callback=lambda *args, **kwargs: [],
  422. fuzzy=self._fuzzy
  423. ).complete()
  424. def _gather_nodes(stack):
  425. nodes = []
  426. for stack_node in stack:
  427. if stack_node.dfa.from_rule == 'small_stmt':
  428. nodes = []
  429. else:
  430. nodes += stack_node.nodes
  431. return nodes
  432. _string_start = re.compile(r'^\w*(\'{3}|"{3}|\'|")')
  433. def _extract_string_while_in_string(leaf, position):
  434. def return_part_of_leaf(leaf):
  435. kwargs = {}
  436. if leaf.line == position[0]:
  437. kwargs['endpos'] = position[1] - leaf.column
  438. match = _string_start.match(leaf.value, **kwargs)
  439. if not match:
  440. return None, None, None
  441. start = match.group(0)
  442. if leaf.line == position[0] and position[1] < leaf.column + match.end():
  443. return None, None, None
  444. return cut_value_at_position(leaf, position)[match.end():], leaf, start
  445. if position < leaf.start_pos:
  446. return None, None, None
  447. if leaf.type == 'string':
  448. return return_part_of_leaf(leaf)
  449. leaves = []
  450. while leaf is not None:
  451. if leaf.type == 'error_leaf' and ('"' in leaf.value or "'" in leaf.value):
  452. if len(leaf.value) > 1:
  453. return return_part_of_leaf(leaf)
  454. prefix_leaf = None
  455. if not leaf.prefix:
  456. prefix_leaf = leaf.get_previous_leaf()
  457. if prefix_leaf is None or prefix_leaf.type != 'name' \
  458. or not all(c in 'rubf' for c in prefix_leaf.value.lower()):
  459. prefix_leaf = None
  460. return (
  461. ''.join(cut_value_at_position(l, position) for l in leaves),
  462. prefix_leaf or leaf,
  463. ('' if prefix_leaf is None else prefix_leaf.value)
  464. + cut_value_at_position(leaf, position),
  465. )
  466. if leaf.line != position[0]:
  467. # Multi line strings are always simple error leaves and contain the
  468. # whole string, single line error leaves are atherefore important
  469. # now and since the line is different, it's not really a single
  470. # line string anymore.
  471. break
  472. leaves.insert(0, leaf)
  473. leaf = leaf.get_previous_leaf()
  474. return None, None, None
  475. def complete_trailer(user_context, values):
  476. completion_names = []
  477. for value in values:
  478. for filter in value.get_filters(origin_scope=user_context.tree_node):
  479. completion_names += filter.values()
  480. if not value.is_stub() and isinstance(value, TreeInstance):
  481. completion_names += _complete_getattr(user_context, value)
  482. python_values = convert_values(values)
  483. for c in python_values:
  484. if c not in values:
  485. for filter in c.get_filters(origin_scope=user_context.tree_node):
  486. completion_names += filter.values()
  487. return completion_names
  488. def _complete_getattr(user_context, instance):
  489. """
  490. A heuristic to make completion for proxy objects work. This is not
  491. intended to work in all cases. It works exactly in this case:
  492. def __getattr__(self, name):
  493. ...
  494. return getattr(any_object, name)
  495. It is important that the return contains getattr directly, otherwise it
  496. won't work anymore. It's really just a stupid heuristic. It will not
  497. work if you write e.g. `return (getatr(o, name))`, because of the
  498. additional parentheses. It will also not work if you move the getattr
  499. to some other place that is not the return statement itself.
  500. It is intentional that it doesn't work in all cases. Generally it's
  501. really hard to do even this case (as you can see below). Most people
  502. will write it like this anyway and the other ones, well they are just
  503. out of luck I guess :) ~dave.
  504. """
  505. names = (instance.get_function_slot_names('__getattr__')
  506. or instance.get_function_slot_names('__getattribute__'))
  507. functions = ValueSet.from_sets(
  508. name.infer()
  509. for name in names
  510. )
  511. for func in functions:
  512. tree_node = func.tree_node
  513. if tree_node is None or tree_node.type != 'funcdef':
  514. continue
  515. for return_stmt in tree_node.iter_return_stmts():
  516. # Basically until the next comment we just try to find out if a
  517. # return statement looks exactly like `return getattr(x, name)`.
  518. if return_stmt.type != 'return_stmt':
  519. continue
  520. atom_expr = return_stmt.children[1]
  521. if atom_expr.type != 'atom_expr':
  522. continue
  523. atom = atom_expr.children[0]
  524. trailer = atom_expr.children[1]
  525. if len(atom_expr.children) != 2 or atom.type != 'name' \
  526. or atom.value != 'getattr':
  527. continue
  528. arglist = trailer.children[1]
  529. if arglist.type != 'arglist' or len(arglist.children) < 3:
  530. continue
  531. context = func.as_context()
  532. object_node = arglist.children[0]
  533. # Make sure it's a param: foo in __getattr__(self, foo)
  534. name_node = arglist.children[2]
  535. name_list = context.goto(name_node, name_node.start_pos)
  536. if not any(n.api_type == 'param' for n in name_list):
  537. continue
  538. # Now that we know that these are most probably completion
  539. # objects, we just infer the object and return them as
  540. # completions.
  541. objects = context.infer_node(object_node)
  542. return complete_trailer(user_context, objects)
  543. return []
  544. def search_in_module(inference_state, module_context, names, wanted_names,
  545. wanted_type, complete=False, fuzzy=False,
  546. ignore_imports=False, convert=False):
  547. for s in wanted_names[:-1]:
  548. new_names = []
  549. for n in names:
  550. if s == n.string_name:
  551. if n.tree_name is not None and n.api_type in ('module', 'namespace') \
  552. and ignore_imports:
  553. continue
  554. new_names += complete_trailer(
  555. module_context,
  556. n.infer()
  557. )
  558. debug.dbg('dot lookup on search %s from %s', new_names, names[:10])
  559. names = new_names
  560. last_name = wanted_names[-1].lower()
  561. for n in names:
  562. string = n.string_name.lower()
  563. if complete and helpers.match(string, last_name, fuzzy=fuzzy) \
  564. or not complete and string == last_name:
  565. if isinstance(n, SubModuleName):
  566. names = [v.name for v in n.infer()]
  567. else:
  568. names = [n]
  569. if convert:
  570. names = convert_names(names)
  571. for n2 in names:
  572. if complete:
  573. def_ = classes.Completion(
  574. inference_state, n2,
  575. stack=None,
  576. like_name_length=len(last_name),
  577. is_fuzzy=fuzzy,
  578. )
  579. else:
  580. def_ = classes.Name(inference_state, n2)
  581. if not wanted_type or wanted_type == def_.type:
  582. yield def_
  583. def extract_imported_names(node):
  584. imported_names = []
  585. if node.type in ['import_as_names', 'dotted_as_names', 'import_as_name']:
  586. for index, child in enumerate(node.children):
  587. if child.type == 'name':
  588. if (index > 0 and node.children[index - 1].type == "keyword"
  589. and node.children[index - 1].value == "as"):
  590. continue
  591. imported_names.append(child.value)
  592. elif child.type == 'import_as_name':
  593. imported_names.extend(extract_imported_names(child))
  594. return imported_names