My dotfiles
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

710 line
26 KiB

  1. import os
  2. import os.path
  3. import io
  4. import re
  5. import sys
  6. import json
  7. import traceback
  8. import platform
  9. jediPreview = False
  10. class RedirectStdout(object):
  11. def __init__(self, new_stdout=None):
  12. """If stdout is None, redirect to /dev/null"""
  13. self._new_stdout = new_stdout or open(os.devnull, "w")
  14. def __enter__(self):
  15. sys.stdout.flush()
  16. self.oldstdout_fno = os.dup(sys.stdout.fileno())
  17. os.dup2(self._new_stdout.fileno(), 1)
  18. def __exit__(self, exc_type, exc_value, traceback):
  19. self._new_stdout.flush()
  20. os.dup2(self.oldstdout_fno, 1)
  21. os.close(self.oldstdout_fno)
  22. class JediCompletion(object):
  23. basic_types = {
  24. "module": "import",
  25. "instance": "variable",
  26. "statement": "value",
  27. "param": "variable",
  28. }
  29. def __init__(self):
  30. self.default_sys_path = sys.path
  31. self.environment = jedi.api.environment.create_environment(
  32. sys.executable, safe=False
  33. )
  34. self._input = io.open(sys.stdin.fileno(), encoding="utf-8")
  35. if (os.path.sep == "/") and (platform.uname()[2].find("Microsoft") > -1):
  36. # WSL; does not support UNC paths
  37. self.drive_mount = "/mnt/"
  38. elif sys.platform == "cygwin":
  39. # cygwin
  40. self.drive_mount = "/cygdrive/"
  41. else:
  42. # Do no normalization, e.g. Windows build of Python.
  43. # Could add additional test: ((os.path.sep == '/') and os.path.isdir('/mnt/c'))
  44. # However, this may have more false positives trying to identify Windows/*nix hybrids
  45. self.drive_mount = ""
  46. def _get_definition_type(self, definition):
  47. # if definition.type not in ['import', 'keyword'] and is_built_in():
  48. # return 'builtin'
  49. try:
  50. if definition.type in ["statement"] and definition.name.isupper():
  51. return "constant"
  52. return self.basic_types.get(definition.type, definition.type)
  53. except Exception:
  54. return "builtin"
  55. def _additional_info(self, completion):
  56. """Provide additional information about the completion object."""
  57. if not hasattr(completion, "_definition") or completion._definition is None:
  58. return ""
  59. if completion.type == "statement":
  60. nodes_to_display = ["InstanceElement", "String", "Node", "Lambda", "Number"]
  61. return "".join(
  62. c.get_code()
  63. for c in completion._definition.children
  64. if type(c).__name__ in nodes_to_display
  65. ).replace("\n", "")
  66. return ""
  67. @classmethod
  68. def _get_top_level_module(cls, path):
  69. """Recursively walk through directories looking for top level module.
  70. Jedi will use current filepath to look for another modules at same
  71. path, but it will not be able to see modules **above**, so our goal
  72. is to find the higher python module available from filepath.
  73. """
  74. _path, _ = os.path.split(path)
  75. if os.path.isfile(os.path.join(_path, "__init__.py")):
  76. return cls._get_top_level_module(_path)
  77. return path
  78. def _generate_signature(self, completion):
  79. """Generate signature with function arguments.
  80. """
  81. if completion.type in ["module"] or not hasattr(completion, "params"):
  82. return ""
  83. return "%s(%s)" % (
  84. completion.name,
  85. ", ".join(p.description[6:] for p in completion.params if p),
  86. )
  87. def _get_call_signatures(self, script, line, column):
  88. """Extract call signatures from jedi.api.Script object in failsafe way.
  89. Returns:
  90. Tuple with original signature object, name and value.
  91. """
  92. _signatures = []
  93. try:
  94. call_signatures = script.get_signatures(line, column)
  95. except KeyError:
  96. call_signatures = []
  97. except:
  98. call_signatures = []
  99. for signature in call_signatures:
  100. for pos, param in enumerate(signature.params):
  101. if not param.name:
  102. continue
  103. name = self._get_param_name(param)
  104. if param.name == "self" and pos == 0:
  105. continue
  106. if name.startswith("*"):
  107. continue
  108. value = self._get_param_value(param)
  109. _signatures.append((signature, name, value))
  110. return _signatures
  111. def _get_param_name(self, p):
  112. if p.name.startswith("param "):
  113. return p.name[6:] # drop leading 'param '
  114. return p.name
  115. def _get_param_value(self, p):
  116. pair = p.description.split("=")
  117. if len(pair) > 1:
  118. return pair[1]
  119. return None
  120. def _get_call_signatures_with_args(self, script, line, column):
  121. """Extract call signatures from jedi.api.Script object in failsafe way.
  122. Returns:
  123. Array with dictionary
  124. """
  125. _signatures = []
  126. try:
  127. call_signatures = script.get_signatures(line, column)
  128. except KeyError:
  129. call_signatures = []
  130. for signature in call_signatures:
  131. sig = {
  132. "name": "",
  133. "description": "",
  134. "docstring": "",
  135. "paramindex": 0,
  136. "params": [],
  137. "bracketstart": [],
  138. }
  139. sig["description"] = signature.description
  140. try:
  141. sig["docstring"] = signature.docstring()
  142. sig["raw_docstring"] = signature.docstring(raw=True)
  143. except Exception:
  144. sig["docstring"] = ""
  145. sig["raw_docstring"] = ""
  146. sig["name"] = signature.name
  147. sig["paramindex"] = signature.index
  148. sig["bracketstart"].append(signature.index)
  149. _signatures.append(sig)
  150. for pos, param in enumerate(signature.params):
  151. if not param.name:
  152. continue
  153. name = self._get_param_name(param)
  154. if param.name == "self" and pos == 0:
  155. continue
  156. value = self._get_param_value(param)
  157. paramDocstring = ""
  158. try:
  159. paramDocstring = param.docstring()
  160. except Exception:
  161. paramDocstring = ""
  162. sig["params"].append(
  163. {
  164. "name": name,
  165. "value": value,
  166. "docstring": paramDocstring,
  167. "description": param.description,
  168. }
  169. )
  170. return _signatures
  171. def _serialize_completions(self, script, line, column, identifier=None, prefix=""):
  172. """Serialize response to be read from VSCode.
  173. Args:
  174. script: Instance of jedi.api.Script object.
  175. identifier: Unique completion identifier to pass back to VSCode.
  176. prefix: String with prefix to filter function arguments.
  177. Used only when fuzzy matcher turned off.
  178. Returns:
  179. Serialized string to send to VSCode.
  180. """
  181. _completions = []
  182. for signature, name, value in self._get_call_signatures(script, line, column):
  183. if not self.fuzzy_matcher and not name.lower().startswith(prefix.lower()):
  184. continue
  185. _completion = {
  186. "type": "property",
  187. "raw_type": "",
  188. "rightLabel": self._additional_info(signature),
  189. }
  190. _completion["description"] = ""
  191. _completion["raw_docstring"] = ""
  192. # we pass 'text' here only for fuzzy matcher
  193. if value:
  194. _completion["snippet"] = "%s=${1:%s}$0" % (name, value)
  195. _completion["text"] = "%s=" % (name)
  196. else:
  197. _completion["snippet"] = "%s=$1$0" % name
  198. _completion["text"] = name
  199. _completion["displayText"] = name
  200. _completions.append(_completion)
  201. try:
  202. completions = script.complete(line, column)
  203. except KeyError:
  204. completions = []
  205. except:
  206. completions = []
  207. for completion in completions:
  208. try:
  209. _completion = {
  210. "text": completion.name,
  211. "type": self._get_definition_type(completion),
  212. "raw_type": completion.type,
  213. "rightLabel": self._additional_info(completion),
  214. }
  215. except Exception:
  216. continue
  217. for c in _completions:
  218. if c["text"] == _completion["text"]:
  219. c["type"] = _completion["type"]
  220. c["raw_type"] = _completion["raw_type"]
  221. if any(
  222. [c["text"].split("=")[0] == _completion["text"] for c in _completions]
  223. ):
  224. # ignore function arguments we already have
  225. continue
  226. _completions.append(_completion)
  227. return json.dumps({"id": identifier, "results": _completions})
  228. def _serialize_methods(self, script, line, column, identifier=None, prefix=""):
  229. _methods = []
  230. try:
  231. completions = script.complete(line, column)
  232. except KeyError:
  233. return []
  234. for completion in completions:
  235. if completion.name == "__autocomplete_python":
  236. instance = completion.parent().name
  237. break
  238. else:
  239. instance = "self.__class__"
  240. for completion in completions:
  241. params = []
  242. if hasattr(completion, "params"):
  243. params = [p.description for p in completion.params if p]
  244. if completion.parent().type == "class":
  245. _methods.append(
  246. {
  247. "parent": completion.parent().name,
  248. "instance": instance,
  249. "name": completion.name,
  250. "params": params,
  251. "moduleName": completion.module_name,
  252. "fileName": completion.module_path,
  253. "line": completion.line,
  254. "column": completion.column,
  255. }
  256. )
  257. return json.dumps({"id": identifier, "results": _methods})
  258. def _serialize_arguments(self, script, line, column, identifier=None):
  259. """Serialize response to be read from VSCode.
  260. Args:
  261. script: Instance of jedi.api.Script object.
  262. identifier: Unique completion identifier to pass back to VSCode.
  263. Returns:
  264. Serialized string to send to VSCode.
  265. """
  266. return json.dumps(
  267. {
  268. "id": identifier,
  269. "results": self._get_call_signatures_with_args(script, line, column),
  270. }
  271. )
  272. def _top_definition(self, definition):
  273. for d in definition.goto_assignments():
  274. if d == definition:
  275. continue
  276. if d.type == "import":
  277. return self._top_definition(d)
  278. else:
  279. return d
  280. return definition
  281. def _extract_range_jedi_0_11_1(self, definition):
  282. from parso.utils import split_lines
  283. # get the scope range
  284. try:
  285. if definition.type in ["class", "function"]:
  286. tree_name = definition._name.tree_name
  287. scope = tree_name.get_definition()
  288. start_line = scope.start_pos[0] - 1
  289. start_column = scope.start_pos[1]
  290. # get the lines
  291. code = scope.get_code(include_prefix=False)
  292. lines = split_lines(code)
  293. # trim the lines
  294. lines = "\n".join(lines).rstrip().split("\n")
  295. end_line = start_line + len(lines) - 1
  296. end_column = len(lines[-1]) - 1
  297. else:
  298. symbol = definition._name.tree_name
  299. start_line = symbol.start_pos[0] - 1
  300. start_column = symbol.start_pos[1]
  301. end_line = symbol.end_pos[0] - 1
  302. end_column = symbol.end_pos[1]
  303. return {
  304. "start_line": start_line,
  305. "start_column": start_column,
  306. "end_line": end_line,
  307. "end_column": end_column,
  308. }
  309. except Exception as e:
  310. return {
  311. "start_line": definition.line - 1,
  312. "start_column": definition.column,
  313. "end_line": definition.line - 1,
  314. "end_column": definition.column,
  315. }
  316. def _extract_range(self, definition):
  317. """Provides the definition range of a given definition
  318. For regular symbols it returns the start and end location of the
  319. characters making up the symbol.
  320. For scoped containers it will return the entire definition of the
  321. scope.
  322. The scope that jedi provides ends with the first character of the next
  323. scope so it's not ideal. For vscode we need the scope to end with the
  324. last character of actual code. That's why we extract the lines that
  325. make up our scope and trim the trailing whitespace.
  326. """
  327. return self._extract_range_jedi_0_11_1(definition)
  328. def _get_definitionsx(self, definitions, identifier=None, ignoreNoModulePath=False):
  329. """Serialize response to be read from VSCode.
  330. Args:
  331. definitions: List of jedi.api.classes.Definition objects.
  332. identifier: Unique completion identifier to pass back to VSCode.
  333. Returns:
  334. Serialized string to send to VSCode.
  335. """
  336. _definitions = []
  337. for definition in definitions:
  338. try:
  339. if definition.type == "import":
  340. definition = self._top_definition(definition)
  341. definitionRange = {
  342. "start_line": 0,
  343. "start_column": 0,
  344. "end_line": 0,
  345. "end_column": 0,
  346. }
  347. module_path = ""
  348. if hasattr(definition, "module_path") and definition.module_path:
  349. module_path = definition.module_path
  350. definitionRange = self._extract_range(definition)
  351. else:
  352. if not ignoreNoModulePath:
  353. continue
  354. try:
  355. parent = definition.parent()
  356. container = parent.name if parent.type != "module" else ""
  357. except Exception:
  358. container = ""
  359. try:
  360. docstring = definition.docstring()
  361. rawdocstring = definition.docstring(raw=True)
  362. except Exception:
  363. docstring = ""
  364. rawdocstring = ""
  365. _definition = {
  366. "text": definition.name,
  367. "type": self._get_definition_type(definition),
  368. "raw_type": definition.type,
  369. "fileName": module_path,
  370. "container": container,
  371. "range": definitionRange,
  372. "description": definition.description,
  373. "docstring": docstring,
  374. "raw_docstring": rawdocstring,
  375. "signature": self._generate_signature(definition),
  376. }
  377. _definitions.append(_definition)
  378. except Exception as e:
  379. pass
  380. return _definitions
  381. def _serialize_definitions(self, definitions, identifier=None):
  382. """Serialize response to be read from VSCode.
  383. Args:
  384. definitions: List of jedi.api.classes.Definition objects.
  385. identifier: Unique completion identifier to pass back to VSCode.
  386. Returns:
  387. Serialized string to send to VSCode.
  388. """
  389. _definitions = []
  390. for definition in definitions:
  391. try:
  392. if definition.module_path:
  393. if definition.type == "import":
  394. definition = self._top_definition(definition)
  395. if not definition.module_path:
  396. continue
  397. try:
  398. parent = definition.parent()
  399. container = parent.name if parent.type != "module" else ""
  400. except Exception:
  401. container = ""
  402. try:
  403. docstring = definition.docstring()
  404. rawdocstring = definition.docstring(raw=True)
  405. except Exception:
  406. docstring = ""
  407. rawdocstring = ""
  408. _definition = {
  409. "text": definition.name,
  410. "type": self._get_definition_type(definition),
  411. "raw_type": definition.type,
  412. "fileName": definition.module_path,
  413. "container": container,
  414. "range": self._extract_range(definition),
  415. "description": definition.description,
  416. "docstring": docstring,
  417. "raw_docstring": rawdocstring,
  418. }
  419. _definitions.append(_definition)
  420. except Exception as e:
  421. pass
  422. return json.dumps({"id": identifier, "results": _definitions})
  423. def _serialize_tooltip(self, definitions, identifier=None):
  424. _definitions = []
  425. for definition in definitions:
  426. signature = definition.name
  427. description = None
  428. if definition.type in ["class", "function"]:
  429. signature = self._generate_signature(definition)
  430. try:
  431. description = definition.docstring(raw=True).strip()
  432. except Exception:
  433. description = ""
  434. if not description and not hasattr(definition, "get_line_code"):
  435. # jedi returns an empty string for compiled objects
  436. description = definition.docstring().strip()
  437. if definition.type == "module":
  438. signature = definition.full_name
  439. try:
  440. description = definition.docstring(raw=True).strip()
  441. except Exception:
  442. description = ""
  443. if not description and hasattr(definition, "get_line_code"):
  444. # jedi returns an empty string for compiled objects
  445. description = definition.docstring().strip()
  446. _definition = {
  447. "type": self._get_definition_type(definition),
  448. "text": definition.name,
  449. "description": description,
  450. "docstring": description,
  451. "signature": signature,
  452. }
  453. _definitions.append(_definition)
  454. return json.dumps({"id": identifier, "results": _definitions})
  455. def _serialize_usages(self, usages, identifier=None):
  456. _usages = []
  457. for usage in usages:
  458. _usages.append(
  459. {
  460. "name": usage.name,
  461. "moduleName": usage.module_name,
  462. "fileName": usage.module_path,
  463. "line": usage.line,
  464. "column": usage.column,
  465. }
  466. )
  467. return json.dumps({"id": identifier, "results": _usages})
  468. def _deserialize(self, request):
  469. """Deserialize request from VSCode.
  470. Args:
  471. request: String with raw request from VSCode.
  472. Returns:
  473. Python dictionary with request data.
  474. """
  475. return json.loads(request)
  476. def _set_request_config(self, config):
  477. """Sets config values for current request.
  478. This includes sys.path modifications which is getting restored to
  479. default value on each request so each project should be isolated
  480. from each other.
  481. Args:
  482. config: Dictionary with config values.
  483. """
  484. sys.path = self.default_sys_path
  485. self.use_snippets = config.get("useSnippets")
  486. self.show_doc_strings = config.get("showDescriptions", True)
  487. self.fuzzy_matcher = config.get("fuzzyMatcher", False)
  488. jedi.settings.case_insensitive_completion = config.get(
  489. "caseInsensitiveCompletion", True
  490. )
  491. for path in config.get("extraPaths", []):
  492. if path and path not in sys.path:
  493. sys.path.insert(0, path)
  494. def _normalize_request_path(self, request):
  495. """Normalize any Windows paths received by a *nix build of
  496. Python. Does not alter the reverse os.path.sep=='\\',
  497. i.e. *nix paths received by a Windows build of Python.
  498. """
  499. if "path" in request:
  500. if not self.drive_mount:
  501. return
  502. newPath = request["path"].replace("\\", "/")
  503. if newPath[0:1] == "/":
  504. # is absolute path with no drive letter
  505. request["path"] = newPath
  506. elif newPath[1:2] == ":":
  507. # is path with drive letter, only absolute can be mapped
  508. request["path"] = self.drive_mount + newPath[0:1].lower() + newPath[2:]
  509. else:
  510. # is relative path
  511. request["path"] = newPath
  512. def _process_request(self, request):
  513. """Accept serialized request from VSCode and write response.
  514. """
  515. request = self._deserialize(request)
  516. self._set_request_config(request.get("config", {}))
  517. self._normalize_request_path(request)
  518. path = self._get_top_level_module(request.get("path", ""))
  519. if len(path) > 0 and path not in sys.path:
  520. sys.path.insert(0, path)
  521. lookup = request.get("lookup", "completions")
  522. if lookup == "names":
  523. return self._serialize_definitions(
  524. jedi.Script(
  525. code=request.get("source", None),
  526. path=request.get("path", ""),
  527. project=jedi.get_default_project(os.path.dirname(path)),
  528. environment=self.environment,
  529. ).get_names(all_scopes=True),
  530. request["id"],
  531. )
  532. line = request["line"] + 1
  533. column = request["column"]
  534. script = jedi.Script(
  535. code=request.get("source", None),
  536. path=request.get("path", ""),
  537. project=jedi.get_default_project(os.path.dirname(path)),
  538. environment=self.environment,
  539. )
  540. if lookup == "definitions":
  541. defs = self._get_definitionsx(
  542. script.goto(line, column, follow_imports=True), request["id"]
  543. )
  544. return json.dumps({"id": request["id"], "results": defs})
  545. if lookup == "tooltip":
  546. if jediPreview:
  547. defs = []
  548. try:
  549. defs = self._get_definitionsx(
  550. script.infer(line, column), request["id"], True
  551. )
  552. except:
  553. pass
  554. try:
  555. if len(defs) == 0:
  556. defs = self._get_definitionsx(
  557. script.goto(line, column), request["id"], True
  558. )
  559. except:
  560. pass
  561. return json.dumps({"id": request["id"], "results": defs})
  562. else:
  563. try:
  564. return self._serialize_tooltip(
  565. script.infer(line, column), request["id"]
  566. )
  567. except:
  568. return json.dumps({"id": request["id"], "results": []})
  569. elif lookup == "arguments":
  570. return self._serialize_arguments(script, line, column, request["id"])
  571. elif lookup == "usages":
  572. return self._serialize_usages(
  573. script.get_references(line, column), request["id"]
  574. )
  575. elif lookup == "methods":
  576. return self._serialize_methods(
  577. script, line, column, request["id"], request.get("prefix", "")
  578. )
  579. else:
  580. return self._serialize_completions(
  581. script, line, column, request["id"], request.get("prefix", "")
  582. )
  583. def _write_response(self, response):
  584. sys.stdout.write(response + "\n")
  585. sys.stdout.flush()
  586. def watch(self):
  587. while True:
  588. try:
  589. rq = self._input.readline()
  590. if len(rq) == 0:
  591. # Reached EOF - indication our parent process is gone.
  592. sys.stderr.write(
  593. "Received EOF from the standard input,exiting" + "\n"
  594. )
  595. sys.stderr.flush()
  596. return
  597. with RedirectStdout():
  598. response = self._process_request(rq)
  599. self._write_response(response)
  600. except Exception:
  601. sys.stderr.write(traceback.format_exc() + "\n")
  602. sys.stderr.flush()
  603. if __name__ == "__main__":
  604. cachePrefix = "v"
  605. modulesToLoad = ""
  606. if len(sys.argv) > 2 and sys.argv[1] == "custom":
  607. jediPath = sys.argv[2]
  608. jediPreview = True
  609. cachePrefix = "custom_v"
  610. if len(sys.argv) > 3:
  611. modulesToLoad = sys.argv[3]
  612. else:
  613. # release
  614. jediPath = os.path.join(os.path.dirname(__file__), "lib", "python")
  615. if len(sys.argv) > 1:
  616. modulesToLoad = sys.argv[1]
  617. sys.path.insert(0, jediPath)
  618. import jedi
  619. digits = jedi.__version__.split(".")
  620. if int(digits[0]) == 0 and int(digits[1]) < 17:
  621. raise RuntimeError("Jedi version %s too old, requires >= 0.17.0" % (jedi.__version__))
  622. else:
  623. if jediPreview:
  624. jedi.settings.cache_directory = os.path.join(
  625. jedi.settings.cache_directory,
  626. cachePrefix + jedi.__version__.replace(".", ""),
  627. )
  628. # remove jedi from path after we import it so it will not be completed
  629. sys.path.pop(0)
  630. if len(modulesToLoad) > 0:
  631. jedi.preload_module(*modulesToLoad.split(","))
  632. JediCompletion().watch()