]>
Commit | Line | Data |
---|---|---|
53e6db90 DC |
1 | """ |
2 | There are a couple of classes documented in here: | |
3 | ||
4 | - :class:`.BaseName` as an abstact base class for almost everything. | |
5 | - :class:`.Name` used in a lot of places | |
6 | - :class:`.Completion` for completions | |
7 | - :class:`.BaseSignature` as a base class for signatures | |
8 | - :class:`.Signature` for :meth:`.Script.get_signatures` only | |
9 | - :class:`.ParamName` used for parameters of signatures | |
10 | - :class:`.Refactoring` for refactorings | |
11 | - :class:`.SyntaxError` for :meth:`.Script.get_syntax_errors` only | |
12 | ||
13 | These classes are the much biggest part of the API, because they contain | |
14 | the interesting information about all operations. | |
15 | """ | |
16 | import re | |
17 | from pathlib import Path | |
18 | from typing import Optional | |
19 | ||
20 | from parso.tree import search_ancestor | |
21 | ||
22 | from jedi import settings | |
23 | from jedi import debug | |
24 | from jedi.inference.utils import unite | |
25 | from jedi.cache import memoize_method | |
26 | from jedi.inference.compiled.mixed import MixedName | |
27 | from jedi.inference.names import ImportName, SubModuleName | |
28 | from jedi.inference.gradual.stub_value import StubModuleValue | |
29 | from jedi.inference.gradual.conversion import convert_names, convert_values | |
30 | from jedi.inference.base_value import ValueSet, HasNoContext | |
31 | from jedi.api.keywords import KeywordName | |
32 | from jedi.api import completion_cache | |
33 | from jedi.api.helpers import filter_follow_imports | |
34 | ||
35 | ||
36 | def _sort_names_by_start_pos(names): | |
37 | return sorted(names, key=lambda s: s.start_pos or (0, 0)) | |
38 | ||
39 | ||
40 | def defined_names(inference_state, value): | |
41 | """ | |
42 | List sub-definitions (e.g., methods in class). | |
43 | ||
44 | :type scope: Scope | |
45 | :rtype: list of Name | |
46 | """ | |
47 | try: | |
48 | context = value.as_context() | |
49 | except HasNoContext: | |
50 | return [] | |
51 | filter = next(context.get_filters()) | |
52 | names = [name for name in filter.values()] | |
53 | return [Name(inference_state, n) for n in _sort_names_by_start_pos(names)] | |
54 | ||
55 | ||
56 | def _values_to_definitions(values): | |
57 | return [Name(c.inference_state, c.name) for c in values] | |
58 | ||
59 | ||
60 | class BaseName: | |
61 | """ | |
62 | The base class for all definitions, completions and signatures. | |
63 | """ | |
64 | _mapping = { | |
65 | 'posixpath': 'os.path', | |
66 | 'riscospath': 'os.path', | |
67 | 'ntpath': 'os.path', | |
68 | 'os2emxpath': 'os.path', | |
69 | 'macpath': 'os.path', | |
70 | 'genericpath': 'os.path', | |
71 | 'posix': 'os', | |
72 | '_io': 'io', | |
73 | '_functools': 'functools', | |
74 | '_collections': 'collections', | |
75 | '_socket': 'socket', | |
76 | '_sqlite3': 'sqlite3', | |
77 | } | |
78 | ||
79 | _tuple_mapping = dict((tuple(k.split('.')), v) for (k, v) in { | |
80 | 'argparse._ActionsContainer': 'argparse.ArgumentParser', | |
81 | }.items()) | |
82 | ||
83 | def __init__(self, inference_state, name): | |
84 | self._inference_state = inference_state | |
85 | self._name = name | |
86 | """ | |
87 | An instance of :class:`parso.python.tree.Name` subclass. | |
88 | """ | |
89 | self.is_keyword = isinstance(self._name, KeywordName) | |
90 | ||
91 | @memoize_method | |
92 | def _get_module_context(self): | |
93 | # This can take a while to complete, because in the worst case of | |
94 | # imports (consider `import a` completions), we need to load all | |
95 | # modules starting with a first. | |
96 | return self._name.get_root_context() | |
97 | ||
98 | @property | |
99 | def module_path(self) -> Optional[Path]: | |
100 | """ | |
101 | Shows the file path of a module. e.g. ``/usr/lib/python3.9/os.py`` | |
102 | """ | |
103 | module = self._get_module_context() | |
104 | if module.is_stub() or not module.is_compiled(): | |
105 | # Compiled modules should not return a module path even if they | |
106 | # have one. | |
107 | path: Optional[Path] = self._get_module_context().py__file__() | |
108 | return path | |
109 | ||
110 | return None | |
111 | ||
112 | @property | |
113 | def name(self): | |
114 | """ | |
115 | Name of variable/function/class/module. | |
116 | ||
117 | For example, for ``x = None`` it returns ``'x'``. | |
118 | ||
119 | :rtype: str or None | |
120 | """ | |
121 | return self._name.get_public_name() | |
122 | ||
123 | @property | |
124 | def type(self): | |
125 | """ | |
126 | The type of the definition. | |
127 | ||
128 | Here is an example of the value of this attribute. Let's consider | |
129 | the following source. As what is in ``variable`` is unambiguous | |
130 | to Jedi, :meth:`jedi.Script.infer` should return a list of | |
131 | definition for ``sys``, ``f``, ``C`` and ``x``. | |
132 | ||
133 | >>> from jedi import Script | |
134 | >>> source = ''' | |
135 | ... import keyword | |
136 | ... | |
137 | ... class C: | |
138 | ... pass | |
139 | ... | |
140 | ... class D: | |
141 | ... pass | |
142 | ... | |
143 | ... x = D() | |
144 | ... | |
145 | ... def f(): | |
146 | ... pass | |
147 | ... | |
148 | ... for variable in [keyword, f, C, x]: | |
149 | ... variable''' | |
150 | ||
151 | >>> script = Script(source) | |
152 | >>> defs = script.infer() | |
153 | ||
154 | Before showing what is in ``defs``, let's sort it by :attr:`line` | |
155 | so that it is easy to relate the result to the source code. | |
156 | ||
157 | >>> defs = sorted(defs, key=lambda d: d.line) | |
158 | >>> print(defs) # doctest: +NORMALIZE_WHITESPACE | |
159 | [<Name full_name='keyword', description='module keyword'>, | |
160 | <Name full_name='__main__.C', description='class C'>, | |
161 | <Name full_name='__main__.D', description='instance D'>, | |
162 | <Name full_name='__main__.f', description='def f'>] | |
163 | ||
164 | Finally, here is what you can get from :attr:`type`: | |
165 | ||
166 | >>> defs = [d.type for d in defs] | |
167 | >>> defs[0] | |
168 | 'module' | |
169 | >>> defs[1] | |
170 | 'class' | |
171 | >>> defs[2] | |
172 | 'instance' | |
173 | >>> defs[3] | |
174 | 'function' | |
175 | ||
176 | Valid values for type are ``module``, ``class``, ``instance``, ``function``, | |
177 | ``param``, ``path``, ``keyword``, ``property`` and ``statement``. | |
178 | ||
179 | """ | |
180 | tree_name = self._name.tree_name | |
181 | resolve = False | |
182 | if tree_name is not None: | |
183 | # TODO move this to their respective names. | |
184 | definition = tree_name.get_definition() | |
185 | if definition is not None and definition.type == 'import_from' and \ | |
186 | tree_name.is_definition(): | |
187 | resolve = True | |
188 | ||
189 | if isinstance(self._name, SubModuleName) or resolve: | |
190 | for value in self._name.infer(): | |
191 | return value.api_type | |
192 | return self._name.api_type | |
193 | ||
194 | @property | |
195 | def module_name(self): | |
196 | """ | |
197 | The module name, a bit similar to what ``__name__`` is in a random | |
198 | Python module. | |
199 | ||
200 | >>> from jedi import Script | |
201 | >>> source = 'import json' | |
202 | >>> script = Script(source, path='example.py') | |
203 | >>> d = script.infer()[0] | |
204 | >>> print(d.module_name) # doctest: +ELLIPSIS | |
205 | json | |
206 | """ | |
207 | return self._get_module_context().py__name__() | |
208 | ||
209 | def in_builtin_module(self): | |
210 | """ | |
211 | Returns True, if this is a builtin module. | |
212 | """ | |
213 | value = self._get_module_context().get_value() | |
214 | if isinstance(value, StubModuleValue): | |
215 | return any(v.is_compiled() for v in value.non_stub_value_set) | |
216 | return value.is_compiled() | |
217 | ||
218 | @property | |
219 | def line(self): | |
220 | """The line where the definition occurs (starting with 1).""" | |
221 | start_pos = self._name.start_pos | |
222 | if start_pos is None: | |
223 | return None | |
224 | return start_pos[0] | |
225 | ||
226 | @property | |
227 | def column(self): | |
228 | """The column where the definition occurs (starting with 0).""" | |
229 | start_pos = self._name.start_pos | |
230 | if start_pos is None: | |
231 | return None | |
232 | return start_pos[1] | |
233 | ||
234 | def get_definition_start_position(self): | |
235 | """ | |
236 | The (row, column) of the start of the definition range. Rows start with | |
237 | 1, columns start with 0. | |
238 | ||
239 | :rtype: Optional[Tuple[int, int]] | |
240 | """ | |
241 | if self._name.tree_name is None: | |
242 | return None | |
243 | definition = self._name.tree_name.get_definition() | |
244 | if definition is None: | |
245 | return self._name.start_pos | |
246 | return definition.start_pos | |
247 | ||
248 | def get_definition_end_position(self): | |
249 | """ | |
250 | The (row, column) of the end of the definition range. Rows start with | |
251 | 1, columns start with 0. | |
252 | ||
253 | :rtype: Optional[Tuple[int, int]] | |
254 | """ | |
255 | if self._name.tree_name is None: | |
256 | return None | |
257 | definition = self._name.tree_name.get_definition() | |
258 | if definition is None: | |
259 | return self._name.tree_name.end_pos | |
260 | if self.type in ("function", "class"): | |
261 | last_leaf = definition.get_last_leaf() | |
262 | if last_leaf.type == "newline": | |
263 | return last_leaf.get_previous_leaf().end_pos | |
264 | return last_leaf.end_pos | |
265 | return definition.end_pos | |
266 | ||
267 | def docstring(self, raw=False, fast=True): | |
268 | r""" | |
269 | Return a document string for this completion object. | |
270 | ||
271 | Example: | |
272 | ||
273 | >>> from jedi import Script | |
274 | >>> source = '''\ | |
275 | ... def f(a, b=1): | |
276 | ... "Document for function f." | |
277 | ... ''' | |
278 | >>> script = Script(source, path='example.py') | |
279 | >>> doc = script.infer(1, len('def f'))[0].docstring() | |
280 | >>> print(doc) | |
281 | f(a, b=1) | |
282 | <BLANKLINE> | |
283 | Document for function f. | |
284 | ||
285 | Notice that useful extra information is added to the actual | |
286 | docstring, e.g. function signatures are prepended to their docstrings. | |
287 | If you need the actual docstring, use ``raw=True`` instead. | |
288 | ||
289 | >>> print(script.infer(1, len('def f'))[0].docstring(raw=True)) | |
290 | Document for function f. | |
291 | ||
292 | :param fast: Don't follow imports that are only one level deep like | |
293 | ``import foo``, but follow ``from foo import bar``. This makes | |
294 | sense for speed reasons. Completing `import a` is slow if you use | |
295 | the ``foo.docstring(fast=False)`` on every object, because it | |
296 | parses all libraries starting with ``a``. | |
297 | """ | |
298 | if isinstance(self._name, ImportName) and fast: | |
299 | return '' | |
300 | doc = self._get_docstring() | |
301 | if raw: | |
302 | return doc | |
303 | ||
304 | signature_text = self._get_docstring_signature() | |
305 | if signature_text and doc: | |
306 | return signature_text + '\n\n' + doc | |
307 | else: | |
308 | return signature_text + doc | |
309 | ||
310 | def _get_docstring(self): | |
311 | return self._name.py__doc__() | |
312 | ||
313 | def _get_docstring_signature(self): | |
314 | return '\n'.join( | |
315 | signature.to_string() | |
316 | for signature in self._get_signatures(for_docstring=True) | |
317 | ) | |
318 | ||
319 | @property | |
320 | def description(self): | |
321 | """ | |
322 | A description of the :class:`.Name` object, which is heavily used | |
323 | in testing. e.g. for ``isinstance`` it returns ``def isinstance``. | |
324 | ||
325 | Example: | |
326 | ||
327 | >>> from jedi import Script | |
328 | >>> source = ''' | |
329 | ... def f(): | |
330 | ... pass | |
331 | ... | |
332 | ... class C: | |
333 | ... pass | |
334 | ... | |
335 | ... variable = f if random.choice([0,1]) else C''' | |
336 | >>> script = Script(source) # line is maximum by default | |
337 | >>> defs = script.infer(column=3) | |
338 | >>> defs = sorted(defs, key=lambda d: d.line) | |
339 | >>> print(defs) # doctest: +NORMALIZE_WHITESPACE | |
340 | [<Name full_name='__main__.f', description='def f'>, | |
341 | <Name full_name='__main__.C', description='class C'>] | |
342 | >>> str(defs[0].description) | |
343 | 'def f' | |
344 | >>> str(defs[1].description) | |
345 | 'class C' | |
346 | ||
347 | """ | |
348 | typ = self.type | |
349 | tree_name = self._name.tree_name | |
350 | if typ == 'param': | |
351 | return typ + ' ' + self._name.to_string() | |
352 | if typ in ('function', 'class', 'module', 'instance') or tree_name is None: | |
353 | if typ == 'function': | |
354 | # For the description we want a short and a pythonic way. | |
355 | typ = 'def' | |
356 | return typ + ' ' + self._name.get_public_name() | |
357 | ||
358 | definition = tree_name.get_definition(include_setitem=True) or tree_name | |
359 | # Remove the prefix, because that's not what we want for get_code | |
360 | # here. | |
361 | txt = definition.get_code(include_prefix=False) | |
362 | # Delete comments: | |
363 | txt = re.sub(r'#[^\n]+\n', ' ', txt) | |
364 | # Delete multi spaces/newlines | |
365 | txt = re.sub(r'\s+', ' ', txt).strip() | |
366 | return txt | |
367 | ||
368 | @property | |
369 | def full_name(self): | |
370 | """ | |
371 | Dot-separated path of this object. | |
372 | ||
373 | It is in the form of ``<module>[.<submodule>[...]][.<object>]``. | |
374 | It is useful when you want to look up Python manual of the | |
375 | object at hand. | |
376 | ||
377 | Example: | |
378 | ||
379 | >>> from jedi import Script | |
380 | >>> source = ''' | |
381 | ... import os | |
382 | ... os.path.join''' | |
383 | >>> script = Script(source, path='example.py') | |
384 | >>> print(script.infer(3, len('os.path.join'))[0].full_name) | |
385 | os.path.join | |
386 | ||
387 | Notice that it returns ``'os.path.join'`` instead of (for example) | |
388 | ``'posixpath.join'``. This is not correct, since the modules name would | |
389 | be ``<module 'posixpath' ...>```. However most users find the latter | |
390 | more practical. | |
391 | """ | |
392 | if not self._name.is_value_name: | |
393 | return None | |
394 | ||
395 | names = self._name.get_qualified_names(include_module_names=True) | |
396 | if names is None: | |
397 | return None | |
398 | ||
399 | names = list(names) | |
400 | try: | |
401 | names[0] = self._mapping[names[0]] | |
402 | except KeyError: | |
403 | pass | |
404 | ||
405 | return '.'.join(names) | |
406 | ||
407 | def is_stub(self): | |
408 | """ | |
409 | Returns True if the current name is defined in a stub file. | |
410 | """ | |
411 | if not self._name.is_value_name: | |
412 | return False | |
413 | ||
414 | return self._name.get_root_context().is_stub() | |
415 | ||
416 | def is_side_effect(self): | |
417 | """ | |
418 | Checks if a name is defined as ``self.foo = 3``. In case of self, this | |
419 | function would return False, for foo it would return True. | |
420 | """ | |
421 | tree_name = self._name.tree_name | |
422 | if tree_name is None: | |
423 | return False | |
424 | return tree_name.is_definition() and tree_name.parent.type == 'trailer' | |
425 | ||
426 | @debug.increase_indent_cm('goto on name') | |
427 | def goto(self, *, follow_imports=False, follow_builtin_imports=False, | |
428 | only_stubs=False, prefer_stubs=False): | |
429 | ||
430 | """ | |
431 | Like :meth:`.Script.goto` (also supports the same params), but does it | |
432 | for the current name. This is typically useful if you are using | |
433 | something like :meth:`.Script.get_names()`. | |
434 | ||
435 | :param follow_imports: The goto call will follow imports. | |
436 | :param follow_builtin_imports: If follow_imports is True will try to | |
437 | look up names in builtins (i.e. compiled or extension modules). | |
438 | :param only_stubs: Only return stubs for this goto call. | |
439 | :param prefer_stubs: Prefer stubs to Python objects for this goto call. | |
440 | :rtype: list of :class:`Name` | |
441 | """ | |
442 | if not self._name.is_value_name: | |
443 | return [] | |
444 | ||
445 | names = self._name.goto() | |
446 | if follow_imports: | |
447 | names = filter_follow_imports(names, follow_builtin_imports) | |
448 | names = convert_names( | |
449 | names, | |
450 | only_stubs=only_stubs, | |
451 | prefer_stubs=prefer_stubs, | |
452 | ) | |
453 | return [self if n == self._name else Name(self._inference_state, n) | |
454 | for n in names] | |
455 | ||
456 | @debug.increase_indent_cm('infer on name') | |
457 | def infer(self, *, only_stubs=False, prefer_stubs=False): | |
458 | """ | |
459 | Like :meth:`.Script.infer`, it can be useful to understand which type | |
460 | the current name has. | |
461 | ||
462 | Return the actual definitions. I strongly recommend not using it for | |
463 | your completions, because it might slow down |jedi|. If you want to | |
464 | read only a few objects (<=20), it might be useful, especially to get | |
465 | the original docstrings. The basic problem of this function is that it | |
466 | follows all results. This means with 1000 completions (e.g. numpy), | |
467 | it's just very, very slow. | |
468 | ||
469 | :param only_stubs: Only return stubs for this goto call. | |
470 | :param prefer_stubs: Prefer stubs to Python objects for this type | |
471 | inference call. | |
472 | :rtype: list of :class:`Name` | |
473 | """ | |
474 | assert not (only_stubs and prefer_stubs) | |
475 | ||
476 | if not self._name.is_value_name: | |
477 | return [] | |
478 | ||
479 | # First we need to make sure that we have stub names (if possible) that | |
480 | # we can follow. If we don't do that, we can end up with the inferred | |
481 | # results of Python objects instead of stubs. | |
482 | names = convert_names([self._name], prefer_stubs=True) | |
483 | values = convert_values( | |
484 | ValueSet.from_sets(n.infer() for n in names), | |
485 | only_stubs=only_stubs, | |
486 | prefer_stubs=prefer_stubs, | |
487 | ) | |
488 | resulting_names = [c.name for c in values] | |
489 | return [self if n == self._name else Name(self._inference_state, n) | |
490 | for n in resulting_names] | |
491 | ||
492 | def parent(self): | |
493 | """ | |
494 | Returns the parent scope of this identifier. | |
495 | ||
496 | :rtype: Name | |
497 | """ | |
498 | if not self._name.is_value_name: | |
499 | return None | |
500 | ||
501 | if self.type in ('function', 'class', 'param') and self._name.tree_name is not None: | |
502 | # Since the parent_context doesn't really match what the user | |
503 | # thinks of that the parent is here, we do these cases separately. | |
504 | # The reason for this is the following: | |
505 | # - class: Nested classes parent_context is always the | |
506 | # parent_context of the most outer one. | |
507 | # - function: Functions in classes have the module as | |
508 | # parent_context. | |
509 | # - param: The parent_context of a param is not its function but | |
510 | # e.g. the outer class or module. | |
511 | cls_or_func_node = self._name.tree_name.get_definition() | |
512 | parent = search_ancestor(cls_or_func_node, 'funcdef', 'classdef', 'file_input') | |
513 | context = self._get_module_context().create_value(parent).as_context() | |
514 | else: | |
515 | context = self._name.parent_context | |
516 | ||
517 | if context is None: | |
518 | return None | |
519 | while context.name is None: | |
520 | # Happens for comprehension contexts | |
521 | context = context.parent_context | |
522 | ||
523 | return Name(self._inference_state, context.name) | |
524 | ||
525 | def __repr__(self): | |
526 | return "<%s %sname=%r, description=%r>" % ( | |
527 | self.__class__.__name__, | |
528 | 'full_' if self.full_name else '', | |
529 | self.full_name or self.name, | |
530 | self.description, | |
531 | ) | |
532 | ||
533 | def get_line_code(self, before=0, after=0): | |
534 | """ | |
535 | Returns the line of code where this object was defined. | |
536 | ||
537 | :param before: Add n lines before the current line to the output. | |
538 | :param after: Add n lines after the current line to the output. | |
539 | ||
540 | :return str: Returns the line(s) of code or an empty string if it's a | |
541 | builtin. | |
542 | """ | |
543 | if not self._name.is_value_name: | |
544 | return '' | |
545 | ||
546 | lines = self._name.get_root_context().code_lines | |
547 | if lines is None: | |
548 | # Probably a builtin module, just ignore in that case. | |
549 | return '' | |
550 | ||
551 | index = self._name.start_pos[0] - 1 | |
552 | start_index = max(index - before, 0) | |
553 | return ''.join(lines[start_index:index + after + 1]) | |
554 | ||
555 | def _get_signatures(self, for_docstring=False): | |
556 | if self._name.api_type == 'property': | |
557 | return [] | |
558 | if for_docstring and self._name.api_type == 'statement' and not self.is_stub(): | |
559 | # For docstrings we don't resolve signatures if they are simple | |
560 | # statements and not stubs. This is a speed optimization. | |
561 | return [] | |
562 | ||
563 | if isinstance(self._name, MixedName): | |
564 | # While this would eventually happen anyway, it's basically just a | |
565 | # shortcut to not infer anything tree related, because it's really | |
566 | # not necessary. | |
567 | return self._name.infer_compiled_value().get_signatures() | |
568 | ||
569 | names = convert_names([self._name], prefer_stubs=True) | |
570 | return [sig for name in names for sig in name.infer().get_signatures()] | |
571 | ||
572 | def get_signatures(self): | |
573 | """ | |
574 | Returns all potential signatures for a function or a class. Multiple | |
575 | signatures are typical if you use Python stubs with ``@overload``. | |
576 | ||
577 | :rtype: list of :class:`BaseSignature` | |
578 | """ | |
579 | return [ | |
580 | BaseSignature(self._inference_state, s) | |
581 | for s in self._get_signatures() | |
582 | ] | |
583 | ||
584 | def execute(self): | |
585 | """ | |
586 | Uses type inference to "execute" this identifier and returns the | |
587 | executed objects. | |
588 | ||
589 | :rtype: list of :class:`Name` | |
590 | """ | |
591 | return _values_to_definitions(self._name.infer().execute_with_values()) | |
592 | ||
593 | def get_type_hint(self): | |
594 | """ | |
595 | Returns type hints like ``Iterable[int]`` or ``Union[int, str]``. | |
596 | ||
597 | This method might be quite slow, especially for functions. The problem | |
598 | is finding executions for those functions to return something like | |
599 | ``Callable[[int, str], str]``. | |
600 | ||
601 | :rtype: str | |
602 | """ | |
603 | return self._name.infer().get_type_hint() | |
604 | ||
605 | ||
606 | class Completion(BaseName): | |
607 | """ | |
608 | ``Completion`` objects are returned from :meth:`.Script.complete`. They | |
609 | provide additional information about a completion. | |
610 | """ | |
611 | def __init__(self, inference_state, name, stack, like_name_length, | |
612 | is_fuzzy, cached_name=None): | |
613 | super().__init__(inference_state, name) | |
614 | ||
615 | self._like_name_length = like_name_length | |
616 | self._stack = stack | |
617 | self._is_fuzzy = is_fuzzy | |
618 | self._cached_name = cached_name | |
619 | ||
620 | # Completion objects with the same Completion name (which means | |
621 | # duplicate items in the completion) | |
622 | self._same_name_completions = [] | |
623 | ||
624 | def _complete(self, like_name): | |
625 | append = '' | |
626 | if settings.add_bracket_after_function \ | |
627 | and self.type == 'function': | |
628 | append = '(' | |
629 | ||
630 | name = self._name.get_public_name() | |
631 | if like_name: | |
632 | name = name[self._like_name_length:] | |
633 | return name + append | |
634 | ||
635 | @property | |
636 | def complete(self): | |
637 | """ | |
638 | Only works with non-fuzzy completions. Returns None if fuzzy | |
639 | completions are used. | |
640 | ||
641 | Return the rest of the word, e.g. completing ``isinstance``:: | |
642 | ||
643 | isinstan# <-- Cursor is here | |
644 | ||
645 | would return the string 'ce'. It also adds additional stuff, depending | |
646 | on your ``settings.py``. | |
647 | ||
648 | Assuming the following function definition:: | |
649 | ||
650 | def foo(param=0): | |
651 | pass | |
652 | ||
653 | completing ``foo(par`` would give a ``Completion`` which ``complete`` | |
654 | would be ``am=``. | |
655 | """ | |
656 | if self._is_fuzzy: | |
657 | return None | |
658 | return self._complete(True) | |
659 | ||
660 | @property | |
661 | def name_with_symbols(self): | |
662 | """ | |
663 | Similar to :attr:`.name`, but like :attr:`.name` returns also the | |
664 | symbols, for example assuming the following function definition:: | |
665 | ||
666 | def foo(param=0): | |
667 | pass | |
668 | ||
669 | completing ``foo(`` would give a ``Completion`` which | |
670 | ``name_with_symbols`` would be "param=". | |
671 | ||
672 | """ | |
673 | return self._complete(False) | |
674 | ||
675 | def docstring(self, raw=False, fast=True): | |
676 | """ | |
677 | Documented under :meth:`BaseName.docstring`. | |
678 | """ | |
679 | if self._like_name_length >= 3: | |
680 | # In this case we can just resolve the like name, because we | |
681 | # wouldn't load like > 100 Python modules anymore. | |
682 | fast = False | |
683 | ||
684 | return super().docstring(raw=raw, fast=fast) | |
685 | ||
686 | def _get_docstring(self): | |
687 | if self._cached_name is not None: | |
688 | return completion_cache.get_docstring( | |
689 | self._cached_name, | |
690 | self._name.get_public_name(), | |
691 | lambda: self._get_cache() | |
692 | ) | |
693 | return super()._get_docstring() | |
694 | ||
695 | def _get_docstring_signature(self): | |
696 | if self._cached_name is not None: | |
697 | return completion_cache.get_docstring_signature( | |
698 | self._cached_name, | |
699 | self._name.get_public_name(), | |
700 | lambda: self._get_cache() | |
701 | ) | |
702 | return super()._get_docstring_signature() | |
703 | ||
704 | def _get_cache(self): | |
705 | return ( | |
706 | super().type, | |
707 | super()._get_docstring_signature(), | |
708 | super()._get_docstring(), | |
709 | ) | |
710 | ||
711 | @property | |
712 | def type(self): | |
713 | """ | |
714 | Documented under :meth:`BaseName.type`. | |
715 | """ | |
716 | # Purely a speed optimization. | |
717 | if self._cached_name is not None: | |
718 | return completion_cache.get_type( | |
719 | self._cached_name, | |
720 | self._name.get_public_name(), | |
721 | lambda: self._get_cache() | |
722 | ) | |
723 | ||
724 | return super().type | |
725 | ||
726 | def get_completion_prefix_length(self): | |
727 | """ | |
728 | Returns the length of the prefix being completed. | |
729 | For example, completing ``isinstance``:: | |
730 | ||
731 | isinstan# <-- Cursor is here | |
732 | ||
733 | would return 8, because len('isinstan') == 8. | |
734 | ||
735 | Assuming the following function definition:: | |
736 | ||
737 | def foo(param=0): | |
738 | pass | |
739 | ||
740 | completing ``foo(par`` would return 3. | |
741 | """ | |
742 | return self._like_name_length | |
743 | ||
744 | def __repr__(self): | |
745 | return '<%s: %s>' % (type(self).__name__, self._name.get_public_name()) | |
746 | ||
747 | ||
748 | class Name(BaseName): | |
749 | """ | |
750 | *Name* objects are returned from many different APIs including | |
751 | :meth:`.Script.goto` or :meth:`.Script.infer`. | |
752 | """ | |
753 | def __init__(self, inference_state, definition): | |
754 | super().__init__(inference_state, definition) | |
755 | ||
756 | @memoize_method | |
757 | def defined_names(self): | |
758 | """ | |
759 | List sub-definitions (e.g., methods in class). | |
760 | ||
761 | :rtype: list of :class:`Name` | |
762 | """ | |
763 | defs = self._name.infer() | |
764 | return sorted( | |
765 | unite(defined_names(self._inference_state, d) for d in defs), | |
766 | key=lambda s: s._name.start_pos or (0, 0) | |
767 | ) | |
768 | ||
769 | def is_definition(self): | |
770 | """ | |
771 | Returns True, if defined as a name in a statement, function or class. | |
772 | Returns False, if it's a reference to such a definition. | |
773 | """ | |
774 | if self._name.tree_name is None: | |
775 | return True | |
776 | else: | |
777 | return self._name.tree_name.is_definition() | |
778 | ||
779 | def __eq__(self, other): | |
780 | return self._name.start_pos == other._name.start_pos \ | |
781 | and self.module_path == other.module_path \ | |
782 | and self.name == other.name \ | |
783 | and self._inference_state == other._inference_state | |
784 | ||
785 | def __ne__(self, other): | |
786 | return not self.__eq__(other) | |
787 | ||
788 | def __hash__(self): | |
789 | return hash((self._name.start_pos, self.module_path, self.name, self._inference_state)) | |
790 | ||
791 | ||
792 | class BaseSignature(Name): | |
793 | """ | |
794 | These signatures are returned by :meth:`BaseName.get_signatures` | |
795 | calls. | |
796 | """ | |
797 | def __init__(self, inference_state, signature): | |
798 | super().__init__(inference_state, signature.name) | |
799 | self._signature = signature | |
800 | ||
801 | @property | |
802 | def params(self): | |
803 | """ | |
804 | Returns definitions for all parameters that a signature defines. | |
805 | This includes stuff like ``*args`` and ``**kwargs``. | |
806 | ||
807 | :rtype: list of :class:`.ParamName` | |
808 | """ | |
809 | return [ParamName(self._inference_state, n) | |
810 | for n in self._signature.get_param_names(resolve_stars=True)] | |
811 | ||
812 | def to_string(self): | |
813 | """ | |
814 | Returns a text representation of the signature. This could for example | |
815 | look like ``foo(bar, baz: int, **kwargs)``. | |
816 | ||
817 | :rtype: str | |
818 | """ | |
819 | return self._signature.to_string() | |
820 | ||
821 | ||
822 | class Signature(BaseSignature): | |
823 | """ | |
824 | A full signature object is the return value of | |
825 | :meth:`.Script.get_signatures`. | |
826 | """ | |
827 | def __init__(self, inference_state, signature, call_details): | |
828 | super().__init__(inference_state, signature) | |
829 | self._call_details = call_details | |
830 | self._signature = signature | |
831 | ||
832 | @property | |
833 | def index(self): | |
834 | """ | |
835 | Returns the param index of the current cursor position. | |
836 | Returns None if the index cannot be found in the curent call. | |
837 | ||
838 | :rtype: int | |
839 | """ | |
840 | return self._call_details.calculate_index( | |
841 | self._signature.get_param_names(resolve_stars=True) | |
842 | ) | |
843 | ||
844 | @property | |
845 | def bracket_start(self): | |
846 | """ | |
847 | Returns a line/column tuple of the bracket that is responsible for the | |
848 | last function call. The first line is 1 and the first column 0. | |
849 | ||
850 | :rtype: int, int | |
851 | """ | |
852 | return self._call_details.bracket_leaf.start_pos | |
853 | ||
854 | def __repr__(self): | |
855 | return '<%s: index=%r %s>' % ( | |
856 | type(self).__name__, | |
857 | self.index, | |
858 | self._signature.to_string(), | |
859 | ) | |
860 | ||
861 | ||
862 | class ParamName(Name): | |
863 | def infer_default(self): | |
864 | """ | |
865 | Returns default values like the ``1`` of ``def foo(x=1):``. | |
866 | ||
867 | :rtype: list of :class:`.Name` | |
868 | """ | |
869 | return _values_to_definitions(self._name.infer_default()) | |
870 | ||
871 | def infer_annotation(self, **kwargs): | |
872 | """ | |
873 | :param execute_annotation: Default True; If False, values are not | |
874 | executed and classes are returned instead of instances. | |
875 | :rtype: list of :class:`.Name` | |
876 | """ | |
877 | return _values_to_definitions(self._name.infer_annotation(ignore_stars=True, **kwargs)) | |
878 | ||
879 | def to_string(self): | |
880 | """ | |
881 | Returns a simple representation of a param, like | |
882 | ``f: Callable[..., Any]``. | |
883 | ||
884 | :rtype: str | |
885 | """ | |
886 | return self._name.to_string() | |
887 | ||
888 | @property | |
889 | def kind(self): | |
890 | """ | |
891 | Returns an enum instance of :mod:`inspect`'s ``Parameter`` enum. | |
892 | ||
893 | :rtype: :py:attr:`inspect.Parameter.kind` | |
894 | """ | |
895 | return self._name.get_kind() |