1
0
forked from VimPlug/jedi

call signature -> signature

This commit is contained in:
Dave Halter
2019-12-20 19:41:57 +01:00
parent 694b05bb8c
commit 5fc308f1f8
20 changed files with 101 additions and 101 deletions

View File

@@ -11,7 +11,7 @@ Changelog
0.15.2 (2019-12-20) 0.15.2 (2019-12-20)
+++++++++++++++++++ +++++++++++++++++++
- Call signatures are now detected a lot better - Signatures are now detected a lot better
- Add fuzzy completions with ``Script(...).completions(fuzzy=True)`` - Add fuzzy completions with ``Script(...).completions(fuzzy=True)``
- Files bigger than one MB (about 20kLOC) get cropped to avoid getting - Files bigger than one MB (about 20kLOC) get cropped to avoid getting
stuck completely. stuck completely.
@@ -38,7 +38,7 @@ New APIs:
- ``Definition.get_signatures() -> List[Signature]``. Signatures are similar to - ``Definition.get_signatures() -> List[Signature]``. Signatures are similar to
``CallSignature``. ``Definition.params`` is therefore deprecated. ``CallSignature``. ``Definition.params`` is therefore deprecated.
- ``Signature.to_string()`` to format call signatures. - ``Signature.to_string()`` to format signatures.
- ``Signature.params -> List[ParamDefinition]``, ParamDefinition has the - ``Signature.params -> List[ParamDefinition]``, ParamDefinition has the
following additional attributes ``infer_default()``, ``infer_annotation()``, following additional attributes ``infer_default()``, ``infer_annotation()``,
``to_string()``, and ``kind``. ``to_string()``, and ``kind``.

View File

