codis 1.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- codis-1.1.1.dist-info/METADATA +194 -0
- codis-1.1.1.dist-info/RECORD +329 -0
- codis-1.1.1.dist-info/WHEEL +5 -0
- codis-1.1.1.dist-info/entry_points.txt +5 -0
- codis-1.1.1.dist-info/licenses/LICENSE +21 -0
- codis-1.1.1.dist-info/top_level.txt +2 -0
- run.py +190 -0
- src/__init__.py +1 -0
- src/__main__.py +81 -0
- src/_app_build.py +1507 -0
- src/_app_editor.py +1274 -0
- src/_app_kui.py +825 -0
- src/_app_lsp.py +625 -0
- src/_app_recovery.py +189 -0
- src/_app_settings.py +1385 -0
- src/_app_tools.py +2471 -0
- src/_app_webpreview.py +126 -0
- src/_font_safety.py +127 -0
- src/_shells.py +172 -0
- src/app.py +1488 -0
- src/chat/__init__.py +1 -0
- src/chat/adapters/__init__.py +33 -0
- src/chat/adapters/base.py +209 -0
- src/chat/adapters/discord.py +190 -0
- src/chat/adapters/http.py +78 -0
- src/chat/adapters/irc.py +360 -0
- src/chat/adapters/matrix.py +219 -0
- src/chat/adapters/mattermost.py +178 -0
- src/chat/adapters/mqtt.py +165 -0
- src/chat/adapters/slack.py +204 -0
- src/chat/adapters/telegram.py +117 -0
- src/chat/adapters/ws.py +154 -0
- src/chat/adapters/xmpp.py +337 -0
- src/chat/history.py +76 -0
- src/chat/models.py +207 -0
- src/chat/probe.py +79 -0
- src/chat/session.py +446 -0
- src/chat/util.py +125 -0
- src/collab/__init__.py +1 -0
- src/collab/net.py +411 -0
- src/collab/ot.py +311 -0
- src/collab/session.py +141 -0
- src/collab/tk_adapter.py +134 -0
- src/config.py +335 -0
- src/constants.py +2552 -0
- src/dep_catalog.py +446 -0
- src/diff/__init__.py +1 -0
- src/diff/engine.py +247 -0
- src/dpi.py +30 -0
- src/editor/__init__.py +1 -0
- src/editor/_pane_lsp.py +2937 -0
- src/editor/_pane_utils.py +171 -0
- src/editor/autocomplete.py +607 -0
- src/editor/code_folding.py +836 -0
- src/editor/color_preview.py +382 -0
- src/editor/complexity_lens.py +281 -0
- src/editor/diff_pane.py +623 -0
- src/editor/file_watcher.py +144 -0
- src/editor/focus_block.py +236 -0
- src/editor/heatmap.py +141 -0
- src/editor/inlay_hints.py +366 -0
- src/editor/inline_blame.py +429 -0
- src/editor/kdocs.py +3376 -0
- src/editor/large_file.py +488 -0
- src/editor/ligatures.py +180 -0
- src/editor/line_numbers.py +598 -0
- src/editor/minimap.py +691 -0
- src/editor/multi_cursor.py +269 -0
- src/editor/pane.py +2082 -0
- src/editor/rhythm.py +206 -0
- src/editor/save_hooks.py +43 -0
- src/editor/smart_selection.py +425 -0
- src/editor/smart_tips.py +719 -0
- src/editor/snippets.py +411 -0
- src/editor/sticky_note_gutter.py +410 -0
- src/editor/sticky_scroll.py +385 -0
- src/editor/suggest.py +464 -0
- src/editor/text_transforms.py +310 -0
- src/editor/vim_mode.py +1074 -0
- src/events/__init__.py +84 -0
- src/events/bus.py +427 -0
- src/events/correlator.py +244 -0
- src/events/kinds.py +125 -0
- src/events/pipeline.py +264 -0
- src/events/stream.py +416 -0
- src/events/window.py +204 -0
- src/extcompat/__init__.py +19 -0
- src/extcompat/code/__init__.py +13 -0
- src/extcompat/code/consent.py +162 -0
- src/extcompat/code/host.py +353 -0
- src/extcompat/code/hosts/py_host.py +763 -0
- src/extcompat/code/locate.py +105 -0
- src/extcompat/code/manager.py +325 -0
- src/extcompat/code/permissions.py +154 -0
- src/extcompat/code/sandbox.py +60 -0
- src/extcompat/colors.py +131 -0
- src/extcompat/common.py +184 -0
- src/extcompat/cson.py +269 -0
- src/extcompat/formats/__init__.py +22 -0
- src/extcompat/formats/_tm.py +189 -0
- src/extcompat/formats/_util.py +31 -0
- src/extcompat/formats/base16.py +66 -0
- src/extcompat/formats/brackets.py +172 -0
- src/extcompat/formats/eclipse.py +193 -0
- src/extcompat/formats/emacs.py +361 -0
- src/extcompat/formats/geany.py +147 -0
- src/extcompat/formats/generic.py +184 -0
- src/extcompat/formats/gtksource.py +117 -0
- src/extcompat/formats/helix.py +91 -0
- src/extcompat/formats/jetbrains.py +343 -0
- src/extcompat/formats/kate.py +130 -0
- src/extcompat/formats/micro.py +131 -0
- src/extcompat/formats/nano.py +111 -0
- src/extcompat/formats/notepadpp.py +140 -0
- src/extcompat/formats/pulsar.py +165 -0
- src/extcompat/formats/pyides.py +163 -0
- src/extcompat/formats/sublime.py +340 -0
- src/extcompat/jsonc.py +65 -0
- src/extcompat/lessish.py +128 -0
- src/extcompat/manager.py +122 -0
- src/extcompat/market/__init__.py +63 -0
- src/extcompat/market/sources.py +211 -0
- src/extcompat/model.py +88 -0
- src/extcompat/net.py +228 -0
- src/extcompat/openvsx.py +63 -0
- src/extcompat/readers.py +362 -0
- src/extcompat/registry.py +73 -0
- src/extcompat/safexml.py +63 -0
- src/extcompat/sexp.py +187 -0
- src/extcompat/sources.py +105 -0
- src/extcompat/store.py +276 -0
- src/extcompat/textmate.py +214 -0
- src/extcompat/themes.py +487 -0
- src/extcompat/yamlite.py +294 -0
- src/fileio.py +94 -0
- src/fs_ops.py +106 -0
- src/i18n.py +233 -0
- src/ia/__init__.py +1 -0
- src/ia/actions.py +295 -0
- src/ia/approval_gate.py +672 -0
- src/ia/checkpoints.py +308 -0
- src/ia/context_builder.py +921 -0
- src/ia/dialdiff.py +408 -0
- src/ia/iaspace.py +2078 -0
- src/ia/pair.py +296 -0
- src/ia/providers.py +954 -0
- src/ia/session.py +335 -0
- src/ia/toolbox.py +2524 -0
- src/launcher_actions.py +204 -0
- src/lint/__init__.py +1 -0
- src/lint/manager.py +1058 -0
- src/locales/.translate_manifest.json +64170 -0
- src/locales/de.json +4936 -0
- src/locales/en.json +4936 -0
- src/locales/es.json +4936 -0
- src/locales/fr.json +4936 -0
- src/locales/it.json +4936 -0
- src/locales/ja.json +4936 -0
- src/locales/ko.json +4936 -0
- src/locales/nl.json +4936 -0
- src/locales/pl.json +4936 -0
- src/locales/pt-BR.json +4936 -0
- src/locales/ru.json +4936 -0
- src/locales/tr.json +4936 -0
- src/locales/uk.json +4936 -0
- src/locales/zh-CN.json +4936 -0
- src/lsp/__init__.py +26 -0
- src/lsp/client.py +2300 -0
- src/lsp/dap_client.py +480 -0
- src/lsp/edits.py +84 -0
- src/lsp/framing.py +73 -0
- src/lsp/protocol.py +931 -0
- src/main.py +260 -0
- src/memtrim.py +91 -0
- src/plugins/__init__.py +1 -0
- src/plugins/api.py +1761 -0
- src/plugins/loader.py +571 -0
- src/plugins/process_runner.py +519 -0
- src/plugins/registry.py +342 -0
- src/plugins/safety.py +367 -0
- src/plugins/startup.py +195 -0
- src/plugins/store.py +1178 -0
- src/proc_registry.py +278 -0
- src/pyexec.py +394 -0
- src/recovery.py +259 -0
- src/stall_trace.py +92 -0
- src/standalone.py +1070 -0
- src/startup_profile.py +35 -0
- src/syntax/__init__.py +1 -0
- src/syntax/highlighter.py +776 -0
- src/syntax/patterns.py +584 -0
- src/system_profile.py +430 -0
- src/terminal/backends.py +658 -0
- src/terminal/internal.py +346 -0
- src/terminal/keys.py +138 -0
- src/terminal/palette.py +67 -0
- src/terminal/session.py +283 -0
- src/terminal/shells.py +79 -0
- src/terminal/view.py +489 -0
- src/terminal/vt.py +870 -0
- src/textfmt.py +22 -0
- src/theme/__init__.py +1 -0
- src/theme/base.py +1281 -0
- src/theme/colors.py +49 -0
- src/theme/manager.py +602 -0
- src/theme/utils.py +312 -0
- src/toolbox.py +329 -0
- src/trash_core.py +531 -0
- src/ui/__init__.py +1 -0
- src/ui/_perf_utils.py +285 -0
- src/ui/_persistence_utils.py +93 -0
- src/ui/accessibility.py +843 -0
- src/ui/activity_bar.py +860 -0
- src/ui/app_embed.py +434 -0
- src/ui/archive_panel.py +608 -0
- src/ui/bookmarks.py +314 -0
- src/ui/breadcrumb.py +383 -0
- src/ui/calculator_panel.py +982 -0
- src/ui/calendar_panel.py +1218 -0
- src/ui/chat_panel.py +1271 -0
- src/ui/chat_profile_dialog.py +278 -0
- src/ui/chat_render.py +128 -0
- src/ui/clock_panel.py +810 -0
- src/ui/code_outline.py +364 -0
- src/ui/code_runner.py +729 -0
- src/ui/code_stats.py +546 -0
- src/ui/collab_panel.py +1009 -0
- src/ui/color_picker.py +547 -0
- src/ui/command_palette.py +452 -0
- src/ui/cursor_manager.py +750 -0
- src/ui/custom_keywords_panel.py +413 -0
- src/ui/debug_panel.py +1037 -0
- src/ui/dependency_graph.py +692 -0
- src/ui/diff_panel.py +381 -0
- src/ui/docs_panel.py +514 -0
- src/ui/doom_embed.py +349 -0
- src/ui/dropdown.py +321 -0
- src/ui/easter_eggs.py +979 -0
- src/ui/env_manager.py +666 -0
- src/ui/extcode_bridge.py +215 -0
- src/ui/extcode_dialogs.py +412 -0
- src/ui/extcompat_dialog.py +583 -0
- src/ui/file_timeline.py +319 -0
- src/ui/file_tree.py +1208 -0
- src/ui/find_in_files.py +1355 -0
- src/ui/flowchart_panel.py +727 -0
- src/ui/formatter_panel.py +490 -0
- src/ui/git_auth.py +763 -0
- src/ui/git_clone_dialog.py +487 -0
- src/ui/git_panel.py +1483 -0
- src/ui/grab_safe.py +84 -0
- src/ui/internal_python_dialog.py +98 -0
- src/ui/k_ui/__init__.py +1305 -0
- src/ui/k_ui/_bgrenderer.py +317 -0
- src/ui/k_ui/_colors.py +213 -0
- src/ui/k_ui/_dock.py +545 -0
- src/ui/k_ui/_easter.py +290 -0
- src/ui/k_ui/_engine.py +5448 -0
- src/ui/k_ui/_perf.py +333 -0
- src/ui/k_ui/_tkutil.py +7 -0
- src/ui/k_ui/_tooltip.py +365 -0
- src/ui/k_ui/_widgets.py +1204 -0
- src/ui/k_ui/_world.py +837 -0
- src/ui/key_remapper.py +856 -0
- src/ui/launcher.py +1252 -0
- src/ui/lazy_panel.py +73 -0
- src/ui/macro_recorder.py +610 -0
- src/ui/menu_bar.py +898 -0
- src/ui/output_panel.py +321 -0
- src/ui/paint_canvas.py +1000 -0
- src/ui/paint_engine.py +535 -0
- src/ui/paint_panel.py +888 -0
- src/ui/panel_detach.py +112 -0
- src/ui/performance_panel.py +861 -0
- src/ui/pip_manager.py +1758 -0
- src/ui/plugin_panel.py +1586 -0
- src/ui/pomodoro_panel.py +447 -0
- src/ui/problems.py +566 -0
- src/ui/process_manager.py +1657 -0
- src/ui/project_templates.py +775 -0
- src/ui/recovery_dialog.py +122 -0
- src/ui/regex_playground.py +304 -0
- src/ui/remote_adapters.py +1398 -0
- src/ui/remote_browser.py +1224 -0
- src/ui/remote_profile_dialog.py +342 -0
- src/ui/render_panel.py +1293 -0
- src/ui/rest_client.py +549 -0
- src/ui/scratchpad.py +548 -0
- src/ui/search_bar.py +1274 -0
- src/ui/settings_editor.py +3349 -0
- src/ui/settings_window.py +1554 -0
- src/ui/snippets_panel.py +597 -0
- src/ui/sql_studio.py +1815 -0
- src/ui/status_bar.py +438 -0
- src/ui/tab_bar.py +654 -0
- src/ui/task_manager.py +1773 -0
- src/ui/terminal.py +525 -0
- src/ui/theme_preview_panel.py +851 -0
- src/ui/thread_safe_tk.py +152 -0
- src/ui/time_tracker.py +574 -0
- src/ui/tkbind.py +43 -0
- src/ui/todo_panel.py +358 -0
- src/ui/toolbox_panels.py +658 -0
- src/ui/trash_manager.py +657 -0
- src/ui/ui_scale.py +294 -0
- src/ui/ux_enhancements.py +41 -0
- src/ui/web_preview.py +397 -0
- src/ui/webdev.py +630 -0
- src/ui/welcome.py +567 -0
- src/ui/window_embed.py +1500 -0
- src/ui/wizard.py +1550 -0
- src/ui/workspace_switcher.py +418 -0
- src/ui/workspace_trust.py +370 -0
- src/ui/zen_audio.py +354 -0
- src/ui/zen_media.py +2271 -0
- src/ui/zen_media_client.py +303 -0
- src/ui/zen_media_host.py +329 -0
- src/ui/zen_player.py +907 -0
- src/ui/zen_player_widgets.py +700 -0
- src/updater/__init__.py +11 -0
- src/updater/assets.py +145 -0
- src/updater/backup.py +101 -0
- src/updater/channel.py +221 -0
- src/updater/dialog.py +492 -0
- src/updater/integrity.py +111 -0
- src/updater/manager.py +727 -0
- src/updater/result.py +114 -0
- src/venv_runtime.py +531 -0
- src/workspace_state.py +25 -0
src/lsp/client.py
ADDED
|
@@ -0,0 +1,2300 @@
|
|
|
1
|
+
"""Codis LSP - Language Server Protocol client (LSP 3.17).
|
|
2
|
+
|
|
3
|
+
Gerencia um processo de servidor por linguagem, comunicando via JSON-RPC 2.0.
|
|
4
|
+
|
|
5
|
+
Servidores suportados (auto-detectados do PATH):
|
|
6
|
+
Python : pylsp, pyright-langserver, jedi-language-server
|
|
7
|
+
JS/TS : typescript-language-server, deno
|
|
8
|
+
Rust : rust-analyzer
|
|
9
|
+
Go : gopls
|
|
10
|
+
C/C++ : clangd
|
|
11
|
+
Java : jdtls (Eclipse JDT)
|
|
12
|
+
Kotlin : kotlin-language-server
|
|
13
|
+
Swift : sourcekit-lsp
|
|
14
|
+
Dart : dart language-server
|
|
15
|
+
PHP : intelephense, phpactor
|
|
16
|
+
Ruby : ruby-lsp, solargraph
|
|
17
|
+
Elixir : elixir-ls
|
|
18
|
+
Erlang : erlang-ls
|
|
19
|
+
Scala : metals
|
|
20
|
+
Haskell : haskell-language-server-wrapper
|
|
21
|
+
Lua : lua-language-server
|
|
22
|
+
Bash/Shell : bash-language-server
|
|
23
|
+
R : r languageserver
|
|
24
|
+
Julia : LanguageServer.jl
|
|
25
|
+
Clojure : clojure-lsp
|
|
26
|
+
Groovy : groovy-language-server
|
|
27
|
+
JSON : vscode-json-languageserver
|
|
28
|
+
HTML : vscode-html-languageserver
|
|
29
|
+
CSS/SCSS : vscode-css-languageserver
|
|
30
|
+
YAML : yaml-language-server
|
|
31
|
+
TOML : taplo
|
|
32
|
+
XML : lemminx
|
|
33
|
+
Markdown : marksman
|
|
34
|
+
Dockerfile : dockerfile-language-server
|
|
35
|
+
Terraform : terraform-ls
|
|
36
|
+
GraphQL : graphql-language-service-cli
|
|
37
|
+
Protobuf : buf-language-server
|
|
38
|
+
Nix : nil, rnix-lsp
|
|
39
|
+
SQL : sqls, sql-language-server
|
|
40
|
+
C# : OmniSharp, csharp-ls
|
|
41
|
+
F# : fsautocomplete
|
|
42
|
+
OCaml : ocamllsp
|
|
43
|
+
|
|
44
|
+
Features implementadas:
|
|
45
|
+
textDocument/hover -> balloon de documentação
|
|
46
|
+
textDocument/completion -> autocomplete aumentado
|
|
47
|
+
textDocument/definition -> ir para definição
|
|
48
|
+
textDocument/declaration -> ir para declaração
|
|
49
|
+
textDocument/typeDefinition -> tipo da definição
|
|
50
|
+
textDocument/implementation -> implementação da interface
|
|
51
|
+
textDocument/references -> todas as referências
|
|
52
|
+
textDocument/signatureHelp -> hints de parâmetros
|
|
53
|
+
textDocument/documentSymbol -> símbolos do documento (outline)
|
|
54
|
+
workspace/symbol -> busca de símbolo no workspace
|
|
55
|
+
textDocument/formatting -> formatação via LSP
|
|
56
|
+
textDocument/rangeFormatting -> formatação de seleção
|
|
57
|
+
textDocument/rename -> renomear símbolo
|
|
58
|
+
textDocument/prepareRename -> validar renomeação
|
|
59
|
+
textDocument/codeAction -> quick fixes e refactors
|
|
60
|
+
textDocument/documentHighlight -> destacar ocorrências
|
|
61
|
+
textDocument/foldingRange -> folding via LSP
|
|
62
|
+
textDocument/inlayHint -> inlay hints via LSP
|
|
63
|
+
callHierarchy/incomingCalls -> hierarquia de chamadas
|
|
64
|
+
callHierarchy/outgoingCalls -> hierarquia de chamadas
|
|
65
|
+
typeHierarchy/supertypes -> hierarquia de tipos
|
|
66
|
+
typeHierarchy/subtypes -> hierarquia de tipos
|
|
67
|
+
textDocument/semanticTokens/full -> colorização semântica
|
|
68
|
+
completionItem/resolve -> documentação lazy
|
|
69
|
+
workspace/executeCommand -> executar comando do servidor
|
|
70
|
+
textDocument/linkedEditingRange -> edição simultânea (HTML tags)
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
from __future__ import annotations
|
|
74
|
+
|
|
75
|
+
import contextlib
|
|
76
|
+
import functools
|
|
77
|
+
import logging
|
|
78
|
+
import os
|
|
79
|
+
import queue
|
|
80
|
+
import shutil
|
|
81
|
+
import signal
|
|
82
|
+
import subprocess
|
|
83
|
+
import sys
|
|
84
|
+
import threading
|
|
85
|
+
import time
|
|
86
|
+
import tkinter as tk
|
|
87
|
+
from collections.abc import Callable
|
|
88
|
+
from pathlib import Path
|
|
89
|
+
from typing import Any
|
|
90
|
+
|
|
91
|
+
from src import proc_registry
|
|
92
|
+
from src.constants import APP_VERSION
|
|
93
|
+
from src.terminal.backends import child_process_env
|
|
94
|
+
|
|
95
|
+
from .framing import FrameDecoder, MessageTooLarge, encode_frame
|
|
96
|
+
from .protocol import (
|
|
97
|
+
SEMANTIC_TOKEN_MODIFIERS,
|
|
98
|
+
SEMANTIC_TOKEN_TYPES,
|
|
99
|
+
CallHierarchyCall,
|
|
100
|
+
CallHierarchyItem,
|
|
101
|
+
CodeAction,
|
|
102
|
+
CompletionItem,
|
|
103
|
+
DocumentHighlight,
|
|
104
|
+
DocumentSymbol,
|
|
105
|
+
FoldingRange,
|
|
106
|
+
Hover,
|
|
107
|
+
InlayHint,
|
|
108
|
+
Location,
|
|
109
|
+
LocationLink,
|
|
110
|
+
LSPMessage,
|
|
111
|
+
PrepareRenameResult,
|
|
112
|
+
Range,
|
|
113
|
+
SemanticTokens,
|
|
114
|
+
SignatureHelp,
|
|
115
|
+
TextEdit,
|
|
116
|
+
TypeHierarchyItem,
|
|
117
|
+
WorkspaceEdit,
|
|
118
|
+
)
|
|
119
|
+
from .protocol import (
|
|
120
|
+
Diagnostic as LSPDiag,
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
logger = logging.getLogger("Codis.LSP")
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
_SERVER_CANDIDATES: dict[str, list[list[str]]] = {
|
|
127
|
+
"python": [
|
|
128
|
+
[sys.executable, "-m", "pylsp"],
|
|
129
|
+
["pylsp"],
|
|
130
|
+
["pyright-langserver", "--stdio"],
|
|
131
|
+
[sys.executable, "-m", "pyright", "--stdio"],
|
|
132
|
+
["jedi-language-server"],
|
|
133
|
+
[sys.executable, "-m", "jedi_language_server"],
|
|
134
|
+
["python-language-server"],
|
|
135
|
+
],
|
|
136
|
+
"javascript": [
|
|
137
|
+
["typescript-language-server", "--stdio"],
|
|
138
|
+
["tsserver", "--stdio"],
|
|
139
|
+
["deno", "lsp"],
|
|
140
|
+
],
|
|
141
|
+
"typescript": [
|
|
142
|
+
["typescript-language-server", "--stdio"],
|
|
143
|
+
["deno", "lsp"],
|
|
144
|
+
],
|
|
145
|
+
"rust": [
|
|
146
|
+
["rust-analyzer"],
|
|
147
|
+
],
|
|
148
|
+
"go": [
|
|
149
|
+
["gopls"],
|
|
150
|
+
],
|
|
151
|
+
"c": [
|
|
152
|
+
["clangd"],
|
|
153
|
+
["ccls"],
|
|
154
|
+
],
|
|
155
|
+
"cpp": [
|
|
156
|
+
["clangd"],
|
|
157
|
+
["ccls"],
|
|
158
|
+
],
|
|
159
|
+
"java": [
|
|
160
|
+
["jdtls"],
|
|
161
|
+
["java-language-server"],
|
|
162
|
+
],
|
|
163
|
+
"kotlin": [
|
|
164
|
+
["kotlin-language-server"],
|
|
165
|
+
],
|
|
166
|
+
"swift": [
|
|
167
|
+
["sourcekit-lsp"],
|
|
168
|
+
],
|
|
169
|
+
"dart": [
|
|
170
|
+
["dart", "language-server", "--client-id", "codis"],
|
|
171
|
+
],
|
|
172
|
+
"php": [
|
|
173
|
+
["intelephense", "--stdio"],
|
|
174
|
+
["phpactor", "language-server"],
|
|
175
|
+
],
|
|
176
|
+
"ruby": [
|
|
177
|
+
["ruby-lsp"],
|
|
178
|
+
["solargraph", "stdio"],
|
|
179
|
+
],
|
|
180
|
+
"elixir": [
|
|
181
|
+
["elixir-ls"],
|
|
182
|
+
["elixir-language-server"],
|
|
183
|
+
],
|
|
184
|
+
"erlang": [
|
|
185
|
+
["erlang-ls", "--transport", "stdio"],
|
|
186
|
+
],
|
|
187
|
+
"scala": [
|
|
188
|
+
["metals"],
|
|
189
|
+
],
|
|
190
|
+
"haskell": [
|
|
191
|
+
["haskell-language-server-wrapper", "--lsp"],
|
|
192
|
+
["haskell-language-server", "--lsp"],
|
|
193
|
+
],
|
|
194
|
+
"lua": [
|
|
195
|
+
["lua-language-server"],
|
|
196
|
+
["lua-lsp"],
|
|
197
|
+
],
|
|
198
|
+
"bash": [
|
|
199
|
+
["bash-language-server", "start"],
|
|
200
|
+
],
|
|
201
|
+
"shell": [
|
|
202
|
+
["bash-language-server", "start"],
|
|
203
|
+
],
|
|
204
|
+
"r": [
|
|
205
|
+
["R", "--slave", "-e", "languageserver::run()"],
|
|
206
|
+
],
|
|
207
|
+
"julia": [
|
|
208
|
+
[
|
|
209
|
+
"julia",
|
|
210
|
+
"--startup-file=no",
|
|
211
|
+
"--history-file=no",
|
|
212
|
+
"-e",
|
|
213
|
+
"using LanguageServer; run()",
|
|
214
|
+
],
|
|
215
|
+
],
|
|
216
|
+
"clojure": [
|
|
217
|
+
["clojure-lsp"],
|
|
218
|
+
],
|
|
219
|
+
"groovy": [
|
|
220
|
+
["groovy-language-server"],
|
|
221
|
+
],
|
|
222
|
+
"json": [
|
|
223
|
+
["vscode-json-languageserver", "--stdio"],
|
|
224
|
+
["vscode-json-language-server", "--stdio"],
|
|
225
|
+
],
|
|
226
|
+
"html": [
|
|
227
|
+
["vscode-html-languageserver", "--stdio"],
|
|
228
|
+
["vscode-html-language-server", "--stdio"],
|
|
229
|
+
],
|
|
230
|
+
"css": [
|
|
231
|
+
["vscode-css-languageserver", "--stdio"],
|
|
232
|
+
["vscode-css-language-server", "--stdio"],
|
|
233
|
+
],
|
|
234
|
+
"scss": [
|
|
235
|
+
["vscode-css-languageserver", "--stdio"],
|
|
236
|
+
["vscode-css-language-server", "--stdio"],
|
|
237
|
+
],
|
|
238
|
+
"less": [
|
|
239
|
+
["vscode-css-languageserver", "--stdio"],
|
|
240
|
+
["vscode-css-language-server", "--stdio"],
|
|
241
|
+
],
|
|
242
|
+
"yaml": [
|
|
243
|
+
["yaml-language-server", "--stdio"],
|
|
244
|
+
],
|
|
245
|
+
"toml": [
|
|
246
|
+
["taplo", "lsp", "stdio"],
|
|
247
|
+
],
|
|
248
|
+
"xml": [
|
|
249
|
+
["lemminx"],
|
|
250
|
+
],
|
|
251
|
+
"markdown": [
|
|
252
|
+
["marksman", "server"],
|
|
253
|
+
["zeta-note"],
|
|
254
|
+
],
|
|
255
|
+
"docker": [
|
|
256
|
+
["docker-langserver", "--stdio"],
|
|
257
|
+
["dockerfile-language-server", "--stdio"],
|
|
258
|
+
],
|
|
259
|
+
"hcl": [
|
|
260
|
+
["terraform-ls", "serve"],
|
|
261
|
+
],
|
|
262
|
+
"graphql": [
|
|
263
|
+
["graphql-lsp", "server", "-m", "stream"],
|
|
264
|
+
],
|
|
265
|
+
"protobuf": [
|
|
266
|
+
["buf", "beta", "lsp"],
|
|
267
|
+
["bufls", "serve"],
|
|
268
|
+
],
|
|
269
|
+
"nix": [
|
|
270
|
+
["nil"],
|
|
271
|
+
["rnix-lsp"],
|
|
272
|
+
],
|
|
273
|
+
"sql": [
|
|
274
|
+
["sqls"],
|
|
275
|
+
["sql-language-server", "up", "--method", "stdio"],
|
|
276
|
+
],
|
|
277
|
+
"csharp": [
|
|
278
|
+
["OmniSharp", "-lsp"],
|
|
279
|
+
["csharp-ls"],
|
|
280
|
+
["omnisharp"],
|
|
281
|
+
],
|
|
282
|
+
"fsharp": [
|
|
283
|
+
["fsautocomplete", "--adaptive-lsp-server-enabled"],
|
|
284
|
+
],
|
|
285
|
+
"ocaml": [
|
|
286
|
+
["ocamllsp"],
|
|
287
|
+
],
|
|
288
|
+
"perl": [
|
|
289
|
+
["perl", "-MPerl::LanguageServer", "-e", "Perl::LanguageServer::run()"],
|
|
290
|
+
["perl-language-server"],
|
|
291
|
+
],
|
|
292
|
+
"powershell": [
|
|
293
|
+
[
|
|
294
|
+
"pwsh",
|
|
295
|
+
"-NoLogo",
|
|
296
|
+
"-NonInteractive",
|
|
297
|
+
"-Command",
|
|
298
|
+
"Import-Module PowerShellEditorServices; Start-EditorServices",
|
|
299
|
+
],
|
|
300
|
+
],
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
# Tentativas seguidas de initialize recusado antes de desistir do servidor.
|
|
304
|
+
_MAX_INIT_FAILURES = 3
|
|
305
|
+
|
|
306
|
+
_LANG_ID_MAP: dict[str, str] = {
|
|
307
|
+
"javascript": "javascript",
|
|
308
|
+
"typescript": "typescript",
|
|
309
|
+
"python": "python",
|
|
310
|
+
"rust": "rust",
|
|
311
|
+
"go": "go",
|
|
312
|
+
"c": "c",
|
|
313
|
+
"cpp": "cpp",
|
|
314
|
+
"java": "java",
|
|
315
|
+
"kotlin": "kotlin",
|
|
316
|
+
"swift": "swift",
|
|
317
|
+
"dart": "dart",
|
|
318
|
+
"php": "php",
|
|
319
|
+
"ruby": "ruby",
|
|
320
|
+
"elixir": "elixir",
|
|
321
|
+
"erlang": "erlang",
|
|
322
|
+
"scala": "scala",
|
|
323
|
+
"haskell": "haskell",
|
|
324
|
+
"lua": "lua",
|
|
325
|
+
"bash": "shellscript",
|
|
326
|
+
"shell": "shellscript",
|
|
327
|
+
"r": "r",
|
|
328
|
+
"julia": "julia",
|
|
329
|
+
"clojure": "clojure",
|
|
330
|
+
"groovy": "groovy",
|
|
331
|
+
"html": "html",
|
|
332
|
+
"vue": "vue",
|
|
333
|
+
"svelte": "svelte",
|
|
334
|
+
"css": "css",
|
|
335
|
+
"scss": "scss",
|
|
336
|
+
"less": "less",
|
|
337
|
+
"json": "json",
|
|
338
|
+
"markdown": "markdown",
|
|
339
|
+
"yaml": "yaml",
|
|
340
|
+
"toml": "toml",
|
|
341
|
+
"xml": "xml",
|
|
342
|
+
"docker": "dockerfile",
|
|
343
|
+
"hcl": "terraform",
|
|
344
|
+
"graphql": "graphql",
|
|
345
|
+
"protobuf": "proto",
|
|
346
|
+
"nix": "nix",
|
|
347
|
+
"sql": "sql",
|
|
348
|
+
"csharp": "csharp",
|
|
349
|
+
"fsharp": "fsharp",
|
|
350
|
+
"ocaml": "ocaml",
|
|
351
|
+
"perl": "perl",
|
|
352
|
+
"powershell": "powershell",
|
|
353
|
+
"bat": "bat",
|
|
354
|
+
"text": "plaintext",
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
_INSTALL_HINTS: dict[str, str] = {
|
|
358
|
+
"python": "pip install python-lsp-server",
|
|
359
|
+
"javascript": "npm i -g typescript-language-server typescript",
|
|
360
|
+
"typescript": "npm i -g typescript-language-server typescript",
|
|
361
|
+
"rust": "rustup component add rust-analyzer",
|
|
362
|
+
"go": "go install golang.org/x/tools/gopls@latest",
|
|
363
|
+
"c": "apt install clangd / brew install llvm",
|
|
364
|
+
"cpp": "apt install clangd / brew install llvm",
|
|
365
|
+
"java": "brew install jdtls (ou instale via IDE)",
|
|
366
|
+
"kotlin": "brew install kotlin-language-server",
|
|
367
|
+
"swift": "xcode-select --install (inclui sourcekit-lsp)",
|
|
368
|
+
"dart": "flutter/dart SDK inclui language-server",
|
|
369
|
+
"php": "npm i -g intelephense",
|
|
370
|
+
"ruby": "gem install ruby-lsp / gem install solargraph",
|
|
371
|
+
"elixir": "asdf install / hex.pm/packages/elixir_ls",
|
|
372
|
+
"erlang": "brew install erlang-ls",
|
|
373
|
+
"scala": "coursier install metals",
|
|
374
|
+
"haskell": "ghcup install hls",
|
|
375
|
+
"lua": "brew install lua-language-server",
|
|
376
|
+
"bash": "npm i -g bash-language-server",
|
|
377
|
+
"shell": "npm i -g bash-language-server",
|
|
378
|
+
"r": "install.packages('languageserver')",
|
|
379
|
+
"julia": "julia -e 'using Pkg; Pkg.add(\"LanguageServer\")'",
|
|
380
|
+
"clojure": "brew install clojure-lsp/brew/clojure-lsp-native",
|
|
381
|
+
"html": "npm i -g vscode-langservers-extracted",
|
|
382
|
+
"css": "npm i -g vscode-langservers-extracted",
|
|
383
|
+
"scss": "npm i -g vscode-langservers-extracted",
|
|
384
|
+
"json": "npm i -g vscode-langservers-extracted",
|
|
385
|
+
"yaml": "npm i -g yaml-language-server",
|
|
386
|
+
"toml": "cargo install taplo-cli / brew install taplo",
|
|
387
|
+
"xml": "brew install lemminx",
|
|
388
|
+
"markdown": "brew install marksman",
|
|
389
|
+
"docker": "npm i -g dockerfile-language-server-nodejs",
|
|
390
|
+
"hcl": "brew install hashicorp/tap/terraform-ls",
|
|
391
|
+
"graphql": "npm i -g graphql-language-service-cli",
|
|
392
|
+
"nix": "nix-env -iA nixpkgs.nil",
|
|
393
|
+
"sql": "go install github.com/lighttiger2505/sqls@latest",
|
|
394
|
+
"csharp": "dotnet tool install -g csharp-ls",
|
|
395
|
+
"fsharp": "dotnet tool install -g fsautocomplete",
|
|
396
|
+
"ocaml": "opam install ocaml-lsp-server",
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def _extra_search_paths() -> list[str]:
|
|
401
|
+
"""Retorna diretórios extras a verificar além do PATH do sistema."""
|
|
402
|
+
extras: list[str] = []
|
|
403
|
+
if sys.platform == "win32":
|
|
404
|
+
import site as _site
|
|
405
|
+
|
|
406
|
+
with contextlib.suppress(Exception):
|
|
407
|
+
for s in _site.getsitepackages():
|
|
408
|
+
scripts = Path(s).parent / "Scripts"
|
|
409
|
+
if scripts.is_dir():
|
|
410
|
+
extras.append(str(scripts))
|
|
411
|
+
|
|
412
|
+
with contextlib.suppress(Exception):
|
|
413
|
+
npm_bin = Path(os.environ.get("APPDATA", "")) / "npm"
|
|
414
|
+
if npm_bin.is_dir():
|
|
415
|
+
extras.append(str(npm_bin))
|
|
416
|
+
|
|
417
|
+
with contextlib.suppress(Exception):
|
|
418
|
+
user_scripts = Path(sys.executable).parent / "Scripts"
|
|
419
|
+
if user_scripts.is_dir():
|
|
420
|
+
extras.append(str(user_scripts))
|
|
421
|
+
else:
|
|
422
|
+
local_bin = Path.home() / ".local" / "bin"
|
|
423
|
+
if local_bin.is_dir():
|
|
424
|
+
extras.append(str(local_bin))
|
|
425
|
+
|
|
426
|
+
for npm_dir in (
|
|
427
|
+
"/usr/local/lib/node_modules/.bin",
|
|
428
|
+
str(Path.home() / ".npm-global" / "bin"),
|
|
429
|
+
"/opt/homebrew/bin",
|
|
430
|
+
):
|
|
431
|
+
if Path(npm_dir).is_dir():
|
|
432
|
+
extras.append(npm_dir)
|
|
433
|
+
return extras
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def _which_extended(exe: str) -> str | None:
|
|
437
|
+
"""shutil.which() com busca em diretórios extras além do PATH."""
|
|
438
|
+
found = shutil.which(exe)
|
|
439
|
+
if found:
|
|
440
|
+
return found
|
|
441
|
+
for extra in _extra_search_paths():
|
|
442
|
+
candidate = Path(extra) / exe
|
|
443
|
+
if candidate.is_file():
|
|
444
|
+
return str(candidate)
|
|
445
|
+
|
|
446
|
+
for ext in (".exe", ".cmd", ".bat"):
|
|
447
|
+
c2 = Path(extra) / (exe + ext)
|
|
448
|
+
if c2.is_file():
|
|
449
|
+
return str(c2)
|
|
450
|
+
return None
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
@functools.lru_cache(maxsize=32)
|
|
454
|
+
def _python_with_module(module: str) -> str | None:
|
|
455
|
+
"""Python que consegue importar ``module`` (ou ``None``).
|
|
456
|
+
|
|
457
|
+
Em desenvolvimento é o próprio interpretador. Compilado, ``sys.executable``
|
|
458
|
+
é o Codis; então pergunta ao Python do ambiente adotado (venv) ou, sem ele,
|
|
459
|
+
ao do sistema, em vez de só olhar o que veio embutido no bundle. Com um venv
|
|
460
|
+
adotado o mesmo vale fora do executável. O resultado é descartado quando o
|
|
461
|
+
ambiente muda (:func:`src.venv_runtime.add_change_listener`).
|
|
462
|
+
"""
|
|
463
|
+
import importlib.util
|
|
464
|
+
|
|
465
|
+
from src import pyexec, venv_runtime
|
|
466
|
+
|
|
467
|
+
if not pyexec.is_frozen() and venv_runtime.env_python() is None:
|
|
468
|
+
return sys.executable if importlib.util.find_spec(module) is not None else None
|
|
469
|
+
try:
|
|
470
|
+
py = pyexec.python_executable()
|
|
471
|
+
except pyexec.NoPythonError:
|
|
472
|
+
return None
|
|
473
|
+
code = f"import importlib.util,sys;sys.exit(0 if importlib.util.find_spec({module!r}) else 1)"
|
|
474
|
+
try:
|
|
475
|
+
rc = subprocess.run(
|
|
476
|
+
[py, "-c", code],
|
|
477
|
+
capture_output=True,
|
|
478
|
+
timeout=20,
|
|
479
|
+
check=False,
|
|
480
|
+
stdin=subprocess.DEVNULL,
|
|
481
|
+
env=pyexec.child_env(),
|
|
482
|
+
).returncode
|
|
483
|
+
except (OSError, subprocess.SubprocessError):
|
|
484
|
+
return None
|
|
485
|
+
return py if rc == 0 else None
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def _register_env_listener() -> None:
|
|
489
|
+
from src import venv_runtime
|
|
490
|
+
|
|
491
|
+
venv_runtime.add_change_listener(_python_with_module.cache_clear)
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
_register_env_listener()
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def _find_server(lang: str) -> list[str] | None:
|
|
498
|
+
"""Retorna o primeiro comando de servidor disponível para a linguagem."""
|
|
499
|
+
for cmd in _SERVER_CANDIDATES.get(lang, []):
|
|
500
|
+
exe = cmd[0]
|
|
501
|
+
if exe == sys.executable:
|
|
502
|
+
with contextlib.suppress(ValueError, IndexError):
|
|
503
|
+
m_idx = cmd.index("-m")
|
|
504
|
+
mod_name = cmd[m_idx + 1].replace("-", "_").split(".")[0]
|
|
505
|
+
py = _python_with_module(mod_name)
|
|
506
|
+
if py is not None:
|
|
507
|
+
return [py, *cmd[1:]]
|
|
508
|
+
else:
|
|
509
|
+
found = _which_extended(exe)
|
|
510
|
+
if found:
|
|
511
|
+
new_cmd = [found] + cmd[1:]
|
|
512
|
+
return new_cmd
|
|
513
|
+
return None
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def _path_to_uri(path: Path) -> str:
|
|
517
|
+
s = path.as_posix()
|
|
518
|
+
if sys.platform == "win32":
|
|
519
|
+
s = "/" + path.as_posix()
|
|
520
|
+
return "file://" + s
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def _kill_process_tree(proc: subprocess.Popen) -> None:
|
|
524
|
+
"""Encerra ``proc`` e todos os seus descendentes sem bloquear por muito tempo.
|
|
525
|
+
|
|
526
|
+
Servidores de linguagem costumam ser lançados por wrappers (``npx``, shims
|
|
527
|
+
``.cmd``) que geram o processo real como filho; matar só o wrapper deixa o
|
|
528
|
+
servidor vivo, segurando pipes e impedindo o encerramento limpo do app.
|
|
529
|
+
"""
|
|
530
|
+
if proc.poll() is not None:
|
|
531
|
+
return
|
|
532
|
+
try:
|
|
533
|
+
if sys.platform == "win32":
|
|
534
|
+
subprocess.run(
|
|
535
|
+
["taskkill", "/F", "/T", "/PID", str(proc.pid)],
|
|
536
|
+
capture_output=True,
|
|
537
|
+
timeout=3,
|
|
538
|
+
check=False,
|
|
539
|
+
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
|
|
540
|
+
)
|
|
541
|
+
elif os.getpgid(proc.pid) == proc.pid:
|
|
542
|
+
os.killpg(proc.pid, signal.SIGKILL)
|
|
543
|
+
else:
|
|
544
|
+
proc.kill()
|
|
545
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
546
|
+
with contextlib.suppress(OSError):
|
|
547
|
+
proc.kill()
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
class LSPClient:
|
|
551
|
+
"""
|
|
552
|
+
Gerencia um processo de servidor LSP e sua comunicação JSON-RPC.
|
|
553
|
+
|
|
554
|
+
Callbacks são sempre chamados na thread Tk via root.after(0, cb).
|
|
555
|
+
"""
|
|
556
|
+
|
|
557
|
+
def __init__(
|
|
558
|
+
self,
|
|
559
|
+
lang: str,
|
|
560
|
+
root_path: Path | None,
|
|
561
|
+
tk_root: tk.Misc,
|
|
562
|
+
on_diagnostics: Callable[[str, list], None] | None = None,
|
|
563
|
+
on_log: Callable[[str], None] | None = None,
|
|
564
|
+
on_apply_edit: Callable | None = None,
|
|
565
|
+
) -> None:
|
|
566
|
+
self.lang = lang
|
|
567
|
+
self.root_path = root_path
|
|
568
|
+
self._tk = tk_root
|
|
569
|
+
self._on_diags = on_diagnostics
|
|
570
|
+
self._on_log = on_log
|
|
571
|
+
self._on_apply_edit = on_apply_edit
|
|
572
|
+
|
|
573
|
+
self._proc: subprocess.Popen | None = None
|
|
574
|
+
self._thread: threading.Thread | None = None
|
|
575
|
+
self._outbox: queue.Queue[bytes | None] = queue.Queue()
|
|
576
|
+
self._pending_lock = threading.Lock()
|
|
577
|
+
self._id_lock = threading.Lock()
|
|
578
|
+
self._id = 0
|
|
579
|
+
self._pending: dict[int, Callable] = {}
|
|
580
|
+
self._initialized = False
|
|
581
|
+
self._pre_init_queue: list[dict] = []
|
|
582
|
+
self._open_docs: dict[str, int] = {}
|
|
583
|
+
self._capabilities: dict = {}
|
|
584
|
+
self._semantic_legend: dict = {}
|
|
585
|
+
self._shutdown = False
|
|
586
|
+
self._init_failures = 0
|
|
587
|
+
|
|
588
|
+
def _reset_session(self) -> None:
|
|
589
|
+
"""Descarta o estado da sessão anterior antes de subir um novo processo.
|
|
590
|
+
|
|
591
|
+
Sem isso, um servidor que caiu deixaria ``_initialized`` verdadeiro e
|
|
592
|
+
pedidos seriam enviados ao processo novo antes do ``initialize``.
|
|
593
|
+
"""
|
|
594
|
+
self._initialized = False
|
|
595
|
+
self._capabilities = {}
|
|
596
|
+
self._semantic_legend = {}
|
|
597
|
+
self._pre_init_queue = []
|
|
598
|
+
self._open_docs.clear()
|
|
599
|
+
with self._pending_lock:
|
|
600
|
+
self._pending.clear()
|
|
601
|
+
|
|
602
|
+
def start(self) -> bool:
|
|
603
|
+
"""Inicia o servidor. Retorna True se iniciado com sucesso."""
|
|
604
|
+
if self._proc and self._proc.poll() is None:
|
|
605
|
+
return True
|
|
606
|
+
if self._init_failures >= _MAX_INIT_FAILURES:
|
|
607
|
+
logger.debug("LSP: '%s' desistiu após falhas no initialize", self.lang)
|
|
608
|
+
return False
|
|
609
|
+
cmd = _find_server(self.lang)
|
|
610
|
+
if not cmd:
|
|
611
|
+
logger.debug("LSP: sem servidor para '%s'", self.lang)
|
|
612
|
+
return False
|
|
613
|
+
try:
|
|
614
|
+
env = child_process_env()
|
|
615
|
+
cwd = str(self.root_path) if self.root_path else None
|
|
616
|
+
spawn_opts: dict[str, Any] = {}
|
|
617
|
+
if sys.platform != "win32":
|
|
618
|
+
spawn_opts["start_new_session"] = True
|
|
619
|
+
self._reset_session()
|
|
620
|
+
self._proc = subprocess.Popen(
|
|
621
|
+
cmd,
|
|
622
|
+
stdin=subprocess.PIPE,
|
|
623
|
+
stdout=subprocess.PIPE,
|
|
624
|
+
stderr=subprocess.PIPE,
|
|
625
|
+
cwd=cwd,
|
|
626
|
+
env=env,
|
|
627
|
+
**spawn_opts,
|
|
628
|
+
)
|
|
629
|
+
proc_registry.track(self._proc, "lsp", "servidor LSP")
|
|
630
|
+
self._shutdown = False
|
|
631
|
+
self._outbox = queue.Queue()
|
|
632
|
+
threading.Thread(
|
|
633
|
+
target=self._writer_loop,
|
|
634
|
+
args=(self._proc, self._outbox),
|
|
635
|
+
daemon=True,
|
|
636
|
+
name=f"lsp-writer-{self.lang}",
|
|
637
|
+
).start()
|
|
638
|
+
self._thread = threading.Thread(
|
|
639
|
+
target=self._reader_loop, daemon=True, name=f"lsp-reader-{self.lang}"
|
|
640
|
+
)
|
|
641
|
+
self._thread.start()
|
|
642
|
+
threading.Thread(
|
|
643
|
+
target=self._stderr_loop, daemon=True, name=f"lsp-stderr-{self.lang}"
|
|
644
|
+
).start()
|
|
645
|
+
self._send_initialize()
|
|
646
|
+
logger.info("LSP: iniciado '%s' → %s", self.lang, cmd[0])
|
|
647
|
+
return True
|
|
648
|
+
except (OSError, FileNotFoundError) as exc:
|
|
649
|
+
logger.debug("LSP: falha ao iniciar '%s': %s", self.lang, exc)
|
|
650
|
+
return False
|
|
651
|
+
|
|
652
|
+
def stop(self, grace: float = 1.0) -> None:
|
|
653
|
+
"""Para o servidor: pede o encerramento e, se não sair em ``grace`` s, mata a árvore.
|
|
654
|
+
|
|
655
|
+
O pedido de ``shutdown``/``exit`` é enfileirado para a thread escritora,
|
|
656
|
+
então um servidor travado nunca bloqueia quem chamou ``stop``.
|
|
657
|
+
|
|
658
|
+
Args:
|
|
659
|
+
grace: Segundos de espera pelo encerramento voluntário.
|
|
660
|
+
"""
|
|
661
|
+
proc = self._proc
|
|
662
|
+
if not proc or proc.poll() is not None:
|
|
663
|
+
return
|
|
664
|
+
self._shutdown = True
|
|
665
|
+
with self._pending_lock:
|
|
666
|
+
self._pending.clear()
|
|
667
|
+
self._send(LSPMessage.request(self._next_id(), "shutdown", None))
|
|
668
|
+
self._send(LSPMessage.notification("exit", None))
|
|
669
|
+
try:
|
|
670
|
+
proc.wait(timeout=grace)
|
|
671
|
+
except subprocess.TimeoutExpired:
|
|
672
|
+
_kill_process_tree(proc)
|
|
673
|
+
with contextlib.suppress(subprocess.TimeoutExpired, OSError):
|
|
674
|
+
proc.wait(timeout=2)
|
|
675
|
+
self._release_pipes(proc)
|
|
676
|
+
self._initialized = False
|
|
677
|
+
self._open_docs.clear()
|
|
678
|
+
|
|
679
|
+
def _release_pipes(self, proc: subprocess.Popen) -> None:
|
|
680
|
+
"""Fecha os pipes do servidor numa thread à parte para nunca bloquear a UI."""
|
|
681
|
+
self._outbox.put(None)
|
|
682
|
+
|
|
683
|
+
def _close() -> None:
|
|
684
|
+
for pipe in (proc.stdin, proc.stdout, proc.stderr):
|
|
685
|
+
if pipe is not None:
|
|
686
|
+
with contextlib.suppress(OSError, ValueError):
|
|
687
|
+
pipe.close()
|
|
688
|
+
|
|
689
|
+
threading.Thread(target=_close, daemon=True, name="lsp-close-pipes").start()
|
|
690
|
+
|
|
691
|
+
@property
|
|
692
|
+
def running(self) -> bool:
|
|
693
|
+
"""``True`` se o servidor está em execução e já respondeu ao initialize."""
|
|
694
|
+
return (
|
|
695
|
+
self._proc is not None and self._proc.poll() is None and self._initialized
|
|
696
|
+
)
|
|
697
|
+
|
|
698
|
+
@property
|
|
699
|
+
def starting(self) -> bool:
|
|
700
|
+
"""``True`` se o processo do servidor está ativo mas o initialize ainda não concluiu."""
|
|
701
|
+
return (
|
|
702
|
+
self._proc is not None
|
|
703
|
+
and self._proc.poll() is None
|
|
704
|
+
and not self._initialized
|
|
705
|
+
)
|
|
706
|
+
|
|
707
|
+
def wait_initialized(self, timeout: float = 8.0) -> bool:
|
|
708
|
+
"""Aguarda initialize (bloqueante - usar apenas em threads de background)."""
|
|
709
|
+
|
|
710
|
+
deadline = time.monotonic() + timeout
|
|
711
|
+
while time.monotonic() < deadline:
|
|
712
|
+
if self._initialized:
|
|
713
|
+
return True
|
|
714
|
+
if self._proc is None or self._proc.poll() is not None:
|
|
715
|
+
return False
|
|
716
|
+
time.sleep(0.05)
|
|
717
|
+
return self._initialized
|
|
718
|
+
|
|
719
|
+
def has_capability(self, *keys: str) -> bool:
|
|
720
|
+
"""Verifica se o servidor declarou uma capability aninhada."""
|
|
721
|
+
node: Any = self._capabilities
|
|
722
|
+
for k in keys:
|
|
723
|
+
if not isinstance(node, dict) or k not in node:
|
|
724
|
+
return False
|
|
725
|
+
node = node[k]
|
|
726
|
+
return bool(node)
|
|
727
|
+
|
|
728
|
+
def did_open(
|
|
729
|
+
self, path: Path, lang: str, content: str, *, diagnostics: bool = True
|
|
730
|
+
) -> None:
|
|
731
|
+
"""Notifica o servidor que um documento foi aberto (``textDocument/didOpen``)."""
|
|
732
|
+
uri = _path_to_uri(path)
|
|
733
|
+
lang_id = _LANG_ID_MAP.get(lang, lang)
|
|
734
|
+
notif = {
|
|
735
|
+
"method": "textDocument/didOpen",
|
|
736
|
+
"params": {
|
|
737
|
+
"textDocument": {
|
|
738
|
+
"uri": uri,
|
|
739
|
+
"languageId": lang_id,
|
|
740
|
+
"version": 1,
|
|
741
|
+
"text": content,
|
|
742
|
+
}
|
|
743
|
+
},
|
|
744
|
+
}
|
|
745
|
+
if not self._initialized:
|
|
746
|
+
self._pre_init_queue.append(notif)
|
|
747
|
+
self._open_docs[uri] = 1
|
|
748
|
+
return
|
|
749
|
+
self._open_docs[uri] = 1
|
|
750
|
+
self._send_notification(notif["method"], notif["params"])
|
|
751
|
+
|
|
752
|
+
if not diagnostics:
|
|
753
|
+
with contextlib.suppress(Exception):
|
|
754
|
+
self._send_notification(
|
|
755
|
+
"textDocument/didChange",
|
|
756
|
+
{"textDocument": {"uri": uri, "version": 1}, "contentChanges": []},
|
|
757
|
+
)
|
|
758
|
+
|
|
759
|
+
def did_change(self, path: Path, content: str) -> None:
|
|
760
|
+
"""Notifica o servidor sobre mudança de conteúdo (``textDocument/didChange``)."""
|
|
761
|
+
uri = _path_to_uri(path)
|
|
762
|
+
if not self._initialized:
|
|
763
|
+
# Servidor ainda subindo: o didOpen está na fila com o texto antigo.
|
|
764
|
+
for notif in self._pre_init_queue:
|
|
765
|
+
doc = notif["params"].get("textDocument", {})
|
|
766
|
+
if notif["method"] == "textDocument/didOpen" and doc.get("uri") == uri:
|
|
767
|
+
doc["text"] = content
|
|
768
|
+
return
|
|
769
|
+
if not self.running:
|
|
770
|
+
return
|
|
771
|
+
if uri not in self._open_docs:
|
|
772
|
+
# Documento aberto antes de o servidor reiniciar: reabre com o texto atual.
|
|
773
|
+
self.did_open(path, self.lang, content)
|
|
774
|
+
return
|
|
775
|
+
version = self._open_docs.get(uri, 0) + 1
|
|
776
|
+
self._open_docs[uri] = version
|
|
777
|
+
self._send_notification(
|
|
778
|
+
"textDocument/didChange",
|
|
779
|
+
{
|
|
780
|
+
"textDocument": {"uri": uri, "version": version},
|
|
781
|
+
"contentChanges": [{"text": content}],
|
|
782
|
+
},
|
|
783
|
+
)
|
|
784
|
+
|
|
785
|
+
def did_save(self, path: Path, content: str | None = None) -> None:
|
|
786
|
+
"""Notifica o servidor que o documento foi salvo (``textDocument/didSave``)."""
|
|
787
|
+
if not self.running:
|
|
788
|
+
return
|
|
789
|
+
uri = _path_to_uri(path)
|
|
790
|
+
if uri not in self._open_docs:
|
|
791
|
+
return
|
|
792
|
+
params: dict[str, Any] = {"textDocument": {"uri": uri}}
|
|
793
|
+
if content is not None:
|
|
794
|
+
params["text"] = content
|
|
795
|
+
self._send_notification("textDocument/didSave", params)
|
|
796
|
+
|
|
797
|
+
def did_close(self, path: Path) -> None:
|
|
798
|
+
"""Notifica o servidor que o documento foi fechado (``textDocument/didClose``)."""
|
|
799
|
+
uri = _path_to_uri(path)
|
|
800
|
+
was_open = self._open_docs.pop(uri, None) is not None
|
|
801
|
+
if not self._initialized:
|
|
802
|
+
self._pre_init_queue = [
|
|
803
|
+
n
|
|
804
|
+
for n in self._pre_init_queue
|
|
805
|
+
if n["params"].get("textDocument", {}).get("uri") != uri
|
|
806
|
+
]
|
|
807
|
+
return
|
|
808
|
+
if not self.running or not was_open:
|
|
809
|
+
return
|
|
810
|
+
self._send_notification("textDocument/didClose",
|
|
811
|
+
{"textDocument": {"uri": uri}})
|
|
812
|
+
|
|
813
|
+
def hover(
|
|
814
|
+
self, path: Path, line: int, col: int, callback: Callable[[Hover | None], None]
|
|
815
|
+
) -> None:
|
|
816
|
+
"""Solicita hover info ao servidor e entrega o resultado via ``callback``."""
|
|
817
|
+
if not self.running:
|
|
818
|
+
callback(None)
|
|
819
|
+
return
|
|
820
|
+
self._request(
|
|
821
|
+
"textDocument/hover",
|
|
822
|
+
{
|
|
823
|
+
"textDocument": {"uri": _path_to_uri(path)},
|
|
824
|
+
"position": {"line": line, "character": col},
|
|
825
|
+
},
|
|
826
|
+
lambda r: callback(Hover.from_dict(r) if r else None),
|
|
827
|
+
)
|
|
828
|
+
|
|
829
|
+
def completion(
|
|
830
|
+
self,
|
|
831
|
+
path: Path,
|
|
832
|
+
line: int,
|
|
833
|
+
col: int,
|
|
834
|
+
trigger: str | None,
|
|
835
|
+
callback: Callable[[list[CompletionItem]], None],
|
|
836
|
+
) -> None:
|
|
837
|
+
"""Solicita itens de completion e entrega a lista via ``callback``."""
|
|
838
|
+
if not self.running:
|
|
839
|
+
callback([])
|
|
840
|
+
return
|
|
841
|
+
ctx: dict[str, Any] = (
|
|
842
|
+
{"triggerKind": 2, "triggerCharacter": trigger}
|
|
843
|
+
if trigger
|
|
844
|
+
else {"triggerKind": 1}
|
|
845
|
+
)
|
|
846
|
+
self._request(
|
|
847
|
+
"textDocument/completion",
|
|
848
|
+
{
|
|
849
|
+
"textDocument": {"uri": _path_to_uri(path)},
|
|
850
|
+
"position": {"line": line, "character": col},
|
|
851
|
+
"context": ctx,
|
|
852
|
+
},
|
|
853
|
+
lambda r: callback(self._parse_completion(r)),
|
|
854
|
+
)
|
|
855
|
+
|
|
856
|
+
def _position_request(
|
|
857
|
+
self,
|
|
858
|
+
method: str,
|
|
859
|
+
capability: str | None,
|
|
860
|
+
path: Path,
|
|
861
|
+
line: int,
|
|
862
|
+
col: int,
|
|
863
|
+
callback: Callable[[Any], None],
|
|
864
|
+
parse: Callable[[Any], Any],
|
|
865
|
+
) -> None:
|
|
866
|
+
"""Pedido LSP sobre uma posição do documento.
|
|
867
|
+
|
|
868
|
+
Sem o servidor ativo (ou sem a ``capability`` anunciada) responde com o
|
|
869
|
+
resultado vazio de ``parse(None)`` em vez de enviar o pedido.
|
|
870
|
+
"""
|
|
871
|
+
if not self.running or (capability and not self.has_capability(capability)):
|
|
872
|
+
callback(parse(None))
|
|
873
|
+
return
|
|
874
|
+
self._request(
|
|
875
|
+
method,
|
|
876
|
+
{
|
|
877
|
+
"textDocument": {"uri": _path_to_uri(path)},
|
|
878
|
+
"position": {"line": line, "character": col},
|
|
879
|
+
},
|
|
880
|
+
lambda r: callback(parse(r)),
|
|
881
|
+
)
|
|
882
|
+
|
|
883
|
+
@staticmethod
|
|
884
|
+
def _items_of(kind: Any) -> Callable[[Any], list]:
|
|
885
|
+
"""Parser de listas de itens ``kind.from_dict`` (resultado ``None`` vira ``[]``)."""
|
|
886
|
+
return lambda r: [kind.from_dict(i) for i in r] if r else []
|
|
887
|
+
|
|
888
|
+
def goto_definition(
|
|
889
|
+
self,
|
|
890
|
+
path: Path,
|
|
891
|
+
line: int,
|
|
892
|
+
col: int,
|
|
893
|
+
callback: Callable[[list[Location]], None],
|
|
894
|
+
) -> None:
|
|
895
|
+
"""Solicita ao LSP a definição do símbolo na posição dada."""
|
|
896
|
+
self._position_request(
|
|
897
|
+
"textDocument/definition", None, path, line, col, callback, self._parse_locations
|
|
898
|
+
)
|
|
899
|
+
|
|
900
|
+
def goto_declaration(
|
|
901
|
+
self,
|
|
902
|
+
path: Path,
|
|
903
|
+
line: int,
|
|
904
|
+
col: int,
|
|
905
|
+
callback: Callable[[list[Location]], None],
|
|
906
|
+
) -> None:
|
|
907
|
+
"""Solicita ao LSP a declaração do símbolo na posição dada."""
|
|
908
|
+
self._position_request(
|
|
909
|
+
"textDocument/declaration", 'declarationProvider', path, line, col, callback, self._parse_locations
|
|
910
|
+
)
|
|
911
|
+
|
|
912
|
+
def goto_type_definition(
|
|
913
|
+
self,
|
|
914
|
+
path: Path,
|
|
915
|
+
line: int,
|
|
916
|
+
col: int,
|
|
917
|
+
callback: Callable[[list[Location]], None],
|
|
918
|
+
) -> None:
|
|
919
|
+
"""Solicita ao LSP o tipo do símbolo na posição dada."""
|
|
920
|
+
self._position_request(
|
|
921
|
+
"textDocument/typeDefinition", 'typeDefinitionProvider', path, line, col, callback, self._parse_locations
|
|
922
|
+
)
|
|
923
|
+
|
|
924
|
+
def goto_implementation(
|
|
925
|
+
self,
|
|
926
|
+
path: Path,
|
|
927
|
+
line: int,
|
|
928
|
+
col: int,
|
|
929
|
+
callback: Callable[[list[Location]], None],
|
|
930
|
+
) -> None:
|
|
931
|
+
"""Solicita ao LSP as implementações do símbolo na posição dada."""
|
|
932
|
+
self._position_request(
|
|
933
|
+
"textDocument/implementation", 'implementationProvider', path, line, col, callback, self._parse_locations
|
|
934
|
+
)
|
|
935
|
+
|
|
936
|
+
def find_references(
|
|
937
|
+
self,
|
|
938
|
+
path: Path,
|
|
939
|
+
line: int,
|
|
940
|
+
col: int,
|
|
941
|
+
callback: Callable[[list[Location]], None],
|
|
942
|
+
) -> None:
|
|
943
|
+
"""Solicita ao LSP todas as referências do símbolo na posição dada."""
|
|
944
|
+
if not self.running:
|
|
945
|
+
callback([])
|
|
946
|
+
return
|
|
947
|
+
self._request(
|
|
948
|
+
"textDocument/references",
|
|
949
|
+
{
|
|
950
|
+
"textDocument": {"uri": _path_to_uri(path)},
|
|
951
|
+
"position": {"line": line, "character": col},
|
|
952
|
+
"context": {"includeDeclaration": True},
|
|
953
|
+
},
|
|
954
|
+
lambda r: callback(self._parse_locations(r)),
|
|
955
|
+
)
|
|
956
|
+
|
|
957
|
+
def signature_help(
|
|
958
|
+
self,
|
|
959
|
+
path: Path,
|
|
960
|
+
line: int,
|
|
961
|
+
col: int,
|
|
962
|
+
callback: Callable[[SignatureHelp | None], None],
|
|
963
|
+
) -> None:
|
|
964
|
+
"""Solicita ao LSP a assinatura da função na posição do cursor."""
|
|
965
|
+
if not self.running:
|
|
966
|
+
callback(None)
|
|
967
|
+
return
|
|
968
|
+
self._request(
|
|
969
|
+
"textDocument/signatureHelp",
|
|
970
|
+
{
|
|
971
|
+
"textDocument": {"uri": _path_to_uri(path)},
|
|
972
|
+
"position": {"line": line, "character": col},
|
|
973
|
+
},
|
|
974
|
+
lambda r: callback(SignatureHelp.from_dict(r) if r else None),
|
|
975
|
+
)
|
|
976
|
+
|
|
977
|
+
def document_symbols(
|
|
978
|
+
self, path: Path, callback: Callable[[list[DocumentSymbol]], None]
|
|
979
|
+
) -> None:
|
|
980
|
+
"""Solicita ao LSP todos os símbolos do documento aberto."""
|
|
981
|
+
if not self.running:
|
|
982
|
+
callback([])
|
|
983
|
+
return
|
|
984
|
+
|
|
985
|
+
def _parse(r: Any) -> None:
|
|
986
|
+
if not r:
|
|
987
|
+
callback([])
|
|
988
|
+
return
|
|
989
|
+
callback([DocumentSymbol.from_dict(s) for s in r])
|
|
990
|
+
|
|
991
|
+
self._request(
|
|
992
|
+
"textDocument/documentSymbol",
|
|
993
|
+
{"textDocument": {"uri": _path_to_uri(path)}},
|
|
994
|
+
_parse,
|
|
995
|
+
)
|
|
996
|
+
|
|
997
|
+
def workspace_symbol(
|
|
998
|
+
self, query: str, callback: Callable[[list[dict]], None]
|
|
999
|
+
) -> None:
|
|
1000
|
+
"""Pesquisa símbolos no workspace inteiro com o termo fornecido."""
|
|
1001
|
+
if not self.running:
|
|
1002
|
+
callback([])
|
|
1003
|
+
return
|
|
1004
|
+
self._request("workspace/symbol",
|
|
1005
|
+
{"query": query}, lambda r: callback(r or []))
|
|
1006
|
+
|
|
1007
|
+
def formatting(
|
|
1008
|
+
self,
|
|
1009
|
+
path: Path,
|
|
1010
|
+
tab_size: int,
|
|
1011
|
+
insert_spaces: bool,
|
|
1012
|
+
callback: Callable[[list[TextEdit]], None],
|
|
1013
|
+
) -> None:
|
|
1014
|
+
"""Solicita ao LSP a formatação completa do documento."""
|
|
1015
|
+
if not self.running:
|
|
1016
|
+
callback([])
|
|
1017
|
+
return
|
|
1018
|
+
|
|
1019
|
+
def _parse(r: Any) -> None:
|
|
1020
|
+
callback([TextEdit.from_dict(e) for e in r] if r else [])
|
|
1021
|
+
|
|
1022
|
+
self._request(
|
|
1023
|
+
"textDocument/formatting",
|
|
1024
|
+
{
|
|
1025
|
+
"textDocument": {"uri": _path_to_uri(path)},
|
|
1026
|
+
"options": {
|
|
1027
|
+
"tabSize": tab_size,
|
|
1028
|
+
"insertSpaces": insert_spaces,
|
|
1029
|
+
"trimTrailingWhitespace": True,
|
|
1030
|
+
"insertFinalNewline": True,
|
|
1031
|
+
},
|
|
1032
|
+
},
|
|
1033
|
+
_parse,
|
|
1034
|
+
)
|
|
1035
|
+
|
|
1036
|
+
def range_formatting(
|
|
1037
|
+
self,
|
|
1038
|
+
path: Path,
|
|
1039
|
+
rng: Range,
|
|
1040
|
+
tab_size: int,
|
|
1041
|
+
insert_spaces: bool,
|
|
1042
|
+
callback: Callable[[list[TextEdit]], None],
|
|
1043
|
+
) -> None:
|
|
1044
|
+
"""Solicita ao LSP a formatação de um intervalo do documento."""
|
|
1045
|
+
if not self.running or not self.has_capability(
|
|
1046
|
+
"documentRangeFormattingProvider"
|
|
1047
|
+
):
|
|
1048
|
+
callback([])
|
|
1049
|
+
return
|
|
1050
|
+
|
|
1051
|
+
def _parse(r: Any) -> None:
|
|
1052
|
+
callback([TextEdit.from_dict(e) for e in r] if r else [])
|
|
1053
|
+
|
|
1054
|
+
self._request(
|
|
1055
|
+
"textDocument/rangeFormatting",
|
|
1056
|
+
{
|
|
1057
|
+
"textDocument": {"uri": _path_to_uri(path)},
|
|
1058
|
+
"range": rng.to_dict(),
|
|
1059
|
+
"options": {"tabSize": tab_size, "insertSpaces": insert_spaces},
|
|
1060
|
+
},
|
|
1061
|
+
_parse,
|
|
1062
|
+
)
|
|
1063
|
+
|
|
1064
|
+
def prepare_rename(
|
|
1065
|
+
self,
|
|
1066
|
+
path: Path,
|
|
1067
|
+
line: int,
|
|
1068
|
+
col: int,
|
|
1069
|
+
callback: Callable[[PrepareRenameResult | None], None],
|
|
1070
|
+
) -> None:
|
|
1071
|
+
"""Verifica se o símbolo na posição pode ser renomeado via LSP."""
|
|
1072
|
+
if not self.running:
|
|
1073
|
+
callback(None)
|
|
1074
|
+
return
|
|
1075
|
+
self._request(
|
|
1076
|
+
"textDocument/prepareRename",
|
|
1077
|
+
{
|
|
1078
|
+
"textDocument": {"uri": _path_to_uri(path)},
|
|
1079
|
+
"position": {"line": line, "character": col},
|
|
1080
|
+
},
|
|
1081
|
+
lambda r: callback(
|
|
1082
|
+
PrepareRenameResult.from_dict(r) if r else None),
|
|
1083
|
+
)
|
|
1084
|
+
|
|
1085
|
+
def rename(
|
|
1086
|
+
self,
|
|
1087
|
+
path: Path,
|
|
1088
|
+
line: int,
|
|
1089
|
+
col: int,
|
|
1090
|
+
new_name: str,
|
|
1091
|
+
callback: Callable[[WorkspaceEdit | None], None],
|
|
1092
|
+
) -> None:
|
|
1093
|
+
"""Solicita ao LSP a renomeação do símbolo para o novo nome."""
|
|
1094
|
+
if not self.running:
|
|
1095
|
+
callback(None)
|
|
1096
|
+
return
|
|
1097
|
+
self._request(
|
|
1098
|
+
"textDocument/rename",
|
|
1099
|
+
{
|
|
1100
|
+
"textDocument": {"uri": _path_to_uri(path)},
|
|
1101
|
+
"position": {"line": line, "character": col},
|
|
1102
|
+
"newName": new_name,
|
|
1103
|
+
},
|
|
1104
|
+
lambda r: callback(WorkspaceEdit.from_dict(r) if r else None),
|
|
1105
|
+
)
|
|
1106
|
+
|
|
1107
|
+
def code_action(
|
|
1108
|
+
self,
|
|
1109
|
+
path: Path,
|
|
1110
|
+
rng: Range,
|
|
1111
|
+
diagnostics: list[dict],
|
|
1112
|
+
callback: Callable[[list[CodeAction]], None],
|
|
1113
|
+
only: list[str] | None = None,
|
|
1114
|
+
) -> None:
|
|
1115
|
+
"""Solicita code actions (quick fix, refactor, etc.) para o range."""
|
|
1116
|
+
if not self.running or not self.has_capability("codeActionProvider"):
|
|
1117
|
+
callback([])
|
|
1118
|
+
return
|
|
1119
|
+
params: dict[str, Any] = {
|
|
1120
|
+
"textDocument": {"uri": _path_to_uri(path)},
|
|
1121
|
+
"range": rng.to_dict(),
|
|
1122
|
+
"context": {"diagnostics": diagnostics},
|
|
1123
|
+
}
|
|
1124
|
+
if only:
|
|
1125
|
+
params["context"]["only"] = only
|
|
1126
|
+
|
|
1127
|
+
def _parse(r: Any) -> None:
|
|
1128
|
+
if not r:
|
|
1129
|
+
callback([])
|
|
1130
|
+
return
|
|
1131
|
+
actions: list[CodeAction] = []
|
|
1132
|
+
for item in r:
|
|
1133
|
+
if isinstance(item, dict):
|
|
1134
|
+
if "command" in item and "title" in item and "kind" not in item:
|
|
1135
|
+
actions.append(
|
|
1136
|
+
CodeAction(
|
|
1137
|
+
title=item.get("title", ""),
|
|
1138
|
+
kind="",
|
|
1139
|
+
command=item,
|
|
1140
|
+
)
|
|
1141
|
+
)
|
|
1142
|
+
else:
|
|
1143
|
+
actions.append(CodeAction.from_dict(item))
|
|
1144
|
+
callback(actions)
|
|
1145
|
+
|
|
1146
|
+
self._request("textDocument/codeAction", params, _parse)
|
|
1147
|
+
|
|
1148
|
+
def document_highlight(
|
|
1149
|
+
self,
|
|
1150
|
+
path: Path,
|
|
1151
|
+
line: int,
|
|
1152
|
+
col: int,
|
|
1153
|
+
callback: Callable[[list[DocumentHighlight]], None],
|
|
1154
|
+
) -> None:
|
|
1155
|
+
"""Destaca todas as ocorrências do símbolo sob o cursor no documento."""
|
|
1156
|
+
self._position_request(
|
|
1157
|
+
"textDocument/documentHighlight", 'documentHighlightProvider', path, line, col, callback, self._items_of(DocumentHighlight)
|
|
1158
|
+
)
|
|
1159
|
+
|
|
1160
|
+
def folding_ranges(
|
|
1161
|
+
self, path: Path, callback: Callable[[list[FoldingRange]], None]
|
|
1162
|
+
) -> None:
|
|
1163
|
+
"""Solicita folding ranges via LSP (mais preciso que heurística regex)."""
|
|
1164
|
+
if not self.running or not self.has_capability("foldingRangeProvider"):
|
|
1165
|
+
callback([])
|
|
1166
|
+
return
|
|
1167
|
+
|
|
1168
|
+
def _parse(r: Any) -> None:
|
|
1169
|
+
callback([FoldingRange.from_dict(f) for f in r] if r else [])
|
|
1170
|
+
|
|
1171
|
+
self._request(
|
|
1172
|
+
"textDocument/foldingRange",
|
|
1173
|
+
{"textDocument": {"uri": _path_to_uri(path)}},
|
|
1174
|
+
_parse,
|
|
1175
|
+
)
|
|
1176
|
+
|
|
1177
|
+
def inlay_hints(
|
|
1178
|
+
self, path: Path, rng: Range, callback: Callable[[list[InlayHint]], None]
|
|
1179
|
+
) -> None:
|
|
1180
|
+
"""Solicita inlay hints para o range visível do documento."""
|
|
1181
|
+
if not self.running or not self.has_capability("inlayHintProvider"):
|
|
1182
|
+
callback([])
|
|
1183
|
+
return
|
|
1184
|
+
|
|
1185
|
+
def _parse(r: Any) -> None:
|
|
1186
|
+
callback([InlayHint.from_dict(h) for h in r] if r else [])
|
|
1187
|
+
|
|
1188
|
+
self._request(
|
|
1189
|
+
"textDocument/inlayHint",
|
|
1190
|
+
{
|
|
1191
|
+
"textDocument": {"uri": _path_to_uri(path)},
|
|
1192
|
+
"range": rng.to_dict(),
|
|
1193
|
+
},
|
|
1194
|
+
_parse,
|
|
1195
|
+
)
|
|
1196
|
+
|
|
1197
|
+
def semantic_tokens(
|
|
1198
|
+
self, path: Path, callback: Callable[[list[dict]], None]
|
|
1199
|
+
) -> None:
|
|
1200
|
+
"""Solicita semantic tokens completos (colorização semântica)."""
|
|
1201
|
+
if not self.running or not self.has_capability("semanticTokensProvider"):
|
|
1202
|
+
callback([])
|
|
1203
|
+
return
|
|
1204
|
+
types = self._semantic_legend.get("tokenTypes", [])
|
|
1205
|
+
mods = self._semantic_legend.get("tokenModifiers", [])
|
|
1206
|
+
|
|
1207
|
+
def _parse(r: Any) -> None:
|
|
1208
|
+
if not r:
|
|
1209
|
+
callback([])
|
|
1210
|
+
return
|
|
1211
|
+
callback(SemanticTokens.from_dict(r).decode(types, mods))
|
|
1212
|
+
|
|
1213
|
+
self._request(
|
|
1214
|
+
"textDocument/semanticTokens/full",
|
|
1215
|
+
{"textDocument": {"uri": _path_to_uri(path)}},
|
|
1216
|
+
_parse,
|
|
1217
|
+
)
|
|
1218
|
+
|
|
1219
|
+
def prepare_call_hierarchy(
|
|
1220
|
+
self,
|
|
1221
|
+
path: Path,
|
|
1222
|
+
line: int,
|
|
1223
|
+
col: int,
|
|
1224
|
+
callback: Callable[[list[CallHierarchyItem]], None],
|
|
1225
|
+
) -> None:
|
|
1226
|
+
"""Prepara a hierarquia de chamadas do símbolo na posição dada."""
|
|
1227
|
+
self._position_request(
|
|
1228
|
+
"textDocument/prepareCallHierarchy", 'callHierarchyProvider', path, line, col, callback, self._items_of(CallHierarchyItem)
|
|
1229
|
+
)
|
|
1230
|
+
|
|
1231
|
+
def incoming_calls(
|
|
1232
|
+
self,
|
|
1233
|
+
item: CallHierarchyItem,
|
|
1234
|
+
callback: Callable[[list[CallHierarchyCall]], None],
|
|
1235
|
+
) -> None:
|
|
1236
|
+
"""Obtém as chamadas entrantes na hierarquia de chamadas LSP."""
|
|
1237
|
+
if not self.running:
|
|
1238
|
+
callback([])
|
|
1239
|
+
return
|
|
1240
|
+
raw = {
|
|
1241
|
+
"name": item.name,
|
|
1242
|
+
"kind": item.kind,
|
|
1243
|
+
"uri": item.uri,
|
|
1244
|
+
"range": item.range.to_dict(),
|
|
1245
|
+
"selectionRange": item.selection_range.to_dict(),
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
def _parse(r: Any) -> None:
|
|
1249
|
+
callback([CallHierarchyCall.from_incoming(c)
|
|
1250
|
+
for c in r] if r else [])
|
|
1251
|
+
|
|
1252
|
+
self._request("callHierarchy/incomingCalls", {"item": raw}, _parse)
|
|
1253
|
+
|
|
1254
|
+
def outgoing_calls(
|
|
1255
|
+
self,
|
|
1256
|
+
item: CallHierarchyItem,
|
|
1257
|
+
callback: Callable[[list[CallHierarchyCall]], None],
|
|
1258
|
+
) -> None:
|
|
1259
|
+
"""Obtém as chamadas saintes na hierarquia de chamadas LSP."""
|
|
1260
|
+
if not self.running:
|
|
1261
|
+
callback([])
|
|
1262
|
+
return
|
|
1263
|
+
raw = {
|
|
1264
|
+
"name": item.name,
|
|
1265
|
+
"kind": item.kind,
|
|
1266
|
+
"uri": item.uri,
|
|
1267
|
+
"range": item.range.to_dict(),
|
|
1268
|
+
"selectionRange": item.selection_range.to_dict(),
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
def _parse(r: Any) -> None:
|
|
1272
|
+
callback([CallHierarchyCall.from_outgoing(c)
|
|
1273
|
+
for c in r] if r else [])
|
|
1274
|
+
|
|
1275
|
+
self._request("callHierarchy/outgoingCalls", {"item": raw}, _parse)
|
|
1276
|
+
|
|
1277
|
+
def prepare_type_hierarchy(
|
|
1278
|
+
self,
|
|
1279
|
+
path: Path,
|
|
1280
|
+
line: int,
|
|
1281
|
+
col: int,
|
|
1282
|
+
callback: Callable[[list[TypeHierarchyItem]], None],
|
|
1283
|
+
) -> None:
|
|
1284
|
+
"""Prepara a hierarquia de tipos do símbolo na posição dada."""
|
|
1285
|
+
self._position_request(
|
|
1286
|
+
"textDocument/prepareTypeHierarchy", 'typeHierarchyProvider', path, line, col, callback, self._items_of(TypeHierarchyItem)
|
|
1287
|
+
)
|
|
1288
|
+
|
|
1289
|
+
def supertypes(
|
|
1290
|
+
self,
|
|
1291
|
+
item: TypeHierarchyItem,
|
|
1292
|
+
callback: Callable[[list[TypeHierarchyItem]], None],
|
|
1293
|
+
) -> None:
|
|
1294
|
+
"""Obtém os supertypes do item na hierarquia de tipos LSP."""
|
|
1295
|
+
if not self.running:
|
|
1296
|
+
callback([])
|
|
1297
|
+
return
|
|
1298
|
+
raw = {
|
|
1299
|
+
"name": item.name,
|
|
1300
|
+
"kind": item.kind,
|
|
1301
|
+
"uri": item.uri,
|
|
1302
|
+
"range": item.range.to_dict(),
|
|
1303
|
+
"selectionRange": item.selection_range.to_dict(),
|
|
1304
|
+
}
|
|
1305
|
+
|
|
1306
|
+
def _parse(r: Any) -> None:
|
|
1307
|
+
callback([TypeHierarchyItem.from_dict(i) for i in r] if r else [])
|
|
1308
|
+
|
|
1309
|
+
self._request("typeHierarchy/supertypes", {"item": raw}, _parse)
|
|
1310
|
+
|
|
1311
|
+
def subtypes(
|
|
1312
|
+
self,
|
|
1313
|
+
item: TypeHierarchyItem,
|
|
1314
|
+
callback: Callable[[list[TypeHierarchyItem]], None],
|
|
1315
|
+
) -> None:
|
|
1316
|
+
"""Obtém os subtypes do item na hierarquia de tipos LSP."""
|
|
1317
|
+
if not self.running:
|
|
1318
|
+
callback([])
|
|
1319
|
+
return
|
|
1320
|
+
raw = {
|
|
1321
|
+
"name": item.name,
|
|
1322
|
+
"kind": item.kind,
|
|
1323
|
+
"uri": item.uri,
|
|
1324
|
+
"range": item.range.to_dict(),
|
|
1325
|
+
"selectionRange": item.selection_range.to_dict(),
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
def _parse(r: Any) -> None:
|
|
1329
|
+
callback([TypeHierarchyItem.from_dict(i) for i in r] if r else [])
|
|
1330
|
+
|
|
1331
|
+
self._request("typeHierarchy/subtypes", {"item": raw}, _parse)
|
|
1332
|
+
|
|
1333
|
+
def execute_command(
|
|
1334
|
+
self,
|
|
1335
|
+
command: str,
|
|
1336
|
+
arguments: list | None,
|
|
1337
|
+
callback: Callable[[Any], None] | None = None,
|
|
1338
|
+
) -> None:
|
|
1339
|
+
"""Executa um comando arbitrário do servidor."""
|
|
1340
|
+
if not self.running:
|
|
1341
|
+
if callback:
|
|
1342
|
+
callback(None)
|
|
1343
|
+
return
|
|
1344
|
+
params: dict[str, Any] = {"command": command}
|
|
1345
|
+
if arguments is not None:
|
|
1346
|
+
params["arguments"] = arguments
|
|
1347
|
+
self._request("workspace/executeCommand", params,
|
|
1348
|
+
callback or (lambda _: None))
|
|
1349
|
+
|
|
1350
|
+
def _next_id(self) -> int:
|
|
1351
|
+
with self._id_lock:
|
|
1352
|
+
self._id += 1
|
|
1353
|
+
return self._id
|
|
1354
|
+
|
|
1355
|
+
def _send(self, data: dict) -> None:
|
|
1356
|
+
if not self._proc or self._proc.poll() is not None:
|
|
1357
|
+
return
|
|
1358
|
+
self._outbox.put(encode_frame(data))
|
|
1359
|
+
|
|
1360
|
+
@staticmethod
|
|
1361
|
+
def _writer_loop(proc: subprocess.Popen, outbox: queue.Queue) -> None:
|
|
1362
|
+
"""Grava as mensagens enfileiradas no stdin do servidor, em ordem.
|
|
1363
|
+
|
|
1364
|
+
Roda em thread própria porque ``write`` bloqueia quando o servidor para
|
|
1365
|
+
de ler e o pipe enche, o que congelaria a interface se fosse feito nela.
|
|
1366
|
+
"""
|
|
1367
|
+
while True:
|
|
1368
|
+
payload = outbox.get()
|
|
1369
|
+
if payload is None or proc.poll() is not None:
|
|
1370
|
+
return
|
|
1371
|
+
try:
|
|
1372
|
+
proc.stdin.write(payload)
|
|
1373
|
+
proc.stdin.flush()
|
|
1374
|
+
except (BrokenPipeError, AttributeError, OSError, ValueError):
|
|
1375
|
+
return
|
|
1376
|
+
|
|
1377
|
+
def _request(self, method: str, params: Any, callback: Callable) -> int:
|
|
1378
|
+
rid = self._next_id()
|
|
1379
|
+
with self._pending_lock:
|
|
1380
|
+
self._pending[rid] = callback
|
|
1381
|
+
self._send(LSPMessage.request(rid, method, params))
|
|
1382
|
+
return rid
|
|
1383
|
+
|
|
1384
|
+
def _send_notification(self, method: str, params: Any = None) -> None:
|
|
1385
|
+
self._send(LSPMessage.notification(method, params))
|
|
1386
|
+
|
|
1387
|
+
def _send_initialize(self) -> None:
|
|
1388
|
+
"""Envia a mensagem initialize com capabilities completas (LSP 3.17)."""
|
|
1389
|
+
root_uri = _path_to_uri(self.root_path) if self.root_path else None
|
|
1390
|
+
rid = self._next_id()
|
|
1391
|
+
with self._pending_lock:
|
|
1392
|
+
self._pending[rid] = self._on_initialized
|
|
1393
|
+
self._send(
|
|
1394
|
+
LSPMessage.request(
|
|
1395
|
+
rid,
|
|
1396
|
+
"initialize",
|
|
1397
|
+
{
|
|
1398
|
+
"processId": os.getpid(),
|
|
1399
|
+
"clientInfo": {"name": "Codis", "version": APP_VERSION},
|
|
1400
|
+
"rootUri": root_uri,
|
|
1401
|
+
"workspaceFolders": (
|
|
1402
|
+
[
|
|
1403
|
+
{
|
|
1404
|
+
"uri": root_uri,
|
|
1405
|
+
"name": self.root_path.name if self.root_path else "",
|
|
1406
|
+
}
|
|
1407
|
+
]
|
|
1408
|
+
if root_uri
|
|
1409
|
+
else None
|
|
1410
|
+
),
|
|
1411
|
+
"capabilities": {
|
|
1412
|
+
"general": {
|
|
1413
|
+
"positionEncodings": ["utf-16"],
|
|
1414
|
+
},
|
|
1415
|
+
"textDocument": {
|
|
1416
|
+
"synchronization": {
|
|
1417
|
+
"dynamicRegistration": False,
|
|
1418
|
+
"willSave": False,
|
|
1419
|
+
"willSaveWaitUntil": False,
|
|
1420
|
+
"didSave": True,
|
|
1421
|
+
},
|
|
1422
|
+
"completion": {
|
|
1423
|
+
"dynamicRegistration": False,
|
|
1424
|
+
"completionItem": {
|
|
1425
|
+
"snippetSupport": True,
|
|
1426
|
+
"commitCharactersSupport": True,
|
|
1427
|
+
"documentationFormat": ["markdown", "plaintext"],
|
|
1428
|
+
"deprecatedSupport": True,
|
|
1429
|
+
"preselectSupport": True,
|
|
1430
|
+
"tagSupport": {"valueSet": [1]},
|
|
1431
|
+
"insertReplaceSupport": True,
|
|
1432
|
+
"resolveSupport": {
|
|
1433
|
+
"properties": [
|
|
1434
|
+
"documentation",
|
|
1435
|
+
"detail",
|
|
1436
|
+
"additionalTextEdits",
|
|
1437
|
+
]
|
|
1438
|
+
},
|
|
1439
|
+
"labelDetailsSupport": True,
|
|
1440
|
+
},
|
|
1441
|
+
"completionItemKind": {"valueSet": list(range(1, 26))},
|
|
1442
|
+
"contextSupport": True,
|
|
1443
|
+
"completionList": {
|
|
1444
|
+
"itemDefaults": [
|
|
1445
|
+
"editRange",
|
|
1446
|
+
"insertTextFormat",
|
|
1447
|
+
"data",
|
|
1448
|
+
]
|
|
1449
|
+
},
|
|
1450
|
+
},
|
|
1451
|
+
"hover": {
|
|
1452
|
+
"dynamicRegistration": False,
|
|
1453
|
+
"contentFormat": ["markdown", "plaintext"],
|
|
1454
|
+
},
|
|
1455
|
+
"signatureHelp": {
|
|
1456
|
+
"dynamicRegistration": False,
|
|
1457
|
+
"signatureInformation": {
|
|
1458
|
+
"documentationFormat": ["markdown", "plaintext"],
|
|
1459
|
+
"parameterInformation": {
|
|
1460
|
+
"labelOffsetSupport": True
|
|
1461
|
+
},
|
|
1462
|
+
"activeParameterSupport": True,
|
|
1463
|
+
},
|
|
1464
|
+
"contextSupport": True,
|
|
1465
|
+
},
|
|
1466
|
+
"definition": {
|
|
1467
|
+
"dynamicRegistration": False,
|
|
1468
|
+
"linkSupport": True,
|
|
1469
|
+
},
|
|
1470
|
+
"declaration": {
|
|
1471
|
+
"dynamicRegistration": False,
|
|
1472
|
+
"linkSupport": True,
|
|
1473
|
+
},
|
|
1474
|
+
"typeDefinition": {
|
|
1475
|
+
"dynamicRegistration": False,
|
|
1476
|
+
"linkSupport": True,
|
|
1477
|
+
},
|
|
1478
|
+
"implementation": {
|
|
1479
|
+
"dynamicRegistration": False,
|
|
1480
|
+
"linkSupport": True,
|
|
1481
|
+
},
|
|
1482
|
+
"references": {"dynamicRegistration": False},
|
|
1483
|
+
"documentHighlight": {"dynamicRegistration": False},
|
|
1484
|
+
"documentSymbol": {
|
|
1485
|
+
"dynamicRegistration": False,
|
|
1486
|
+
"symbolKind": {"valueSet": list(range(1, 27))},
|
|
1487
|
+
"hierarchicalDocumentSymbolSupport": True,
|
|
1488
|
+
"tagSupport": {"valueSet": [1]},
|
|
1489
|
+
"labelSupport": True,
|
|
1490
|
+
},
|
|
1491
|
+
"codeAction": {
|
|
1492
|
+
"dynamicRegistration": False,
|
|
1493
|
+
"codeActionLiteralSupport": {
|
|
1494
|
+
"codeActionKind": {
|
|
1495
|
+
"valueSet": [
|
|
1496
|
+
"",
|
|
1497
|
+
"quickfix",
|
|
1498
|
+
"refactor",
|
|
1499
|
+
"refactor.extract",
|
|
1500
|
+
"refactor.inline",
|
|
1501
|
+
"refactor.rewrite",
|
|
1502
|
+
"source",
|
|
1503
|
+
"source.organizeImports",
|
|
1504
|
+
"source.fixAll",
|
|
1505
|
+
]
|
|
1506
|
+
},
|
|
1507
|
+
},
|
|
1508
|
+
"isPreferredSupport": True,
|
|
1509
|
+
"resolveSupport": {"properties": ["edit"]},
|
|
1510
|
+
},
|
|
1511
|
+
"formatting": {"dynamicRegistration": False},
|
|
1512
|
+
"rangeFormatting": {"dynamicRegistration": False},
|
|
1513
|
+
"rename": {
|
|
1514
|
+
"dynamicRegistration": False,
|
|
1515
|
+
"prepareSupport": True,
|
|
1516
|
+
"prepareSupportDefaultBehavior": 1,
|
|
1517
|
+
"honorsChangeAnnotations": False,
|
|
1518
|
+
},
|
|
1519
|
+
"foldingRange": {
|
|
1520
|
+
"dynamicRegistration": False,
|
|
1521
|
+
"rangeLimit": 5000,
|
|
1522
|
+
"lineFoldingOnly": True,
|
|
1523
|
+
},
|
|
1524
|
+
"semanticTokens": {
|
|
1525
|
+
"dynamicRegistration": False,
|
|
1526
|
+
"requests": {"full": True, "range": False},
|
|
1527
|
+
"tokenTypes": SEMANTIC_TOKEN_TYPES,
|
|
1528
|
+
"tokenModifiers": SEMANTIC_TOKEN_MODIFIERS,
|
|
1529
|
+
"formats": ["relative"],
|
|
1530
|
+
"overlappingTokenSupport": False,
|
|
1531
|
+
"multilineTokenSupport": False,
|
|
1532
|
+
},
|
|
1533
|
+
"inlayHint": {
|
|
1534
|
+
"dynamicRegistration": False,
|
|
1535
|
+
"resolveSupport": {
|
|
1536
|
+
"properties": [
|
|
1537
|
+
"tooltip",
|
|
1538
|
+
"textEdits",
|
|
1539
|
+
"label.tooltip",
|
|
1540
|
+
"label.location",
|
|
1541
|
+
]
|
|
1542
|
+
},
|
|
1543
|
+
},
|
|
1544
|
+
"callHierarchy": {"dynamicRegistration": False},
|
|
1545
|
+
"typeHierarchy": {"dynamicRegistration": False},
|
|
1546
|
+
"linkedEditingRange": {"dynamicRegistration": False},
|
|
1547
|
+
"publishDiagnostics": {
|
|
1548
|
+
"relatedInformation": True,
|
|
1549
|
+
"versionSupport": True,
|
|
1550
|
+
"tagSupport": {"valueSet": [1, 2]},
|
|
1551
|
+
"codeDescriptionSupport": True,
|
|
1552
|
+
"dataSupport": True,
|
|
1553
|
+
},
|
|
1554
|
+
},
|
|
1555
|
+
"workspace": {
|
|
1556
|
+
"applyEdit": True,
|
|
1557
|
+
"workspaceEdit": {
|
|
1558
|
+
"documentChanges": True,
|
|
1559
|
+
"resourceOperations": ["create", "rename", "delete"],
|
|
1560
|
+
"failureHandling": "textOnlyTransactional",
|
|
1561
|
+
"normalizesLineEndings": True,
|
|
1562
|
+
},
|
|
1563
|
+
"symbol": {
|
|
1564
|
+
"dynamicRegistration": False,
|
|
1565
|
+
"symbolKind": {"valueSet": list(range(1, 27))},
|
|
1566
|
+
"tagSupport": {"valueSet": [1]},
|
|
1567
|
+
"resolveSupport": {"properties": ["location.range"]},
|
|
1568
|
+
},
|
|
1569
|
+
"executeCommand": {"dynamicRegistration": False},
|
|
1570
|
+
"configuration": True,
|
|
1571
|
+
"workspaceFolders": True,
|
|
1572
|
+
"semanticTokens": {"refreshSupport": True},
|
|
1573
|
+
"inlayHint": {"refreshSupport": True},
|
|
1574
|
+
},
|
|
1575
|
+
"window": {
|
|
1576
|
+
"showMessage": {
|
|
1577
|
+
"messageActionItem": {
|
|
1578
|
+
"additionalPropertiesSupport": True
|
|
1579
|
+
}
|
|
1580
|
+
},
|
|
1581
|
+
"showDocument": {"support": False},
|
|
1582
|
+
"workDoneProgress": False,
|
|
1583
|
+
},
|
|
1584
|
+
},
|
|
1585
|
+
},
|
|
1586
|
+
)
|
|
1587
|
+
)
|
|
1588
|
+
|
|
1589
|
+
def _on_initialized(self, result: Any) -> None:
|
|
1590
|
+
"""Conclui o handshake. ``result`` é ``None`` quando o servidor respondeu erro."""
|
|
1591
|
+
if not isinstance(result, dict):
|
|
1592
|
+
self._init_failures += 1
|
|
1593
|
+
logger.warning(
|
|
1594
|
+
"LSP[%s]: o servidor recusou o initialize (resposta inválida); encerrando",
|
|
1595
|
+
self.lang,
|
|
1596
|
+
)
|
|
1597
|
+
self._pre_init_queue = []
|
|
1598
|
+
self._open_docs.clear()
|
|
1599
|
+
threading.Thread(
|
|
1600
|
+
target=self.stop,
|
|
1601
|
+
args=(0.5,),
|
|
1602
|
+
daemon=True,
|
|
1603
|
+
name=f"lsp-abort-{self.lang}",
|
|
1604
|
+
).start()
|
|
1605
|
+
return
|
|
1606
|
+
self._init_failures = 0
|
|
1607
|
+
caps = result.get("capabilities")
|
|
1608
|
+
self._capabilities = caps if isinstance(caps, dict) else {}
|
|
1609
|
+
|
|
1610
|
+
st_prov = self._capabilities.get("semanticTokensProvider", {})
|
|
1611
|
+
legend = st_prov.get("legend", {}) if isinstance(st_prov, dict) else {}
|
|
1612
|
+
if legend:
|
|
1613
|
+
self._semantic_legend = legend
|
|
1614
|
+
self._initialized = True
|
|
1615
|
+
self._send_notification("initialized", {})
|
|
1616
|
+
logger.debug(
|
|
1617
|
+
"LSP: '%s' inicializado. caps=%s",
|
|
1618
|
+
self.lang,
|
|
1619
|
+
list(self._capabilities.keys()),
|
|
1620
|
+
)
|
|
1621
|
+
for notif in self._pre_init_queue:
|
|
1622
|
+
self._send_notification(notif["method"], notif["params"])
|
|
1623
|
+
self._pre_init_queue.clear()
|
|
1624
|
+
|
|
1625
|
+
def _reader_loop(self) -> None:
|
|
1626
|
+
decoder = FrameDecoder()
|
|
1627
|
+
while not self._shutdown:
|
|
1628
|
+
if not self._proc or self._proc.poll() is not None:
|
|
1629
|
+
break
|
|
1630
|
+
try:
|
|
1631
|
+
chunk = self._proc.stdout.read1(65536)
|
|
1632
|
+
if not chunk:
|
|
1633
|
+
break
|
|
1634
|
+
for msg in decoder.feed(chunk):
|
|
1635
|
+
self._safe_dispatch(msg)
|
|
1636
|
+
except MessageTooLarge as exc:
|
|
1637
|
+
logger.warning("LSP[%s]: %s descartada", self.lang, exc)
|
|
1638
|
+
self._shutdown = True
|
|
1639
|
+
return
|
|
1640
|
+
except (OSError, EOFError) as exc:
|
|
1641
|
+
logger.debug("LSP[%s] reader encerrado: %s", self.lang, exc)
|
|
1642
|
+
break
|
|
1643
|
+
|
|
1644
|
+
def _stderr_loop(self) -> None:
|
|
1645
|
+
while not self._shutdown:
|
|
1646
|
+
if not self._proc or self._proc.poll() is not None:
|
|
1647
|
+
break
|
|
1648
|
+
try:
|
|
1649
|
+
line = self._proc.stderr.readline()
|
|
1650
|
+
if not line:
|
|
1651
|
+
break
|
|
1652
|
+
text = line.decode("utf-8", errors="replace").rstrip()
|
|
1653
|
+
if text:
|
|
1654
|
+
logger.debug("LSP[%s] stderr: %s", self.lang, text)
|
|
1655
|
+
if self._on_log and not self._shutdown:
|
|
1656
|
+
with contextlib.suppress(tk.TclError, AttributeError):
|
|
1657
|
+
self._tk.after(0, lambda t=text: self._on_log(t))
|
|
1658
|
+
except (OSError, EOFError) as exc:
|
|
1659
|
+
logger.debug("LSP[%s] stderr encerrado: %s", self.lang, exc)
|
|
1660
|
+
break
|
|
1661
|
+
|
|
1662
|
+
def _safe_dispatch(self, msg: Any) -> None:
|
|
1663
|
+
"""Despacha uma mensagem sem deixar uma mensagem malformada matar a thread leitora."""
|
|
1664
|
+
if not isinstance(msg, dict):
|
|
1665
|
+
return
|
|
1666
|
+
try:
|
|
1667
|
+
self._dispatch(msg)
|
|
1668
|
+
except Exception:
|
|
1669
|
+
logger.exception("LSP[%s]: erro ao tratar mensagem do servidor", self.lang)
|
|
1670
|
+
|
|
1671
|
+
def _run_callback(self, cb: Callable, result: Any) -> None:
|
|
1672
|
+
"""Executa o callback de uma resposta na thread Tk, isolando falhas dele."""
|
|
1673
|
+
try:
|
|
1674
|
+
cb(result)
|
|
1675
|
+
except Exception:
|
|
1676
|
+
logger.exception("LSP[%s]: erro no callback de resposta", self.lang)
|
|
1677
|
+
|
|
1678
|
+
def _dispatch(self, msg: dict) -> None:
|
|
1679
|
+
if "id" in msg and "method" not in msg:
|
|
1680
|
+
rid = msg["id"]
|
|
1681
|
+
with self._pending_lock:
|
|
1682
|
+
cb = self._pending.pop(rid, None)
|
|
1683
|
+
if cb:
|
|
1684
|
+
result = msg.get("result")
|
|
1685
|
+
error = msg.get("error")
|
|
1686
|
+
if error:
|
|
1687
|
+
logger.debug("LSP[%s] erro %s: %s", self.lang, rid, error)
|
|
1688
|
+
result = None
|
|
1689
|
+
if not self._shutdown:
|
|
1690
|
+
with contextlib.suppress(tk.TclError):
|
|
1691
|
+
self._tk.after(
|
|
1692
|
+
0, lambda r=result, c=cb: self._run_callback(c, r)
|
|
1693
|
+
)
|
|
1694
|
+
elif "method" in msg:
|
|
1695
|
+
self._handle_notification(msg)
|
|
1696
|
+
|
|
1697
|
+
def _handle_notification(self, msg: dict) -> None:
|
|
1698
|
+
method = msg["method"]
|
|
1699
|
+
params = msg.get("params")
|
|
1700
|
+
if not isinstance(params, dict):
|
|
1701
|
+
params = {}
|
|
1702
|
+
req_id = msg.get("id")
|
|
1703
|
+
|
|
1704
|
+
if method == "textDocument/publishDiagnostics":
|
|
1705
|
+
self._handle_diagnostics(params)
|
|
1706
|
+
elif method in ("window/logMessage", "$/logTrace"):
|
|
1707
|
+
text = params.get("message", "")
|
|
1708
|
+
if text and self._on_log and not self._shutdown:
|
|
1709
|
+
with contextlib.suppress(tk.TclError):
|
|
1710
|
+
self._tk.after(0, lambda t=text: self._on_log(t))
|
|
1711
|
+
elif method == "window/showMessage":
|
|
1712
|
+
logger.info("LSP[%s] msg: %s", self.lang,
|
|
1713
|
+
params.get("message", ""))
|
|
1714
|
+
elif method == "window/showMessageRequest" and req_id is not None:
|
|
1715
|
+
actions = params.get("actions", [])
|
|
1716
|
+
self._send(LSPMessage.response(
|
|
1717
|
+
req_id, actions[0] if actions else None))
|
|
1718
|
+
elif (
|
|
1719
|
+
method == "client/registerCapability"
|
|
1720
|
+
and req_id is not None
|
|
1721
|
+
or method == "client/unregisterCapability"
|
|
1722
|
+
and req_id is not None
|
|
1723
|
+
):
|
|
1724
|
+
self._send(LSPMessage.response(req_id, {}))
|
|
1725
|
+
elif method == "workspace/configuration" and req_id is not None:
|
|
1726
|
+
items = params.get("items", [])
|
|
1727
|
+
self._send(LSPMessage.response(req_id, [None] * len(items)))
|
|
1728
|
+
elif method == "workspace/workspaceFolders" and req_id is not None:
|
|
1729
|
+
root_uri = _path_to_uri(self.root_path) if self.root_path else None
|
|
1730
|
+
folders = (
|
|
1731
|
+
[{"uri": root_uri, "name": self.root_path.name}] if root_uri else []
|
|
1732
|
+
)
|
|
1733
|
+
self._send(LSPMessage.response(req_id, folders))
|
|
1734
|
+
elif method == "workspace/applyEdit" and req_id is not None:
|
|
1735
|
+
edit_data = params.get("edit", {})
|
|
1736
|
+
applied = False
|
|
1737
|
+
if self._on_apply_edit and edit_data and not self._shutdown:
|
|
1738
|
+
try:
|
|
1739
|
+
we = WorkspaceEdit.from_dict(edit_data)
|
|
1740
|
+
with contextlib.suppress(tk.TclError):
|
|
1741
|
+
self._tk.after(0, lambda w=we: self._on_apply_edit(w))
|
|
1742
|
+
applied = True
|
|
1743
|
+
except Exception as exc:
|
|
1744
|
+
logger.debug("workspace/applyEdit handler error: %s", exc)
|
|
1745
|
+
self._send(LSPMessage.response(req_id, {"applied": applied}))
|
|
1746
|
+
elif method in ("$/progress", "window/workDoneProgress/create"):
|
|
1747
|
+
if req_id is not None:
|
|
1748
|
+
self._send(LSPMessage.response(req_id, None))
|
|
1749
|
+
elif (
|
|
1750
|
+
method == "workspace/semanticTokens/refresh"
|
|
1751
|
+
and req_id is not None
|
|
1752
|
+
or method == "workspace/inlayHint/refresh"
|
|
1753
|
+
and req_id is not None
|
|
1754
|
+
):
|
|
1755
|
+
self._send(LSPMessage.response(req_id, None))
|
|
1756
|
+
elif req_id is not None:
|
|
1757
|
+
# Pedido do servidor que este cliente não implementa: sem resposta,
|
|
1758
|
+
# o servidor ficaria esperando para sempre.
|
|
1759
|
+
self._send(LSPMessage.error_response(
|
|
1760
|
+
req_id, -32601, f"Método não suportado: {method}"))
|
|
1761
|
+
|
|
1762
|
+
def _handle_diagnostics(self, params: dict) -> None:
|
|
1763
|
+
if not self._on_diags or self._shutdown:
|
|
1764
|
+
return
|
|
1765
|
+
uri = params.get("uri", "")
|
|
1766
|
+
raw = params.get("diagnostics")
|
|
1767
|
+
diags = [
|
|
1768
|
+
LSPDiag.from_dict(d) for d in (raw if isinstance(raw, list) else [])
|
|
1769
|
+
if isinstance(d, dict)
|
|
1770
|
+
]
|
|
1771
|
+
with contextlib.suppress(tk.TclError):
|
|
1772
|
+
self._tk.after(0, lambda u=uri, d=diags: self._on_diags(u, d))
|
|
1773
|
+
|
|
1774
|
+
@staticmethod
|
|
1775
|
+
def _parse_completion(result: Any) -> list[CompletionItem]:
|
|
1776
|
+
if result is None:
|
|
1777
|
+
return []
|
|
1778
|
+
if isinstance(result, dict):
|
|
1779
|
+
items = result.get("items")
|
|
1780
|
+
items = items if isinstance(items, list) else []
|
|
1781
|
+
elif isinstance(result, list):
|
|
1782
|
+
items = result
|
|
1783
|
+
else:
|
|
1784
|
+
return []
|
|
1785
|
+
return [CompletionItem.from_dict(i) for i in items if isinstance(i, dict)]
|
|
1786
|
+
|
|
1787
|
+
@staticmethod
|
|
1788
|
+
def _parse_locations(result: Any) -> list[Location]:
|
|
1789
|
+
if result is None:
|
|
1790
|
+
return []
|
|
1791
|
+
if isinstance(result, dict):
|
|
1792
|
+
result = [result]
|
|
1793
|
+
elif not isinstance(result, list):
|
|
1794
|
+
return []
|
|
1795
|
+
out: list[Location] = []
|
|
1796
|
+
for item in result:
|
|
1797
|
+
if not isinstance(item, dict):
|
|
1798
|
+
continue
|
|
1799
|
+
if "targetUri" in item:
|
|
1800
|
+
link = LocationLink.from_dict(item)
|
|
1801
|
+
out.append(
|
|
1802
|
+
Location(uri=link.target_uri,
|
|
1803
|
+
range=link.target_selection_range)
|
|
1804
|
+
)
|
|
1805
|
+
else:
|
|
1806
|
+
out.append(Location.from_dict(item))
|
|
1807
|
+
return out
|
|
1808
|
+
|
|
1809
|
+
|
|
1810
|
+
class LSPManager:
|
|
1811
|
+
"""
|
|
1812
|
+
Gerencia múltiplos LSPClient (um por linguagem).
|
|
1813
|
+
API unificada usada por EditorPane e CodisApp.
|
|
1814
|
+
Suporta enable/disable global e por linguagem.
|
|
1815
|
+
"""
|
|
1816
|
+
|
|
1817
|
+
def __init__(
|
|
1818
|
+
self,
|
|
1819
|
+
tk_root: tk.Misc,
|
|
1820
|
+
root_path: Path | None = None,
|
|
1821
|
+
on_diagnostics: Callable[[str, str, list], None] | None = None,
|
|
1822
|
+
on_log: Callable[[str, str], None] | None = None,
|
|
1823
|
+
on_apply_edit: Callable[[WorkspaceEdit], None] | None = None,
|
|
1824
|
+
) -> None:
|
|
1825
|
+
self._tk = tk_root
|
|
1826
|
+
self._root_path = root_path
|
|
1827
|
+
self._on_diags = on_diagnostics
|
|
1828
|
+
self._on_log = on_log
|
|
1829
|
+
self._on_apply_edit = on_apply_edit
|
|
1830
|
+
self._clients: dict[str, LSPClient] = {}
|
|
1831
|
+
self._enabled = True
|
|
1832
|
+
self._disabled_langs: set[str] = set()
|
|
1833
|
+
|
|
1834
|
+
def set_root(self, path: Path | None) -> None:
|
|
1835
|
+
"""Define o diretório raiz do workspace para todos os servidores LSP."""
|
|
1836
|
+
self._root_path = path
|
|
1837
|
+
for c in list(self._clients.values()):
|
|
1838
|
+
c.stop()
|
|
1839
|
+
self._clients.clear()
|
|
1840
|
+
|
|
1841
|
+
def set_enabled(self, enabled: bool) -> None:
|
|
1842
|
+
"""Habilita ou desabilita o cliente LSP, iniciando ou parando servidores."""
|
|
1843
|
+
self._enabled = enabled
|
|
1844
|
+
if not enabled:
|
|
1845
|
+
self.stop_all()
|
|
1846
|
+
|
|
1847
|
+
def enable_lang(self, lang: str) -> LSPClient | None:
|
|
1848
|
+
"""Habilita LSP manualmente para uma linguagem e inicia o servidor."""
|
|
1849
|
+
self._disabled_langs.discard(lang)
|
|
1850
|
+
return self.client_for(lang)
|
|
1851
|
+
|
|
1852
|
+
def disable_lang(self, lang: str) -> None:
|
|
1853
|
+
"""Desabilita LSP para uma linguagem específica e para o servidor."""
|
|
1854
|
+
self._disabled_langs.add(lang)
|
|
1855
|
+
if lang in self._clients:
|
|
1856
|
+
self._clients[lang].stop()
|
|
1857
|
+
del self._clients[lang]
|
|
1858
|
+
|
|
1859
|
+
def is_lang_enabled(self, lang: str) -> bool:
|
|
1860
|
+
"""Retorna ``True`` se LSP está globalmente habilitado e a linguagem não foi desabilitada."""
|
|
1861
|
+
return self._enabled and lang not in self._disabled_langs
|
|
1862
|
+
|
|
1863
|
+
def stop_all(self, timeout: float = 3.0) -> None:
|
|
1864
|
+
"""Para todos os servidores LSP em paralelo, com prazo total de ``timeout`` s.
|
|
1865
|
+
|
|
1866
|
+
Servidores que não saírem no prazo têm a árvore de processos morta, de
|
|
1867
|
+
modo que o encerramento do app nunca fique preso esperando por eles.
|
|
1868
|
+
"""
|
|
1869
|
+
clients = list(self._clients.items())
|
|
1870
|
+
self._clients.clear()
|
|
1871
|
+
|
|
1872
|
+
def _stop_one(lang: str, client: LSPClient) -> None:
|
|
1873
|
+
try:
|
|
1874
|
+
client.stop(grace=min(1.0, timeout))
|
|
1875
|
+
except Exception as exc:
|
|
1876
|
+
logger.debug("LSPManager: erro ao parar '%s': %s", lang, exc)
|
|
1877
|
+
|
|
1878
|
+
workers = [
|
|
1879
|
+
threading.Thread(target=_stop_one, args=item, daemon=True, name=f"lsp-stop-{item[0]}")
|
|
1880
|
+
for item in clients
|
|
1881
|
+
]
|
|
1882
|
+
for worker in workers:
|
|
1883
|
+
worker.start()
|
|
1884
|
+
deadline = time.monotonic() + timeout
|
|
1885
|
+
for worker in workers:
|
|
1886
|
+
worker.join(max(0.0, deadline - time.monotonic()))
|
|
1887
|
+
for _, client in clients:
|
|
1888
|
+
proc = client._proc
|
|
1889
|
+
if proc is not None and proc.poll() is None:
|
|
1890
|
+
_kill_process_tree(proc)
|
|
1891
|
+
|
|
1892
|
+
def restart_lang(self, lang: str) -> LSPClient | None:
|
|
1893
|
+
"""Reinicia o servidor para uma linguagem."""
|
|
1894
|
+
if lang in self._clients:
|
|
1895
|
+
self._clients[lang].stop()
|
|
1896
|
+
del self._clients[lang]
|
|
1897
|
+
return self.client_for(lang)
|
|
1898
|
+
|
|
1899
|
+
def client_for(self, lang: str) -> LSPClient | None:
|
|
1900
|
+
"""
|
|
1901
|
+
Retorna o LSPClient para a linguagem, iniciando-o se necessário.
|
|
1902
|
+
Retorna None se LSP estiver desabilitado global ou por linguagem.
|
|
1903
|
+
"""
|
|
1904
|
+
if not self._enabled or lang in self._disabled_langs:
|
|
1905
|
+
return None
|
|
1906
|
+
if lang in self._clients:
|
|
1907
|
+
c = self._clients[lang]
|
|
1908
|
+
if c._proc is not None and c._proc.poll() is None:
|
|
1909
|
+
return c
|
|
1910
|
+
c.start()
|
|
1911
|
+
if c._proc is not None and c._proc.poll() is None:
|
|
1912
|
+
return c
|
|
1913
|
+
return None
|
|
1914
|
+
|
|
1915
|
+
def _on_diag(uri: str, diags: list) -> None:
|
|
1916
|
+
if self._on_diags:
|
|
1917
|
+
self._on_diags(lang, uri, diags)
|
|
1918
|
+
|
|
1919
|
+
def _on_log_cb(msg: str) -> None:
|
|
1920
|
+
if self._on_log:
|
|
1921
|
+
self._on_log(lang, msg)
|
|
1922
|
+
|
|
1923
|
+
c = LSPClient(
|
|
1924
|
+
lang=lang,
|
|
1925
|
+
root_path=self._root_path,
|
|
1926
|
+
tk_root=self._tk,
|
|
1927
|
+
on_diagnostics=_on_diag,
|
|
1928
|
+
on_log=_on_log_cb,
|
|
1929
|
+
on_apply_edit=self._on_apply_edit,
|
|
1930
|
+
)
|
|
1931
|
+
self._clients[lang] = c
|
|
1932
|
+
return c if c.start() else None
|
|
1933
|
+
|
|
1934
|
+
@staticmethod
|
|
1935
|
+
def available_for(lang: str) -> bool:
|
|
1936
|
+
"""Verifica (sem iniciar) se há servidor disponível para a linguagem."""
|
|
1937
|
+
return _find_server(lang) is not None
|
|
1938
|
+
|
|
1939
|
+
@staticmethod
|
|
1940
|
+
def install_hint(lang: str) -> str:
|
|
1941
|
+
"""Retorna o comando de instalação sugerido para o servidor da linguagem."""
|
|
1942
|
+
return _INSTALL_HINTS.get(lang, "")
|
|
1943
|
+
|
|
1944
|
+
def status(self) -> dict[str, str]:
|
|
1945
|
+
"""Retorna {lang: 'running'|'starting'|'stopped'|'available'|'disabled'|'unavailable'}."""
|
|
1946
|
+
result: dict[str, str] = {}
|
|
1947
|
+
for lang in _SERVER_CANDIDATES:
|
|
1948
|
+
if lang in self._disabled_langs:
|
|
1949
|
+
result[lang] = "disabled"
|
|
1950
|
+
elif lang in self._clients:
|
|
1951
|
+
c = self._clients[lang]
|
|
1952
|
+
if c.running:
|
|
1953
|
+
result[lang] = "running"
|
|
1954
|
+
elif c.starting:
|
|
1955
|
+
result[lang] = "starting"
|
|
1956
|
+
else:
|
|
1957
|
+
result[lang] = "stopped"
|
|
1958
|
+
elif _find_server(lang):
|
|
1959
|
+
result[lang] = "available"
|
|
1960
|
+
else:
|
|
1961
|
+
result[lang] = "unavailable"
|
|
1962
|
+
return result
|
|
1963
|
+
|
|
1964
|
+
def did_open(
|
|
1965
|
+
self, path: Path, lang: str, content: str, *, diagnostics: bool = True
|
|
1966
|
+
) -> None:
|
|
1967
|
+
"""Notifica o LSP que um documento foi aberto."""
|
|
1968
|
+
c = self.client_for(lang)
|
|
1969
|
+
if c:
|
|
1970
|
+
c.did_open(path, lang, content, diagnostics=diagnostics)
|
|
1971
|
+
|
|
1972
|
+
def did_change(self, path: Path, lang: str, content: str) -> None:
|
|
1973
|
+
"""Notifica o LSP sobre mudanças incrementais no documento."""
|
|
1974
|
+
c = self.client_for(lang)
|
|
1975
|
+
if c:
|
|
1976
|
+
c.did_change(path, content)
|
|
1977
|
+
|
|
1978
|
+
def did_save(self, path: Path, lang: str, content: str | None = None) -> None:
|
|
1979
|
+
"""Notifica o LSP que o documento foi salvo."""
|
|
1980
|
+
c = self.client_for(lang)
|
|
1981
|
+
if c:
|
|
1982
|
+
c.did_save(path, content)
|
|
1983
|
+
|
|
1984
|
+
def did_close(self, path: Path, lang: str) -> None:
|
|
1985
|
+
"""Notifica o LSP que o documento foi fechado."""
|
|
1986
|
+
c = self.client_for(lang)
|
|
1987
|
+
if c:
|
|
1988
|
+
c.did_close(path)
|
|
1989
|
+
|
|
1990
|
+
def hover(
|
|
1991
|
+
self,
|
|
1992
|
+
path: Path,
|
|
1993
|
+
lang: str,
|
|
1994
|
+
line: int,
|
|
1995
|
+
col: int,
|
|
1996
|
+
callback: Callable[[Hover | None], None],
|
|
1997
|
+
) -> None:
|
|
1998
|
+
"""Solicita ao LSP informações de hover para a posição dada."""
|
|
1999
|
+
c = self.client_for(lang)
|
|
2000
|
+
if c:
|
|
2001
|
+
c.hover(path, line, col, callback)
|
|
2002
|
+
else:
|
|
2003
|
+
callback(None)
|
|
2004
|
+
|
|
2005
|
+
def completion(
|
|
2006
|
+
self,
|
|
2007
|
+
path: Path,
|
|
2008
|
+
lang: str,
|
|
2009
|
+
line: int,
|
|
2010
|
+
col: int,
|
|
2011
|
+
trigger: str | None,
|
|
2012
|
+
callback: Callable[[list[CompletionItem]], None],
|
|
2013
|
+
) -> None:
|
|
2014
|
+
"""Solicita ao LSP sugestões de autocompletar na posição dada."""
|
|
2015
|
+
c = self.client_for(lang)
|
|
2016
|
+
if c:
|
|
2017
|
+
c.completion(path, line, col, trigger, callback)
|
|
2018
|
+
else:
|
|
2019
|
+
callback([])
|
|
2020
|
+
|
|
2021
|
+
def goto_definition(
|
|
2022
|
+
self,
|
|
2023
|
+
path: Path,
|
|
2024
|
+
lang: str,
|
|
2025
|
+
line: int,
|
|
2026
|
+
col: int,
|
|
2027
|
+
callback: Callable[[list[Location]], None],
|
|
2028
|
+
) -> None:
|
|
2029
|
+
"""Solicita ao LSP a definição do símbolo na posição dada."""
|
|
2030
|
+
c = self.client_for(lang)
|
|
2031
|
+
if c:
|
|
2032
|
+
c.goto_definition(path, line, col, callback)
|
|
2033
|
+
else:
|
|
2034
|
+
callback([])
|
|
2035
|
+
|
|
2036
|
+
def goto_declaration(
|
|
2037
|
+
self,
|
|
2038
|
+
path: Path,
|
|
2039
|
+
lang: str,
|
|
2040
|
+
line: int,
|
|
2041
|
+
col: int,
|
|
2042
|
+
callback: Callable[[list[Location]], None],
|
|
2043
|
+
) -> None:
|
|
2044
|
+
"""Solicita ao LSP a declaração do símbolo na posição dada."""
|
|
2045
|
+
c = self.client_for(lang)
|
|
2046
|
+
if c:
|
|
2047
|
+
c.goto_declaration(path, line, col, callback)
|
|
2048
|
+
else:
|
|
2049
|
+
callback([])
|
|
2050
|
+
|
|
2051
|
+
def goto_type_definition(
|
|
2052
|
+
self,
|
|
2053
|
+
path: Path,
|
|
2054
|
+
lang: str,
|
|
2055
|
+
line: int,
|
|
2056
|
+
col: int,
|
|
2057
|
+
callback: Callable[[list[Location]], None],
|
|
2058
|
+
) -> None:
|
|
2059
|
+
"""Solicita ao LSP o tipo do símbolo na posição dada."""
|
|
2060
|
+
c = self.client_for(lang)
|
|
2061
|
+
if c:
|
|
2062
|
+
c.goto_type_definition(path, line, col, callback)
|
|
2063
|
+
else:
|
|
2064
|
+
callback([])
|
|
2065
|
+
|
|
2066
|
+
def goto_implementation(
|
|
2067
|
+
self,
|
|
2068
|
+
path: Path,
|
|
2069
|
+
lang: str,
|
|
2070
|
+
line: int,
|
|
2071
|
+
col: int,
|
|
2072
|
+
callback: Callable[[list[Location]], None],
|
|
2073
|
+
) -> None:
|
|
2074
|
+
"""Solicita ao LSP as implementações do símbolo na posição dada."""
|
|
2075
|
+
c = self.client_for(lang)
|
|
2076
|
+
if c:
|
|
2077
|
+
c.goto_implementation(path, line, col, callback)
|
|
2078
|
+
else:
|
|
2079
|
+
callback([])
|
|
2080
|
+
|
|
2081
|
+
def find_references(
|
|
2082
|
+
self,
|
|
2083
|
+
path: Path,
|
|
2084
|
+
lang: str,
|
|
2085
|
+
line: int,
|
|
2086
|
+
col: int,
|
|
2087
|
+
callback: Callable[[list[Location]], None],
|
|
2088
|
+
) -> None:
|
|
2089
|
+
"""Solicita ao LSP todas as referências do símbolo na posição dada."""
|
|
2090
|
+
c = self.client_for(lang)
|
|
2091
|
+
if c:
|
|
2092
|
+
c.find_references(path, line, col, callback)
|
|
2093
|
+
else:
|
|
2094
|
+
callback([])
|
|
2095
|
+
|
|
2096
|
+
def signature_help(
|
|
2097
|
+
self,
|
|
2098
|
+
path: Path,
|
|
2099
|
+
lang: str,
|
|
2100
|
+
line: int,
|
|
2101
|
+
col: int,
|
|
2102
|
+
callback: Callable[[SignatureHelp | None], None],
|
|
2103
|
+
) -> None:
|
|
2104
|
+
"""Solicita ao LSP a assinatura da função na posição do cursor."""
|
|
2105
|
+
c = self.client_for(lang)
|
|
2106
|
+
if c:
|
|
2107
|
+
c.signature_help(path, line, col, callback)
|
|
2108
|
+
else:
|
|
2109
|
+
callback(None)
|
|
2110
|
+
|
|
2111
|
+
def document_symbols(
|
|
2112
|
+
self, path: Path, lang: str, callback: Callable[[list[DocumentSymbol]], None]
|
|
2113
|
+
) -> None:
|
|
2114
|
+
"""Solicita ao LSP todos os símbolos do documento aberto."""
|
|
2115
|
+
c = self.client_for(lang)
|
|
2116
|
+
if c:
|
|
2117
|
+
c.document_symbols(path, callback)
|
|
2118
|
+
else:
|
|
2119
|
+
callback([])
|
|
2120
|
+
|
|
2121
|
+
def workspace_symbol(
|
|
2122
|
+
self, query: str, callback: Callable[[list[dict]], None]
|
|
2123
|
+
) -> None:
|
|
2124
|
+
"""Pesquisa símbolos no workspace inteiro com o termo fornecido."""
|
|
2125
|
+
for c in self._clients.values():
|
|
2126
|
+
if c.running:
|
|
2127
|
+
c.workspace_symbol(query, callback)
|
|
2128
|
+
return
|
|
2129
|
+
callback([])
|
|
2130
|
+
|
|
2131
|
+
def formatting(
|
|
2132
|
+
self,
|
|
2133
|
+
path: Path,
|
|
2134
|
+
lang: str,
|
|
2135
|
+
tab_size: int,
|
|
2136
|
+
insert_spaces: bool,
|
|
2137
|
+
callback: Callable[[list[TextEdit]], None],
|
|
2138
|
+
) -> None:
|
|
2139
|
+
"""Solicita ao LSP a formatação completa do documento."""
|
|
2140
|
+
c = self.client_for(lang)
|
|
2141
|
+
if c:
|
|
2142
|
+
c.formatting(path, tab_size, insert_spaces, callback)
|
|
2143
|
+
else:
|
|
2144
|
+
callback([])
|
|
2145
|
+
|
|
2146
|
+
def range_formatting(
|
|
2147
|
+
self,
|
|
2148
|
+
path: Path,
|
|
2149
|
+
lang: str,
|
|
2150
|
+
rng: Range,
|
|
2151
|
+
tab_size: int,
|
|
2152
|
+
insert_spaces: bool,
|
|
2153
|
+
callback: Callable[[list[TextEdit]], None],
|
|
2154
|
+
) -> None:
|
|
2155
|
+
"""Solicita ao LSP a formatação de um intervalo do documento."""
|
|
2156
|
+
c = self.client_for(lang)
|
|
2157
|
+
if c:
|
|
2158
|
+
c.range_formatting(path, rng, tab_size, insert_spaces, callback)
|
|
2159
|
+
else:
|
|
2160
|
+
callback([])
|
|
2161
|
+
|
|
2162
|
+
def prepare_rename(
|
|
2163
|
+
self,
|
|
2164
|
+
path: Path,
|
|
2165
|
+
lang: str,
|
|
2166
|
+
line: int,
|
|
2167
|
+
col: int,
|
|
2168
|
+
callback: Callable[[PrepareRenameResult | None], None],
|
|
2169
|
+
) -> None:
|
|
2170
|
+
"""Verifica se o símbolo na posição pode ser renomeado via LSP."""
|
|
2171
|
+
c = self.client_for(lang)
|
|
2172
|
+
if c:
|
|
2173
|
+
c.prepare_rename(path, line, col, callback)
|
|
2174
|
+
else:
|
|
2175
|
+
callback(None)
|
|
2176
|
+
|
|
2177
|
+
def rename(
|
|
2178
|
+
self,
|
|
2179
|
+
path: Path,
|
|
2180
|
+
lang: str,
|
|
2181
|
+
line: int,
|
|
2182
|
+
col: int,
|
|
2183
|
+
new_name: str,
|
|
2184
|
+
callback: Callable[[WorkspaceEdit | None], None],
|
|
2185
|
+
) -> None:
|
|
2186
|
+
"""Solicita ao LSP a renomeação do símbolo para o novo nome."""
|
|
2187
|
+
c = self.client_for(lang)
|
|
2188
|
+
if c:
|
|
2189
|
+
c.rename(path, line, col, new_name, callback)
|
|
2190
|
+
else:
|
|
2191
|
+
callback(None)
|
|
2192
|
+
|
|
2193
|
+
def code_action(
|
|
2194
|
+
self,
|
|
2195
|
+
path: Path,
|
|
2196
|
+
lang: str,
|
|
2197
|
+
rng: Range,
|
|
2198
|
+
diagnostics: list[dict],
|
|
2199
|
+
callback: Callable[[list[CodeAction]], None],
|
|
2200
|
+
only: list[str] | None = None,
|
|
2201
|
+
) -> None:
|
|
2202
|
+
"""Solicita ao LSP code actions disponíveis no intervalo dado."""
|
|
2203
|
+
c = self.client_for(lang)
|
|
2204
|
+
if c:
|
|
2205
|
+
c.code_action(path, rng, diagnostics, callback, only)
|
|
2206
|
+
else:
|
|
2207
|
+
callback([])
|
|
2208
|
+
|
|
2209
|
+
def document_highlight(
|
|
2210
|
+
self,
|
|
2211
|
+
path: Path,
|
|
2212
|
+
lang: str,
|
|
2213
|
+
line: int,
|
|
2214
|
+
col: int,
|
|
2215
|
+
callback: Callable[[list[DocumentHighlight]], None],
|
|
2216
|
+
) -> None:
|
|
2217
|
+
"""Solicita ao LSP os realces de ocorrências do símbolo."""
|
|
2218
|
+
c = self.client_for(lang)
|
|
2219
|
+
if c:
|
|
2220
|
+
c.document_highlight(path, line, col, callback)
|
|
2221
|
+
else:
|
|
2222
|
+
callback([])
|
|
2223
|
+
|
|
2224
|
+
def folding_ranges(
|
|
2225
|
+
self, path: Path, lang: str, callback: Callable[[list[FoldingRange]], None]
|
|
2226
|
+
) -> None:
|
|
2227
|
+
"""Solicita ao LSP as regiões de folding do documento."""
|
|
2228
|
+
c = self.client_for(lang)
|
|
2229
|
+
if c:
|
|
2230
|
+
c.folding_ranges(path, callback)
|
|
2231
|
+
else:
|
|
2232
|
+
callback([])
|
|
2233
|
+
|
|
2234
|
+
def inlay_hints(
|
|
2235
|
+
self,
|
|
2236
|
+
path: Path,
|
|
2237
|
+
lang: str,
|
|
2238
|
+
rng: Range,
|
|
2239
|
+
callback: Callable[[list[InlayHint]], None],
|
|
2240
|
+
) -> None:
|
|
2241
|
+
"""Solicita ao LSP os inlay hints do intervalo especificado."""
|
|
2242
|
+
c = self.client_for(lang)
|
|
2243
|
+
if c:
|
|
2244
|
+
c.inlay_hints(path, rng, callback)
|
|
2245
|
+
else:
|
|
2246
|
+
callback([])
|
|
2247
|
+
|
|
2248
|
+
def semantic_tokens(
|
|
2249
|
+
self, path: Path, lang: str, callback: Callable[[list[dict]], None]
|
|
2250
|
+
) -> None:
|
|
2251
|
+
"""Solicita ao LSP os tokens semânticos do documento."""
|
|
2252
|
+
c = self.client_for(lang)
|
|
2253
|
+
if c:
|
|
2254
|
+
c.semantic_tokens(path, callback)
|
|
2255
|
+
else:
|
|
2256
|
+
callback([])
|
|
2257
|
+
|
|
2258
|
+
def prepare_call_hierarchy(
|
|
2259
|
+
self,
|
|
2260
|
+
path: Path,
|
|
2261
|
+
lang: str,
|
|
2262
|
+
line: int,
|
|
2263
|
+
col: int,
|
|
2264
|
+
callback: Callable[[list[CallHierarchyItem]], None],
|
|
2265
|
+
) -> None:
|
|
2266
|
+
"""Prepara a hierarquia de chamadas do símbolo na posição dada."""
|
|
2267
|
+
c = self.client_for(lang)
|
|
2268
|
+
if c:
|
|
2269
|
+
c.prepare_call_hierarchy(path, line, col, callback)
|
|
2270
|
+
else:
|
|
2271
|
+
callback([])
|
|
2272
|
+
|
|
2273
|
+
def prepare_type_hierarchy(
|
|
2274
|
+
self,
|
|
2275
|
+
path: Path,
|
|
2276
|
+
lang: str,
|
|
2277
|
+
line: int,
|
|
2278
|
+
col: int,
|
|
2279
|
+
callback: Callable[[list[TypeHierarchyItem]], None],
|
|
2280
|
+
) -> None:
|
|
2281
|
+
"""Prepara a hierarquia de tipos do símbolo na posição dada."""
|
|
2282
|
+
c = self.client_for(lang)
|
|
2283
|
+
if c:
|
|
2284
|
+
c.prepare_type_hierarchy(path, line, col, callback)
|
|
2285
|
+
else:
|
|
2286
|
+
callback([])
|
|
2287
|
+
|
|
2288
|
+
def execute_command(
|
|
2289
|
+
self,
|
|
2290
|
+
lang: str,
|
|
2291
|
+
command: str,
|
|
2292
|
+
arguments: list | None = None,
|
|
2293
|
+
callback: Callable[[Any], None] | None = None,
|
|
2294
|
+
) -> None:
|
|
2295
|
+
"""Executa um comando registrado no servidor LSP."""
|
|
2296
|
+
c = self.client_for(lang)
|
|
2297
|
+
if c:
|
|
2298
|
+
c.execute_command(command, arguments, callback)
|
|
2299
|
+
elif callback:
|
|
2300
|
+
callback(None)
|