blob: ca898a15353c6336ae2ca8d78a213c8854463a11 [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"
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"
Kadir Cetinkaya689bf932018-08-24 13:09:41 +000015#include "llvm/ADT/ScopeExit.h"
Simon Marchi9569fd52018-03-16 14:30:42 +000016#include "llvm/Support/Errc.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000017#include "llvm/Support/FormatVariadic.h"
Eric Liu5740ff52018-01-31 16:26:27 +000018#include "llvm/Support/Path.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000019
Ilya Biryukov38d79772017-05-16 09:38:59 +000020using namespace clang::clangd;
21using namespace clang;
Sam McCalld20d7982018-07-09 14:25:59 +000022using namespace llvm;
Ilya Biryukov38d79772017-05-16 09:38:59 +000023
Ilya Biryukovafb55542017-05-16 14:40:30 +000024namespace {
25
Eric Liu5740ff52018-01-31 16:26:27 +000026/// \brief Supports a test URI scheme with relaxed constraints for lit tests.
27/// The path in a test URI will be combined with a platform-specific fake
28/// directory to form an absolute path. For example, test:///a.cpp is resolved
29/// C:\clangd-test\a.cpp on Windows and /clangd-test/a.cpp on Unix.
30class TestScheme : public URIScheme {
31public:
32 llvm::Expected<std::string>
33 getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,
34 llvm::StringRef /*HintPath*/) const override {
35 using namespace llvm::sys;
36 // Still require "/" in body to mimic file scheme, as we want lengths of an
37 // equivalent URI in both schemes to be the same.
38 if (!Body.startswith("/"))
39 return llvm::make_error<llvm::StringError>(
40 "Expect URI body to be an absolute path starting with '/': " + Body,
41 llvm::inconvertibleErrorCode());
42 Body = Body.ltrim('/');
Nico Weber0da22902018-04-10 13:14:03 +000043#ifdef _WIN32
Eric Liu5740ff52018-01-31 16:26:27 +000044 constexpr char TestDir[] = "C:\\clangd-test";
45#else
46 constexpr char TestDir[] = "/clangd-test";
47#endif
48 llvm::SmallVector<char, 16> Path(Body.begin(), Body.end());
49 path::native(Path);
50 auto Err = fs::make_absolute(TestDir, Path);
Eric Liucda25262018-02-01 12:44:52 +000051 if (Err)
52 llvm_unreachable("Failed to make absolute path in test scheme.");
Eric Liu5740ff52018-01-31 16:26:27 +000053 return std::string(Path.begin(), Path.end());
54 }
55
56 llvm::Expected<URI>
57 uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
58 llvm_unreachable("Clangd must never create a test URI.");
59 }
60};
61
62static URISchemeRegistry::Add<TestScheme>
63 X("test", "Test scheme for clangd lit tests.");
64
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000065SymbolKindBitset defaultSymbolKinds() {
66 SymbolKindBitset Defaults;
67 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
68 ++I)
69 Defaults.set(I);
70 return Defaults;
71}
72
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +000073CompletionItemKindBitset defaultCompletionItemKinds() {
74 CompletionItemKindBitset Defaults;
75 for (size_t I = CompletionItemKindMin;
76 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
77 Defaults.set(I);
78 return Defaults;
79}
80
Ilya Biryukovafb55542017-05-16 14:40:30 +000081} // namespace
82
Sam McCalld1a7a372018-01-31 13:40:48 +000083void ClangdLSPServer::onInitialize(InitializeParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +000084 if (Params.initializationOptions)
85 applyConfiguration(*Params.initializationOptions);
86
Ilya Biryukov7d60d202018-02-16 12:20:47 +000087 if (Params.rootUri && *Params.rootUri)
Ilya Biryukov652364b2018-09-26 05:48:29 +000088 Server->setRootPath(Params.rootUri->file());
Ilya Biryukov23bc73b2018-02-15 14:32:57 +000089 else if (Params.rootPath && !Params.rootPath->empty())
Ilya Biryukov652364b2018-09-26 05:48:29 +000090 Server->setRootPath(*Params.rootPath);
Ilya Biryukov23bc73b2018-02-15 14:32:57 +000091
92 CCOpts.EnableSnippets =
93 Params.capabilities.textDocument.completion.completionItem.snippetSupport;
Alex Lorenz8626d362018-08-10 17:25:07 +000094 DiagOpts.EmbedFixesInDiagnostics =
95 Params.capabilities.textDocument.publishDiagnostics.clangdFixSupport;
Alex Lorenz0ce8a7a2018-08-22 20:30:06 +000096 DiagOpts.SendDiagnosticCategory =
97 Params.capabilities.textDocument.publishDiagnostics.categorySupport;
Ilya Biryukov23bc73b2018-02-15 14:32:57 +000098
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000099 if (Params.capabilities.workspace && Params.capabilities.workspace->symbol &&
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000100 Params.capabilities.workspace->symbol->symbolKind &&
101 Params.capabilities.workspace->symbol->symbolKind->valueSet) {
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000102 for (SymbolKind Kind :
103 *Params.capabilities.workspace->symbol->symbolKind->valueSet) {
104 SupportedSymbolKinds.set(static_cast<size_t>(Kind));
105 }
106 }
107
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000108 if (Params.capabilities.textDocument.completion.completionItemKind &&
109 Params.capabilities.textDocument.completion.completionItemKind->valueSet)
110 for (CompletionItemKind Kind : *Params.capabilities.textDocument.completion
111 .completionItemKind->valueSet)
112 SupportedCompletionItemKinds.set(static_cast<size_t>(Kind));
113
Sam McCalld20d7982018-07-09 14:25:59 +0000114 reply(json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000115 {{"capabilities",
Sam McCalld20d7982018-07-09 14:25:59 +0000116 json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000117 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000118 {"documentFormattingProvider", true},
119 {"documentRangeFormattingProvider", true},
120 {"documentOnTypeFormattingProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000121 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000122 {"firstTriggerCharacter", "}"},
123 {"moreTriggerCharacter", {}},
124 }},
125 {"codeActionProvider", true},
126 {"completionProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000127 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000128 {"resolveProvider", false},
129 {"triggerCharacters", {".", ">", ":"}},
130 }},
131 {"signatureHelpProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000132 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000133 {"triggerCharacters", {"(", ","}},
134 }},
135 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000136 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000137 {"hoverProvider", true},
Haojian Wu345099c2017-11-09 11:30:04 +0000138 {"renameProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000139 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000140 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000141 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000142 {"executeCommandProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000143 json::Object{
Eric Liu2c190532018-05-15 15:23:53 +0000144 {"commands", {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND}},
Sam McCall0930ab02017-11-07 15:49:35 +0000145 }},
146 }}}});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000147}
148
Sam McCalld1a7a372018-01-31 13:40:48 +0000149void ClangdLSPServer::onShutdown(ShutdownParams &Params) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000150 // Do essentially nothing, just say we're ready to exit.
151 ShutdownRequestReceived = true;
Sam McCalld1a7a372018-01-31 13:40:48 +0000152 reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000153}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000154
Sam McCalld1a7a372018-01-31 13:40:48 +0000155void ClangdLSPServer::onExit(ExitParams &Params) { IsDone = true; }
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000156
Sam McCalld1a7a372018-01-31 13:40:48 +0000157void ClangdLSPServer::onDocumentDidOpen(DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000158 PathRef File = Params.textDocument.uri.file();
Alex Lorenzf8087862018-08-01 17:39:29 +0000159 if (Params.metadata && !Params.metadata->extraFlags.empty())
160 CDB.setExtraFlagsForFile(File, std::move(Params.metadata->extraFlags));
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000161
Simon Marchi9569fd52018-03-16 14:30:42 +0000162 std::string &Contents = Params.textDocument.text;
163
Simon Marchi98082622018-03-26 14:41:40 +0000164 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000165 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000166}
167
Sam McCalld1a7a372018-01-31 13:40:48 +0000168void ClangdLSPServer::onDocumentDidChange(DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000169 auto WantDiags = WantDiagnostics::Auto;
170 if (Params.wantDiagnostics.hasValue())
171 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
172 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000173
174 PathRef File = Params.textDocument.uri.file();
Simon Marchi98082622018-03-26 14:41:40 +0000175 llvm::Expected<std::string> Contents =
176 DraftMgr.updateDraft(File, Params.contentChanges);
177 if (!Contents) {
178 // If this fails, we are most likely going to be not in sync anymore with
179 // the client. It is better to remove the draft and let further operations
180 // fail rather than giving wrong results.
181 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000182 Server->removeDocument(File);
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000183 CDB.invalidate(File);
Sam McCallbed58852018-07-11 10:35:11 +0000184 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000185 return;
186 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000187
Ilya Biryukov652364b2018-09-26 05:48:29 +0000188 Server->addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000189}
190
Sam McCalld1a7a372018-01-31 13:40:48 +0000191void ClangdLSPServer::onFileEvent(DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000192 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000193}
194
Sam McCalld1a7a372018-01-31 13:40:48 +0000195void ClangdLSPServer::onCommand(ExecuteCommandParams &Params) {
Eric Liuc5105f92018-02-16 14:15:55 +0000196 auto ApplyEdit = [](WorkspaceEdit WE) {
197 ApplyWorkspaceEditParams Edit;
198 Edit.edit = std::move(WE);
199 // We don't need the response so id == 1 is OK.
200 // Ideally, we would wait for the response and if there is no error, we
201 // would reply success/failure to the original RPC.
202 call("workspace/applyEdit", Edit);
203 };
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000204 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
205 Params.workspaceEdit) {
206 // The flow for "apply-fix" :
207 // 1. We publish a diagnostic, including fixits
208 // 2. The user clicks on the diagnostic, the editor asks us for code actions
209 // 3. We send code actions, with the fixit embedded as context
210 // 4. The user selects the fixit, the editor asks us to apply it
211 // 5. We unwrap the changes and send them back to the editor
212 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
213 // we ignore it)
214
Sam McCalld1a7a372018-01-31 13:40:48 +0000215 reply("Fix applied.");
Eric Liuc5105f92018-02-16 14:15:55 +0000216 ApplyEdit(*Params.workspaceEdit);
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000217 } else {
218 // We should not get here because ExecuteCommandParams would not have
219 // parsed in the first place and this handler should not be called. But if
220 // more commands are added, this will be here has a safe guard.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000221 replyError(
Sam McCalld1a7a372018-01-31 13:40:48 +0000222 ErrorCode::InvalidParams,
Haojian Wu2375c922017-11-07 10:21:02 +0000223 llvm::formatv("Unsupported command \"{0}\".", Params.command).str());
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000224 }
225}
226
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000227void ClangdLSPServer::onWorkspaceSymbol(WorkspaceSymbolParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000228 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000229 Params.query, CCOpts.Limit,
230 [this](llvm::Expected<std::vector<SymbolInformation>> Items) {
231 if (!Items)
232 return replyError(ErrorCode::InternalError,
233 llvm::toString(Items.takeError()));
234 for (auto &Sym : *Items)
235 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
236
Sam McCalld20d7982018-07-09 14:25:59 +0000237 reply(json::Array(*Items));
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000238 });
239}
240
Sam McCalld1a7a372018-01-31 13:40:48 +0000241void ClangdLSPServer::onRename(RenameParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000242 Path File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000243 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000244 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000245 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000246 "onRename called for non-added file");
247
Ilya Biryukov652364b2018-09-26 05:48:29 +0000248 Server->rename(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000249 File, Params.position, Params.newName,
250 [File, Code,
251 Params](llvm::Expected<std::vector<tooling::Replacement>> Replacements) {
252 if (!Replacements)
253 return replyError(ErrorCode::InternalError,
254 llvm::toString(Replacements.takeError()));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000255
Eric Liu9133ecd2018-05-11 12:12:08 +0000256 // Turn the replacements into the format specified by the Language
257 // Server Protocol. Fuse them into one big JSON array.
258 std::vector<TextEdit> Edits;
259 for (const auto &R : *Replacements)
260 Edits.push_back(replacementToEdit(*Code, R));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000261 WorkspaceEdit WE;
262 WE.changes = {{Params.textDocument.uri.uri(), Edits}};
263 reply(WE);
264 });
Haojian Wu345099c2017-11-09 11:30:04 +0000265}
266
Sam McCalld1a7a372018-01-31 13:40:48 +0000267void ClangdLSPServer::onDocumentDidClose(DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000268 PathRef File = Params.textDocument.uri.file();
269 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000270 Server->removeDocument(File);
Alex Lorenzf8087862018-08-01 17:39:29 +0000271 CDB.invalidate(File);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000272}
273
Sam McCall4db732a2017-09-30 10:08:52 +0000274void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCalld1a7a372018-01-31 13:40:48 +0000275 DocumentOnTypeFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000276 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000277 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000278 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000279 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000280 "onDocumentOnTypeFormatting called for non-added file");
281
Ilya Biryukov652364b2018-09-26 05:48:29 +0000282 auto ReplacementsOrError = Server->formatOnType(*Code, File, Params.position);
Raoul Wols212bcf82017-12-12 20:25:06 +0000283 if (ReplacementsOrError)
Sam McCalld20d7982018-07-09 14:25:59 +0000284 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000285 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000286 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000287 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000288}
289
Sam McCall4db732a2017-09-30 10:08:52 +0000290void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCalld1a7a372018-01-31 13:40:48 +0000291 DocumentRangeFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000292 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000293 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000294 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000295 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000296 "onDocumentRangeFormatting called for non-added file");
297
Ilya Biryukov652364b2018-09-26 05:48:29 +0000298 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000299 if (ReplacementsOrError)
Sam McCalld20d7982018-07-09 14:25:59 +0000300 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000301 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000302 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000303 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000304}
305
Sam McCalld1a7a372018-01-31 13:40:48 +0000306void ClangdLSPServer::onDocumentFormatting(DocumentFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000307 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000308 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000309 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000310 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000311 "onDocumentFormatting called for non-added file");
312
Ilya Biryukov652364b2018-09-26 05:48:29 +0000313 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000314 if (ReplacementsOrError)
Sam McCalld20d7982018-07-09 14:25:59 +0000315 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000316 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000317 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000318 llvm::toString(ReplacementsOrError.takeError()));
Sam McCall4db732a2017-09-30 10:08:52 +0000319}
320
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000321void ClangdLSPServer::onDocumentSymbol(DocumentSymbolParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000322 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000323 Params.textDocument.uri.file(),
324 [this](llvm::Expected<std::vector<SymbolInformation>> Items) {
325 if (!Items)
326 return replyError(ErrorCode::InvalidParams,
327 llvm::toString(Items.takeError()));
328 for (auto &Sym : *Items)
329 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Sam McCalld20d7982018-07-09 14:25:59 +0000330 reply(json::Array(*Items));
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000331 });
332}
333
Sam McCalld1a7a372018-01-31 13:40:48 +0000334void ClangdLSPServer::onCodeAction(CodeActionParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000335 // We provide a code action for each diagnostic at the requested location
336 // which has FixIts available.
Simon Marchi9569fd52018-03-16 14:30:42 +0000337 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000338 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000339 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000340 "onCodeAction called for non-added file");
341
Sam McCalld20d7982018-07-09 14:25:59 +0000342 json::Array Commands;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000343 for (Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000344 for (auto &F : getFixes(Params.textDocument.uri.file(), D)) {
Sam McCalldd0566b2017-11-06 15:40:30 +0000345 WorkspaceEdit WE;
Ilya Biryukov71028b82018-03-12 15:28:22 +0000346 std::vector<TextEdit> Edits(F.Edits.begin(), F.Edits.end());
Eric Liu78ed91a72018-01-29 15:37:46 +0000347 WE.changes = {{Params.textDocument.uri.uri(), std::move(Edits)}};
Sam McCalld20d7982018-07-09 14:25:59 +0000348 Commands.push_back(json::Object{
Ilya Biryukov71028b82018-03-12 15:28:22 +0000349 {"title", llvm::formatv("Apply fix: {0}", F.Message)},
Sam McCalldd0566b2017-11-06 15:40:30 +0000350 {"command", ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND},
351 {"arguments", {WE}},
352 });
353 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000354 }
Sam McCalld1a7a372018-01-31 13:40:48 +0000355 reply(std::move(Commands));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000356}
357
Sam McCalld1a7a372018-01-31 13:40:48 +0000358void ClangdLSPServer::onCompletion(TextDocumentPositionParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000359 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
360 [this](llvm::Expected<CodeCompleteResult> List) {
361 if (!List)
362 return replyError(List.takeError());
363 CompletionList LSPList;
364 LSPList.isIncomplete = List->HasMore;
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000365 for (const auto &R : List->Completions) {
366 CompletionItem C = R.render(CCOpts);
367 C.kind = adjustKindToCapability(
368 C.kind, SupportedCompletionItemKinds);
369 LSPList.items.push_back(std::move(C));
370 }
Ilya Biryukov652364b2018-09-26 05:48:29 +0000371 return reply(std::move(LSPList));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000372 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000373}
374
Ilya Biryukov652364b2018-09-26 05:48:29 +0000375void ClangdLSPServer::onSignatureHelp(TextDocumentPositionParams &Params) {
376 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
377 [](llvm::Expected<SignatureHelp> SignatureHelp) {
378 if (!SignatureHelp)
379 return replyError(
380 ErrorCode::InvalidParams,
381 llvm::toString(SignatureHelp.takeError()));
382 reply(*SignatureHelp);
383 });
384}
385
Sam McCalld1a7a372018-01-31 13:40:48 +0000386void ClangdLSPServer::onGoToDefinition(TextDocumentPositionParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000387 Server->findDefinitions(Params.textDocument.uri.file(), Params.position,
388 [](llvm::Expected<std::vector<Location>> Items) {
389 if (!Items)
390 return replyError(
391 ErrorCode::InvalidParams,
392 llvm::toString(Items.takeError()));
393 reply(json::Array(*Items));
394 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000395}
396
Sam McCalld1a7a372018-01-31 13:40:48 +0000397void ClangdLSPServer::onSwitchSourceHeader(TextDocumentIdentifier &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000398 llvm::Optional<Path> Result = Server->switchSourceHeader(Params.uri.file());
Sam McCalld1a7a372018-01-31 13:40:48 +0000399 reply(Result ? URI::createFile(*Result).toString() : "");
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000400}
401
Sam McCalld1a7a372018-01-31 13:40:48 +0000402void ClangdLSPServer::onDocumentHighlight(TextDocumentPositionParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000403 Server->findDocumentHighlights(
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000404 Params.textDocument.uri.file(), Params.position,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000405 [](llvm::Expected<std::vector<DocumentHighlight>> Highlights) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000406 if (!Highlights)
407 return replyError(ErrorCode::InternalError,
408 llvm::toString(Highlights.takeError()));
Sam McCalld20d7982018-07-09 14:25:59 +0000409 reply(json::Array(*Highlights));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000410 });
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000411}
412
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000413void ClangdLSPServer::onHover(TextDocumentPositionParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000414 Server->findHover(Params.textDocument.uri.file(), Params.position,
415 [](llvm::Expected<llvm::Optional<Hover>> H) {
416 if (!H) {
417 replyError(ErrorCode::InternalError,
418 llvm::toString(H.takeError()));
419 return;
420 }
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000421
Ilya Biryukov652364b2018-09-26 05:48:29 +0000422 reply(*H);
423 });
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000424}
425
Simon Marchi88016782018-08-01 11:28:49 +0000426void ClangdLSPServer::applyConfiguration(
427 const ClangdConfigurationParamsChange &Settings) {
Simon Marchi5178f922018-02-22 14:00:39 +0000428 // Compilation database change.
429 if (Settings.compilationDatabasePath.hasValue()) {
Alex Lorenzf8087862018-08-01 17:39:29 +0000430 CDB.setCompileCommandsDir(Settings.compilationDatabasePath.getValue());
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000431
Simon Marchi9569fd52018-03-16 14:30:42 +0000432 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +0000433 }
Alex Lorenzf8087862018-08-01 17:39:29 +0000434
435 // Update to the compilation database.
436 if (Settings.compilationDatabaseChanges) {
437 const auto &CompileCommandUpdates = *Settings.compilationDatabaseChanges;
438 bool ShouldReparseOpenFiles = false;
439 for (auto &Entry : CompileCommandUpdates) {
440 /// The opened files need to be reparsed only when some existing
441 /// entries are changed.
442 PathRef File = Entry.first;
443 if (!CDB.setCompilationCommandForFile(
444 File, tooling::CompileCommand(
445 std::move(Entry.second.workingDirectory), File,
446 std::move(Entry.second.compilationCommand),
447 /*Output=*/"")))
448 ShouldReparseOpenFiles = true;
449 }
450 if (ShouldReparseOpenFiles)
451 reparseOpenedFiles();
452 }
Simon Marchi5178f922018-02-22 14:00:39 +0000453}
454
Simon Marchi88016782018-08-01 11:28:49 +0000455// FIXME: This function needs to be properly tested.
456void ClangdLSPServer::onChangeConfiguration(
457 DidChangeConfigurationParams &Params) {
458 applyConfiguration(Params.settings);
459}
460
Sam McCall1ad142f2018-09-05 11:53:07 +0000461void ClangdLSPServer::onReference(ReferenceParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000462 Server->findReferences(Params.textDocument.uri.file(), Params.position,
463 [](llvm::Expected<std::vector<Location>> Locations) {
464 if (!Locations)
465 return replyError(
466 ErrorCode::InternalError,
467 llvm::toString(Locations.takeError()));
468 reply(llvm::json::Array(*Locations));
469 });
Sam McCall1ad142f2018-09-05 11:53:07 +0000470}
471
Sam McCall7363a2f2018-03-05 17:28:54 +0000472ClangdLSPServer::ClangdLSPServer(JSONOutput &Out,
Sam McCalladccab62017-11-23 16:58:22 +0000473 const clangd::CodeCompleteOptions &CCOpts,
Eric Liubfac8f72017-12-19 18:00:37 +0000474 llvm::Optional<Path> CompileCommandsDir,
Alex Lorenzf8087862018-08-01 17:39:29 +0000475 bool ShouldUseInMemoryCDB,
Sam McCall7363a2f2018-03-05 17:28:54 +0000476 const ClangdServer::Options &Opts)
Alex Lorenzf8087862018-08-01 17:39:29 +0000477 : Out(Out), CDB(ShouldUseInMemoryCDB ? CompilationDB::makeInMemory()
478 : CompilationDB::makeDirectoryBased(
479 std::move(CompileCommandsDir))),
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000480 CCOpts(CCOpts), SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000481 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Ilya Biryukov652364b2018-09-26 05:48:29 +0000482 Server(new ClangdServer(CDB.getCDB(), FSProvider, /*DiagConsumer=*/*this,
483 Opts)) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000484
Sam McCall27a07cf2018-06-05 09:34:46 +0000485bool ClangdLSPServer::run(std::FILE *In, JSONStreamStyle InputStyle) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000486 assert(!IsDone && "Run was called before");
Ilya Biryukov652364b2018-09-26 05:48:29 +0000487 assert(Server);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000488
Ilya Biryukovafb55542017-05-16 14:40:30 +0000489 // Set up JSONRPCDispatcher.
Sam McCalld20d7982018-07-09 14:25:59 +0000490 JSONRPCDispatcher Dispatcher([](const json::Value &Params) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000491 replyError(ErrorCode::MethodNotFound, "method not found");
Ilya Biryukov940901e2017-12-13 12:51:22 +0000492 });
Simon Marchi6e8eb9d2018-03-07 21:47:25 +0000493 registerCallbackHandlers(Dispatcher, /*Callbacks=*/*this);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000494
Ilya Biryukovafb55542017-05-16 14:40:30 +0000495 // Run the Language Server loop.
Sam McCall5ed599e2018-02-06 10:47:30 +0000496 runLanguageServerLoop(In, Out, InputStyle, Dispatcher, IsDone);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000497
498 // Make sure IsDone is set to true after this method exits to ensure assertion
499 // at the start of the method fires if it's ever executed again.
500 IsDone = true;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000501 // Destroy ClangdServer to ensure all worker threads finish.
502 Server.reset();
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000503
504 return ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000505}
506
Ilya Biryukov71028b82018-03-12 15:28:22 +0000507std::vector<Fix> ClangdLSPServer::getFixes(StringRef File,
508 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000509 std::lock_guard<std::mutex> Lock(FixItsMutex);
510 auto DiagToFixItsIter = FixItsMap.find(File);
511 if (DiagToFixItsIter == FixItsMap.end())
512 return {};
513
514 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
515 auto FixItsIter = DiagToFixItsMap.find(D);
516 if (FixItsIter == DiagToFixItsMap.end())
517 return {};
518
519 return FixItsIter->second;
520}
521
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000522void ClangdLSPServer::onDiagnosticsReady(PathRef File,
523 std::vector<Diag> Diagnostics) {
Sam McCalld20d7982018-07-09 14:25:59 +0000524 json::Array DiagnosticsJSON;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000525
526 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000527 for (auto &Diag : Diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000528 toLSPDiags(Diag, [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Alex Lorenz8626d362018-08-10 17:25:07 +0000529 json::Object LSPDiag({
Ilya Biryukov71028b82018-03-12 15:28:22 +0000530 {"range", Diag.range},
531 {"severity", Diag.severity},
532 {"message", Diag.message},
533 });
Alex Lorenz8626d362018-08-10 17:25:07 +0000534 // LSP extension: embed the fixes in the diagnostic.
535 if (DiagOpts.EmbedFixesInDiagnostics && !Fixes.empty()) {
536 json::Array ClangdFixes;
537 for (const auto &Fix : Fixes) {
538 WorkspaceEdit WE;
539 URIForFile URI{File};
540 WE.changes = {{URI.uri(), std::vector<TextEdit>(Fix.Edits.begin(),
541 Fix.Edits.end())}};
542 ClangdFixes.push_back(
543 json::Object{{"edit", toJSON(WE)}, {"title", Fix.Message}});
544 }
545 LSPDiag["clangd_fixes"] = std::move(ClangdFixes);
546 }
Alex Lorenz0ce8a7a2018-08-22 20:30:06 +0000547 if (DiagOpts.SendDiagnosticCategory && !Diag.category.empty())
Alex Lorenz37146432018-08-14 22:21:40 +0000548 LSPDiag["category"] = Diag.category;
Alex Lorenz8626d362018-08-10 17:25:07 +0000549 DiagnosticsJSON.push_back(std::move(LSPDiag));
Ilya Biryukov71028b82018-03-12 15:28:22 +0000550
551 auto &FixItsForDiagnostic = LocalFixIts[Diag];
Kirill Bobyrev4a5ff882018-10-07 14:49:41 +0000552 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
Sam McCalldd0566b2017-11-06 15:40:30 +0000553 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000554 }
555
556 // Cache FixIts
557 {
558 // FIXME(ibiryukov): should be deleted when documents are removed
559 std::lock_guard<std::mutex> Lock(FixItsMutex);
560 FixItsMap[File] = LocalFixIts;
561 }
562
563 // Publish diagnostics.
Sam McCalld20d7982018-07-09 14:25:59 +0000564 Out.writeMessage(json::Object{
Sam McCalldd0566b2017-11-06 15:40:30 +0000565 {"jsonrpc", "2.0"},
566 {"method", "textDocument/publishDiagnostics"},
567 {"params",
Sam McCalld20d7982018-07-09 14:25:59 +0000568 json::Object{
Eric Liu78ed91a72018-01-29 15:37:46 +0000569 {"uri", URIForFile{File}},
Sam McCalldd0566b2017-11-06 15:40:30 +0000570 {"diagnostics", std::move(DiagnosticsJSON)},
571 }},
572 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000573}
Simon Marchi9569fd52018-03-16 14:30:42 +0000574
575void ClangdLSPServer::reparseOpenedFiles() {
576 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +0000577 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
578 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +0000579}
Alex Lorenzf8087862018-08-01 17:39:29 +0000580
581ClangdLSPServer::CompilationDB ClangdLSPServer::CompilationDB::makeInMemory() {
582 return CompilationDB(llvm::make_unique<InMemoryCompilationDb>(), nullptr,
583 /*IsDirectoryBased=*/false);
584}
585
586ClangdLSPServer::CompilationDB
587ClangdLSPServer::CompilationDB::makeDirectoryBased(
588 llvm::Optional<Path> CompileCommandsDir) {
589 auto CDB = llvm::make_unique<DirectoryBasedGlobalCompilationDatabase>(
590 std::move(CompileCommandsDir));
591 auto CachingCDB = llvm::make_unique<CachingCompilationDb>(*CDB);
592 return CompilationDB(std::move(CDB), std::move(CachingCDB),
593 /*IsDirectoryBased=*/true);
594}
595
596void ClangdLSPServer::CompilationDB::invalidate(PathRef File) {
597 if (!IsDirectoryBased)
598 static_cast<InMemoryCompilationDb *>(CDB.get())->invalidate(File);
599 else
600 CachingCDB->invalidate(File);
601}
602
603bool ClangdLSPServer::CompilationDB::setCompilationCommandForFile(
604 PathRef File, tooling::CompileCommand CompilationCommand) {
605 if (IsDirectoryBased) {
606 elog("Trying to set compile command for {0} while using directory-based "
607 "compilation database",
608 File);
609 return false;
610 }
611 return static_cast<InMemoryCompilationDb *>(CDB.get())
612 ->setCompilationCommandForFile(File, std::move(CompilationCommand));
613}
614
615void ClangdLSPServer::CompilationDB::setExtraFlagsForFile(
616 PathRef File, std::vector<std::string> ExtraFlags) {
617 if (!IsDirectoryBased) {
618 elog("Trying to set extra flags for {0} while using in-memory compilation "
619 "database",
620 File);
621 return;
622 }
623 static_cast<DirectoryBasedGlobalCompilationDatabase *>(CDB.get())
624 ->setExtraFlagsForFile(File, std::move(ExtraFlags));
625 CachingCDB->invalidate(File);
626}
627
628void ClangdLSPServer::CompilationDB::setCompileCommandsDir(Path P) {
629 if (!IsDirectoryBased) {
630 elog("Trying to set compile commands dir while using in-memory compilation "
631 "database");
632 return;
633 }
634 static_cast<DirectoryBasedGlobalCompilationDatabase *>(CDB.get())
635 ->setCompileCommandsDir(P);
636 CachingCDB->clear();
637}
638
639GlobalCompilationDatabase &ClangdLSPServer::CompilationDB::getCDB() {
640 if (CachingCDB)
641 return *CachingCDB;
642 return *CDB;
643}