@@ -377,12 +377,12 @@ class Script(object):
:rtype: list of :class:`classes.Signature` :rtype: list of :class:`classes.Signature`
""" """
pos = line, column pos = line, column
call_details = helpers.get_call_signature_details(self._module_node, pos) call_details = helpers.get_signature_details(self._module_node, pos)
if call_details is None: if call_details is None:
return [] return []
context = self._get_module_context().create_context(call_details.bracket_leaf) context = self._get_module_context().create_context(call_details.bracket_leaf)
definitions = helpers.cache_call_signatures( definitions = helpers.cache_signatures(
self._inference_state, self._inference_state,
context, context,
call_details.bracket_leaf, call_details.bracket_leaf,

View File

@@ -225,7 +225,7 @@ class BaseDefinition(object):
Document for function f. Document for function f.
Notice that useful extra information is added to the actual Notice that useful extra information is added to the actual
docstring. For function, it is call signature. If you need docstring. For function, it is signature. If you need
actual docstring, use ``raw=True`` instead. actual docstring, use ``raw=True`` instead.
>>> print(script.infer(1, len('def f'))[0].docstring(raw=True)) >>> print(script.infer(1, len('def f'))[0].docstring(raw=True))

View File

@@ -18,9 +18,9 @@ from jedi.inference.gradual.conversion import convert_values
from jedi.parser_utils import cut_value_at_position from jedi.parser_utils import cut_value_at_position
def get_call_signature_param_names(call_signatures): def get_signature_param_names(signatures):
# add named params # add named params
for call_sig in call_signatures: for call_sig in signatures:
for p in call_sig.params: for p in call_sig.params:
# Allow protected access, because it's a public API. # Allow protected access, because it's a public API.
if p._name.get_kind() in (Parameter.POSITIONAL_OR_KEYWORD, if p._name.get_kind() in (Parameter.POSITIONAL_OR_KEYWORD,
@@ -74,7 +74,7 @@ def get_flow_scope_node(module_node, position):
class Completion: class Completion:
def __init__(self, inference_state, module_context, code_lines, position, def __init__(self, inference_state, module_context, code_lines, position,
call_signatures_callback, fuzzy=False): signatures_callback, fuzzy=False):
self._inference_state = inference_state self._inference_state = inference_state
self._module_context = module_context self._module_context = module_context
self._module_node = module_context.tree_node self._module_node = module_context.tree_node
@@ -86,7 +86,7 @@ class Completion:
# everything. We want the start of the name we're on. # everything. We want the start of the name we're on.
self._original_position = position self._original_position = position
self._position = position[0], position[1] - len(self._like_name) self._position = position[0], position[1] - len(self._like_name)
self._call_signatures_callback = call_signatures_callback self._signatures_callback = signatures_callback
self._fuzzy = fuzzy self._fuzzy = fuzzy
@@ -96,7 +96,7 @@ class Completion:
if string is not None: if string is not None:
completions = list(complete_file_name( completions = list(complete_file_name(
self._inference_state, self._module_context, start_leaf, string, self._inference_state, self._module_context, start_leaf, string,
self._like_name, self._call_signatures_callback, self._like_name, self._signatures_callback,
self._code_lines, self._original_position, self._code_lines, self._original_position,
fuzzy fuzzy
)) ))
@@ -226,8 +226,8 @@ class Completion:
# 3. Decorators are very primitive and have an optional `(` with # 3. Decorators are very primitive and have an optional `(` with
# optional arglist in them. # optional arglist in them.
if nodes[-1] in ['(', ','] and nonterminals[-1] in ('trailer', 'arglist', 'decorator'): if nodes[-1] in ['(', ','] and nonterminals[-1] in ('trailer', 'arglist', 'decorator'):
call_signatures = self._call_signatures_callback(*self._position) signatures = self._signatures_callback(*self._position)
completion_names += get_call_signature_param_names(call_signatures) completion_names += get_signature_param_names(signatures)
return completion_names return completion_names

View File

@@ -9,7 +9,7 @@ from jedi.parser_utils import get_string_quote
def complete_file_name(inference_state, module_context, start_leaf, string, def complete_file_name(inference_state, module_context, start_leaf, string,
like_name, call_signatures_callback, code_lines, position, fuzzy): like_name, signatures_callback, code_lines, position, fuzzy):
# First we want to find out what can actually be changed as a name. # First we want to find out what can actually be changed as a name.
like_name_length = len(os.path.basename(string) + like_name) like_name_length = len(os.path.basename(string) + like_name)
@@ -23,7 +23,7 @@ def complete_file_name(inference_state, module_context, start_leaf, string,
must_start_with = os.path.basename(string) + like_name must_start_with = os.path.basename(string) + like_name
string = os.path.dirname(string) string = os.path.dirname(string)
sigs = call_signatures_callback(*position) sigs = signatures_callback(*position)
is_in_os_path_join = sigs and all(s.full_name == 'os.path.join' for s in sigs) is_in_os_path_join = sigs and all(s.full_name == 'os.path.join' for s in sigs)
if is_in_os_path_join: if is_in_os_path_join:
to_be_added = _add_os_path_join(module_context, start_leaf, sigs[0].bracket_start) to_be_added = _add_os_path_join(module_context, start_leaf, sigs[0].bracket_start)

View File

@@ -14,7 +14,7 @@ from jedi.inference.base_value import NO_VALUES
from jedi.inference.syntax_tree import infer_atom from jedi.inference.syntax_tree import infer_atom
from jedi.inference.helpers import infer_call_of_leaf from jedi.inference.helpers import infer_call_of_leaf
from jedi.inference.compiled import get_string_value_set from jedi.inference.compiled import get_string_value_set
from jedi.cache import call_signature_time_cache from jedi.cache import signature_time_cache
CompletionParts = namedtuple('CompletionParts', ['path', 'has_dot', 'name']) CompletionParts = namedtuple('CompletionParts', ['path', 'has_dot', 'name'])
@@ -326,7 +326,7 @@ def _get_index_and_key(nodes, position):
return nodes_before.count(','), key_str return nodes_before.count(','), key_str
def _get_call_signature_details_from_error_node(node, additional_children, position): def _get_signature_details_from_error_node(node, additional_children, position):
for index, element in reversed(list(enumerate(node.children))): for index, element in reversed(list(enumerate(node.children))):
# `index > 0` means that it's a trailer and not an atom. # `index > 0` means that it's a trailer and not an atom.
if element == '(' and element.end_pos <= position and index > 0: if element == '(' and element.end_pos <= position and index > 0:
@@ -340,7 +340,7 @@ def _get_call_signature_details_from_error_node(node, additional_children, posit
return CallDetails(element, children + additional_children, position) return CallDetails(element, children + additional_children, position)
def get_call_signature_details(module, position): def get_signature_details(module, position):
leaf = module.get_leaf_for_position(position, include_prefixes=True) leaf = module.get_leaf_for_position(position, include_prefixes=True)
# It's easier to deal with the previous token than the next one in this # It's easier to deal with the previous token than the next one in this
# case. # case.
@@ -355,15 +355,15 @@ def get_call_signature_details(module, position):
node = leaf.parent node = leaf.parent
while node is not None: while node is not None:
if node.type in ('funcdef', 'classdef'): if node.type in ('funcdef', 'classdef'):
# Don't show call signatures if there's stuff before it that just # Don't show signatures if there's stuff before it that just
# makes it feel strange to have a call signature. # makes it feel strange to have a signature.
return None return None
additional_children = [] additional_children = []
for n in reversed(node.children): for n in reversed(node.children):
if n.start_pos < position: if n.start_pos < position:
if n.type == 'error_node': if n.type == 'error_node':
result = _get_call_signature_details_from_error_node( result = _get_signature_details_from_error_node(
n, additional_children, position n, additional_children, position
) )
if result is not None: if result is not None:
@@ -390,8 +390,8 @@ def get_call_signature_details(module, position):
return None return None
@call_signature_time_cache("call_signatures_validity") @signature_time_cache("call_signatures_validity")
def cache_call_signatures(inference_state, context, bracket_leaf, code_lines, user_pos): def cache_signatures(inference_state, context, bracket_leaf, code_lines, user_pos):
"""This function calculates the cache key.""" """This function calculates the cache key."""
line_index = user_pos[0] - 1 line_index = user_pos[0] - 1

View File

@@ -75,7 +75,7 @@ def clear_time_caches(delete_all=False):
del tc[key] del tc[key]
def call_signature_time_cache(time_add_setting): def signature_time_cache(time_add_setting):
""" """
This decorator works as follows: Call it with a setting and after that This decorator works as follows: Call it with a setting and after that
use the function with a callable that returns the key. use the function with a callable that returns the key.

View File

@@ -107,7 +107,7 @@ class TreeSignature(AbstractSignature):
for executed_param_name in executed_param_names) for executed_param_name in executed_param_names)
if debug.enable_notice: if debug.enable_notice:
tree_node = self._function_value.tree_node tree_node = self._function_value.tree_node
signature = parser_utils.get_call_signature(tree_node) signature = parser_utils.get_signature(tree_node)
if matches: if matches:
debug.dbg("Overloading match: %s@%s (%s)", debug.dbg("Overloading match: %s@%s (%s)",
signature, tree_node.start_pos[0], arguments, color='BLUE') signature, tree_node.start_pos[0], arguments, color='BLUE')

View File

@@ -127,10 +127,10 @@ def safe_literal_eval(value):
return '' return ''
def get_call_signature(funcdef, width=72, call_string=None, def get_signature(funcdef, width=72, call_string=None,
omit_first_param=False, omit_return_annotation=False): omit_first_param=False, omit_return_annotation=False):
""" """
Generate call signature of this function. Generate a string signature of a function.
:param width: Fold lines if a line is longer than this value. :param width: Fold lines if a line is longer than this value.
:type width: int :type width: int

View File

@@ -6,12 +6,12 @@ import pytest
from ..helpers import TestCase from ..helpers import TestCase
from jedi import cache from jedi import cache
from jedi.parser_utils import get_call_signature from jedi.parser_utils import get_signature
from jedi import Interpreter from jedi import Interpreter
def assert_signature(Script, source, expected_name, expected_index=0, line=None, column=None): def assert_signature(Script, source, expected_name, expected_index=0, line=None, column=None):
signatures = Script(source, line, column).call_signatures() signatures = Script(source).find_signatures(line, column)
assert len(signatures) <= 1 assert len(signatures) <= 1
@@ -96,12 +96,12 @@ class TestSignatures(TestCase):
def test_with(Script): def test_with(Script):
# jedi-vim #9 # jedi-vim #9
sigs = Script("with open(").call_signatures() sigs = Script("with open(").find_signatures()
assert sigs assert sigs
assert all(sig.name == 'open' for sig in sigs) assert all(sig.name == 'open' for sig in sigs)
def test_call_signatures_empty_parentheses_pre_space(Script): def test_find_signatures_empty_parentheses_pre_space(Script):
s = dedent("""\ s = dedent("""\
def f(a, b): def f(a, b):
pass pass
@@ -118,10 +118,10 @@ def test_multiple_signatures(Script):
def f(a, b): def f(a, b):
pass pass
f(""") f(""")
assert len(Script(s).call_signatures()) == 2 assert len(Script(s).find_signatures()) == 2
def test_call_signatures_whitespace(Script): def test_find_signatures_whitespace(Script):
s = dedent("""\ s = dedent("""\
abs( abs(
def x(): def x():
@@ -148,7 +148,7 @@ def test_decorator_in_class(Script):
C().test(""") C().test(""")
signatures = Script(s).call_signatures() signatures = Script(s).find_signatures()
assert len(signatures) == 1 assert len(signatures) == 1
x = [p.description for p in signatures[0].params] x = [p.description for p in signatures[0].params]
assert x == ['param *args'] assert x == ['param *args']
@@ -176,14 +176,14 @@ def test_brackets_in_string_literals(Script):
def test_function_definitions_should_break(Script): def test_function_definitions_should_break(Script):
""" """
Function definitions (and other tokens that cannot exist within call Function definitions (and other tokens that cannot exist within call
signatures) should break and not be able to return a call signature. signatures) should break and not be able to return a signature.
""" """
assert_signature(Script, 'abs(\ndef x', 'abs', 0) assert_signature(Script, 'abs(\ndef x', 'abs', 0)
assert not Script('abs(\ndef x(): pass').call_signatures() assert not Script('abs(\ndef x(): pass').find_signatures()
def test_flow_call(Script): def test_flow_call(Script):
assert not Script('if (1').call_signatures() assert not Script('if (1').find_signatures()
def test_chained_calls(Script): def test_chained_calls(Script):
@@ -209,11 +209,11 @@ def test_return(Script):
assert_signature(Script, source, 'join', 0, column=len(" return '.'.join(")) assert_signature(Script, source, 'join', 0, column=len(" return '.'.join("))
def test_call_signature_on_module(Script): def test_find_signature_on_module(Script):
"""github issue #240""" """github issue #240"""
s = 'import datetime; datetime(' s = 'import datetime; datetime('
# just don't throw an exception (if numpy doesn't exist, just ignore it) # just don't throw an exception (if numpy doesn't exist, just ignore it)
assert Script(s).call_signatures() == [] assert Script(s).find_signatures() == []
def test_complex(Script, environment): def test_complex(Script, environment):
@@ -234,7 +234,7 @@ def test_complex(Script, environment):
re.compile( re.compile(
return it * 2 return it * 2
""" """
sig1, sig2 = sorted(Script(s, line=4, column=27).call_signatures(), key=lambda s: s.line) sig1, sig2 = sorted(Script(s).find_signatures(line=4, column=27), key=lambda s: s.line)
assert sig1.name == sig2.name == 'compile' assert sig1.name == sig2.name == 'compile'
assert sig1.index == sig2.index == 0 assert sig1.index == sig2.index == 0
func1, = sig1._name.infer() func1, = sig1._name.infer()
@@ -243,14 +243,14 @@ def test_complex(Script, environment):
if environment.version_info.major == 3: if environment.version_info.major == 3:
# Do these checks just for Python 3, I'm too lazy to deal with this # Do these checks just for Python 3, I'm too lazy to deal with this
# legacy stuff. ~ dave. # legacy stuff. ~ dave.
assert get_call_signature(func1.tree_node) \ assert get_signature(func1.tree_node) \
== 'compile(pattern: AnyStr, flags: _FlagsType = ...) -> Pattern[AnyStr]' == 'compile(pattern: AnyStr, flags: _FlagsType = ...) -> Pattern[AnyStr]'
assert get_call_signature(func2.tree_node) \ assert get_signature(func2.tree_node) \
== 'compile(pattern: Pattern[AnyStr], flags: _FlagsType = ...) ->\nPattern[AnyStr]' == 'compile(pattern: Pattern[AnyStr], flags: _FlagsType = ...) ->\nPattern[AnyStr]'
# jedi-vim #70 # jedi-vim #70
s = """def foo(""" s = """def foo("""
assert Script(s).call_signatures() == [] assert Script(s).find_signatures() == []
# jedi-vim #116 # jedi-vim #116
s = """import itertools; test = getattr(itertools, 'chain'); test(""" s = """import itertools; test = getattr(itertools, 'chain'); test("""
@@ -258,13 +258,13 @@ def test_complex(Script, environment):
def _params(Script, source, line=None, column=None): def _params(Script, source, line=None, column=None):
signatures = Script(source, line, column).call_signatures() signatures = Script(source, line, column).find_signatures()
assert len(signatures) == 1 assert len(signatures) == 1
return signatures[0].params return signatures[0].params
def test_int_params(Script): def test_int_params(Script):
sig1, sig2 = Script('int(').call_signatures() sig1, sig2 = Script('int(').find_signatures()
# int is defined as: `int(x[, base])` # int is defined as: `int(x[, base])`
assert len(sig1.params) == 1 assert len(sig1.params) == 1
assert sig1.params[0].name == 'x' assert sig1.params[0].name == 'x'
@@ -275,13 +275,13 @@ def test_int_params(Script):
def test_pow_params(Script): def test_pow_params(Script):
# See Github #1357. # See Github #1357.
for sig in Script('pow(').call_signatures(): for sig in Script('pow(').find_signatures():
param_names = [p.name for p in sig.params] param_names = [p.name for p in sig.params]
assert param_names in (['x', 'y'], ['x', 'y', 'z']) assert param_names in (['x', 'y'], ['x', 'y', 'z'])
def test_param_name(Script): def test_param_name(Script):
sigs = Script('open(something,').call_signatures() sigs = Script('open(something,').find_signatures()
for sig in sigs: for sig in sigs:
# All of the signatures (in Python the function is overloaded), # All of the signatures (in Python the function is overloaded),
# contain the same param names. # contain the same param names.
@@ -304,11 +304,11 @@ def test_builtins(Script):
def test_signature_is_definition(Script): def test_signature_is_definition(Script):
""" """
Through inheritance, a call signature is a sub class of Definition. Through inheritance, a signature is a sub class of Definition.
Check if the attributes match. Check if the attributes match.
""" """
s = """class Spam(): pass\nSpam""" s = """class Spam(): pass\nSpam"""
signature = Script(s + '(').call_signatures()[0] signature = Script(s + '(').find_signatures()[0]
definition = Script(s + '(').infer(column=0)[0] definition = Script(s + '(').infer(column=0)[0]
signature.line == 1 signature.line == 1
signature.column == 6 signature.column == 6
@@ -330,15 +330,15 @@ def test_signature_is_definition(Script):
def test_no_signature(Script): def test_no_signature(Script):
# str doesn't have a __call__ method # str doesn't have a __call__ method
assert Script('str()(').call_signatures() == [] assert Script('str()(').find_signatures() == []
s = dedent("""\ s = dedent("""\
class X(): class X():
pass pass
X()(""") X()(""")
assert Script(s).call_signatures() == [] assert Script(s).find_signatures() == []
assert len(Script(s, column=2).call_signatures()) == 1 assert len(Script(s).find_signatures(column=2)) == 1
assert Script('').call_signatures() == [] assert Script('').find_signatures() == []
def test_dict_literal_in_incomplete_call(Script): def test_dict_literal_in_incomplete_call(Script):
@@ -354,24 +354,24 @@ def test_dict_literal_in_incomplete_call(Script):
c = Foo() c = Foo()
""" """
script = Script(dedent(source), line=4, column=15) script = Script(dedent(source))
assert script.call_signatures() assert script.find_signatures(line=4, column=15)
def test_completion_interference(Script): def test_completion_interference(Script):
"""Seems to cause problems, see also #396.""" """Seems to cause problems, see also #396."""
cache.parser_cache.pop(None, None) cache.parser_cache.pop(None, None)
assert Script('open(').call_signatures() assert Script('open(').find_signatures()
# complete something usual, before doing the same call_signatures again. # complete something usual, before doing the same find_signatures again.
assert Script('from datetime import ').complete() assert Script('from datetime import ').complete()
assert Script('open(').call_signatures() assert Script('open(').find_signatures()
def test_keyword_argument_index(Script, environment): def test_keyword_argument_index(Script, environment):
def get(source, column=None): def get(source, column=None):
return Script(source, column=column).call_signatures()[0] return Script(source).find_signatures(column=column)[0]
# The signature of sorted changed from 2 to 3. # The signature of sorted changed from 2 to 3.
py2_offset = int(environment.version_info.major == 2) py2_offset = int(environment.version_info.major == 2)
@@ -509,7 +509,7 @@ def test_signature_index(skip_python2, Script, environment, code, call, expected
if environment.version_info < (3, 8): if environment.version_info < (3, 8):
code = code.replace('/,', '') code = code.replace('/,', '')
sig, = Script(code + '\n' + call + ending, column=len(call)).call_signatures() sig, = Script(code + '\n' + call + ending).find_signatures(column=len(call))
index = sig.index index = sig.index
assert expected_index == index assert expected_index == index
@@ -547,14 +547,14 @@ def test_arg_defaults(Script, environment, code):
yield Interpreter(code + '2(', namespaces=[executed_locals]) yield Interpreter(code + '2(', namespaces=[executed_locals])
for script in iter_scripts(): for script in iter_scripts():
signatures = script.call_signatures() signatures = script.find_signatures()
assert signatures[0].params[0].description in ('param arg="bla"', "param arg='bla'") assert signatures[0].params[0].description in ('param arg="bla"', "param arg='bla'")
assert signatures[0].params[1].description == 'param arg1=1' assert signatures[0].params[1].description == 'param arg1=1'
def test_bracket_start(Script): def test_bracket_start(Script):
def bracket_start(src): def bracket_start(src):
signatures = Script(src).call_signatures() signatures = Script(src).find_signatures()
assert len(signatures) == 1 assert len(signatures) == 1
return signatures[0].bracket_start return signatures[0].bracket_start
@@ -564,7 +564,7 @@ def test_bracket_start(Script):
def test_different_caller(Script): def test_different_caller(Script):
""" """
It's possible to not use names, but another function result or an array It's possible to not use names, but another function result or an array
index and then get the call signature of it. index and then get the signature of it.
""" """
assert_signature(Script, '[abs][0](', 'abs', 0) assert_signature(Script, '[abs][0](', 'abs', 0)
@@ -579,14 +579,14 @@ def test_in_function(Script):
class X(): class X():
@property @property
def func(''') def func(''')
assert not Script(code).call_signatures() assert not Script(code).find_signatures()
def test_lambda_params(Script): def test_lambda_params(Script):
code = dedent('''\ code = dedent('''\
my_lambda = lambda x: x+1 my_lambda = lambda x: x+1
my_lambda(1)''') my_lambda(1)''')
sig, = Script(code, column=11).call_signatures() sig, = Script(code).find_signatures(column=11)
assert sig.index == 0 assert sig.index == 0
assert sig.name == '<lambda>' assert sig.name == '<lambda>'
assert [p.name for p in sig.params] == ['x'] assert [p.name for p in sig.params] == ['x']
@@ -601,19 +601,19 @@ class X():
def test_class_creation(Script): def test_class_creation(Script):
sig, = Script(CLASS_CODE + 'X(').call_signatures() sig, = Script(CLASS_CODE + 'X(').find_signatures()
assert sig.index == 0 assert sig.index == 0
assert sig.name == 'X' assert sig.name == 'X'
assert [p.name for p in sig.params] == ['foo', 'bar'] assert [p.name for p in sig.params] == ['foo', 'bar']
def test_call_init_on_class(Script): def test_call_init_on_class(Script):
sig, = Script(CLASS_CODE + 'X.__init__(').call_signatures() sig, = Script(CLASS_CODE + 'X.__init__(').find_signatures()
assert [p.name for p in sig.params] == ['self', 'foo', 'bar'] assert [p.name for p in sig.params] == ['self', 'foo', 'bar']
def test_call_init_on_instance(Script): def test_call_init_on_instance(Script):
sig, = Script(CLASS_CODE + 'X().__init__(').call_signatures() sig, = Script(CLASS_CODE + 'X().__init__(').find_signatures()
assert [p.name for p in sig.params] == ['foo', 'bar'] assert [p.name for p in sig.params] == ['foo', 'bar']
@@ -623,14 +623,14 @@ def test_call_magic_method(Script):
def __call__(self, baz): def __call__(self, baz):
pass pass
''') ''')
sig, = Script(code + 'X()(').call_signatures() sig, = Script(code + 'X()(').find_signatures()
assert sig.index == 0 assert sig.index == 0
assert sig.name == 'X' assert sig.name == 'X'
assert [p.name for p in sig.params] == ['baz'] assert [p.name for p in sig.params] == ['baz']
sig, = Script(code + 'X.__call__(').call_signatures() sig, = Script(code + 'X.__call__(').find_signatures()
assert [p.name for p in sig.params] == ['self', 'baz'] assert [p.name for p in sig.params] == ['self', 'baz']
sig, = Script(code + 'X().__call__(').call_signatures() sig, = Script(code + 'X().__call__(').find_signatures()
assert [p.name for p in sig.params] == ['baz'] assert [p.name for p in sig.params] == ['baz']
@@ -642,9 +642,9 @@ def test_cursor_after_signature(Script, column):
foo() # _ foo() # _
""") """)
script = Script(source, 4, column) script = Script(source)
assert not script.call_signatures() assert not script.find_signatures(4, column)
@pytest.mark.parametrize( @pytest.mark.parametrize(
@@ -661,7 +661,7 @@ def test_cursor_after_signature(Script, column):
] ]
) )
def test_base_signatures(Script, code, line, column, name, index): def test_base_signatures(Script, code, line, column, name, index):
sig, = Script(code, line=line, column=column).call_signatures() sig, = Script(code).find_signatures(line=line, column=column)
assert sig.name == name assert sig.name == name
assert sig.index == index assert sig.index == index

View File

@@ -92,7 +92,7 @@ def test_basedefinition_type_import(Script, src, expected_result, column):
assert types == {expected_result} assert types == {expected_result}
def test_function_call_signature_in_doc(Script): def test_function_signature_in_doc(Script):
defs = Script(""" defs = Script("""
def f(x, y=1, z='a'): def f(x, y=1, z='a'):
pass pass
@@ -107,7 +107,7 @@ def test_param_docstring(names):
assert param.docstring() == '' assert param.docstring() == ''
def test_class_call_signature(Script): def test_class_signature(Script):
defs = Script(""" defs = Script("""
class Foo: class Foo:
def __init__(self, x, y=1, z='a'): def __init__(self, x, y=1, z='a'):
@@ -215,7 +215,7 @@ def test_param_endings(Script):
Params should be represented without the comma and whitespace they have Params should be represented without the comma and whitespace they have
around them. around them.
""" """
sig = Script('def x(a, b=5, c=""): pass\n x(').call_signatures()[0] sig = Script('def x(a, b=5, c=""): pass\n x(').find_signatures()[0]
assert [p.description for p in sig.params] == ['param a', 'param b=5', 'param c=""'] assert [p.description for p in sig.params] == ['param a', 'param b=5', 'param c=""']

View File

@@ -548,7 +548,7 @@ def test_partial_signatures(code, expected, index):
b = functools.partial(func, 1) b = functools.partial(func, 1)
c = functools.partial(func, 1, c=2) c = functools.partial(func, 1, c=2)
sig, = jedi.Interpreter(code, [locals()]).call_signatures() sig, = jedi.Interpreter(code, [locals()]).find_signatures()
assert sig.name == 'partial' assert sig.name == 'partial'
assert [p.name for p in sig.params] == expected assert [p.name for p in sig.params] == expected
assert index == sig.index assert index == sig.index

View File

@@ -70,5 +70,5 @@ def test_param_kind_and_name(code, index, param_code, kind, Script, skip_python2
def test_staticmethod(Script): def test_staticmethod(Script):
s, = Script('staticmethod(').call_signatures() s, = Script('staticmethod(').find_signatures()
assert s.to_string() == 'staticmethod(f: Callable[..., Any])' assert s.to_string() == 'staticmethod(f: Callable[..., Any])'

View File

@@ -3,12 +3,12 @@ Test all things related to the ``jedi.cache`` module.
""" """
def test_cache_call_signatures(Script): def test_cache_find_signatures(Script):
""" """
See github issue #390. See github issue #390.
""" """
def check(column, call_name, path=None): def check(column, call_name, path=None):
assert Script(s, 1, column, path).call_signatures()[0].name == call_name assert Script(s, path=path).find_signatures(1, column)[0].name == call_name
s = 'str(int())' s = 'str(int())'
@@ -26,4 +26,4 @@ def test_cache_call_signatures(Script):
def test_cache_line_split_issues(Script): def test_cache_line_split_issues(Script):
"""Should still work even if there's a newline.""" """Should still work even if there's a newline."""
assert Script('int(\n').call_signatures()[0].name == 'int' assert Script('int(\n').find_signatures()[0].name == 'int'

View File

@@ -422,5 +422,5 @@ def test_basic_str_init_signature(Script, disable_typeshed):
class Foo(str): class Foo(str):
pass pass
Foo(''') Foo(''')
c, = Script(code).call_signatures() c, = Script(code).find_signatures()
assert c.name == 'Foo' assert c.name == 'Foo'

View File

@@ -13,7 +13,7 @@ def test_completions(Script):
assert len(s.complete()) >= 15 assert len(s.complete()) >= 15
def test_call_signatures_extension(Script): def test_find_signatures_extension(Script):
if os.name == 'nt': if os.name == 'nt':
func = 'LoadLibrary' func = 'LoadLibrary'
params = 1 params = 1
@@ -21,14 +21,14 @@ def test_call_signatures_extension(Script):
func = 'dlopen' func = 'dlopen'
params = 2 params = 2
s = Script('import _ctypes; _ctypes.%s(' % (func,)) s = Script('import _ctypes; _ctypes.%s(' % (func,))
sigs = s.call_signatures() sigs = s.find_signatures()
assert len(sigs) == 1 assert len(sigs) == 1
assert len(sigs[0].params) == params assert len(sigs[0].params) == params
def test_call_signatures_stdlib(Script): def test_find_signatures_stdlib(Script):
s = Script('import math; math.cos(') s = Script('import math; math.cos(')
sigs = s.call_signatures() sigs = s.find_signatures()
assert len(sigs) == 1 assert len(sigs) == 1
assert len(sigs[0].params) == 1 assert len(sigs[0].params) == 1

View File

@@ -90,9 +90,9 @@ def test_tree_signature(Script, environment, code, expected):
pytest.skip() pytest.skip()
if expected is None: if expected is None:
assert not Script(code).call_signatures() assert not Script(code).find_signatures()
else: else:
sig, = Script(code).call_signatures() sig, = Script(code).find_signatures()
assert expected == sig.to_string() assert expected == sig.to_string()
@@ -182,7 +182,7 @@ def test_nested_signatures(Script, environment, combination, expected, skip_pre_
super().foo(**kwargs) super().foo(**kwargs)
''') ''')
code += 'z = ' + combination + '\nz(' code += 'z = ' + combination + '\nz('
sig, = Script(code).call_signatures() sig, = Script(code).find_signatures()
computed = sig.to_string() computed = sig.to_string()
if not re.match(r'\w+\(', expected): if not re.match(r'\w+\(', expected):
expected = '<lambda>(' + expected + ')' expected = '<lambda>(' + expected + ')'
@@ -191,7 +191,7 @@ def test_nested_signatures(Script, environment, combination, expected, skip_pre_
def test_pow_signature(Script): def test_pow_signature(Script):
# See github #1357 # See github #1357
sigs = Script('pow(').call_signatures() sigs = Script('pow(').find_signatures()
strings = {sig.to_string() for sig in sigs} strings = {sig.to_string() for sig in sigs}
assert strings == {'pow(x: float, y: float, z: float, /) -> float', assert strings == {'pow(x: float, y: float, z: float, /) -> float',
'pow(x: float, y: float, /) -> float', 'pow(x: float, y: float, /) -> float',
@@ -230,7 +230,7 @@ def test_pow_signature(Script):
] ]
) )
def test_wraps_signature(Script, code, signature, skip_pre_python35): def test_wraps_signature(Script, code, signature, skip_pre_python35):
sigs = Script(code).call_signatures() sigs = Script(code).find_signatures()
assert {sig.to_string() for sig in sigs} == {signature} assert {sig.to_string() for sig in sigs} == {signature}
@@ -263,7 +263,7 @@ def test_dataclass_signature(Script, skip_pre_python37, start, start_params):
code = 'from dataclasses import dataclass\n' + start + code code = 'from dataclasses import dataclass\n' + start + code
sig, = Script(code).call_signatures() sig, = Script(code).find_signatures()
assert [p.name for p in sig.params] == start_params + ['name', 'price', 'quantity'] assert [p.name for p in sig.params] == start_params + ['name', 'price', 'quantity']
quantity, = sig.params[-1].infer() quantity, = sig.params[-1].infer()
assert quantity.name == 'int' assert quantity.name == 'int'
@@ -289,13 +289,13 @@ def test_param_resolving_to_static(Script, stmt, expected, skip_pre_python35):
def simple(a, b, *, c): ... def simple(a, b, *, c): ...
full_redirect(simple)('''.format(stmt=stmt)) full_redirect(simple)('''.format(stmt=stmt))
sig, = Script(code).call_signatures() sig, = Script(code).find_signatures()
assert sig.to_string() == expected assert sig.to_string() == expected
def test_overload(Script): def test_overload(Script):
dir_ = get_example_dir('typing_overload') dir_ = get_example_dir('typing_overload')
code = 'from file import with_overload; with_overload(' code = 'from file import with_overload; with_overload('
x1, x2 = Script(code, path=os.path.join(dir_, 'foo.py')).call_signatures() x1, x2 = Script(code, path=os.path.join(dir_, 'foo.py')).find_signatures()
assert x1.to_string() == 'with_overload(x: int, y: int) -> float' assert x1.to_string() == 'with_overload(x: int, y: int) -> float'
assert x2.to_string() == 'with_overload(x: str, y: list) -> float' assert x2.to_string() == 'with_overload(x: str, y: list) -> float'

View File

@@ -6,7 +6,7 @@ from parso import parse
def test_form_feed_characters(Script): def test_form_feed_characters(Script):
s = "\f\nclass Test(object):\n pass" s = "\f\nclass Test(object):\n pass"
Script(s, line=2, column=18).call_signatures() Script(s).find_signatures(line=2, column=18)
def check_p(src): def check_p(src):

View File

@@ -62,13 +62,13 @@ def test_hex_values_in_docstring():
@pytest.mark.parametrize( @pytest.mark.parametrize(
'code,call_signature', [ 'code,signature', [
('def my_function(x, typed: Type, z):\n return', 'my_function(x, typed: Type, z)'), ('def my_function(x, typed: Type, z):\n return', 'my_function(x, typed: Type, z)'),
('def my_function(x, y, z) -> str:\n return', 'my_function(x, y, z) -> str'), ('def my_function(x, y, z) -> str:\n return', 'my_function(x, y, z) -> str'),
('lambda x, y, z: x + y * z\n', '<lambda>(x, y, z)') ('lambda x, y, z: x + y * z\n', '<lambda>(x, y, z)')
]) ])
def test_get_call_signature(code, call_signature): def test_get_signature(code, signature):
node = parse(code, version='3.5').children[0] node = parse(code, version='3.5').children[0]
if node.type == 'simple_stmt': if node.type == 'simple_stmt':
node = node.children[0] node = node.children[0]
assert parser_utils.get_call_signature(node) == call_signature assert parser_utils.get_signature(node) == signature

View File

@@ -39,8 +39,8 @@ def test_os_path_join(Script):
@_check_speed(0.15) @_check_speed(0.15)
def test_scipy_speed(Script): def test_scipy_speed(Script):
s = 'import scipy.weave; scipy.weave.inline(' s = 'import scipy.weave; scipy.weave.inline('
script = Script(s, 1, len(s), '') script = Script(s, path='')
script.call_signatures() script.find_signatures(1, len(s))
@_check_speed(0.8) @_check_speed(0.8)