blob: 073d8b1e93b4db75a228c578f9997135cebae91d [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 Marchiabeed662018-10-16 15:55:03 +000084 if (Params.initializationOptions) {
85 const ClangdInitializationOptions &Opts = *Params.initializationOptions;
86
87 // Explicit compilation database path.
88 if (Opts.compilationDatabasePath.hasValue()) {
89 CDB.setCompileCommandsDir(Opts.compilationDatabasePath.getValue());
90 }
91
92 applyConfiguration(Opts.ParamsChange);
93 }
Simon Marchi88016782018-08-01 11:28:49 +000094
Ilya Biryukov7d60d202018-02-16 12:20:47 +000095 if (Params.rootUri && *Params.rootUri)
Ilya Biryukov652364b2018-09-26 05:48:29 +000096 Server->setRootPath(Params.rootUri->file());
Ilya Biryukov23bc73b2018-02-15 14:32:57 +000097 else if (Params.rootPath && !Params.rootPath->empty())
Ilya Biryukov652364b2018-09-26 05:48:29 +000098 Server->setRootPath(*Params.rootPath);
Ilya Biryukov23bc73b2018-02-15 14:32:57 +000099
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000100 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
101 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
102 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
103 if (Params.capabilities.WorkspaceSymbolKinds)
104 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
105 if (Params.capabilities.CompletionItemKinds)
106 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
107 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000108
Sam McCalld20d7982018-07-09 14:25:59 +0000109 reply(json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000110 {{"capabilities",
Sam McCalld20d7982018-07-09 14:25:59 +0000111 json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000112 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000113 {"documentFormattingProvider", true},
114 {"documentRangeFormattingProvider", true},
115 {"documentOnTypeFormattingProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000116 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000117 {"firstTriggerCharacter", "}"},
118 {"moreTriggerCharacter", {}},
119 }},
120 {"codeActionProvider", true},
121 {"completionProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000122 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000123 {"resolveProvider", false},
124 {"triggerCharacters", {".", ">", ":"}},
125 }},
126 {"signatureHelpProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000127 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000128 {"triggerCharacters", {"(", ","}},
129 }},
130 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000131 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000132 {"hoverProvider", true},
Haojian Wu345099c2017-11-09 11:30:04 +0000133 {"renameProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000134 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000135 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000136 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000137 {"executeCommandProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000138 json::Object{
Eric Liu2c190532018-05-15 15:23:53 +0000139 {"commands", {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND}},
Sam McCall0930ab02017-11-07 15:49:35 +0000140 }},
141 }}}});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000142}
143
Sam McCalld1a7a372018-01-31 13:40:48 +0000144void ClangdLSPServer::onShutdown(ShutdownParams &Params) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000145 // Do essentially nothing, just say we're ready to exit.
146 ShutdownRequestReceived = true;
Sam McCalld1a7a372018-01-31 13:40:48 +0000147 reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000148}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000149
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000150void ClangdLSPServer::onExit(ExitParams &Params) {
151 // No work to do.
152 // JSONRPCDispatcher shuts down the transport after this notification.
153}
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000154
Sam McCalld1a7a372018-01-31 13:40:48 +0000155void ClangdLSPServer::onDocumentDidOpen(DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000156 PathRef File = Params.textDocument.uri.file();
Alex Lorenzf8087862018-08-01 17:39:29 +0000157 if (Params.metadata && !Params.metadata->extraFlags.empty())
158 CDB.setExtraFlagsForFile(File, std::move(Params.metadata->extraFlags));
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000159
Simon Marchi9569fd52018-03-16 14:30:42 +0000160 std::string &Contents = Params.textDocument.text;
161
Simon Marchi98082622018-03-26 14:41:40 +0000162 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000163 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000164}
165
Sam McCalld1a7a372018-01-31 13:40:48 +0000166void ClangdLSPServer::onDocumentDidChange(DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000167 auto WantDiags = WantDiagnostics::Auto;
168 if (Params.wantDiagnostics.hasValue())
169 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
170 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000171
172 PathRef File = Params.textDocument.uri.file();
Simon Marchi98082622018-03-26 14:41:40 +0000173 llvm::Expected<std::string> Contents =
174 DraftMgr.updateDraft(File, Params.contentChanges);
175 if (!Contents) {
176 // If this fails, we are most likely going to be not in sync anymore with
177 // the client. It is better to remove the draft and let further operations
178 // fail rather than giving wrong results.
179 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000180 Server->removeDocument(File);
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000181 CDB.invalidate(File);
Sam McCallbed58852018-07-11 10:35:11 +0000182 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000183 return;
184 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000185
Ilya Biryukov652364b2018-09-26 05:48:29 +0000186 Server->addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000187}
188
Sam McCalld1a7a372018-01-31 13:40:48 +0000189void ClangdLSPServer::onFileEvent(DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000190 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000191}
192
Sam McCalld1a7a372018-01-31 13:40:48 +0000193void ClangdLSPServer::onCommand(ExecuteCommandParams &Params) {
Eric Liuc5105f92018-02-16 14:15:55 +0000194 auto ApplyEdit = [](WorkspaceEdit WE) {
195 ApplyWorkspaceEditParams Edit;
196 Edit.edit = std::move(WE);
197 // We don't need the response so id == 1 is OK.
198 // Ideally, we would wait for the response and if there is no error, we
199 // would reply success/failure to the original RPC.
200 call("workspace/applyEdit", Edit);
201 };
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000202 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
203 Params.workspaceEdit) {
204 // The flow for "apply-fix" :
205 // 1. We publish a diagnostic, including fixits
206 // 2. The user clicks on the diagnostic, the editor asks us for code actions
207 // 3. We send code actions, with the fixit embedded as context
208 // 4. The user selects the fixit, the editor asks us to apply it
209 // 5. We unwrap the changes and send them back to the editor
210 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
211 // we ignore it)
212
Sam McCalld1a7a372018-01-31 13:40:48 +0000213 reply("Fix applied.");
Eric Liuc5105f92018-02-16 14:15:55 +0000214 ApplyEdit(*Params.workspaceEdit);
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000215 } else {
216 // We should not get here because ExecuteCommandParams would not have
217 // parsed in the first place and this handler should not be called. But if
218 // more commands are added, this will be here has a safe guard.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000219 replyError(
Sam McCalld1a7a372018-01-31 13:40:48 +0000220 ErrorCode::InvalidParams,
Haojian Wu2375c922017-11-07 10:21:02 +0000221 llvm::formatv("Unsupported command \"{0}\".", Params.command).str());
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000222 }
223}
224
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000225void ClangdLSPServer::onWorkspaceSymbol(WorkspaceSymbolParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000226 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000227 Params.query, CCOpts.Limit,
228 [this](llvm::Expected<std::vector<SymbolInformation>> Items) {
229 if (!Items)
230 return replyError(ErrorCode::InternalError,
231 llvm::toString(Items.takeError()));
232 for (auto &Sym : *Items)
233 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
234
Sam McCalld20d7982018-07-09 14:25:59 +0000235 reply(json::Array(*Items));
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000236 });
237}
238
Sam McCalld1a7a372018-01-31 13:40:48 +0000239void ClangdLSPServer::onRename(RenameParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000240 Path File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000241 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000242 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000243 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000244 "onRename called for non-added file");
245
Ilya Biryukov652364b2018-09-26 05:48:29 +0000246 Server->rename(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000247 File, Params.position, Params.newName,
248 [File, Code,
249 Params](llvm::Expected<std::vector<tooling::Replacement>> Replacements) {
250 if (!Replacements)
251 return replyError(ErrorCode::InternalError,
252 llvm::toString(Replacements.takeError()));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000253
Eric Liu9133ecd2018-05-11 12:12:08 +0000254 // Turn the replacements into the format specified by the Language
255 // Server Protocol. Fuse them into one big JSON array.
256 std::vector<TextEdit> Edits;
257 for (const auto &R : *Replacements)
258 Edits.push_back(replacementToEdit(*Code, R));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000259 WorkspaceEdit WE;
260 WE.changes = {{Params.textDocument.uri.uri(), Edits}};
261 reply(WE);
262 });
Haojian Wu345099c2017-11-09 11:30:04 +0000263}
264
Sam McCalld1a7a372018-01-31 13:40:48 +0000265void ClangdLSPServer::onDocumentDidClose(DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000266 PathRef File = Params.textDocument.uri.file();
267 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000268 Server->removeDocument(File);
Alex Lorenzf8087862018-08-01 17:39:29 +0000269 CDB.invalidate(File);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000270}
271
Sam McCall4db732a2017-09-30 10:08:52 +0000272void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCalld1a7a372018-01-31 13:40:48 +0000273 DocumentOnTypeFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000274 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000275 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000276 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000277 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000278 "onDocumentOnTypeFormatting called for non-added file");
279
Ilya Biryukov652364b2018-09-26 05:48:29 +0000280 auto ReplacementsOrError = Server->formatOnType(*Code, File, Params.position);
Raoul Wols212bcf82017-12-12 20:25:06 +0000281 if (ReplacementsOrError)
Sam McCalld20d7982018-07-09 14:25:59 +0000282 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000283 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000284 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000285 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000286}
287
Sam McCall4db732a2017-09-30 10:08:52 +0000288void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCalld1a7a372018-01-31 13:40:48 +0000289 DocumentRangeFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000290 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000291 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000292 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000293 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000294 "onDocumentRangeFormatting called for non-added file");
295
Ilya Biryukov652364b2018-09-26 05:48:29 +0000296 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000297 if (ReplacementsOrError)
Sam McCalld20d7982018-07-09 14:25:59 +0000298 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000299 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000300 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000301 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000302}
303
Sam McCalld1a7a372018-01-31 13:40:48 +0000304void ClangdLSPServer::onDocumentFormatting(DocumentFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000305 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000306 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000307 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000308 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000309 "onDocumentFormatting called for non-added file");
310
Ilya Biryukov652364b2018-09-26 05:48:29 +0000311 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000312 if (ReplacementsOrError)
Sam McCalld20d7982018-07-09 14:25:59 +0000313 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000314 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000315 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000316 llvm::toString(ReplacementsOrError.takeError()));
Sam McCall4db732a2017-09-30 10:08:52 +0000317}
318
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000319void ClangdLSPServer::onDocumentSymbol(DocumentSymbolParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000320 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000321 Params.textDocument.uri.file(),
322 [this](llvm::Expected<std::vector<SymbolInformation>> Items) {
323 if (!Items)
324 return replyError(ErrorCode::InvalidParams,
325 llvm::toString(Items.takeError()));
326 for (auto &Sym : *Items)
327 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Sam McCalld20d7982018-07-09 14:25:59 +0000328 reply(json::Array(*Items));
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000329 });
330}
331
Sam McCall20841d42018-10-16 16:29:41 +0000332static Optional<Command> asCommand(const CodeAction &Action) {
333 Command Cmd;
334 if (Action.command && Action.edit)
335 return llvm::None; // Not representable. (We never emit these anyway).
336 if (Action.command) {
337 Cmd = *Action.command;
338 } else if (Action.edit) {
339 Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
340 Cmd.workspaceEdit = *Action.edit;
341 } else {
342 return llvm::None;
343 }
344 Cmd.title = Action.title;
345 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
346 Cmd.title = "Apply fix: " + Cmd.title;
347 return Cmd;
348}
349
Sam McCalld1a7a372018-01-31 13:40:48 +0000350void ClangdLSPServer::onCodeAction(CodeActionParams &Params) {
Sam McCall20841d42018-10-16 16:29:41 +0000351 // We provide a code action for Fixes on the specified diagnostics.
352 if (!DraftMgr.getDraft(Params.textDocument.uri.file()))
Sam McCalld1a7a372018-01-31 13:40:48 +0000353 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000354 "onCodeAction called for non-added file");
355
Sam McCall20841d42018-10-16 16:29:41 +0000356 std::vector<CodeAction> Actions;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000357 for (Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000358 for (auto &F : getFixes(Params.textDocument.uri.file(), D)) {
Sam McCall20841d42018-10-16 16:29:41 +0000359 Actions.emplace_back();
360 Actions.back().title = F.Message;
361 Actions.back().kind = CodeAction::QUICKFIX_KIND;
362 Actions.back().diagnostics = {D};
363 Actions.back().edit.emplace();
364 Actions.back().edit->changes.emplace();
365 (*Actions.back().edit->changes)[Params.textDocument.uri.uri()] = {
366 F.Edits.begin(), F.Edits.end()};
Sam McCalldd0566b2017-11-06 15:40:30 +0000367 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000368 }
Sam McCall20841d42018-10-16 16:29:41 +0000369
370 if (SupportsCodeAction)
371 reply(json::Array(Actions));
372 else {
373 std::vector<Command> Commands;
374 for (const auto &Action : Actions)
375 if (auto Command = asCommand(Action))
376 Commands.push_back(std::move(*Command));
377 reply(json::Array(Commands));
378 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000379}
380
Sam McCalld1a7a372018-01-31 13:40:48 +0000381void ClangdLSPServer::onCompletion(TextDocumentPositionParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000382 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
383 [this](llvm::Expected<CodeCompleteResult> List) {
384 if (!List)
385 return replyError(List.takeError());
386 CompletionList LSPList;
387 LSPList.isIncomplete = List->HasMore;
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000388 for (const auto &R : List->Completions) {
389 CompletionItem C = R.render(CCOpts);
390 C.kind = adjustKindToCapability(
391 C.kind, SupportedCompletionItemKinds);
392 LSPList.items.push_back(std::move(C));
393 }
Ilya Biryukov652364b2018-09-26 05:48:29 +0000394 return reply(std::move(LSPList));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000395 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000396}
397
Ilya Biryukov652364b2018-09-26 05:48:29 +0000398void ClangdLSPServer::onSignatureHelp(TextDocumentPositionParams &Params) {
399 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
400 [](llvm::Expected<SignatureHelp> SignatureHelp) {
401 if (!SignatureHelp)
402 return replyError(
403 ErrorCode::InvalidParams,
404 llvm::toString(SignatureHelp.takeError()));
405 reply(*SignatureHelp);
406 });
407}
408
Sam McCalld1a7a372018-01-31 13:40:48 +0000409void ClangdLSPServer::onGoToDefinition(TextDocumentPositionParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000410 Server->findDefinitions(Params.textDocument.uri.file(), Params.position,
411 [](llvm::Expected<std::vector<Location>> Items) {
412 if (!Items)
413 return replyError(
414 ErrorCode::InvalidParams,
415 llvm::toString(Items.takeError()));
416 reply(json::Array(*Items));
417 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000418}
419
Sam McCalld1a7a372018-01-31 13:40:48 +0000420void ClangdLSPServer::onSwitchSourceHeader(TextDocumentIdentifier &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000421 llvm::Optional<Path> Result = Server->switchSourceHeader(Params.uri.file());
Sam McCalld1a7a372018-01-31 13:40:48 +0000422 reply(Result ? URI::createFile(*Result).toString() : "");
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000423}
424
Sam McCalld1a7a372018-01-31 13:40:48 +0000425void ClangdLSPServer::onDocumentHighlight(TextDocumentPositionParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000426 Server->findDocumentHighlights(
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000427 Params.textDocument.uri.file(), Params.position,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000428 [](llvm::Expected<std::vector<DocumentHighlight>> Highlights) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000429 if (!Highlights)
430 return replyError(ErrorCode::InternalError,
431 llvm::toString(Highlights.takeError()));
Sam McCalld20d7982018-07-09 14:25:59 +0000432 reply(json::Array(*Highlights));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000433 });
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000434}
435
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000436void ClangdLSPServer::onHover(TextDocumentPositionParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000437 Server->findHover(Params.textDocument.uri.file(), Params.position,
438 [](llvm::Expected<llvm::Optional<Hover>> H) {
439 if (!H) {
440 replyError(ErrorCode::InternalError,
441 llvm::toString(H.takeError()));
442 return;
443 }
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000444
Ilya Biryukov652364b2018-09-26 05:48:29 +0000445 reply(*H);
446 });
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000447}
448
Simon Marchi88016782018-08-01 11:28:49 +0000449void ClangdLSPServer::applyConfiguration(
Simon Marchiabeed662018-10-16 15:55:03 +0000450 const ClangdConfigurationParamsChange &Params) {
451 // Per-file update to the compilation database.
452 if (Params.compilationDatabaseChanges) {
453 const auto &CompileCommandUpdates = *Params.compilationDatabaseChanges;
Alex Lorenzf8087862018-08-01 17:39:29 +0000454 bool ShouldReparseOpenFiles = false;
455 for (auto &Entry : CompileCommandUpdates) {
456 /// The opened files need to be reparsed only when some existing
457 /// entries are changed.
458 PathRef File = Entry.first;
459 if (!CDB.setCompilationCommandForFile(
460 File, tooling::CompileCommand(
461 std::move(Entry.second.workingDirectory), File,
462 std::move(Entry.second.compilationCommand),
463 /*Output=*/"")))
464 ShouldReparseOpenFiles = true;
465 }
466 if (ShouldReparseOpenFiles)
467 reparseOpenedFiles();
468 }
Simon Marchi5178f922018-02-22 14:00:39 +0000469}
470
Simon Marchi88016782018-08-01 11:28:49 +0000471// FIXME: This function needs to be properly tested.
472void ClangdLSPServer::onChangeConfiguration(
473 DidChangeConfigurationParams &Params) {
474 applyConfiguration(Params.settings);
475}
476
Sam McCall1ad142f2018-09-05 11:53:07 +0000477void ClangdLSPServer::onReference(ReferenceParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000478 Server->findReferences(Params.textDocument.uri.file(), Params.position,
479 [](llvm::Expected<std::vector<Location>> Locations) {
480 if (!Locations)
481 return replyError(
482 ErrorCode::InternalError,
483 llvm::toString(Locations.takeError()));
484 reply(llvm::json::Array(*Locations));
485 });
Sam McCall1ad142f2018-09-05 11:53:07 +0000486}
487
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000488ClangdLSPServer::ClangdLSPServer(class Transport &Transp,
Sam McCalladccab62017-11-23 16:58:22 +0000489 const clangd::CodeCompleteOptions &CCOpts,
Eric Liubfac8f72017-12-19 18:00:37 +0000490 llvm::Optional<Path> CompileCommandsDir,
Alex Lorenzf8087862018-08-01 17:39:29 +0000491 bool ShouldUseInMemoryCDB,
Sam McCall7363a2f2018-03-05 17:28:54 +0000492 const ClangdServer::Options &Opts)
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000493 : Transp(Transp),
494 CDB(ShouldUseInMemoryCDB ? CompilationDB::makeInMemory()
495 : CompilationDB::makeDirectoryBased(
496 std::move(CompileCommandsDir))),
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000497 CCOpts(CCOpts), SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000498 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Ilya Biryukov652364b2018-09-26 05:48:29 +0000499 Server(new ClangdServer(CDB.getCDB(), FSProvider, /*DiagConsumer=*/*this,
500 Opts)) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000501
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000502bool ClangdLSPServer::run() {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000503 assert(Server);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000504
Ilya Biryukovafb55542017-05-16 14:40:30 +0000505 // Set up JSONRPCDispatcher.
Sam McCalld20d7982018-07-09 14:25:59 +0000506 JSONRPCDispatcher Dispatcher([](const json::Value &Params) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000507 replyError(ErrorCode::MethodNotFound, "method not found");
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000508 return true;
Ilya Biryukov940901e2017-12-13 12:51:22 +0000509 });
Simon Marchi6e8eb9d2018-03-07 21:47:25 +0000510 registerCallbackHandlers(Dispatcher, /*Callbacks=*/*this);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000511
Ilya Biryukovafb55542017-05-16 14:40:30 +0000512 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000513 bool CleanExit = true;
514 if (auto Err = Dispatcher.runLanguageServerLoop(Transp)) {
515 elog("Transport error: {0}", std::move(Err));
516 CleanExit = false;
517 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000518
Ilya Biryukov652364b2018-09-26 05:48:29 +0000519 // Destroy ClangdServer to ensure all worker threads finish.
520 Server.reset();
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000521
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000522 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000523}
524
Ilya Biryukov71028b82018-03-12 15:28:22 +0000525std::vector<Fix> ClangdLSPServer::getFixes(StringRef File,
526 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000527 std::lock_guard<std::mutex> Lock(FixItsMutex);
528 auto DiagToFixItsIter = FixItsMap.find(File);
529 if (DiagToFixItsIter == FixItsMap.end())
530 return {};
531
532 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
533 auto FixItsIter = DiagToFixItsMap.find(D);
534 if (FixItsIter == DiagToFixItsMap.end())
535 return {};
536
537 return FixItsIter->second;
538}
539
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000540void ClangdLSPServer::onDiagnosticsReady(PathRef File,
541 std::vector<Diag> Diagnostics) {
Sam McCalld20d7982018-07-09 14:25:59 +0000542 json::Array DiagnosticsJSON;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000543
544 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000545 for (auto &Diag : Diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000546 toLSPDiags(Diag, [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Alex Lorenz8626d362018-08-10 17:25:07 +0000547 json::Object LSPDiag({
Ilya Biryukov71028b82018-03-12 15:28:22 +0000548 {"range", Diag.range},
549 {"severity", Diag.severity},
550 {"message", Diag.message},
551 });
Alex Lorenz8626d362018-08-10 17:25:07 +0000552 // LSP extension: embed the fixes in the diagnostic.
553 if (DiagOpts.EmbedFixesInDiagnostics && !Fixes.empty()) {
554 json::Array ClangdFixes;
555 for (const auto &Fix : Fixes) {
556 WorkspaceEdit WE;
557 URIForFile URI{File};
558 WE.changes = {{URI.uri(), std::vector<TextEdit>(Fix.Edits.begin(),
559 Fix.Edits.end())}};
560 ClangdFixes.push_back(
561 json::Object{{"edit", toJSON(WE)}, {"title", Fix.Message}});
562 }
563 LSPDiag["clangd_fixes"] = std::move(ClangdFixes);
564 }
Alex Lorenz0ce8a7a2018-08-22 20:30:06 +0000565 if (DiagOpts.SendDiagnosticCategory && !Diag.category.empty())
Alex Lorenz37146432018-08-14 22:21:40 +0000566 LSPDiag["category"] = Diag.category;
Alex Lorenz8626d362018-08-10 17:25:07 +0000567 DiagnosticsJSON.push_back(std::move(LSPDiag));
Ilya Biryukov71028b82018-03-12 15:28:22 +0000568
569 auto &FixItsForDiagnostic = LocalFixIts[Diag];
Kirill Bobyrev4a5ff882018-10-07 14:49:41 +0000570 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
Sam McCalldd0566b2017-11-06 15:40:30 +0000571 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000572 }
573
574 // Cache FixIts
575 {
576 // FIXME(ibiryukov): should be deleted when documents are removed
577 std::lock_guard<std::mutex> Lock(FixItsMutex);
578 FixItsMap[File] = LocalFixIts;
579 }
580
581 // Publish diagnostics.
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000582 Transp.notify("textDocument/publishDiagnostics",
583 json::Object{
584 {"uri", URIForFile{File}},
585 {"diagnostics", std::move(DiagnosticsJSON)},
586 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000587}
Simon Marchi9569fd52018-03-16 14:30:42 +0000588
589void ClangdLSPServer::reparseOpenedFiles() {
590 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +0000591 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
592 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +0000593}
Alex Lorenzf8087862018-08-01 17:39:29 +0000594
595ClangdLSPServer::CompilationDB ClangdLSPServer::CompilationDB::makeInMemory() {
596 return CompilationDB(llvm::make_unique<InMemoryCompilationDb>(), nullptr,
597 /*IsDirectoryBased=*/false);
598}
599
600ClangdLSPServer::CompilationDB
601ClangdLSPServer::CompilationDB::makeDirectoryBased(
602 llvm::Optional<Path> CompileCommandsDir) {
603 auto CDB = llvm::make_unique<DirectoryBasedGlobalCompilationDatabase>(
604 std::move(CompileCommandsDir));
605 auto CachingCDB = llvm::make_unique<CachingCompilationDb>(*CDB);
606 return CompilationDB(std::move(CDB), std::move(CachingCDB),
607 /*IsDirectoryBased=*/true);
608}
609
610void ClangdLSPServer::CompilationDB::invalidate(PathRef File) {
611 if (!IsDirectoryBased)
612 static_cast<InMemoryCompilationDb *>(CDB.get())->invalidate(File);
613 else
614 CachingCDB->invalidate(File);
615}
616
617bool ClangdLSPServer::CompilationDB::setCompilationCommandForFile(
618 PathRef File, tooling::CompileCommand CompilationCommand) {
619 if (IsDirectoryBased) {
620 elog("Trying to set compile command for {0} while using directory-based "
621 "compilation database",
622 File);
623 return false;
624 }
625 return static_cast<InMemoryCompilationDb *>(CDB.get())
626 ->setCompilationCommandForFile(File, std::move(CompilationCommand));
627}
628
629void ClangdLSPServer::CompilationDB::setExtraFlagsForFile(
630 PathRef File, std::vector<std::string> ExtraFlags) {
631 if (!IsDirectoryBased) {
632 elog("Trying to set extra flags for {0} while using in-memory compilation "
633 "database",
634 File);
635 return;
636 }
637 static_cast<DirectoryBasedGlobalCompilationDatabase *>(CDB.get())
638 ->setExtraFlagsForFile(File, std::move(ExtraFlags));
639 CachingCDB->invalidate(File);
640}
641
642void ClangdLSPServer::CompilationDB::setCompileCommandsDir(Path P) {
643 if (!IsDirectoryBased) {
644 elog("Trying to set compile commands dir while using in-memory compilation "
645 "database");
646 return;
647 }
648 static_cast<DirectoryBasedGlobalCompilationDatabase *>(CDB.get())
649 ->setCompileCommandsDir(P);
650 CachingCDB->clear();
651}
652
653GlobalCompilationDatabase &ClangdLSPServer::CompilationDB::getCDB() {
654 if (CachingCDB)
655 return *CachingCDB;
656 return *CDB;
657}