blob: 98c50d1fe3ffe5ba43165c01a883f4505268a5e0 [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//
Kirill Bobyrev8e35f1e2018-08-14 16:03:32 +00008//===----------------------------------------------------------------------===//
Ilya Biryukov38d79772017-05-16 09:38:59 +00009
10#include "ClangdLSPServer.h"
Kadir Cetinkaya689bf932018-08-24 13:09:41 +000011#include "Cancellation.h"
Ilya Biryukov71028b82018-03-12 15:28:22 +000012#include "Diagnostics.h"
Ilya Biryukov38d79772017-05-16 09:38:59 +000013#include "JSONRPCDispatcher.h"
Sam McCallb536a2a2017-12-19 12:23:48 +000014#include "SourceCode.h"
Eric Liu78ed91a72018-01-29 15:37:46 +000015#include "URI.h"
Kadir Cetinkaya689bf932018-08-24 13:09:41 +000016#include "llvm/ADT/ScopeExit.h"
Simon Marchi9569fd52018-03-16 14:30:42 +000017#include "llvm/Support/Errc.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000018#include "llvm/Support/FormatVariadic.h"
Eric Liu5740ff52018-01-31 16:26:27 +000019#include "llvm/Support/Path.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000020
Ilya Biryukov38d79772017-05-16 09:38:59 +000021using namespace clang::clangd;
22using namespace clang;
Sam McCalld20d7982018-07-09 14:25:59 +000023using namespace llvm;
Ilya Biryukov38d79772017-05-16 09:38:59 +000024
Ilya Biryukovafb55542017-05-16 14:40:30 +000025namespace {
26
Eric Liu5740ff52018-01-31 16:26:27 +000027/// \brief Supports a test URI scheme with relaxed constraints for lit tests.
28/// The path in a test URI will be combined with a platform-specific fake
29/// directory to form an absolute path. For example, test:///a.cpp is resolved
30/// C:\clangd-test\a.cpp on Windows and /clangd-test/a.cpp on Unix.
31class TestScheme : public URIScheme {
32public:
33 llvm::Expected<std::string>
34 getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,
35 llvm::StringRef /*HintPath*/) const override {
36 using namespace llvm::sys;
37 // Still require "/" in body to mimic file scheme, as we want lengths of an
38 // equivalent URI in both schemes to be the same.
39 if (!Body.startswith("/"))
40 return llvm::make_error<llvm::StringError>(
41 "Expect URI body to be an absolute path starting with '/': " + Body,
42 llvm::inconvertibleErrorCode());
43 Body = Body.ltrim('/');
Nico Weber0da22902018-04-10 13:14:03 +000044#ifdef _WIN32
Eric Liu5740ff52018-01-31 16:26:27 +000045 constexpr char TestDir[] = "C:\\clangd-test";
46#else
47 constexpr char TestDir[] = "/clangd-test";
48#endif
49 llvm::SmallVector<char, 16> Path(Body.begin(), Body.end());
50 path::native(Path);
51 auto Err = fs::make_absolute(TestDir, Path);
Eric Liucda25262018-02-01 12:44:52 +000052 if (Err)
53 llvm_unreachable("Failed to make absolute path in test scheme.");
Eric Liu5740ff52018-01-31 16:26:27 +000054 return std::string(Path.begin(), Path.end());
55 }
56
57 llvm::Expected<URI>
58 uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
59 llvm_unreachable("Clangd must never create a test URI.");
60 }
61};
62
63static URISchemeRegistry::Add<TestScheme>
64 X("test", "Test scheme for clangd lit tests.");
65
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000066SymbolKindBitset defaultSymbolKinds() {
67 SymbolKindBitset Defaults;
68 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
69 ++I)
70 Defaults.set(I);
71 return Defaults;
72}
73
Kadir Cetinkaya689bf932018-08-24 13:09:41 +000074std::string NormalizeRequestID(const json::Value &ID) {
75 auto NormalizedID = parseNumberOrString(&ID);
76 assert(NormalizedID && "Was not able to parse request id.");
77 return std::move(*NormalizedID);
78}
Ilya Biryukovafb55542017-05-16 14:40:30 +000079} // namespace
80
Sam McCalld1a7a372018-01-31 13:40:48 +000081void ClangdLSPServer::onInitialize(InitializeParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +000082 if (Params.initializationOptions)
83 applyConfiguration(*Params.initializationOptions);
84
Ilya Biryukov7d60d202018-02-16 12:20:47 +000085 if (Params.rootUri && *Params.rootUri)
86 Server.setRootPath(Params.rootUri->file());
Ilya Biryukov23bc73b2018-02-15 14:32:57 +000087 else if (Params.rootPath && !Params.rootPath->empty())
88 Server.setRootPath(*Params.rootPath);
89
90 CCOpts.EnableSnippets =
91 Params.capabilities.textDocument.completion.completionItem.snippetSupport;
Alex Lorenz8626d362018-08-10 17:25:07 +000092 DiagOpts.EmbedFixesInDiagnostics =
93 Params.capabilities.textDocument.publishDiagnostics.clangdFixSupport;
Alex Lorenz0ce8a7a2018-08-22 20:30:06 +000094 DiagOpts.SendDiagnosticCategory =
95 Params.capabilities.textDocument.publishDiagnostics.categorySupport;
Ilya Biryukov23bc73b2018-02-15 14:32:57 +000096
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000097 if (Params.capabilities.workspace && Params.capabilities.workspace->symbol &&
98 Params.capabilities.workspace->symbol->symbolKind) {
99 for (SymbolKind Kind :
100 *Params.capabilities.workspace->symbol->symbolKind->valueSet) {
101 SupportedSymbolKinds.set(static_cast<size_t>(Kind));
102 }
103 }
104
Sam McCalld20d7982018-07-09 14:25:59 +0000105 reply(json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000106 {{"capabilities",
Sam McCalld20d7982018-07-09 14:25:59 +0000107 json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000108 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000109 {"documentFormattingProvider", true},
110 {"documentRangeFormattingProvider", true},
111 {"documentOnTypeFormattingProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000112 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000113 {"firstTriggerCharacter", "}"},
114 {"moreTriggerCharacter", {}},
115 }},
116 {"codeActionProvider", true},
117 {"completionProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000118 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000119 {"resolveProvider", false},
120 {"triggerCharacters", {".", ">", ":"}},
121 }},
122 {"signatureHelpProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000123 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000124 {"triggerCharacters", {"(", ","}},
125 }},
126 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000127 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000128 {"hoverProvider", true},
Haojian Wu345099c2017-11-09 11:30:04 +0000129 {"renameProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000130 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000131 {"workspaceSymbolProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000132 {"executeCommandProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000133 json::Object{
Eric Liu2c190532018-05-15 15:23:53 +0000134 {"commands", {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND}},
Sam McCall0930ab02017-11-07 15:49:35 +0000135 }},
136 }}}});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000137}
138
Sam McCalld1a7a372018-01-31 13:40:48 +0000139void ClangdLSPServer::onShutdown(ShutdownParams &Params) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000140 // Do essentially nothing, just say we're ready to exit.
141 ShutdownRequestReceived = true;
Sam McCalld1a7a372018-01-31 13:40:48 +0000142 reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000143}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000144
Sam McCalld1a7a372018-01-31 13:40:48 +0000145void ClangdLSPServer::onExit(ExitParams &Params) { IsDone = true; }
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000146
Sam McCalld1a7a372018-01-31 13:40:48 +0000147void ClangdLSPServer::onDocumentDidOpen(DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000148 PathRef File = Params.textDocument.uri.file();
Alex Lorenzf8087862018-08-01 17:39:29 +0000149 if (Params.metadata && !Params.metadata->extraFlags.empty())
150 CDB.setExtraFlagsForFile(File, std::move(Params.metadata->extraFlags));
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000151
Simon Marchi9569fd52018-03-16 14:30:42 +0000152 std::string &Contents = Params.textDocument.text;
153
Simon Marchi98082622018-03-26 14:41:40 +0000154 DraftMgr.addDraft(File, Contents);
Simon Marchi9569fd52018-03-16 14:30:42 +0000155 Server.addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000156}
157
Sam McCalld1a7a372018-01-31 13:40:48 +0000158void ClangdLSPServer::onDocumentDidChange(DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000159 auto WantDiags = WantDiagnostics::Auto;
160 if (Params.wantDiagnostics.hasValue())
161 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
162 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000163
164 PathRef File = Params.textDocument.uri.file();
Simon Marchi98082622018-03-26 14:41:40 +0000165 llvm::Expected<std::string> Contents =
166 DraftMgr.updateDraft(File, Params.contentChanges);
167 if (!Contents) {
168 // If this fails, we are most likely going to be not in sync anymore with
169 // the client. It is better to remove the draft and let further operations
170 // fail rather than giving wrong results.
171 DraftMgr.removeDraft(File);
172 Server.removeDocument(File);
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000173 CDB.invalidate(File);
Sam McCallbed58852018-07-11 10:35:11 +0000174 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000175 return;
176 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000177
Simon Marchi98082622018-03-26 14:41:40 +0000178 Server.addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000179}
180
Sam McCalld1a7a372018-01-31 13:40:48 +0000181void ClangdLSPServer::onFileEvent(DidChangeWatchedFilesParams &Params) {
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000182 Server.onFileEvent(Params);
183}
184
Sam McCalld1a7a372018-01-31 13:40:48 +0000185void ClangdLSPServer::onCommand(ExecuteCommandParams &Params) {
Eric Liuc5105f92018-02-16 14:15:55 +0000186 auto ApplyEdit = [](WorkspaceEdit WE) {
187 ApplyWorkspaceEditParams Edit;
188 Edit.edit = std::move(WE);
189 // We don't need the response so id == 1 is OK.
190 // Ideally, we would wait for the response and if there is no error, we
191 // would reply success/failure to the original RPC.
192 call("workspace/applyEdit", Edit);
193 };
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000194 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
195 Params.workspaceEdit) {
196 // The flow for "apply-fix" :
197 // 1. We publish a diagnostic, including fixits
198 // 2. The user clicks on the diagnostic, the editor asks us for code actions
199 // 3. We send code actions, with the fixit embedded as context
200 // 4. The user selects the fixit, the editor asks us to apply it
201 // 5. We unwrap the changes and send them back to the editor
202 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
203 // we ignore it)
204
Sam McCalld1a7a372018-01-31 13:40:48 +0000205 reply("Fix applied.");
Eric Liuc5105f92018-02-16 14:15:55 +0000206 ApplyEdit(*Params.workspaceEdit);
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000207 } else {
208 // We should not get here because ExecuteCommandParams would not have
209 // parsed in the first place and this handler should not be called. But if
210 // more commands are added, this will be here has a safe guard.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000211 replyError(
Sam McCalld1a7a372018-01-31 13:40:48 +0000212 ErrorCode::InvalidParams,
Haojian Wu2375c922017-11-07 10:21:02 +0000213 llvm::formatv("Unsupported command \"{0}\".", Params.command).str());
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000214 }
215}
216
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000217void ClangdLSPServer::onWorkspaceSymbol(WorkspaceSymbolParams &Params) {
218 Server.workspaceSymbols(
219 Params.query, CCOpts.Limit,
220 [this](llvm::Expected<std::vector<SymbolInformation>> Items) {
221 if (!Items)
222 return replyError(ErrorCode::InternalError,
223 llvm::toString(Items.takeError()));
224 for (auto &Sym : *Items)
225 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
226
Sam McCalld20d7982018-07-09 14:25:59 +0000227 reply(json::Array(*Items));
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000228 });
229}
230
Sam McCalld1a7a372018-01-31 13:40:48 +0000231void ClangdLSPServer::onRename(RenameParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000232 Path File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000233 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000234 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000235 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000236 "onRename called for non-added file");
237
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000238 Server.rename(
239 File, Params.position, Params.newName,
240 [File, Code,
241 Params](llvm::Expected<std::vector<tooling::Replacement>> Replacements) {
242 if (!Replacements)
243 return replyError(ErrorCode::InternalError,
244 llvm::toString(Replacements.takeError()));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000245
Eric Liu9133ecd2018-05-11 12:12:08 +0000246 // Turn the replacements into the format specified by the Language
247 // Server Protocol. Fuse them into one big JSON array.
248 std::vector<TextEdit> Edits;
249 for (const auto &R : *Replacements)
250 Edits.push_back(replacementToEdit(*Code, R));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000251 WorkspaceEdit WE;
252 WE.changes = {{Params.textDocument.uri.uri(), Edits}};
253 reply(WE);
254 });
Haojian Wu345099c2017-11-09 11:30:04 +0000255}
256
Sam McCalld1a7a372018-01-31 13:40:48 +0000257void ClangdLSPServer::onDocumentDidClose(DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000258 PathRef File = Params.textDocument.uri.file();
259 DraftMgr.removeDraft(File);
260 Server.removeDocument(File);
Alex Lorenzf8087862018-08-01 17:39:29 +0000261 CDB.invalidate(File);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000262}
263
Sam McCall4db732a2017-09-30 10:08:52 +0000264void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCalld1a7a372018-01-31 13:40:48 +0000265 DocumentOnTypeFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000266 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000267 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000268 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000269 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000270 "onDocumentOnTypeFormatting called for non-added file");
271
272 auto ReplacementsOrError = Server.formatOnType(*Code, File, Params.position);
Raoul Wols212bcf82017-12-12 20:25:06 +0000273 if (ReplacementsOrError)
Sam McCalld20d7982018-07-09 14:25:59 +0000274 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000275 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000276 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000277 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000278}
279
Sam McCall4db732a2017-09-30 10:08:52 +0000280void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCalld1a7a372018-01-31 13:40:48 +0000281 DocumentRangeFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000282 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000283 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000284 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000285 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000286 "onDocumentRangeFormatting called for non-added file");
287
288 auto ReplacementsOrError = Server.formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000289 if (ReplacementsOrError)
Sam McCalld20d7982018-07-09 14:25:59 +0000290 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000291 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000292 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000293 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000294}
295
Sam McCalld1a7a372018-01-31 13:40:48 +0000296void ClangdLSPServer::onDocumentFormatting(DocumentFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000297 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000298 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000299 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000300 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000301 "onDocumentFormatting called for non-added file");
302
303 auto ReplacementsOrError = Server.formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000304 if (ReplacementsOrError)
Sam McCalld20d7982018-07-09 14:25:59 +0000305 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000306 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000307 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000308 llvm::toString(ReplacementsOrError.takeError()));
Sam McCall4db732a2017-09-30 10:08:52 +0000309}
310
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000311void ClangdLSPServer::onDocumentSymbol(DocumentSymbolParams &Params) {
312 Server.documentSymbols(
313 Params.textDocument.uri.file(),
314 [this](llvm::Expected<std::vector<SymbolInformation>> Items) {
315 if (!Items)
316 return replyError(ErrorCode::InvalidParams,
317 llvm::toString(Items.takeError()));
318 for (auto &Sym : *Items)
319 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Sam McCalld20d7982018-07-09 14:25:59 +0000320 reply(json::Array(*Items));
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000321 });
322}
323
Sam McCalld1a7a372018-01-31 13:40:48 +0000324void ClangdLSPServer::onCodeAction(CodeActionParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000325 // We provide a code action for each diagnostic at the requested location
326 // which has FixIts available.
Simon Marchi9569fd52018-03-16 14:30:42 +0000327 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000328 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000329 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000330 "onCodeAction called for non-added file");
331
Sam McCalld20d7982018-07-09 14:25:59 +0000332 json::Array Commands;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000333 for (Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000334 for (auto &F : getFixes(Params.textDocument.uri.file(), D)) {
Sam McCalldd0566b2017-11-06 15:40:30 +0000335 WorkspaceEdit WE;
Ilya Biryukov71028b82018-03-12 15:28:22 +0000336 std::vector<TextEdit> Edits(F.Edits.begin(), F.Edits.end());
Eric Liu78ed91a72018-01-29 15:37:46 +0000337 WE.changes = {{Params.textDocument.uri.uri(), std::move(Edits)}};
Sam McCalld20d7982018-07-09 14:25:59 +0000338 Commands.push_back(json::Object{
Ilya Biryukov71028b82018-03-12 15:28:22 +0000339 {"title", llvm::formatv("Apply fix: {0}", F.Message)},
Sam McCalldd0566b2017-11-06 15:40:30 +0000340 {"command", ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND},
341 {"arguments", {WE}},
342 });
343 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000344 }
Sam McCalld1a7a372018-01-31 13:40:48 +0000345 reply(std::move(Commands));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000346}
347
Sam McCalld1a7a372018-01-31 13:40:48 +0000348void ClangdLSPServer::onCompletion(TextDocumentPositionParams &Params) {
Kadir Cetinkaya689bf932018-08-24 13:09:41 +0000349 CreateSpaceForTaskHandle();
350 TaskHandle TH = Server.codeComplete(
351 Params.textDocument.uri.file(), Params.position, CCOpts,
352 [this](llvm::Expected<CodeCompleteResult> List) {
353 auto _ = llvm::make_scope_exit([this]() { CleanupTaskHandle(); });
354
355 if (!List)
356 return replyError(List.takeError());
357 CompletionList LSPList;
358 LSPList.isIncomplete = List->HasMore;
359 for (const auto &R : List->Completions)
360 LSPList.items.push_back(R.render(CCOpts));
361 return reply(std::move(LSPList));
362 });
363 StoreTaskHandle(std::move(TH));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000364}
365
Sam McCalld1a7a372018-01-31 13:40:48 +0000366void ClangdLSPServer::onSignatureHelp(TextDocumentPositionParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000367 Server.signatureHelp(Params.textDocument.uri.file(), Params.position,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000368 [](llvm::Expected<SignatureHelp> SignatureHelp) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000369 if (!SignatureHelp)
370 return replyError(
371 ErrorCode::InvalidParams,
372 llvm::toString(SignatureHelp.takeError()));
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000373 reply(*SignatureHelp);
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000374 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000375}
376
Sam McCalld1a7a372018-01-31 13:40:48 +0000377void ClangdLSPServer::onGoToDefinition(TextDocumentPositionParams &Params) {
Kadir Cetinkaya689bf932018-08-24 13:09:41 +0000378 Server.findDefinitions(Params.textDocument.uri.file(), Params.position,
379 [](llvm::Expected<std::vector<Location>> Items) {
380 if (!Items)
381 return replyError(
382 ErrorCode::InvalidParams,
383 llvm::toString(Items.takeError()));
384 reply(json::Array(*Items));
385 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000386}
387
Sam McCalld1a7a372018-01-31 13:40:48 +0000388void ClangdLSPServer::onSwitchSourceHeader(TextDocumentIdentifier &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000389 llvm::Optional<Path> Result = Server.switchSourceHeader(Params.uri.file());
Sam McCalld1a7a372018-01-31 13:40:48 +0000390 reply(Result ? URI::createFile(*Result).toString() : "");
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000391}
392
Sam McCalld1a7a372018-01-31 13:40:48 +0000393void ClangdLSPServer::onDocumentHighlight(TextDocumentPositionParams &Params) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000394 Server.findDocumentHighlights(
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000395 Params.textDocument.uri.file(), Params.position,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000396 [](llvm::Expected<std::vector<DocumentHighlight>> Highlights) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000397 if (!Highlights)
398 return replyError(ErrorCode::InternalError,
399 llvm::toString(Highlights.takeError()));
Sam McCalld20d7982018-07-09 14:25:59 +0000400 reply(json::Array(*Highlights));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000401 });
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000402}
403
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000404void ClangdLSPServer::onHover(TextDocumentPositionParams &Params) {
405 Server.findHover(Params.textDocument.uri.file(), Params.position,
Sam McCall682cfe72018-06-04 10:37:16 +0000406 [](llvm::Expected<llvm::Optional<Hover>> H) {
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000407 if (!H) {
408 replyError(ErrorCode::InternalError,
409 llvm::toString(H.takeError()));
410 return;
411 }
412
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000413 reply(*H);
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000414 });
415}
416
Simon Marchi88016782018-08-01 11:28:49 +0000417void ClangdLSPServer::applyConfiguration(
418 const ClangdConfigurationParamsChange &Settings) {
Simon Marchi5178f922018-02-22 14:00:39 +0000419 // Compilation database change.
420 if (Settings.compilationDatabasePath.hasValue()) {
Alex Lorenzf8087862018-08-01 17:39:29 +0000421 CDB.setCompileCommandsDir(Settings.compilationDatabasePath.getValue());
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000422
Simon Marchi9569fd52018-03-16 14:30:42 +0000423 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +0000424 }
Alex Lorenzf8087862018-08-01 17:39:29 +0000425
426 // Update to the compilation database.
427 if (Settings.compilationDatabaseChanges) {
428 const auto &CompileCommandUpdates = *Settings.compilationDatabaseChanges;
429 bool ShouldReparseOpenFiles = false;
430 for (auto &Entry : CompileCommandUpdates) {
431 /// The opened files need to be reparsed only when some existing
432 /// entries are changed.
433 PathRef File = Entry.first;
434 if (!CDB.setCompilationCommandForFile(
435 File, tooling::CompileCommand(
436 std::move(Entry.second.workingDirectory), File,
437 std::move(Entry.second.compilationCommand),
438 /*Output=*/"")))
439 ShouldReparseOpenFiles = true;
440 }
441 if (ShouldReparseOpenFiles)
442 reparseOpenedFiles();
443 }
Simon Marchi5178f922018-02-22 14:00:39 +0000444}
445
Simon Marchi88016782018-08-01 11:28:49 +0000446// FIXME: This function needs to be properly tested.
447void ClangdLSPServer::onChangeConfiguration(
448 DidChangeConfigurationParams &Params) {
449 applyConfiguration(Params.settings);
450}
451
Sam McCall7363a2f2018-03-05 17:28:54 +0000452ClangdLSPServer::ClangdLSPServer(JSONOutput &Out,
Sam McCalladccab62017-11-23 16:58:22 +0000453 const clangd::CodeCompleteOptions &CCOpts,
Eric Liubfac8f72017-12-19 18:00:37 +0000454 llvm::Optional<Path> CompileCommandsDir,
Alex Lorenzf8087862018-08-01 17:39:29 +0000455 bool ShouldUseInMemoryCDB,
Sam McCall7363a2f2018-03-05 17:28:54 +0000456 const ClangdServer::Options &Opts)
Alex Lorenzf8087862018-08-01 17:39:29 +0000457 : Out(Out), CDB(ShouldUseInMemoryCDB ? CompilationDB::makeInMemory()
458 : CompilationDB::makeDirectoryBased(
459 std::move(CompileCommandsDir))),
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000460 CCOpts(CCOpts), SupportedSymbolKinds(defaultSymbolKinds()),
Alex Lorenzf8087862018-08-01 17:39:29 +0000461 Server(CDB.getCDB(), FSProvider, /*DiagConsumer=*/*this, Opts) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000462
Sam McCall27a07cf2018-06-05 09:34:46 +0000463bool ClangdLSPServer::run(std::FILE *In, JSONStreamStyle InputStyle) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000464 assert(!IsDone && "Run was called before");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000465
Ilya Biryukovafb55542017-05-16 14:40:30 +0000466 // Set up JSONRPCDispatcher.
Sam McCalld20d7982018-07-09 14:25:59 +0000467 JSONRPCDispatcher Dispatcher([](const json::Value &Params) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000468 replyError(ErrorCode::MethodNotFound, "method not found");
Ilya Biryukov940901e2017-12-13 12:51:22 +0000469 });
Simon Marchi6e8eb9d2018-03-07 21:47:25 +0000470 registerCallbackHandlers(Dispatcher, /*Callbacks=*/*this);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000471
Ilya Biryukovafb55542017-05-16 14:40:30 +0000472 // Run the Language Server loop.
Sam McCall5ed599e2018-02-06 10:47:30 +0000473 runLanguageServerLoop(In, Out, InputStyle, Dispatcher, IsDone);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000474
475 // Make sure IsDone is set to true after this method exits to ensure assertion
476 // at the start of the method fires if it's ever executed again.
477 IsDone = true;
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000478
479 return ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000480}
481
Ilya Biryukov71028b82018-03-12 15:28:22 +0000482std::vector<Fix> ClangdLSPServer::getFixes(StringRef File,
483 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000484 std::lock_guard<std::mutex> Lock(FixItsMutex);
485 auto DiagToFixItsIter = FixItsMap.find(File);
486 if (DiagToFixItsIter == FixItsMap.end())
487 return {};
488
489 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
490 auto FixItsIter = DiagToFixItsMap.find(D);
491 if (FixItsIter == DiagToFixItsMap.end())
492 return {};
493
494 return FixItsIter->second;
495}
496
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000497void ClangdLSPServer::onDiagnosticsReady(PathRef File,
498 std::vector<Diag> Diagnostics) {
Sam McCalld20d7982018-07-09 14:25:59 +0000499 json::Array DiagnosticsJSON;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000500
501 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000502 for (auto &Diag : Diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000503 toLSPDiags(Diag, [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Alex Lorenz8626d362018-08-10 17:25:07 +0000504 json::Object LSPDiag({
Ilya Biryukov71028b82018-03-12 15:28:22 +0000505 {"range", Diag.range},
506 {"severity", Diag.severity},
507 {"message", Diag.message},
508 });
Alex Lorenz8626d362018-08-10 17:25:07 +0000509 // LSP extension: embed the fixes in the diagnostic.
510 if (DiagOpts.EmbedFixesInDiagnostics && !Fixes.empty()) {
511 json::Array ClangdFixes;
512 for (const auto &Fix : Fixes) {
513 WorkspaceEdit WE;
514 URIForFile URI{File};
515 WE.changes = {{URI.uri(), std::vector<TextEdit>(Fix.Edits.begin(),
516 Fix.Edits.end())}};
517 ClangdFixes.push_back(
518 json::Object{{"edit", toJSON(WE)}, {"title", Fix.Message}});
519 }
520 LSPDiag["clangd_fixes"] = std::move(ClangdFixes);
521 }
Alex Lorenz0ce8a7a2018-08-22 20:30:06 +0000522 if (DiagOpts.SendDiagnosticCategory && !Diag.category.empty())
Alex Lorenz37146432018-08-14 22:21:40 +0000523 LSPDiag["category"] = Diag.category;
Alex Lorenz8626d362018-08-10 17:25:07 +0000524 DiagnosticsJSON.push_back(std::move(LSPDiag));
Ilya Biryukov71028b82018-03-12 15:28:22 +0000525
526 auto &FixItsForDiagnostic = LocalFixIts[Diag];
527 std::copy(Fixes.begin(), Fixes.end(),
528 std::back_inserter(FixItsForDiagnostic));
Sam McCalldd0566b2017-11-06 15:40:30 +0000529 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000530 }
531
532 // Cache FixIts
533 {
534 // FIXME(ibiryukov): should be deleted when documents are removed
535 std::lock_guard<std::mutex> Lock(FixItsMutex);
536 FixItsMap[File] = LocalFixIts;
537 }
538
539 // Publish diagnostics.
Sam McCalld20d7982018-07-09 14:25:59 +0000540 Out.writeMessage(json::Object{
Sam McCalldd0566b2017-11-06 15:40:30 +0000541 {"jsonrpc", "2.0"},
542 {"method", "textDocument/publishDiagnostics"},
543 {"params",
Sam McCalld20d7982018-07-09 14:25:59 +0000544 json::Object{
Eric Liu78ed91a72018-01-29 15:37:46 +0000545 {"uri", URIForFile{File}},
Sam McCalldd0566b2017-11-06 15:40:30 +0000546 {"diagnostics", std::move(DiagnosticsJSON)},
547 }},
548 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000549}
Simon Marchi9569fd52018-03-16 14:30:42 +0000550
551void ClangdLSPServer::reparseOpenedFiles() {
552 for (const Path &FilePath : DraftMgr.getActiveFiles())
553 Server.addDocument(FilePath, *DraftMgr.getDraft(FilePath),
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000554 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +0000555}
Alex Lorenzf8087862018-08-01 17:39:29 +0000556
557ClangdLSPServer::CompilationDB ClangdLSPServer::CompilationDB::makeInMemory() {
558 return CompilationDB(llvm::make_unique<InMemoryCompilationDb>(), nullptr,
559 /*IsDirectoryBased=*/false);
560}
561
562ClangdLSPServer::CompilationDB
563ClangdLSPServer::CompilationDB::makeDirectoryBased(
564 llvm::Optional<Path> CompileCommandsDir) {
565 auto CDB = llvm::make_unique<DirectoryBasedGlobalCompilationDatabase>(
566 std::move(CompileCommandsDir));
567 auto CachingCDB = llvm::make_unique<CachingCompilationDb>(*CDB);
568 return CompilationDB(std::move(CDB), std::move(CachingCDB),
569 /*IsDirectoryBased=*/true);
570}
571
572void ClangdLSPServer::CompilationDB::invalidate(PathRef File) {
573 if (!IsDirectoryBased)
574 static_cast<InMemoryCompilationDb *>(CDB.get())->invalidate(File);
575 else
576 CachingCDB->invalidate(File);
577}
578
579bool ClangdLSPServer::CompilationDB::setCompilationCommandForFile(
580 PathRef File, tooling::CompileCommand CompilationCommand) {
581 if (IsDirectoryBased) {
582 elog("Trying to set compile command for {0} while using directory-based "
583 "compilation database",
584 File);
585 return false;
586 }
587 return static_cast<InMemoryCompilationDb *>(CDB.get())
588 ->setCompilationCommandForFile(File, std::move(CompilationCommand));
589}
590
591void ClangdLSPServer::CompilationDB::setExtraFlagsForFile(
592 PathRef File, std::vector<std::string> ExtraFlags) {
593 if (!IsDirectoryBased) {
594 elog("Trying to set extra flags for {0} while using in-memory compilation "
595 "database",
596 File);
597 return;
598 }
599 static_cast<DirectoryBasedGlobalCompilationDatabase *>(CDB.get())
600 ->setExtraFlagsForFile(File, std::move(ExtraFlags));
601 CachingCDB->invalidate(File);
602}
603
604void ClangdLSPServer::CompilationDB::setCompileCommandsDir(Path P) {
605 if (!IsDirectoryBased) {
606 elog("Trying to set compile commands dir while using in-memory compilation "
607 "database");
608 return;
609 }
610 static_cast<DirectoryBasedGlobalCompilationDatabase *>(CDB.get())
611 ->setCompileCommandsDir(P);
612 CachingCDB->clear();
613}
614
615GlobalCompilationDatabase &ClangdLSPServer::CompilationDB::getCDB() {
616 if (CachingCDB)
617 return *CachingCDB;
618 return *CDB;
619}
Kadir Cetinkaya689bf932018-08-24 13:09:41 +0000620
621void ClangdLSPServer::onCancelRequest(CancelParams &Params) {
622 std::lock_guard<std::mutex> Lock(TaskHandlesMutex);
623 const auto &It = TaskHandles.find(Params.ID);
624 if (It == TaskHandles.end())
625 return;
626 if (It->second)
627 It->second->cancel();
628 TaskHandles.erase(It);
629}
630
631void ClangdLSPServer::CleanupTaskHandle() {
632 const json::Value *ID = getRequestId();
633 if (!ID)
634 return;
635 std::string NormalizedID = NormalizeRequestID(*ID);
636 std::lock_guard<std::mutex> Lock(TaskHandlesMutex);
637 TaskHandles.erase(NormalizedID);
638}
639
640void ClangdLSPServer::CreateSpaceForTaskHandle() {
641 const json::Value *ID = getRequestId();
642 if (!ID)
643 return;
644 std::string NormalizedID = NormalizeRequestID(*ID);
645 std::lock_guard<std::mutex> Lock(TaskHandlesMutex);
646 if (!TaskHandles.insert({NormalizedID, nullptr}).second)
647 elog("Creation of space for task handle: {0} failed.", NormalizedID);
648}
649
650void ClangdLSPServer::StoreTaskHandle(TaskHandle TH) {
651 const json::Value *ID = getRequestId();
652 if (!ID)
653 return;
654 std::string NormalizedID = NormalizeRequestID(*ID);
655 std::lock_guard<std::mutex> Lock(TaskHandlesMutex);
656 auto It = TaskHandles.find(NormalizedID);
657 if (It == TaskHandles.end()) {
658 elog("CleanupTaskHandle called before store can happen for request:{0}.",
659 NormalizedID);
660 return;
661 }
662 if (It->second != nullptr)
663 elog("TaskHandle didn't get cleared for: {0}.", NormalizedID);
664 It->second = std::move(TH);
665}