blob: b8c2a79b64402db32efe4256a531f21d5390edf8 [file] [log] [blame]
Ilya Biryukov38d79772017-05-16 09:38:59 +00001//===--- ClangdLSPServer.cpp - LSP server ------------------------*- C++-*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===---------------------------------------------------------------------===//
9
10#include "ClangdLSPServer.h"
Ilya Biryukov71028b82018-03-12 15:28:22 +000011#include "Diagnostics.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000012#include "JSONRPCDispatcher.h"
Sam McCallb536a2a2017-12-19 12:23:48 +000013#include "SourceCode.h"
Eric Liu78ed91a72018-01-29 15:37:46 +000014#include "URI.h"
Simon Marchi9569fd52018-03-16 14:30:42 +000015#include "llvm/Support/Errc.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000016#include "llvm/Support/FormatVariadic.h"
Eric Liu5740ff52018-01-31 16:26:27 +000017#include "llvm/Support/Path.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000018
Ilya Biryukov38d79772017-05-16 09:38:59 +000019using namespace clang::clangd;
20using namespace clang;
Sam McCalld20d7982018-07-09 14:25:59 +000021using namespace llvm;
Ilya Biryukov38d79772017-05-16 09:38:59 +000022
Ilya Biryukovafb55542017-05-16 14:40:30 +000023namespace {
24
Eric Liu5740ff52018-01-31 16:26:27 +000025/// \brief Supports a test URI scheme with relaxed constraints for lit tests.
26/// The path in a test URI will be combined with a platform-specific fake
27/// directory to form an absolute path. For example, test:///a.cpp is resolved
28/// C:\clangd-test\a.cpp on Windows and /clangd-test/a.cpp on Unix.
29class TestScheme : public URIScheme {
30public:
31 llvm::Expected<std::string>
32 getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,
33 llvm::StringRef /*HintPath*/) const override {
34 using namespace llvm::sys;
35 // Still require "/" in body to mimic file scheme, as we want lengths of an
36 // equivalent URI in both schemes to be the same.
37 if (!Body.startswith("/"))
38 return llvm::make_error<llvm::StringError>(
39 "Expect URI body to be an absolute path starting with '/': " + Body,
40 llvm::inconvertibleErrorCode());
41 Body = Body.ltrim('/');
Nico Weber0da22902018-04-10 13:14:03 +000042#ifdef _WIN32
Eric Liu5740ff52018-01-31 16:26:27 +000043 constexpr char TestDir[] = "C:\\clangd-test";
44#else
45 constexpr char TestDir[] = "/clangd-test";
46#endif
47 llvm::SmallVector<char, 16> Path(Body.begin(), Body.end());
48 path::native(Path);
49 auto Err = fs::make_absolute(TestDir, Path);
Eric Liucda25262018-02-01 12:44:52 +000050 if (Err)
51 llvm_unreachable("Failed to make absolute path in test scheme.");
Eric Liu5740ff52018-01-31 16:26:27 +000052 return std::string(Path.begin(), Path.end());
53 }
54
55 llvm::Expected<URI>
56 uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
57 llvm_unreachable("Clangd must never create a test URI.");
58 }
59};
60
61static URISchemeRegistry::Add<TestScheme>
62 X("test", "Test scheme for clangd lit tests.");
63
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000064SymbolKindBitset defaultSymbolKinds() {
65 SymbolKindBitset Defaults;
66 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
67 ++I)
68 Defaults.set(I);
69 return Defaults;
70}
71
Ilya Biryukovafb55542017-05-16 14:40:30 +000072} // namespace
73
Sam McCalld1a7a372018-01-31 13:40:48 +000074void ClangdLSPServer::onInitialize(InitializeParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +000075 if (Params.rootUri && *Params.rootUri)
76 Server.setRootPath(Params.rootUri->file());
Ilya Biryukov23bc73b2018-02-15 14:32:57 +000077 else if (Params.rootPath && !Params.rootPath->empty())
78 Server.setRootPath(*Params.rootPath);
79
80 CCOpts.EnableSnippets =
81 Params.capabilities.textDocument.completion.completionItem.snippetSupport;
82
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000083 if (Params.capabilities.workspace && Params.capabilities.workspace->symbol &&
84 Params.capabilities.workspace->symbol->symbolKind) {
85 for (SymbolKind Kind :
86 *Params.capabilities.workspace->symbol->symbolKind->valueSet) {
87 SupportedSymbolKinds.set(static_cast<size_t>(Kind));
88 }
89 }
90
Sam McCalld20d7982018-07-09 14:25:59 +000091 reply(json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +000092 {{"capabilities",
Sam McCalld20d7982018-07-09 14:25:59 +000093 json::Object{
Simon Marchi98082622018-03-26 14:41:40 +000094 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +000095 {"documentFormattingProvider", true},
96 {"documentRangeFormattingProvider", true},
97 {"documentOnTypeFormattingProvider",
Sam McCalld20d7982018-07-09 14:25:59 +000098 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +000099 {"firstTriggerCharacter", "}"},
100 {"moreTriggerCharacter", {}},
101 }},
102 {"codeActionProvider", true},
103 {"completionProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000104 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000105 {"resolveProvider", false},
106 {"triggerCharacters", {".", ">", ":"}},
107 }},
108 {"signatureHelpProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000109 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000110 {"triggerCharacters", {"(", ","}},
111 }},
112 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000113 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000114 {"hoverProvider", true},
Haojian Wu345099c2017-11-09 11:30:04 +0000115 {"renameProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000116 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000117 {"workspaceSymbolProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000118 {"executeCommandProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000119 json::Object{
Eric Liu2c190532018-05-15 15:23:53 +0000120 {"commands", {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND}},
Sam McCall0930ab02017-11-07 15:49:35 +0000121 }},
122 }}}});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000123}
124
Sam McCalld1a7a372018-01-31 13:40:48 +0000125void ClangdLSPServer::onShutdown(ShutdownParams &Params) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000126 // Do essentially nothing, just say we're ready to exit.
127 ShutdownRequestReceived = true;
Sam McCalld1a7a372018-01-31 13:40:48 +0000128 reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000129}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000130
Sam McCalld1a7a372018-01-31 13:40:48 +0000131void ClangdLSPServer::onExit(ExitParams &Params) { IsDone = true; }
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000132
Sam McCalld1a7a372018-01-31 13:40:48 +0000133void ClangdLSPServer::onDocumentDidOpen(DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000134 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000135 if (Params.metadata && !Params.metadata->extraFlags.empty()) {
136 NonCachedCDB.setExtraFlagsForFile(File,
137 std::move(Params.metadata->extraFlags));
138 CDB.invalidate(File);
139 }
140
Simon Marchi9569fd52018-03-16 14:30:42 +0000141 std::string &Contents = Params.textDocument.text;
142
Simon Marchi98082622018-03-26 14:41:40 +0000143 DraftMgr.addDraft(File, Contents);
Simon Marchi9569fd52018-03-16 14:30:42 +0000144 Server.addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000145}
146
Sam McCalld1a7a372018-01-31 13:40:48 +0000147void ClangdLSPServer::onDocumentDidChange(DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000148 auto WantDiags = WantDiagnostics::Auto;
149 if (Params.wantDiagnostics.hasValue())
150 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
151 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000152
153 PathRef File = Params.textDocument.uri.file();
Simon Marchi98082622018-03-26 14:41:40 +0000154 llvm::Expected<std::string> Contents =
155 DraftMgr.updateDraft(File, Params.contentChanges);
156 if (!Contents) {
157 // If this fails, we are most likely going to be not in sync anymore with
158 // the client. It is better to remove the draft and let further operations
159 // fail rather than giving wrong results.
160 DraftMgr.removeDraft(File);
161 Server.removeDocument(File);
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000162 CDB.invalidate(File);
Sam McCallbed58852018-07-11 10:35:11 +0000163 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000164 return;
165 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000166
Simon Marchi98082622018-03-26 14:41:40 +0000167 Server.addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000168}
169
Sam McCalld1a7a372018-01-31 13:40:48 +0000170void ClangdLSPServer::onFileEvent(DidChangeWatchedFilesParams &Params) {
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000171 Server.onFileEvent(Params);
172}
173
Sam McCalld1a7a372018-01-31 13:40:48 +0000174void ClangdLSPServer::onCommand(ExecuteCommandParams &Params) {
Eric Liuc5105f92018-02-16 14:15:55 +0000175 auto ApplyEdit = [](WorkspaceEdit WE) {
176 ApplyWorkspaceEditParams Edit;
177 Edit.edit = std::move(WE);
178 // We don't need the response so id == 1 is OK.
179 // Ideally, we would wait for the response and if there is no error, we
180 // would reply success/failure to the original RPC.
181 call("workspace/applyEdit", Edit);
182 };
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000183 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
184 Params.workspaceEdit) {
185 // The flow for "apply-fix" :
186 // 1. We publish a diagnostic, including fixits
187 // 2. The user clicks on the diagnostic, the editor asks us for code actions
188 // 3. We send code actions, with the fixit embedded as context
189 // 4. The user selects the fixit, the editor asks us to apply it
190 // 5. We unwrap the changes and send them back to the editor
191 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
192 // we ignore it)
193
Sam McCalld1a7a372018-01-31 13:40:48 +0000194 reply("Fix applied.");
Eric Liuc5105f92018-02-16 14:15:55 +0000195 ApplyEdit(*Params.workspaceEdit);
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000196 } else {
197 // We should not get here because ExecuteCommandParams would not have
198 // parsed in the first place and this handler should not be called. But if
199 // more commands are added, this will be here has a safe guard.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000200 replyError(
Sam McCalld1a7a372018-01-31 13:40:48 +0000201 ErrorCode::InvalidParams,
Haojian Wu2375c922017-11-07 10:21:02 +0000202 llvm::formatv("Unsupported command \"{0}\".", Params.command).str());
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000203 }
204}
205
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000206void ClangdLSPServer::onWorkspaceSymbol(WorkspaceSymbolParams &Params) {
207 Server.workspaceSymbols(
208 Params.query, CCOpts.Limit,
209 [this](llvm::Expected<std::vector<SymbolInformation>> Items) {
210 if (!Items)
211 return replyError(ErrorCode::InternalError,
212 llvm::toString(Items.takeError()));
213 for (auto &Sym : *Items)
214 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
215
Sam McCalld20d7982018-07-09 14:25:59 +0000216 reply(json::Array(*Items));
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000217 });
218}
219
Sam McCalld1a7a372018-01-31 13:40:48 +0000220void ClangdLSPServer::onRename(RenameParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000221 Path File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000222 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000223 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000224 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000225 "onRename called for non-added file");
226
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000227 Server.rename(
228 File, Params.position, Params.newName,
229 [File, Code,
230 Params](llvm::Expected<std::vector<tooling::Replacement>> Replacements) {
231 if (!Replacements)
232 return replyError(ErrorCode::InternalError,
233 llvm::toString(Replacements.takeError()));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000234
Eric Liu9133ecd2018-05-11 12:12:08 +0000235 // Turn the replacements into the format specified by the Language
236 // Server Protocol. Fuse them into one big JSON array.
237 std::vector<TextEdit> Edits;
238 for (const auto &R : *Replacements)
239 Edits.push_back(replacementToEdit(*Code, R));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000240 WorkspaceEdit WE;
241 WE.changes = {{Params.textDocument.uri.uri(), Edits}};
242 reply(WE);
243 });
Haojian Wu345099c2017-11-09 11:30:04 +0000244}
245
Sam McCalld1a7a372018-01-31 13:40:48 +0000246void ClangdLSPServer::onDocumentDidClose(DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000247 PathRef File = Params.textDocument.uri.file();
248 DraftMgr.removeDraft(File);
249 Server.removeDocument(File);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000250}
251
Sam McCall4db732a2017-09-30 10:08:52 +0000252void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCalld1a7a372018-01-31 13:40:48 +0000253 DocumentOnTypeFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000254 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000255 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000256 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000257 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000258 "onDocumentOnTypeFormatting called for non-added file");
259
260 auto ReplacementsOrError = Server.formatOnType(*Code, File, Params.position);
Raoul Wols212bcf82017-12-12 20:25:06 +0000261 if (ReplacementsOrError)
Sam McCalld20d7982018-07-09 14:25:59 +0000262 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000263 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000264 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000265 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000266}
267
Sam McCall4db732a2017-09-30 10:08:52 +0000268void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCalld1a7a372018-01-31 13:40:48 +0000269 DocumentRangeFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000270 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000271 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000272 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000273 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000274 "onDocumentRangeFormatting called for non-added file");
275
276 auto ReplacementsOrError = Server.formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000277 if (ReplacementsOrError)
Sam McCalld20d7982018-07-09 14:25:59 +0000278 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000279 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000280 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000281 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000282}
283
Sam McCalld1a7a372018-01-31 13:40:48 +0000284void ClangdLSPServer::onDocumentFormatting(DocumentFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000285 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000286 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000287 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000288 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000289 "onDocumentFormatting called for non-added file");
290
291 auto ReplacementsOrError = Server.formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000292 if (ReplacementsOrError)
Sam McCalld20d7982018-07-09 14:25:59 +0000293 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000294 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000295 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000296 llvm::toString(ReplacementsOrError.takeError()));
Sam McCall4db732a2017-09-30 10:08:52 +0000297}
298
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000299void ClangdLSPServer::onDocumentSymbol(DocumentSymbolParams &Params) {
300 Server.documentSymbols(
301 Params.textDocument.uri.file(),
302 [this](llvm::Expected<std::vector<SymbolInformation>> Items) {
303 if (!Items)
304 return replyError(ErrorCode::InvalidParams,
305 llvm::toString(Items.takeError()));
306 for (auto &Sym : *Items)
307 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Sam McCalld20d7982018-07-09 14:25:59 +0000308 reply(json::Array(*Items));
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000309 });
310}
311
Sam McCalld1a7a372018-01-31 13:40:48 +0000312void ClangdLSPServer::onCodeAction(CodeActionParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000313 // We provide a code action for each diagnostic at the requested location
314 // which has FixIts available.
Simon Marchi9569fd52018-03-16 14:30:42 +0000315 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000316 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000317 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000318 "onCodeAction called for non-added file");
319
Sam McCalld20d7982018-07-09 14:25:59 +0000320 json::Array Commands;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000321 for (Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000322 for (auto &F : getFixes(Params.textDocument.uri.file(), D)) {
Sam McCalldd0566b2017-11-06 15:40:30 +0000323 WorkspaceEdit WE;
Ilya Biryukov71028b82018-03-12 15:28:22 +0000324 std::vector<TextEdit> Edits(F.Edits.begin(), F.Edits.end());
Eric Liu78ed91a72018-01-29 15:37:46 +0000325 WE.changes = {{Params.textDocument.uri.uri(), std::move(Edits)}};
Sam McCalld20d7982018-07-09 14:25:59 +0000326 Commands.push_back(json::Object{
Ilya Biryukov71028b82018-03-12 15:28:22 +0000327 {"title", llvm::formatv("Apply fix: {0}", F.Message)},
Sam McCalldd0566b2017-11-06 15:40:30 +0000328 {"command", ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND},
329 {"arguments", {WE}},
330 });
331 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000332 }
Sam McCalld1a7a372018-01-31 13:40:48 +0000333 reply(std::move(Commands));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000334}
335
Sam McCalld1a7a372018-01-31 13:40:48 +0000336void ClangdLSPServer::onCompletion(TextDocumentPositionParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000337 Server.codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
Sam McCalle746a2b2018-07-02 11:13:16 +0000338 [this](llvm::Expected<CodeCompleteResult> List) {
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000339 if (!List)
340 return replyError(ErrorCode::InvalidParams,
341 llvm::toString(List.takeError()));
Sam McCalle746a2b2018-07-02 11:13:16 +0000342 CompletionList LSPList;
343 LSPList.isIncomplete = List->HasMore;
344 for (const auto &R : List->Completions)
345 LSPList.items.push_back(R.render(CCOpts));
346 reply(std::move(LSPList));
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000347 });
Ilya Biryukovafb55542017-05-16 14:40:30 +0000348}
349
Sam McCalld1a7a372018-01-31 13:40:48 +0000350void ClangdLSPServer::onSignatureHelp(TextDocumentPositionParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000351 Server.signatureHelp(Params.textDocument.uri.file(), Params.position,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000352 [](llvm::Expected<SignatureHelp> SignatureHelp) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000353 if (!SignatureHelp)
354 return replyError(
355 ErrorCode::InvalidParams,
356 llvm::toString(SignatureHelp.takeError()));
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000357 reply(*SignatureHelp);
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000358 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000359}
360
Sam McCalld1a7a372018-01-31 13:40:48 +0000361void ClangdLSPServer::onGoToDefinition(TextDocumentPositionParams &Params) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000362 Server.findDefinitions(
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000363 Params.textDocument.uri.file(), Params.position,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000364 [](llvm::Expected<std::vector<Location>> Items) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000365 if (!Items)
366 return replyError(ErrorCode::InvalidParams,
367 llvm::toString(Items.takeError()));
Sam McCalld20d7982018-07-09 14:25:59 +0000368 reply(json::Array(*Items));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000369 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000370}
371
Sam McCalld1a7a372018-01-31 13:40:48 +0000372void ClangdLSPServer::onSwitchSourceHeader(TextDocumentIdentifier &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000373 llvm::Optional<Path> Result = Server.switchSourceHeader(Params.uri.file());
Sam McCalld1a7a372018-01-31 13:40:48 +0000374 reply(Result ? URI::createFile(*Result).toString() : "");
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000375}
376
Sam McCalld1a7a372018-01-31 13:40:48 +0000377void ClangdLSPServer::onDocumentHighlight(TextDocumentPositionParams &Params) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000378 Server.findDocumentHighlights(
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000379 Params.textDocument.uri.file(), Params.position,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000380 [](llvm::Expected<std::vector<DocumentHighlight>> Highlights) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000381 if (!Highlights)
382 return replyError(ErrorCode::InternalError,
383 llvm::toString(Highlights.takeError()));
Sam McCalld20d7982018-07-09 14:25:59 +0000384 reply(json::Array(*Highlights));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000385 });
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000386}
387
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000388void ClangdLSPServer::onHover(TextDocumentPositionParams &Params) {
389 Server.findHover(Params.textDocument.uri.file(), Params.position,
Sam McCall682cfe72018-06-04 10:37:16 +0000390 [](llvm::Expected<llvm::Optional<Hover>> H) {
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000391 if (!H) {
392 replyError(ErrorCode::InternalError,
393 llvm::toString(H.takeError()));
394 return;
395 }
396
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000397 reply(*H);
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000398 });
399}
400
Simon Marchi5178f922018-02-22 14:00:39 +0000401// FIXME: This function needs to be properly tested.
402void ClangdLSPServer::onChangeConfiguration(
403 DidChangeConfigurationParams &Params) {
404 ClangdConfigurationParamsChange &Settings = Params.settings;
405
406 // Compilation database change.
407 if (Settings.compilationDatabasePath.hasValue()) {
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000408 NonCachedCDB.setCompileCommandsDir(
409 Settings.compilationDatabasePath.getValue());
410 CDB.clear();
411
Simon Marchi9569fd52018-03-16 14:30:42 +0000412 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +0000413 }
414}
415
Sam McCall7363a2f2018-03-05 17:28:54 +0000416ClangdLSPServer::ClangdLSPServer(JSONOutput &Out,
Sam McCalladccab62017-11-23 16:58:22 +0000417 const clangd::CodeCompleteOptions &CCOpts,
Eric Liubfac8f72017-12-19 18:00:37 +0000418 llvm::Optional<Path> CompileCommandsDir,
Sam McCall7363a2f2018-03-05 17:28:54 +0000419 const ClangdServer::Options &Opts)
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000420 : Out(Out), NonCachedCDB(std::move(CompileCommandsDir)), CDB(NonCachedCDB),
421 CCOpts(CCOpts), SupportedSymbolKinds(defaultSymbolKinds()),
Sam McCall7363a2f2018-03-05 17:28:54 +0000422 Server(CDB, FSProvider, /*DiagConsumer=*/*this, Opts) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000423
Sam McCall27a07cf2018-06-05 09:34:46 +0000424bool ClangdLSPServer::run(std::FILE *In, JSONStreamStyle InputStyle) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000425 assert(!IsDone && "Run was called before");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000426
Ilya Biryukovafb55542017-05-16 14:40:30 +0000427 // Set up JSONRPCDispatcher.
Sam McCalld20d7982018-07-09 14:25:59 +0000428 JSONRPCDispatcher Dispatcher([](const json::Value &Params) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000429 replyError(ErrorCode::MethodNotFound, "method not found");
Ilya Biryukov940901e2017-12-13 12:51:22 +0000430 });
Simon Marchi6e8eb9d2018-03-07 21:47:25 +0000431 registerCallbackHandlers(Dispatcher, /*Callbacks=*/*this);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000432
Ilya Biryukovafb55542017-05-16 14:40:30 +0000433 // Run the Language Server loop.
Sam McCall5ed599e2018-02-06 10:47:30 +0000434 runLanguageServerLoop(In, Out, InputStyle, Dispatcher, IsDone);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000435
436 // Make sure IsDone is set to true after this method exits to ensure assertion
437 // at the start of the method fires if it's ever executed again.
438 IsDone = true;
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000439
440 return ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000441}
442
Ilya Biryukov71028b82018-03-12 15:28:22 +0000443std::vector<Fix> ClangdLSPServer::getFixes(StringRef File,
444 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000445 std::lock_guard<std::mutex> Lock(FixItsMutex);
446 auto DiagToFixItsIter = FixItsMap.find(File);
447 if (DiagToFixItsIter == FixItsMap.end())
448 return {};
449
450 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
451 auto FixItsIter = DiagToFixItsMap.find(D);
452 if (FixItsIter == DiagToFixItsMap.end())
453 return {};
454
455 return FixItsIter->second;
456}
457
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000458void ClangdLSPServer::onDiagnosticsReady(PathRef File,
459 std::vector<Diag> Diagnostics) {
Sam McCalld20d7982018-07-09 14:25:59 +0000460 json::Array DiagnosticsJSON;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000461
462 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000463 for (auto &Diag : Diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000464 toLSPDiags(Diag, [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCalld20d7982018-07-09 14:25:59 +0000465 DiagnosticsJSON.push_back(json::Object{
Ilya Biryukov71028b82018-03-12 15:28:22 +0000466 {"range", Diag.range},
467 {"severity", Diag.severity},
468 {"message", Diag.message},
469 });
470
471 auto &FixItsForDiagnostic = LocalFixIts[Diag];
472 std::copy(Fixes.begin(), Fixes.end(),
473 std::back_inserter(FixItsForDiagnostic));
Sam McCalldd0566b2017-11-06 15:40:30 +0000474 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000475 }
476
477 // Cache FixIts
478 {
479 // FIXME(ibiryukov): should be deleted when documents are removed
480 std::lock_guard<std::mutex> Lock(FixItsMutex);
481 FixItsMap[File] = LocalFixIts;
482 }
483
484 // Publish diagnostics.
Sam McCalld20d7982018-07-09 14:25:59 +0000485 Out.writeMessage(json::Object{
Sam McCalldd0566b2017-11-06 15:40:30 +0000486 {"jsonrpc", "2.0"},
487 {"method", "textDocument/publishDiagnostics"},
488 {"params",
Sam McCalld20d7982018-07-09 14:25:59 +0000489 json::Object{
Eric Liu78ed91a72018-01-29 15:37:46 +0000490 {"uri", URIForFile{File}},
Sam McCalldd0566b2017-11-06 15:40:30 +0000491 {"diagnostics", std::move(DiagnosticsJSON)},
492 }},
493 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000494}
Simon Marchi9569fd52018-03-16 14:30:42 +0000495
496void ClangdLSPServer::reparseOpenedFiles() {
497 for (const Path &FilePath : DraftMgr.getActiveFiles())
498 Server.addDocument(FilePath, *DraftMgr.getDraft(FilePath),
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000499 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +0000500}