blob: b1863062d390f75249412454c16e146ffab6a4ac [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
100 CCOpts.EnableSnippets =
101 Params.capabilities.textDocument.completion.completionItem.snippetSupport;
Alex Lorenz8626d362018-08-10 17:25:07 +0000102 DiagOpts.EmbedFixesInDiagnostics =
103 Params.capabilities.textDocument.publishDiagnostics.clangdFixSupport;
Alex Lorenz0ce8a7a2018-08-22 20:30:06 +0000104 DiagOpts.SendDiagnosticCategory =
105 Params.capabilities.textDocument.publishDiagnostics.categorySupport;
Sam McCall20841d42018-10-16 16:29:41 +0000106 SupportsCodeAction =
107 Params.capabilities.textDocument.codeActionLiteralSupport;
Ilya Biryukov23bc73b2018-02-15 14:32:57 +0000108
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000109 if (Params.capabilities.workspace && Params.capabilities.workspace->symbol &&
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000110 Params.capabilities.workspace->symbol->symbolKind &&
111 Params.capabilities.workspace->symbol->symbolKind->valueSet) {
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000112 for (SymbolKind Kind :
113 *Params.capabilities.workspace->symbol->symbolKind->valueSet) {
114 SupportedSymbolKinds.set(static_cast<size_t>(Kind));
115 }
116 }
117
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000118 if (Params.capabilities.textDocument.completion.completionItemKind &&
119 Params.capabilities.textDocument.completion.completionItemKind->valueSet)
120 for (CompletionItemKind Kind : *Params.capabilities.textDocument.completion
121 .completionItemKind->valueSet)
122 SupportedCompletionItemKinds.set(static_cast<size_t>(Kind));
123
Sam McCalld20d7982018-07-09 14:25:59 +0000124 reply(json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000125 {{"capabilities",
Sam McCalld20d7982018-07-09 14:25:59 +0000126 json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000127 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000128 {"documentFormattingProvider", true},
129 {"documentRangeFormattingProvider", true},
130 {"documentOnTypeFormattingProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000131 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000132 {"firstTriggerCharacter", "}"},
133 {"moreTriggerCharacter", {}},
134 }},
135 {"codeActionProvider", true},
136 {"completionProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000137 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000138 {"resolveProvider", false},
139 {"triggerCharacters", {".", ">", ":"}},
140 }},
141 {"signatureHelpProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000142 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000143 {"triggerCharacters", {"(", ","}},
144 }},
145 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000146 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000147 {"hoverProvider", true},
Haojian Wu345099c2017-11-09 11:30:04 +0000148 {"renameProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000149 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000150 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000151 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000152 {"executeCommandProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000153 json::Object{
Eric Liu2c190532018-05-15 15:23:53 +0000154 {"commands", {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND}},
Sam McCall0930ab02017-11-07 15:49:35 +0000155 }},
156 }}}});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000157}
158
Sam McCalld1a7a372018-01-31 13:40:48 +0000159void ClangdLSPServer::onShutdown(ShutdownParams &Params) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000160 // Do essentially nothing, just say we're ready to exit.
161 ShutdownRequestReceived = true;
Sam McCalld1a7a372018-01-31 13:40:48 +0000162 reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000163}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000164
Sam McCalld1a7a372018-01-31 13:40:48 +0000165void ClangdLSPServer::onExit(ExitParams &Params) { IsDone = true; }
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000166
Sam McCalld1a7a372018-01-31 13:40:48 +0000167void ClangdLSPServer::onDocumentDidOpen(DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000168 PathRef File = Params.textDocument.uri.file();
Alex Lorenzf8087862018-08-01 17:39:29 +0000169 if (Params.metadata && !Params.metadata->extraFlags.empty())
170 CDB.setExtraFlagsForFile(File, std::move(Params.metadata->extraFlags));
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000171
Simon Marchi9569fd52018-03-16 14:30:42 +0000172 std::string &Contents = Params.textDocument.text;
173
Simon Marchi98082622018-03-26 14:41:40 +0000174 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000175 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000176}
177
Sam McCalld1a7a372018-01-31 13:40:48 +0000178void ClangdLSPServer::onDocumentDidChange(DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000179 auto WantDiags = WantDiagnostics::Auto;
180 if (Params.wantDiagnostics.hasValue())
181 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
182 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000183
184 PathRef File = Params.textDocument.uri.file();
Simon Marchi98082622018-03-26 14:41:40 +0000185 llvm::Expected<std::string> Contents =
186 DraftMgr.updateDraft(File, Params.contentChanges);
187 if (!Contents) {
188 // If this fails, we are most likely going to be not in sync anymore with
189 // the client. It is better to remove the draft and let further operations
190 // fail rather than giving wrong results.
191 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000192 Server->removeDocument(File);
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000193 CDB.invalidate(File);
Sam McCallbed58852018-07-11 10:35:11 +0000194 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000195 return;
196 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000197
Ilya Biryukov652364b2018-09-26 05:48:29 +0000198 Server->addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000199}
200
Sam McCalld1a7a372018-01-31 13:40:48 +0000201void ClangdLSPServer::onFileEvent(DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000202 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000203}
204
Sam McCalld1a7a372018-01-31 13:40:48 +0000205void ClangdLSPServer::onCommand(ExecuteCommandParams &Params) {
Eric Liuc5105f92018-02-16 14:15:55 +0000206 auto ApplyEdit = [](WorkspaceEdit WE) {
207 ApplyWorkspaceEditParams Edit;
208 Edit.edit = std::move(WE);
209 // We don't need the response so id == 1 is OK.
210 // Ideally, we would wait for the response and if there is no error, we
211 // would reply success/failure to the original RPC.
212 call("workspace/applyEdit", Edit);
213 };
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000214 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
215 Params.workspaceEdit) {
216 // The flow for "apply-fix" :
217 // 1. We publish a diagnostic, including fixits
218 // 2. The user clicks on the diagnostic, the editor asks us for code actions
219 // 3. We send code actions, with the fixit embedded as context
220 // 4. The user selects the fixit, the editor asks us to apply it
221 // 5. We unwrap the changes and send them back to the editor
222 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
223 // we ignore it)
224
Sam McCalld1a7a372018-01-31 13:40:48 +0000225 reply("Fix applied.");
Eric Liuc5105f92018-02-16 14:15:55 +0000226 ApplyEdit(*Params.workspaceEdit);
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000227 } else {
228 // We should not get here because ExecuteCommandParams would not have
229 // parsed in the first place and this handler should not be called. But if
230 // more commands are added, this will be here has a safe guard.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000231 replyError(
Sam McCalld1a7a372018-01-31 13:40:48 +0000232 ErrorCode::InvalidParams,
Haojian Wu2375c922017-11-07 10:21:02 +0000233 llvm::formatv("Unsupported command \"{0}\".", Params.command).str());
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000234 }
235}
236
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000237void ClangdLSPServer::onWorkspaceSymbol(WorkspaceSymbolParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000238 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000239 Params.query, CCOpts.Limit,
240 [this](llvm::Expected<std::vector<SymbolInformation>> Items) {
241 if (!Items)
242 return replyError(ErrorCode::InternalError,
243 llvm::toString(Items.takeError()));
244 for (auto &Sym : *Items)
245 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
246
Sam McCalld20d7982018-07-09 14:25:59 +0000247 reply(json::Array(*Items));
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000248 });
249}
250
Sam McCalld1a7a372018-01-31 13:40:48 +0000251void ClangdLSPServer::onRename(RenameParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000252 Path File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000253 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000254 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000255 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000256 "onRename called for non-added file");
257
Ilya Biryukov652364b2018-09-26 05:48:29 +0000258 Server->rename(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000259 File, Params.position, Params.newName,
260 [File, Code,
261 Params](llvm::Expected<std::vector<tooling::Replacement>> Replacements) {
262 if (!Replacements)
263 return replyError(ErrorCode::InternalError,
264 llvm::toString(Replacements.takeError()));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000265
Eric Liu9133ecd2018-05-11 12:12:08 +0000266 // Turn the replacements into the format specified by the Language
267 // Server Protocol. Fuse them into one big JSON array.
268 std::vector<TextEdit> Edits;
269 for (const auto &R : *Replacements)
270 Edits.push_back(replacementToEdit(*Code, R));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000271 WorkspaceEdit WE;
272 WE.changes = {{Params.textDocument.uri.uri(), Edits}};
273 reply(WE);
274 });
Haojian Wu345099c2017-11-09 11:30:04 +0000275}
276
Sam McCalld1a7a372018-01-31 13:40:48 +0000277void ClangdLSPServer::onDocumentDidClose(DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000278 PathRef File = Params.textDocument.uri.file();
279 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000280 Server->removeDocument(File);
Alex Lorenzf8087862018-08-01 17:39:29 +0000281 CDB.invalidate(File);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000282}
283
Sam McCall4db732a2017-09-30 10:08:52 +0000284void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCalld1a7a372018-01-31 13:40:48 +0000285 DocumentOnTypeFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000286 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000287 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000288 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000289 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000290 "onDocumentOnTypeFormatting called for non-added file");
291
Ilya Biryukov652364b2018-09-26 05:48:29 +0000292 auto ReplacementsOrError = Server->formatOnType(*Code, File, Params.position);
Raoul Wols212bcf82017-12-12 20:25:06 +0000293 if (ReplacementsOrError)
Sam McCalld20d7982018-07-09 14:25:59 +0000294 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000295 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000296 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000297 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000298}
299
Sam McCall4db732a2017-09-30 10:08:52 +0000300void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCalld1a7a372018-01-31 13:40:48 +0000301 DocumentRangeFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000302 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000303 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000304 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000305 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000306 "onDocumentRangeFormatting called for non-added file");
307
Ilya Biryukov652364b2018-09-26 05:48:29 +0000308 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000309 if (ReplacementsOrError)
Sam McCalld20d7982018-07-09 14:25:59 +0000310 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000311 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000312 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000313 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000314}
315
Sam McCalld1a7a372018-01-31 13:40:48 +0000316void ClangdLSPServer::onDocumentFormatting(DocumentFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000317 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000318 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000319 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000320 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000321 "onDocumentFormatting called for non-added file");
322
Ilya Biryukov652364b2018-09-26 05:48:29 +0000323 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000324 if (ReplacementsOrError)
Sam McCalld20d7982018-07-09 14:25:59 +0000325 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000326 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000327 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000328 llvm::toString(ReplacementsOrError.takeError()));
Sam McCall4db732a2017-09-30 10:08:52 +0000329}
330
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000331void ClangdLSPServer::onDocumentSymbol(DocumentSymbolParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000332 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000333 Params.textDocument.uri.file(),
334 [this](llvm::Expected<std::vector<SymbolInformation>> Items) {
335 if (!Items)
336 return replyError(ErrorCode::InvalidParams,
337 llvm::toString(Items.takeError()));
338 for (auto &Sym : *Items)
339 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Sam McCalld20d7982018-07-09 14:25:59 +0000340 reply(json::Array(*Items));
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000341 });
342}
343
Sam McCall20841d42018-10-16 16:29:41 +0000344static Optional<Command> asCommand(const CodeAction &Action) {
345 Command Cmd;
346 if (Action.command && Action.edit)
347 return llvm::None; // Not representable. (We never emit these anyway).
348 if (Action.command) {
349 Cmd = *Action.command;
350 } else if (Action.edit) {
351 Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
352 Cmd.workspaceEdit = *Action.edit;
353 } else {
354 return llvm::None;
355 }
356 Cmd.title = Action.title;
357 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
358 Cmd.title = "Apply fix: " + Cmd.title;
359 return Cmd;
360}
361
Sam McCalld1a7a372018-01-31 13:40:48 +0000362void ClangdLSPServer::onCodeAction(CodeActionParams &Params) {
Sam McCall20841d42018-10-16 16:29:41 +0000363 // We provide a code action for Fixes on the specified diagnostics.
364 if (!DraftMgr.getDraft(Params.textDocument.uri.file()))
Sam McCalld1a7a372018-01-31 13:40:48 +0000365 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000366 "onCodeAction called for non-added file");
367
Sam McCall20841d42018-10-16 16:29:41 +0000368 std::vector<CodeAction> Actions;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000369 for (Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000370 for (auto &F : getFixes(Params.textDocument.uri.file(), D)) {
Sam McCall20841d42018-10-16 16:29:41 +0000371 Actions.emplace_back();
372 Actions.back().title = F.Message;
373 Actions.back().kind = CodeAction::QUICKFIX_KIND;
374 Actions.back().diagnostics = {D};
375 Actions.back().edit.emplace();
376 Actions.back().edit->changes.emplace();
377 (*Actions.back().edit->changes)[Params.textDocument.uri.uri()] = {
378 F.Edits.begin(), F.Edits.end()};
Sam McCalldd0566b2017-11-06 15:40:30 +0000379 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000380 }
Sam McCall20841d42018-10-16 16:29:41 +0000381
382 if (SupportsCodeAction)
383 reply(json::Array(Actions));
384 else {
385 std::vector<Command> Commands;
386 for (const auto &Action : Actions)
387 if (auto Command = asCommand(Action))
388 Commands.push_back(std::move(*Command));
389 reply(json::Array(Commands));
390 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000391}
392
Sam McCalld1a7a372018-01-31 13:40:48 +0000393void ClangdLSPServer::onCompletion(TextDocumentPositionParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000394 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
395 [this](llvm::Expected<CodeCompleteResult> List) {
396 if (!List)
397 return replyError(List.takeError());
398 CompletionList LSPList;
399 LSPList.isIncomplete = List->HasMore;
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000400 for (const auto &R : List->Completions) {
401 CompletionItem C = R.render(CCOpts);
402 C.kind = adjustKindToCapability(
403 C.kind, SupportedCompletionItemKinds);
404 LSPList.items.push_back(std::move(C));
405 }
Ilya Biryukov652364b2018-09-26 05:48:29 +0000406 return reply(std::move(LSPList));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000407 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000408}
409
Ilya Biryukov652364b2018-09-26 05:48:29 +0000410void ClangdLSPServer::onSignatureHelp(TextDocumentPositionParams &Params) {
411 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
412 [](llvm::Expected<SignatureHelp> SignatureHelp) {
413 if (!SignatureHelp)
414 return replyError(
415 ErrorCode::InvalidParams,
416 llvm::toString(SignatureHelp.takeError()));
417 reply(*SignatureHelp);
418 });
419}
420
Sam McCalld1a7a372018-01-31 13:40:48 +0000421void ClangdLSPServer::onGoToDefinition(TextDocumentPositionParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000422 Server->findDefinitions(Params.textDocument.uri.file(), Params.position,
423 [](llvm::Expected<std::vector<Location>> Items) {
424 if (!Items)
425 return replyError(
426 ErrorCode::InvalidParams,
427 llvm::toString(Items.takeError()));
428 reply(json::Array(*Items));
429 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000430}
431
Sam McCalld1a7a372018-01-31 13:40:48 +0000432void ClangdLSPServer::onSwitchSourceHeader(TextDocumentIdentifier &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000433 llvm::Optional<Path> Result = Server->switchSourceHeader(Params.uri.file());
Sam McCalld1a7a372018-01-31 13:40:48 +0000434 reply(Result ? URI::createFile(*Result).toString() : "");
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000435}
436
Sam McCalld1a7a372018-01-31 13:40:48 +0000437void ClangdLSPServer::onDocumentHighlight(TextDocumentPositionParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000438 Server->findDocumentHighlights(
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000439 Params.textDocument.uri.file(), Params.position,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000440 [](llvm::Expected<std::vector<DocumentHighlight>> Highlights) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000441 if (!Highlights)
442 return replyError(ErrorCode::InternalError,
443 llvm::toString(Highlights.takeError()));
Sam McCalld20d7982018-07-09 14:25:59 +0000444 reply(json::Array(*Highlights));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000445 });
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000446}
447
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000448void ClangdLSPServer::onHover(TextDocumentPositionParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000449 Server->findHover(Params.textDocument.uri.file(), Params.position,
450 [](llvm::Expected<llvm::Optional<Hover>> H) {
451 if (!H) {
452 replyError(ErrorCode::InternalError,
453 llvm::toString(H.takeError()));
454 return;
455 }
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000456
Ilya Biryukov652364b2018-09-26 05:48:29 +0000457 reply(*H);
458 });
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000459}
460
Simon Marchi88016782018-08-01 11:28:49 +0000461void ClangdLSPServer::applyConfiguration(
Simon Marchiabeed662018-10-16 15:55:03 +0000462 const ClangdConfigurationParamsChange &Params) {
463 // Per-file update to the compilation database.
464 if (Params.compilationDatabaseChanges) {
465 const auto &CompileCommandUpdates = *Params.compilationDatabaseChanges;
Alex Lorenzf8087862018-08-01 17:39:29 +0000466 bool ShouldReparseOpenFiles = false;
467 for (auto &Entry : CompileCommandUpdates) {
468 /// The opened files need to be reparsed only when some existing
469 /// entries are changed.
470 PathRef File = Entry.first;
471 if (!CDB.setCompilationCommandForFile(
472 File, tooling::CompileCommand(
473 std::move(Entry.second.workingDirectory), File,
474 std::move(Entry.second.compilationCommand),
475 /*Output=*/"")))
476 ShouldReparseOpenFiles = true;
477 }
478 if (ShouldReparseOpenFiles)
479 reparseOpenedFiles();
480 }
Simon Marchi5178f922018-02-22 14:00:39 +0000481}
482
Simon Marchi88016782018-08-01 11:28:49 +0000483// FIXME: This function needs to be properly tested.
484void ClangdLSPServer::onChangeConfiguration(
485 DidChangeConfigurationParams &Params) {
486 applyConfiguration(Params.settings);
487}
488
Sam McCall1ad142f2018-09-05 11:53:07 +0000489void ClangdLSPServer::onReference(ReferenceParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000490 Server->findReferences(Params.textDocument.uri.file(), Params.position,
491 [](llvm::Expected<std::vector<Location>> Locations) {
492 if (!Locations)
493 return replyError(
494 ErrorCode::InternalError,
495 llvm::toString(Locations.takeError()));
496 reply(llvm::json::Array(*Locations));
497 });
Sam McCall1ad142f2018-09-05 11:53:07 +0000498}
499
Sam McCall7363a2f2018-03-05 17:28:54 +0000500ClangdLSPServer::ClangdLSPServer(JSONOutput &Out,
Sam McCalladccab62017-11-23 16:58:22 +0000501 const clangd::CodeCompleteOptions &CCOpts,
Eric Liubfac8f72017-12-19 18:00:37 +0000502 llvm::Optional<Path> CompileCommandsDir,
Alex Lorenzf8087862018-08-01 17:39:29 +0000503 bool ShouldUseInMemoryCDB,
Sam McCall7363a2f2018-03-05 17:28:54 +0000504 const ClangdServer::Options &Opts)
Alex Lorenzf8087862018-08-01 17:39:29 +0000505 : Out(Out), CDB(ShouldUseInMemoryCDB ? CompilationDB::makeInMemory()
506 : CompilationDB::makeDirectoryBased(
507 std::move(CompileCommandsDir))),
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000508 CCOpts(CCOpts), SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000509 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Ilya Biryukov652364b2018-09-26 05:48:29 +0000510 Server(new ClangdServer(CDB.getCDB(), FSProvider, /*DiagConsumer=*/*this,
511 Opts)) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000512
Sam McCall27a07cf2018-06-05 09:34:46 +0000513bool ClangdLSPServer::run(std::FILE *In, JSONStreamStyle InputStyle) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000514 assert(!IsDone && "Run was called before");
Ilya Biryukov652364b2018-09-26 05:48:29 +0000515 assert(Server);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000516
Ilya Biryukovafb55542017-05-16 14:40:30 +0000517 // Set up JSONRPCDispatcher.
Sam McCalld20d7982018-07-09 14:25:59 +0000518 JSONRPCDispatcher Dispatcher([](const json::Value &Params) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000519 replyError(ErrorCode::MethodNotFound, "method not found");
Ilya Biryukov940901e2017-12-13 12:51:22 +0000520 });
Simon Marchi6e8eb9d2018-03-07 21:47:25 +0000521 registerCallbackHandlers(Dispatcher, /*Callbacks=*/*this);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000522
Ilya Biryukovafb55542017-05-16 14:40:30 +0000523 // Run the Language Server loop.
Sam McCall5ed599e2018-02-06 10:47:30 +0000524 runLanguageServerLoop(In, Out, InputStyle, Dispatcher, IsDone);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000525
526 // Make sure IsDone is set to true after this method exits to ensure assertion
527 // at the start of the method fires if it's ever executed again.
528 IsDone = true;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000529 // Destroy ClangdServer to ensure all worker threads finish.
530 Server.reset();
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000531
532 return ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000533}
534
Ilya Biryukov71028b82018-03-12 15:28:22 +0000535std::vector<Fix> ClangdLSPServer::getFixes(StringRef File,
536 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000537 std::lock_guard<std::mutex> Lock(FixItsMutex);
538 auto DiagToFixItsIter = FixItsMap.find(File);
539 if (DiagToFixItsIter == FixItsMap.end())
540 return {};
541
542 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
543 auto FixItsIter = DiagToFixItsMap.find(D);
544 if (FixItsIter == DiagToFixItsMap.end())
545 return {};
546
547 return FixItsIter->second;
548}
549
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000550void ClangdLSPServer::onDiagnosticsReady(PathRef File,
551 std::vector<Diag> Diagnostics) {
Sam McCalld20d7982018-07-09 14:25:59 +0000552 json::Array DiagnosticsJSON;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000553
554 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000555 for (auto &Diag : Diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000556 toLSPDiags(Diag, [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Alex Lorenz8626d362018-08-10 17:25:07 +0000557 json::Object LSPDiag({
Ilya Biryukov71028b82018-03-12 15:28:22 +0000558 {"range", Diag.range},
559 {"severity", Diag.severity},
560 {"message", Diag.message},
561 });
Alex Lorenz8626d362018-08-10 17:25:07 +0000562 // LSP extension: embed the fixes in the diagnostic.
563 if (DiagOpts.EmbedFixesInDiagnostics && !Fixes.empty()) {
564 json::Array ClangdFixes;
565 for (const auto &Fix : Fixes) {
566 WorkspaceEdit WE;
567 URIForFile URI{File};
568 WE.changes = {{URI.uri(), std::vector<TextEdit>(Fix.Edits.begin(),
569 Fix.Edits.end())}};
570 ClangdFixes.push_back(
571 json::Object{{"edit", toJSON(WE)}, {"title", Fix.Message}});
572 }
573 LSPDiag["clangd_fixes"] = std::move(ClangdFixes);
574 }
Alex Lorenz0ce8a7a2018-08-22 20:30:06 +0000575 if (DiagOpts.SendDiagnosticCategory && !Diag.category.empty())
Alex Lorenz37146432018-08-14 22:21:40 +0000576 LSPDiag["category"] = Diag.category;
Alex Lorenz8626d362018-08-10 17:25:07 +0000577 DiagnosticsJSON.push_back(std::move(LSPDiag));
Ilya Biryukov71028b82018-03-12 15:28:22 +0000578
579 auto &FixItsForDiagnostic = LocalFixIts[Diag];
Kirill Bobyrev4a5ff882018-10-07 14:49:41 +0000580 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
Sam McCalldd0566b2017-11-06 15:40:30 +0000581 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000582 }
583
584 // Cache FixIts
585 {
586 // FIXME(ibiryukov): should be deleted when documents are removed
587 std::lock_guard<std::mutex> Lock(FixItsMutex);
588 FixItsMap[File] = LocalFixIts;
589 }
590
591 // Publish diagnostics.
Sam McCalld20d7982018-07-09 14:25:59 +0000592 Out.writeMessage(json::Object{
Sam McCalldd0566b2017-11-06 15:40:30 +0000593 {"jsonrpc", "2.0"},
594 {"method", "textDocument/publishDiagnostics"},
595 {"params",
Sam McCalld20d7982018-07-09 14:25:59 +0000596 json::Object{
Eric Liu78ed91a72018-01-29 15:37:46 +0000597 {"uri", URIForFile{File}},
Sam McCalldd0566b2017-11-06 15:40:30 +0000598 {"diagnostics", std::move(DiagnosticsJSON)},
599 }},
600 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000601}
Simon Marchi9569fd52018-03-16 14:30:42 +0000602
603void ClangdLSPServer::reparseOpenedFiles() {
604 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +0000605 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
606 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +0000607}
Alex Lorenzf8087862018-08-01 17:39:29 +0000608
609ClangdLSPServer::CompilationDB ClangdLSPServer::CompilationDB::makeInMemory() {
610 return CompilationDB(llvm::make_unique<InMemoryCompilationDb>(), nullptr,
611 /*IsDirectoryBased=*/false);
612}
613
614ClangdLSPServer::CompilationDB
615ClangdLSPServer::CompilationDB::makeDirectoryBased(
616 llvm::Optional<Path> CompileCommandsDir) {
617 auto CDB = llvm::make_unique<DirectoryBasedGlobalCompilationDatabase>(
618 std::move(CompileCommandsDir));
619 auto CachingCDB = llvm::make_unique<CachingCompilationDb>(*CDB);
620 return CompilationDB(std::move(CDB), std::move(CachingCDB),
621 /*IsDirectoryBased=*/true);
622}
623
624void ClangdLSPServer::CompilationDB::invalidate(PathRef File) {
625 if (!IsDirectoryBased)
626 static_cast<InMemoryCompilationDb *>(CDB.get())->invalidate(File);
627 else
628 CachingCDB->invalidate(File);
629}
630
631bool ClangdLSPServer::CompilationDB::setCompilationCommandForFile(
632 PathRef File, tooling::CompileCommand CompilationCommand) {
633 if (IsDirectoryBased) {
634 elog("Trying to set compile command for {0} while using directory-based "
635 "compilation database",
636 File);
637 return false;
638 }
639 return static_cast<InMemoryCompilationDb *>(CDB.get())
640 ->setCompilationCommandForFile(File, std::move(CompilationCommand));
641}
642
643void ClangdLSPServer::CompilationDB::setExtraFlagsForFile(
644 PathRef File, std::vector<std::string> ExtraFlags) {
645 if (!IsDirectoryBased) {
646 elog("Trying to set extra flags for {0} while using in-memory compilation "
647 "database",
648 File);
649 return;
650 }
651 static_cast<DirectoryBasedGlobalCompilationDatabase *>(CDB.get())
652 ->setExtraFlagsForFile(File, std::move(ExtraFlags));
653 CachingCDB->invalidate(File);
654}
655
656void ClangdLSPServer::CompilationDB::setCompileCommandsDir(Path P) {
657 if (!IsDirectoryBased) {
658 elog("Trying to set compile commands dir while using in-memory compilation "
659 "database");
660 return;
661 }
662 static_cast<DirectoryBasedGlobalCompilationDatabase *>(CDB.get())
663 ->setCompileCommandsDir(P);
664 CachingCDB->clear();
665}
666
667GlobalCompilationDatabase &ClangdLSPServer::CompilationDB::getCDB() {
668 if (CachingCDB)
669 return *CachingCDB;
670 return *CDB;
671}