blob: 021c287bb9878fd894e4b63f6dcd458ceb65e2cf [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;
Ilya Biryukov23bc73b2018-02-15 14:32:57 +0000106
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000107 if (Params.capabilities.workspace && Params.capabilities.workspace->symbol &&
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000108 Params.capabilities.workspace->symbol->symbolKind &&
109 Params.capabilities.workspace->symbol->symbolKind->valueSet) {
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000110 for (SymbolKind Kind :
111 *Params.capabilities.workspace->symbol->symbolKind->valueSet) {
112 SupportedSymbolKinds.set(static_cast<size_t>(Kind));
113 }
114 }
115
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000116 if (Params.capabilities.textDocument.completion.completionItemKind &&
117 Params.capabilities.textDocument.completion.completionItemKind->valueSet)
118 for (CompletionItemKind Kind : *Params.capabilities.textDocument.completion
119 .completionItemKind->valueSet)
120 SupportedCompletionItemKinds.set(static_cast<size_t>(Kind));
121
Sam McCalld20d7982018-07-09 14:25:59 +0000122 reply(json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000123 {{"capabilities",
Sam McCalld20d7982018-07-09 14:25:59 +0000124 json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000125 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000126 {"documentFormattingProvider", true},
127 {"documentRangeFormattingProvider", true},
128 {"documentOnTypeFormattingProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000129 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000130 {"firstTriggerCharacter", "}"},
131 {"moreTriggerCharacter", {}},
132 }},
133 {"codeActionProvider", true},
134 {"completionProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000135 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000136 {"resolveProvider", false},
137 {"triggerCharacters", {".", ">", ":"}},
138 }},
139 {"signatureHelpProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000140 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000141 {"triggerCharacters", {"(", ","}},
142 }},
143 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000144 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000145 {"hoverProvider", true},
Haojian Wu345099c2017-11-09 11:30:04 +0000146 {"renameProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000147 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000148 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000149 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000150 {"executeCommandProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000151 json::Object{
Eric Liu2c190532018-05-15 15:23:53 +0000152 {"commands", {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND}},
Sam McCall0930ab02017-11-07 15:49:35 +0000153 }},
154 }}}});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000155}
156
Sam McCalld1a7a372018-01-31 13:40:48 +0000157void ClangdLSPServer::onShutdown(ShutdownParams &Params) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000158 // Do essentially nothing, just say we're ready to exit.
159 ShutdownRequestReceived = true;
Sam McCalld1a7a372018-01-31 13:40:48 +0000160 reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000161}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000162
Sam McCalld1a7a372018-01-31 13:40:48 +0000163void ClangdLSPServer::onExit(ExitParams &Params) { IsDone = true; }
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000164
Sam McCalld1a7a372018-01-31 13:40:48 +0000165void ClangdLSPServer::onDocumentDidOpen(DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000166 PathRef File = Params.textDocument.uri.file();
Alex Lorenzf8087862018-08-01 17:39:29 +0000167 if (Params.metadata && !Params.metadata->extraFlags.empty())
168 CDB.setExtraFlagsForFile(File, std::move(Params.metadata->extraFlags));
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000169
Simon Marchi9569fd52018-03-16 14:30:42 +0000170 std::string &Contents = Params.textDocument.text;
171
Simon Marchi98082622018-03-26 14:41:40 +0000172 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000173 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000174}
175
Sam McCalld1a7a372018-01-31 13:40:48 +0000176void ClangdLSPServer::onDocumentDidChange(DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000177 auto WantDiags = WantDiagnostics::Auto;
178 if (Params.wantDiagnostics.hasValue())
179 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
180 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000181
182 PathRef File = Params.textDocument.uri.file();
Simon Marchi98082622018-03-26 14:41:40 +0000183 llvm::Expected<std::string> Contents =
184 DraftMgr.updateDraft(File, Params.contentChanges);
185 if (!Contents) {
186 // If this fails, we are most likely going to be not in sync anymore with
187 // the client. It is better to remove the draft and let further operations
188 // fail rather than giving wrong results.
189 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000190 Server->removeDocument(File);
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000191 CDB.invalidate(File);
Sam McCallbed58852018-07-11 10:35:11 +0000192 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000193 return;
194 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000195
Ilya Biryukov652364b2018-09-26 05:48:29 +0000196 Server->addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000197}
198
Sam McCalld1a7a372018-01-31 13:40:48 +0000199void ClangdLSPServer::onFileEvent(DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000200 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000201}
202
Sam McCalld1a7a372018-01-31 13:40:48 +0000203void ClangdLSPServer::onCommand(ExecuteCommandParams &Params) {
Eric Liuc5105f92018-02-16 14:15:55 +0000204 auto ApplyEdit = [](WorkspaceEdit WE) {
205 ApplyWorkspaceEditParams Edit;
206 Edit.edit = std::move(WE);
207 // We don't need the response so id == 1 is OK.
208 // Ideally, we would wait for the response and if there is no error, we
209 // would reply success/failure to the original RPC.
210 call("workspace/applyEdit", Edit);
211 };
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000212 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
213 Params.workspaceEdit) {
214 // The flow for "apply-fix" :
215 // 1. We publish a diagnostic, including fixits
216 // 2. The user clicks on the diagnostic, the editor asks us for code actions
217 // 3. We send code actions, with the fixit embedded as context
218 // 4. The user selects the fixit, the editor asks us to apply it
219 // 5. We unwrap the changes and send them back to the editor
220 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
221 // we ignore it)
222
Sam McCalld1a7a372018-01-31 13:40:48 +0000223 reply("Fix applied.");
Eric Liuc5105f92018-02-16 14:15:55 +0000224 ApplyEdit(*Params.workspaceEdit);
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000225 } else {
226 // We should not get here because ExecuteCommandParams would not have
227 // parsed in the first place and this handler should not be called. But if
228 // more commands are added, this will be here has a safe guard.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000229 replyError(
Sam McCalld1a7a372018-01-31 13:40:48 +0000230 ErrorCode::InvalidParams,
Haojian Wu2375c922017-11-07 10:21:02 +0000231 llvm::formatv("Unsupported command \"{0}\".", Params.command).str());
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000232 }
233}
234
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000235void ClangdLSPServer::onWorkspaceSymbol(WorkspaceSymbolParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000236 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000237 Params.query, CCOpts.Limit,
238 [this](llvm::Expected<std::vector<SymbolInformation>> Items) {
239 if (!Items)
240 return replyError(ErrorCode::InternalError,
241 llvm::toString(Items.takeError()));
242 for (auto &Sym : *Items)
243 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
244
Sam McCalld20d7982018-07-09 14:25:59 +0000245 reply(json::Array(*Items));
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000246 });
247}
248
Sam McCalld1a7a372018-01-31 13:40:48 +0000249void ClangdLSPServer::onRename(RenameParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000250 Path File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000251 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000252 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000253 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000254 "onRename called for non-added file");
255
Ilya Biryukov652364b2018-09-26 05:48:29 +0000256 Server->rename(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000257 File, Params.position, Params.newName,
258 [File, Code,
259 Params](llvm::Expected<std::vector<tooling::Replacement>> Replacements) {
260 if (!Replacements)
261 return replyError(ErrorCode::InternalError,
262 llvm::toString(Replacements.takeError()));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000263
Eric Liu9133ecd2018-05-11 12:12:08 +0000264 // Turn the replacements into the format specified by the Language
265 // Server Protocol. Fuse them into one big JSON array.
266 std::vector<TextEdit> Edits;
267 for (const auto &R : *Replacements)
268 Edits.push_back(replacementToEdit(*Code, R));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000269 WorkspaceEdit WE;
270 WE.changes = {{Params.textDocument.uri.uri(), Edits}};
271 reply(WE);
272 });
Haojian Wu345099c2017-11-09 11:30:04 +0000273}
274
Sam McCalld1a7a372018-01-31 13:40:48 +0000275void ClangdLSPServer::onDocumentDidClose(DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000276 PathRef File = Params.textDocument.uri.file();
277 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000278 Server->removeDocument(File);
Alex Lorenzf8087862018-08-01 17:39:29 +0000279 CDB.invalidate(File);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000280}
281
Sam McCall4db732a2017-09-30 10:08:52 +0000282void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCalld1a7a372018-01-31 13:40:48 +0000283 DocumentOnTypeFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000284 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000285 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000286 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000287 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000288 "onDocumentOnTypeFormatting called for non-added file");
289
Ilya Biryukov652364b2018-09-26 05:48:29 +0000290 auto ReplacementsOrError = Server->formatOnType(*Code, File, Params.position);
Raoul Wols212bcf82017-12-12 20:25:06 +0000291 if (ReplacementsOrError)
Sam McCalld20d7982018-07-09 14:25:59 +0000292 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000293 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000294 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000295 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000296}
297
Sam McCall4db732a2017-09-30 10:08:52 +0000298void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCalld1a7a372018-01-31 13:40:48 +0000299 DocumentRangeFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000300 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000301 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000302 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000303 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000304 "onDocumentRangeFormatting called for non-added file");
305
Ilya Biryukov652364b2018-09-26 05:48:29 +0000306 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000307 if (ReplacementsOrError)
Sam McCalld20d7982018-07-09 14:25:59 +0000308 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000309 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000310 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000311 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000312}
313
Sam McCalld1a7a372018-01-31 13:40:48 +0000314void ClangdLSPServer::onDocumentFormatting(DocumentFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000315 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000316 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000317 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000318 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000319 "onDocumentFormatting called for non-added file");
320
Ilya Biryukov652364b2018-09-26 05:48:29 +0000321 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000322 if (ReplacementsOrError)
Sam McCalld20d7982018-07-09 14:25:59 +0000323 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000324 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000325 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000326 llvm::toString(ReplacementsOrError.takeError()));
Sam McCall4db732a2017-09-30 10:08:52 +0000327}
328
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000329void ClangdLSPServer::onDocumentSymbol(DocumentSymbolParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000330 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000331 Params.textDocument.uri.file(),
332 [this](llvm::Expected<std::vector<SymbolInformation>> Items) {
333 if (!Items)
334 return replyError(ErrorCode::InvalidParams,
335 llvm::toString(Items.takeError()));
336 for (auto &Sym : *Items)
337 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Sam McCalld20d7982018-07-09 14:25:59 +0000338 reply(json::Array(*Items));
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000339 });
340}
341
Sam McCalld1a7a372018-01-31 13:40:48 +0000342void ClangdLSPServer::onCodeAction(CodeActionParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000343 // We provide a code action for each diagnostic at the requested location
344 // which has FixIts available.
Simon Marchi9569fd52018-03-16 14:30:42 +0000345 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000346 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000347 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000348 "onCodeAction called for non-added file");
349
Sam McCallcbf497f2018-10-12 16:51:48 +0000350 std::vector<Command> Commands;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000351 for (Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000352 for (auto &F : getFixes(Params.textDocument.uri.file(), D)) {
Sam McCalldd0566b2017-11-06 15:40:30 +0000353 WorkspaceEdit WE;
Ilya Biryukov71028b82018-03-12 15:28:22 +0000354 std::vector<TextEdit> Edits(F.Edits.begin(), F.Edits.end());
Sam McCallcbf497f2018-10-12 16:51:48 +0000355 Commands.emplace_back();
356 Commands.back().title = llvm::formatv("Apply fix: {0}", F.Message);
357 Commands.back().command = ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND;
358 Commands.back().workspaceEdit.emplace();
359 Commands.back().workspaceEdit->changes = {
360 {Params.textDocument.uri.uri(), std::move(Edits)},
361 };
Sam McCalldd0566b2017-11-06 15:40:30 +0000362 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000363 }
Sam McCallcbf497f2018-10-12 16:51:48 +0000364 reply(json::Array(Commands));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000365}
366
Sam McCalld1a7a372018-01-31 13:40:48 +0000367void ClangdLSPServer::onCompletion(TextDocumentPositionParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000368 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
369 [this](llvm::Expected<CodeCompleteResult> List) {
370 if (!List)
371 return replyError(List.takeError());
372 CompletionList LSPList;
373 LSPList.isIncomplete = List->HasMore;
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000374 for (const auto &R : List->Completions) {
375 CompletionItem C = R.render(CCOpts);
376 C.kind = adjustKindToCapability(
377 C.kind, SupportedCompletionItemKinds);
378 LSPList.items.push_back(std::move(C));
379 }
Ilya Biryukov652364b2018-09-26 05:48:29 +0000380 return reply(std::move(LSPList));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000381 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000382}
383
Ilya Biryukov652364b2018-09-26 05:48:29 +0000384void ClangdLSPServer::onSignatureHelp(TextDocumentPositionParams &Params) {
385 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
386 [](llvm::Expected<SignatureHelp> SignatureHelp) {
387 if (!SignatureHelp)
388 return replyError(
389 ErrorCode::InvalidParams,
390 llvm::toString(SignatureHelp.takeError()));
391 reply(*SignatureHelp);
392 });
393}
394
Sam McCalld1a7a372018-01-31 13:40:48 +0000395void ClangdLSPServer::onGoToDefinition(TextDocumentPositionParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000396 Server->findDefinitions(Params.textDocument.uri.file(), Params.position,
397 [](llvm::Expected<std::vector<Location>> Items) {
398 if (!Items)
399 return replyError(
400 ErrorCode::InvalidParams,
401 llvm::toString(Items.takeError()));
402 reply(json::Array(*Items));
403 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000404}
405
Sam McCalld1a7a372018-01-31 13:40:48 +0000406void ClangdLSPServer::onSwitchSourceHeader(TextDocumentIdentifier &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000407 llvm::Optional<Path> Result = Server->switchSourceHeader(Params.uri.file());
Sam McCalld1a7a372018-01-31 13:40:48 +0000408 reply(Result ? URI::createFile(*Result).toString() : "");
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000409}
410
Sam McCalld1a7a372018-01-31 13:40:48 +0000411void ClangdLSPServer::onDocumentHighlight(TextDocumentPositionParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000412 Server->findDocumentHighlights(
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000413 Params.textDocument.uri.file(), Params.position,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000414 [](llvm::Expected<std::vector<DocumentHighlight>> Highlights) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000415 if (!Highlights)
416 return replyError(ErrorCode::InternalError,
417 llvm::toString(Highlights.takeError()));
Sam McCalld20d7982018-07-09 14:25:59 +0000418 reply(json::Array(*Highlights));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000419 });
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000420}
421
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000422void ClangdLSPServer::onHover(TextDocumentPositionParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000423 Server->findHover(Params.textDocument.uri.file(), Params.position,
424 [](llvm::Expected<llvm::Optional<Hover>> H) {
425 if (!H) {
426 replyError(ErrorCode::InternalError,
427 llvm::toString(H.takeError()));
428 return;
429 }
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000430
Ilya Biryukov652364b2018-09-26 05:48:29 +0000431 reply(*H);
432 });
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000433}
434
Simon Marchi88016782018-08-01 11:28:49 +0000435void ClangdLSPServer::applyConfiguration(
Simon Marchiabeed662018-10-16 15:55:03 +0000436 const ClangdConfigurationParamsChange &Params) {
437 // Per-file update to the compilation database.
438 if (Params.compilationDatabaseChanges) {
439 const auto &CompileCommandUpdates = *Params.compilationDatabaseChanges;
Alex Lorenzf8087862018-08-01 17:39:29 +0000440 bool ShouldReparseOpenFiles = false;
441 for (auto &Entry : CompileCommandUpdates) {
442 /// The opened files need to be reparsed only when some existing
443 /// entries are changed.
444 PathRef File = Entry.first;
445 if (!CDB.setCompilationCommandForFile(
446 File, tooling::CompileCommand(
447 std::move(Entry.second.workingDirectory), File,
448 std::move(Entry.second.compilationCommand),
449 /*Output=*/"")))
450 ShouldReparseOpenFiles = true;
451 }
452 if (ShouldReparseOpenFiles)
453 reparseOpenedFiles();
454 }
Simon Marchi5178f922018-02-22 14:00:39 +0000455}
456
Simon Marchi88016782018-08-01 11:28:49 +0000457// FIXME: This function needs to be properly tested.
458void ClangdLSPServer::onChangeConfiguration(
459 DidChangeConfigurationParams &Params) {
460 applyConfiguration(Params.settings);
461}
462
Sam McCall1ad142f2018-09-05 11:53:07 +0000463void ClangdLSPServer::onReference(ReferenceParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000464 Server->findReferences(Params.textDocument.uri.file(), Params.position,
465 [](llvm::Expected<std::vector<Location>> Locations) {
466 if (!Locations)
467 return replyError(
468 ErrorCode::InternalError,
469 llvm::toString(Locations.takeError()));
470 reply(llvm::json::Array(*Locations));
471 });
Sam McCall1ad142f2018-09-05 11:53:07 +0000472}
473
Sam McCall7363a2f2018-03-05 17:28:54 +0000474ClangdLSPServer::ClangdLSPServer(JSONOutput &Out,
Sam McCalladccab62017-11-23 16:58:22 +0000475 const clangd::CodeCompleteOptions &CCOpts,
Eric Liubfac8f72017-12-19 18:00:37 +0000476 llvm::Optional<Path> CompileCommandsDir,
Alex Lorenzf8087862018-08-01 17:39:29 +0000477 bool ShouldUseInMemoryCDB,
Sam McCall7363a2f2018-03-05 17:28:54 +0000478 const ClangdServer::Options &Opts)
Alex Lorenzf8087862018-08-01 17:39:29 +0000479 : Out(Out), CDB(ShouldUseInMemoryCDB ? CompilationDB::makeInMemory()
480 : CompilationDB::makeDirectoryBased(
481 std::move(CompileCommandsDir))),
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000482 CCOpts(CCOpts), SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000483 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Ilya Biryukov652364b2018-09-26 05:48:29 +0000484 Server(new ClangdServer(CDB.getCDB(), FSProvider, /*DiagConsumer=*/*this,
485 Opts)) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000486
Sam McCall27a07cf2018-06-05 09:34:46 +0000487bool ClangdLSPServer::run(std::FILE *In, JSONStreamStyle InputStyle) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000488 assert(!IsDone && "Run was called before");
Ilya Biryukov652364b2018-09-26 05:48:29 +0000489 assert(Server);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000490
Ilya Biryukovafb55542017-05-16 14:40:30 +0000491 // Set up JSONRPCDispatcher.
Sam McCalld20d7982018-07-09 14:25:59 +0000492 JSONRPCDispatcher Dispatcher([](const json::Value &Params) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000493 replyError(ErrorCode::MethodNotFound, "method not found");
Ilya Biryukov940901e2017-12-13 12:51:22 +0000494 });
Simon Marchi6e8eb9d2018-03-07 21:47:25 +0000495 registerCallbackHandlers(Dispatcher, /*Callbacks=*/*this);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000496
Ilya Biryukovafb55542017-05-16 14:40:30 +0000497 // Run the Language Server loop.
Sam McCall5ed599e2018-02-06 10:47:30 +0000498 runLanguageServerLoop(In, Out, InputStyle, Dispatcher, IsDone);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000499
500 // Make sure IsDone is set to true after this method exits to ensure assertion
501 // at the start of the method fires if it's ever executed again.
502 IsDone = true;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000503 // Destroy ClangdServer to ensure all worker threads finish.
504 Server.reset();
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000505
506 return ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000507}
508
Ilya Biryukov71028b82018-03-12 15:28:22 +0000509std::vector<Fix> ClangdLSPServer::getFixes(StringRef File,
510 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000511 std::lock_guard<std::mutex> Lock(FixItsMutex);
512 auto DiagToFixItsIter = FixItsMap.find(File);
513 if (DiagToFixItsIter == FixItsMap.end())
514 return {};
515
516 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
517 auto FixItsIter = DiagToFixItsMap.find(D);
518 if (FixItsIter == DiagToFixItsMap.end())
519 return {};
520
521 return FixItsIter->second;
522}
523
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000524void ClangdLSPServer::onDiagnosticsReady(PathRef File,
525 std::vector<Diag> Diagnostics) {
Sam McCalld20d7982018-07-09 14:25:59 +0000526 json::Array DiagnosticsJSON;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000527
528 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000529 for (auto &Diag : Diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000530 toLSPDiags(Diag, [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Alex Lorenz8626d362018-08-10 17:25:07 +0000531 json::Object LSPDiag({
Ilya Biryukov71028b82018-03-12 15:28:22 +0000532 {"range", Diag.range},
533 {"severity", Diag.severity},
534 {"message", Diag.message},
535 });
Alex Lorenz8626d362018-08-10 17:25:07 +0000536 // LSP extension: embed the fixes in the diagnostic.
537 if (DiagOpts.EmbedFixesInDiagnostics && !Fixes.empty()) {
538 json::Array ClangdFixes;
539 for (const auto &Fix : Fixes) {
540 WorkspaceEdit WE;
541 URIForFile URI{File};
542 WE.changes = {{URI.uri(), std::vector<TextEdit>(Fix.Edits.begin(),
543 Fix.Edits.end())}};
544 ClangdFixes.push_back(
545 json::Object{{"edit", toJSON(WE)}, {"title", Fix.Message}});
546 }
547 LSPDiag["clangd_fixes"] = std::move(ClangdFixes);
548 }
Alex Lorenz0ce8a7a2018-08-22 20:30:06 +0000549 if (DiagOpts.SendDiagnosticCategory && !Diag.category.empty())
Alex Lorenz37146432018-08-14 22:21:40 +0000550 LSPDiag["category"] = Diag.category;
Alex Lorenz8626d362018-08-10 17:25:07 +0000551 DiagnosticsJSON.push_back(std::move(LSPDiag));
Ilya Biryukov71028b82018-03-12 15:28:22 +0000552
553 auto &FixItsForDiagnostic = LocalFixIts[Diag];
Kirill Bobyrev4a5ff882018-10-07 14:49:41 +0000554 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
Sam McCalldd0566b2017-11-06 15:40:30 +0000555 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000556 }
557
558 // Cache FixIts
559 {
560 // FIXME(ibiryukov): should be deleted when documents are removed
561 std::lock_guard<std::mutex> Lock(FixItsMutex);
562 FixItsMap[File] = LocalFixIts;
563 }
564
565 // Publish diagnostics.
Sam McCalld20d7982018-07-09 14:25:59 +0000566 Out.writeMessage(json::Object{
Sam McCalldd0566b2017-11-06 15:40:30 +0000567 {"jsonrpc", "2.0"},
568 {"method", "textDocument/publishDiagnostics"},
569 {"params",
Sam McCalld20d7982018-07-09 14:25:59 +0000570 json::Object{
Eric Liu78ed91a72018-01-29 15:37:46 +0000571 {"uri", URIForFile{File}},
Sam McCalldd0566b2017-11-06 15:40:30 +0000572 {"diagnostics", std::move(DiagnosticsJSON)},
573 }},
574 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000575}
Simon Marchi9569fd52018-03-16 14:30:42 +0000576
577void ClangdLSPServer::reparseOpenedFiles() {
578 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +0000579 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
580 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +0000581}
Alex Lorenzf8087862018-08-01 17:39:29 +0000582
583ClangdLSPServer::CompilationDB ClangdLSPServer::CompilationDB::makeInMemory() {
584 return CompilationDB(llvm::make_unique<InMemoryCompilationDb>(), nullptr,
585 /*IsDirectoryBased=*/false);
586}
587
588ClangdLSPServer::CompilationDB
589ClangdLSPServer::CompilationDB::makeDirectoryBased(
590 llvm::Optional<Path> CompileCommandsDir) {
591 auto CDB = llvm::make_unique<DirectoryBasedGlobalCompilationDatabase>(
592 std::move(CompileCommandsDir));
593 auto CachingCDB = llvm::make_unique<CachingCompilationDb>(*CDB);
594 return CompilationDB(std::move(CDB), std::move(CachingCDB),
595 /*IsDirectoryBased=*/true);
596}
597
598void ClangdLSPServer::CompilationDB::invalidate(PathRef File) {
599 if (!IsDirectoryBased)
600 static_cast<InMemoryCompilationDb *>(CDB.get())->invalidate(File);
601 else
602 CachingCDB->invalidate(File);
603}
604
605bool ClangdLSPServer::CompilationDB::setCompilationCommandForFile(
606 PathRef File, tooling::CompileCommand CompilationCommand) {
607 if (IsDirectoryBased) {
608 elog("Trying to set compile command for {0} while using directory-based "
609 "compilation database",
610 File);
611 return false;
612 }
613 return static_cast<InMemoryCompilationDb *>(CDB.get())
614 ->setCompilationCommandForFile(File, std::move(CompilationCommand));
615}
616
617void ClangdLSPServer::CompilationDB::setExtraFlagsForFile(
618 PathRef File, std::vector<std::string> ExtraFlags) {
619 if (!IsDirectoryBased) {
620 elog("Trying to set extra flags for {0} while using in-memory compilation "
621 "database",
622 File);
623 return;
624 }
625 static_cast<DirectoryBasedGlobalCompilationDatabase *>(CDB.get())
626 ->setExtraFlagsForFile(File, std::move(ExtraFlags));
627 CachingCDB->invalidate(File);
628}
629
630void ClangdLSPServer::CompilationDB::setCompileCommandsDir(Path P) {
631 if (!IsDirectoryBased) {
632 elog("Trying to set compile commands dir while using in-memory compilation "
633 "database");
634 return;
635 }
636 static_cast<DirectoryBasedGlobalCompilationDatabase *>(CDB.get())
637 ->setCompileCommandsDir(P);
638 CachingCDB->clear();
639}
640
641GlobalCompilationDatabase &ClangdLSPServer::CompilationDB::getCDB() {
642 if (CachingCDB)
643 return *CachingCDB;
644 return *CDB;
645}