blob: c68d422d319cbebf5097055a8097f6bcbeea63b2 [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
Ilya Biryukovafb55542017-05-16 14:40:30 +000073} // namespace
74
Sam McCalld1a7a372018-01-31 13:40:48 +000075void ClangdLSPServer::onInitialize(InitializeParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +000076 if (Params.initializationOptions)
77 applyConfiguration(*Params.initializationOptions);
78
Ilya Biryukov7d60d202018-02-16 12:20:47 +000079 if (Params.rootUri && *Params.rootUri)
80 Server.setRootPath(Params.rootUri->file());
Ilya Biryukov23bc73b2018-02-15 14:32:57 +000081 else if (Params.rootPath && !Params.rootPath->empty())
82 Server.setRootPath(*Params.rootPath);
83
84 CCOpts.EnableSnippets =
85 Params.capabilities.textDocument.completion.completionItem.snippetSupport;
Alex Lorenz8626d362018-08-10 17:25:07 +000086 DiagOpts.EmbedFixesInDiagnostics =
87 Params.capabilities.textDocument.publishDiagnostics.clangdFixSupport;
Alex Lorenz0ce8a7a2018-08-22 20:30:06 +000088 DiagOpts.SendDiagnosticCategory =
89 Params.capabilities.textDocument.publishDiagnostics.categorySupport;
Ilya Biryukov23bc73b2018-02-15 14:32:57 +000090
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000091 if (Params.capabilities.workspace && Params.capabilities.workspace->symbol &&
92 Params.capabilities.workspace->symbol->symbolKind) {
93 for (SymbolKind Kind :
94 *Params.capabilities.workspace->symbol->symbolKind->valueSet) {
95 SupportedSymbolKinds.set(static_cast<size_t>(Kind));
96 }
97 }
98
Sam McCalld20d7982018-07-09 14:25:59 +000099 reply(json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000100 {{"capabilities",
Sam McCalld20d7982018-07-09 14:25:59 +0000101 json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000102 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000103 {"documentFormattingProvider", true},
104 {"documentRangeFormattingProvider", true},
105 {"documentOnTypeFormattingProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000106 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000107 {"firstTriggerCharacter", "}"},
108 {"moreTriggerCharacter", {}},
109 }},
110 {"codeActionProvider", true},
111 {"completionProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000112 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000113 {"resolveProvider", false},
114 {"triggerCharacters", {".", ">", ":"}},
115 }},
116 {"signatureHelpProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000117 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000118 {"triggerCharacters", {"(", ","}},
119 }},
120 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000121 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000122 {"hoverProvider", true},
Haojian Wu345099c2017-11-09 11:30:04 +0000123 {"renameProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000124 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000125 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000126 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000127 {"executeCommandProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000128 json::Object{
Eric Liu2c190532018-05-15 15:23:53 +0000129 {"commands", {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND}},
Sam McCall0930ab02017-11-07 15:49:35 +0000130 }},
131 }}}});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000132}
133
Sam McCalld1a7a372018-01-31 13:40:48 +0000134void ClangdLSPServer::onShutdown(ShutdownParams &Params) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000135 // Do essentially nothing, just say we're ready to exit.
136 ShutdownRequestReceived = true;
Sam McCalld1a7a372018-01-31 13:40:48 +0000137 reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000138}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000139
Sam McCalld1a7a372018-01-31 13:40:48 +0000140void ClangdLSPServer::onExit(ExitParams &Params) { IsDone = true; }
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000141
Sam McCalld1a7a372018-01-31 13:40:48 +0000142void ClangdLSPServer::onDocumentDidOpen(DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000143 PathRef File = Params.textDocument.uri.file();
Alex Lorenzf8087862018-08-01 17:39:29 +0000144 if (Params.metadata && !Params.metadata->extraFlags.empty())
145 CDB.setExtraFlagsForFile(File, std::move(Params.metadata->extraFlags));
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000146
Simon Marchi9569fd52018-03-16 14:30:42 +0000147 std::string &Contents = Params.textDocument.text;
148
Simon Marchi98082622018-03-26 14:41:40 +0000149 DraftMgr.addDraft(File, Contents);
Simon Marchi9569fd52018-03-16 14:30:42 +0000150 Server.addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000151}
152
Sam McCalld1a7a372018-01-31 13:40:48 +0000153void ClangdLSPServer::onDocumentDidChange(DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000154 auto WantDiags = WantDiagnostics::Auto;
155 if (Params.wantDiagnostics.hasValue())
156 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
157 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000158
159 PathRef File = Params.textDocument.uri.file();
Simon Marchi98082622018-03-26 14:41:40 +0000160 llvm::Expected<std::string> Contents =
161 DraftMgr.updateDraft(File, Params.contentChanges);
162 if (!Contents) {
163 // If this fails, we are most likely going to be not in sync anymore with
164 // the client. It is better to remove the draft and let further operations
165 // fail rather than giving wrong results.
166 DraftMgr.removeDraft(File);
167 Server.removeDocument(File);
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000168 CDB.invalidate(File);
Sam McCallbed58852018-07-11 10:35:11 +0000169 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000170 return;
171 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000172
Simon Marchi98082622018-03-26 14:41:40 +0000173 Server.addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000174}
175
Sam McCalld1a7a372018-01-31 13:40:48 +0000176void ClangdLSPServer::onFileEvent(DidChangeWatchedFilesParams &Params) {
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000177 Server.onFileEvent(Params);
178}
179
Sam McCalld1a7a372018-01-31 13:40:48 +0000180void ClangdLSPServer::onCommand(ExecuteCommandParams &Params) {
Eric Liuc5105f92018-02-16 14:15:55 +0000181 auto ApplyEdit = [](WorkspaceEdit WE) {
182 ApplyWorkspaceEditParams Edit;
183 Edit.edit = std::move(WE);
184 // We don't need the response so id == 1 is OK.
185 // Ideally, we would wait for the response and if there is no error, we
186 // would reply success/failure to the original RPC.
187 call("workspace/applyEdit", Edit);
188 };
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000189 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
190 Params.workspaceEdit) {
191 // The flow for "apply-fix" :
192 // 1. We publish a diagnostic, including fixits
193 // 2. The user clicks on the diagnostic, the editor asks us for code actions
194 // 3. We send code actions, with the fixit embedded as context
195 // 4. The user selects the fixit, the editor asks us to apply it
196 // 5. We unwrap the changes and send them back to the editor
197 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
198 // we ignore it)
199
Sam McCalld1a7a372018-01-31 13:40:48 +0000200 reply("Fix applied.");
Eric Liuc5105f92018-02-16 14:15:55 +0000201 ApplyEdit(*Params.workspaceEdit);
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000202 } else {
203 // We should not get here because ExecuteCommandParams would not have
204 // parsed in the first place and this handler should not be called. But if
205 // more commands are added, this will be here has a safe guard.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000206 replyError(
Sam McCalld1a7a372018-01-31 13:40:48 +0000207 ErrorCode::InvalidParams,
Haojian Wu2375c922017-11-07 10:21:02 +0000208 llvm::formatv("Unsupported command \"{0}\".", Params.command).str());
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000209 }
210}
211
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000212void ClangdLSPServer::onWorkspaceSymbol(WorkspaceSymbolParams &Params) {
213 Server.workspaceSymbols(
214 Params.query, CCOpts.Limit,
215 [this](llvm::Expected<std::vector<SymbolInformation>> Items) {
216 if (!Items)
217 return replyError(ErrorCode::InternalError,
218 llvm::toString(Items.takeError()));
219 for (auto &Sym : *Items)
220 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
221
Sam McCalld20d7982018-07-09 14:25:59 +0000222 reply(json::Array(*Items));
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000223 });
224}
225
Sam McCalld1a7a372018-01-31 13:40:48 +0000226void ClangdLSPServer::onRename(RenameParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000227 Path File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000228 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000229 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000230 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000231 "onRename called for non-added file");
232
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000233 Server.rename(
234 File, Params.position, Params.newName,
235 [File, Code,
236 Params](llvm::Expected<std::vector<tooling::Replacement>> Replacements) {
237 if (!Replacements)
238 return replyError(ErrorCode::InternalError,
239 llvm::toString(Replacements.takeError()));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000240
Eric Liu9133ecd2018-05-11 12:12:08 +0000241 // Turn the replacements into the format specified by the Language
242 // Server Protocol. Fuse them into one big JSON array.
243 std::vector<TextEdit> Edits;
244 for (const auto &R : *Replacements)
245 Edits.push_back(replacementToEdit(*Code, R));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000246 WorkspaceEdit WE;
247 WE.changes = {{Params.textDocument.uri.uri(), Edits}};
248 reply(WE);
249 });
Haojian Wu345099c2017-11-09 11:30:04 +0000250}
251
Sam McCalld1a7a372018-01-31 13:40:48 +0000252void ClangdLSPServer::onDocumentDidClose(DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000253 PathRef File = Params.textDocument.uri.file();
254 DraftMgr.removeDraft(File);
255 Server.removeDocument(File);
Alex Lorenzf8087862018-08-01 17:39:29 +0000256 CDB.invalidate(File);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000257}
258
Sam McCall4db732a2017-09-30 10:08:52 +0000259void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCalld1a7a372018-01-31 13:40:48 +0000260 DocumentOnTypeFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000261 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000262 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000263 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000264 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000265 "onDocumentOnTypeFormatting called for non-added file");
266
267 auto ReplacementsOrError = Server.formatOnType(*Code, File, Params.position);
Raoul Wols212bcf82017-12-12 20:25:06 +0000268 if (ReplacementsOrError)
Sam McCalld20d7982018-07-09 14:25:59 +0000269 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000270 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000271 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000272 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000273}
274
Sam McCall4db732a2017-09-30 10:08:52 +0000275void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCalld1a7a372018-01-31 13:40:48 +0000276 DocumentRangeFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000277 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000278 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000279 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000280 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000281 "onDocumentRangeFormatting called for non-added file");
282
283 auto ReplacementsOrError = Server.formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000284 if (ReplacementsOrError)
Sam McCalld20d7982018-07-09 14:25:59 +0000285 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000286 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000287 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000288 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000289}
290
Sam McCalld1a7a372018-01-31 13:40:48 +0000291void ClangdLSPServer::onDocumentFormatting(DocumentFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000292 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000293 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000294 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000295 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000296 "onDocumentFormatting called for non-added file");
297
298 auto ReplacementsOrError = Server.formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000299 if (ReplacementsOrError)
Sam McCalld20d7982018-07-09 14:25:59 +0000300 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000301 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000302 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000303 llvm::toString(ReplacementsOrError.takeError()));
Sam McCall4db732a2017-09-30 10:08:52 +0000304}
305
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000306void ClangdLSPServer::onDocumentSymbol(DocumentSymbolParams &Params) {
307 Server.documentSymbols(
308 Params.textDocument.uri.file(),
309 [this](llvm::Expected<std::vector<SymbolInformation>> Items) {
310 if (!Items)
311 return replyError(ErrorCode::InvalidParams,
312 llvm::toString(Items.takeError()));
313 for (auto &Sym : *Items)
314 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Sam McCalld20d7982018-07-09 14:25:59 +0000315 reply(json::Array(*Items));
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000316 });
317}
318
Sam McCalld1a7a372018-01-31 13:40:48 +0000319void ClangdLSPServer::onCodeAction(CodeActionParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000320 // We provide a code action for each diagnostic at the requested location
321 // which has FixIts available.
Simon Marchi9569fd52018-03-16 14:30:42 +0000322 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000323 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000324 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000325 "onCodeAction called for non-added file");
326
Sam McCalld20d7982018-07-09 14:25:59 +0000327 json::Array Commands;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000328 for (Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000329 for (auto &F : getFixes(Params.textDocument.uri.file(), D)) {
Sam McCalldd0566b2017-11-06 15:40:30 +0000330 WorkspaceEdit WE;
Ilya Biryukov71028b82018-03-12 15:28:22 +0000331 std::vector<TextEdit> Edits(F.Edits.begin(), F.Edits.end());
Eric Liu78ed91a72018-01-29 15:37:46 +0000332 WE.changes = {{Params.textDocument.uri.uri(), std::move(Edits)}};
Sam McCalld20d7982018-07-09 14:25:59 +0000333 Commands.push_back(json::Object{
Ilya Biryukov71028b82018-03-12 15:28:22 +0000334 {"title", llvm::formatv("Apply fix: {0}", F.Message)},
Sam McCalldd0566b2017-11-06 15:40:30 +0000335 {"command", ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND},
336 {"arguments", {WE}},
337 });
338 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000339 }
Sam McCalld1a7a372018-01-31 13:40:48 +0000340 reply(std::move(Commands));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000341}
342
Sam McCalld1a7a372018-01-31 13:40:48 +0000343void ClangdLSPServer::onCompletion(TextDocumentPositionParams &Params) {
Sam McCall45be5cf2018-09-13 12:58:36 +0000344 Server.codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
345 [this](llvm::Expected<CodeCompleteResult> List) {
346 if (!List)
347 return replyError(List.takeError());
348 CompletionList LSPList;
349 LSPList.isIncomplete = List->HasMore;
350 for (const auto &R : List->Completions)
351 LSPList.items.push_back(R.render(CCOpts));
352 return reply(std::move(LSPList));
353 });
Ilya Biryukovafb55542017-05-16 14:40:30 +0000354}
355
Sam McCalld1a7a372018-01-31 13:40:48 +0000356void ClangdLSPServer::onSignatureHelp(TextDocumentPositionParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000357 Server.signatureHelp(Params.textDocument.uri.file(), Params.position,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000358 [](llvm::Expected<SignatureHelp> SignatureHelp) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000359 if (!SignatureHelp)
360 return replyError(
361 ErrorCode::InvalidParams,
362 llvm::toString(SignatureHelp.takeError()));
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000363 reply(*SignatureHelp);
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000364 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000365}
366
Sam McCalld1a7a372018-01-31 13:40:48 +0000367void ClangdLSPServer::onGoToDefinition(TextDocumentPositionParams &Params) {
Kadir Cetinkaya689bf932018-08-24 13:09:41 +0000368 Server.findDefinitions(Params.textDocument.uri.file(), Params.position,
369 [](llvm::Expected<std::vector<Location>> Items) {
370 if (!Items)
371 return replyError(
372 ErrorCode::InvalidParams,
373 llvm::toString(Items.takeError()));
374 reply(json::Array(*Items));
375 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000376}
377
Sam McCalld1a7a372018-01-31 13:40:48 +0000378void ClangdLSPServer::onSwitchSourceHeader(TextDocumentIdentifier &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000379 llvm::Optional<Path> Result = Server.switchSourceHeader(Params.uri.file());
Sam McCalld1a7a372018-01-31 13:40:48 +0000380 reply(Result ? URI::createFile(*Result).toString() : "");
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000381}
382
Sam McCalld1a7a372018-01-31 13:40:48 +0000383void ClangdLSPServer::onDocumentHighlight(TextDocumentPositionParams &Params) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000384 Server.findDocumentHighlights(
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000385 Params.textDocument.uri.file(), Params.position,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000386 [](llvm::Expected<std::vector<DocumentHighlight>> Highlights) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000387 if (!Highlights)
388 return replyError(ErrorCode::InternalError,
389 llvm::toString(Highlights.takeError()));
Sam McCalld20d7982018-07-09 14:25:59 +0000390 reply(json::Array(*Highlights));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000391 });
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000392}
393
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000394void ClangdLSPServer::onHover(TextDocumentPositionParams &Params) {
395 Server.findHover(Params.textDocument.uri.file(), Params.position,
Sam McCall682cfe72018-06-04 10:37:16 +0000396 [](llvm::Expected<llvm::Optional<Hover>> H) {
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000397 if (!H) {
398 replyError(ErrorCode::InternalError,
399 llvm::toString(H.takeError()));
400 return;
401 }
402
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000403 reply(*H);
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000404 });
405}
406
Simon Marchi88016782018-08-01 11:28:49 +0000407void ClangdLSPServer::applyConfiguration(
408 const ClangdConfigurationParamsChange &Settings) {
Simon Marchi5178f922018-02-22 14:00:39 +0000409 // Compilation database change.
410 if (Settings.compilationDatabasePath.hasValue()) {
Alex Lorenzf8087862018-08-01 17:39:29 +0000411 CDB.setCompileCommandsDir(Settings.compilationDatabasePath.getValue());
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000412
Simon Marchi9569fd52018-03-16 14:30:42 +0000413 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +0000414 }
Alex Lorenzf8087862018-08-01 17:39:29 +0000415
416 // Update to the compilation database.
417 if (Settings.compilationDatabaseChanges) {
418 const auto &CompileCommandUpdates = *Settings.compilationDatabaseChanges;
419 bool ShouldReparseOpenFiles = false;
420 for (auto &Entry : CompileCommandUpdates) {
421 /// The opened files need to be reparsed only when some existing
422 /// entries are changed.
423 PathRef File = Entry.first;
424 if (!CDB.setCompilationCommandForFile(
425 File, tooling::CompileCommand(
426 std::move(Entry.second.workingDirectory), File,
427 std::move(Entry.second.compilationCommand),
428 /*Output=*/"")))
429 ShouldReparseOpenFiles = true;
430 }
431 if (ShouldReparseOpenFiles)
432 reparseOpenedFiles();
433 }
Simon Marchi5178f922018-02-22 14:00:39 +0000434}
435
Simon Marchi88016782018-08-01 11:28:49 +0000436// FIXME: This function needs to be properly tested.
437void ClangdLSPServer::onChangeConfiguration(
438 DidChangeConfigurationParams &Params) {
439 applyConfiguration(Params.settings);
440}
441
Sam McCall1ad142f2018-09-05 11:53:07 +0000442void ClangdLSPServer::onReference(ReferenceParams &Params) {
443 Server.findReferences(Params.textDocument.uri.file(), Params.position,
444 [](llvm::Expected<std::vector<Location>> Locations) {
445 if (!Locations)
446 return replyError(
447 ErrorCode::InternalError,
448 llvm::toString(Locations.takeError()));
449 reply(llvm::json::Array(*Locations));
450 });
451}
452
Sam McCall7363a2f2018-03-05 17:28:54 +0000453ClangdLSPServer::ClangdLSPServer(JSONOutput &Out,
Sam McCalladccab62017-11-23 16:58:22 +0000454 const clangd::CodeCompleteOptions &CCOpts,
Eric Liubfac8f72017-12-19 18:00:37 +0000455 llvm::Optional<Path> CompileCommandsDir,
Alex Lorenzf8087862018-08-01 17:39:29 +0000456 bool ShouldUseInMemoryCDB,
Sam McCall7363a2f2018-03-05 17:28:54 +0000457 const ClangdServer::Options &Opts)
Alex Lorenzf8087862018-08-01 17:39:29 +0000458 : Out(Out), CDB(ShouldUseInMemoryCDB ? CompilationDB::makeInMemory()
459 : CompilationDB::makeDirectoryBased(
460 std::move(CompileCommandsDir))),
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000461 CCOpts(CCOpts), SupportedSymbolKinds(defaultSymbolKinds()),
Alex Lorenzf8087862018-08-01 17:39:29 +0000462 Server(CDB.getCDB(), FSProvider, /*DiagConsumer=*/*this, Opts) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000463
Sam McCall27a07cf2018-06-05 09:34:46 +0000464bool ClangdLSPServer::run(std::FILE *In, JSONStreamStyle InputStyle) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000465 assert(!IsDone && "Run was called before");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000466
Ilya Biryukovafb55542017-05-16 14:40:30 +0000467 // Set up JSONRPCDispatcher.
Sam McCalld20d7982018-07-09 14:25:59 +0000468 JSONRPCDispatcher Dispatcher([](const json::Value &Params) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000469 replyError(ErrorCode::MethodNotFound, "method not found");
Ilya Biryukov940901e2017-12-13 12:51:22 +0000470 });
Simon Marchi6e8eb9d2018-03-07 21:47:25 +0000471 registerCallbackHandlers(Dispatcher, /*Callbacks=*/*this);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000472
Ilya Biryukovafb55542017-05-16 14:40:30 +0000473 // Run the Language Server loop.
Sam McCall5ed599e2018-02-06 10:47:30 +0000474 runLanguageServerLoop(In, Out, InputStyle, Dispatcher, IsDone);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000475
476 // Make sure IsDone is set to true after this method exits to ensure assertion
477 // at the start of the method fires if it's ever executed again.
478 IsDone = true;
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000479
480 return ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000481}
482
Ilya Biryukov71028b82018-03-12 15:28:22 +0000483std::vector<Fix> ClangdLSPServer::getFixes(StringRef File,
484 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000485 std::lock_guard<std::mutex> Lock(FixItsMutex);
486 auto DiagToFixItsIter = FixItsMap.find(File);
487 if (DiagToFixItsIter == FixItsMap.end())
488 return {};
489
490 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
491 auto FixItsIter = DiagToFixItsMap.find(D);
492 if (FixItsIter == DiagToFixItsMap.end())
493 return {};
494
495 return FixItsIter->second;
496}
497
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000498void ClangdLSPServer::onDiagnosticsReady(PathRef File,
499 std::vector<Diag> Diagnostics) {
Sam McCalld20d7982018-07-09 14:25:59 +0000500 json::Array DiagnosticsJSON;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000501
502 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000503 for (auto &Diag : Diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000504 toLSPDiags(Diag, [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Alex Lorenz8626d362018-08-10 17:25:07 +0000505 json::Object LSPDiag({
Ilya Biryukov71028b82018-03-12 15:28:22 +0000506 {"range", Diag.range},
507 {"severity", Diag.severity},
508 {"message", Diag.message},
509 });
Alex Lorenz8626d362018-08-10 17:25:07 +0000510 // LSP extension: embed the fixes in the diagnostic.
511 if (DiagOpts.EmbedFixesInDiagnostics && !Fixes.empty()) {
512 json::Array ClangdFixes;
513 for (const auto &Fix : Fixes) {
514 WorkspaceEdit WE;
515 URIForFile URI{File};
516 WE.changes = {{URI.uri(), std::vector<TextEdit>(Fix.Edits.begin(),
517 Fix.Edits.end())}};
518 ClangdFixes.push_back(
519 json::Object{{"edit", toJSON(WE)}, {"title", Fix.Message}});
520 }
521 LSPDiag["clangd_fixes"] = std::move(ClangdFixes);
522 }
Alex Lorenz0ce8a7a2018-08-22 20:30:06 +0000523 if (DiagOpts.SendDiagnosticCategory && !Diag.category.empty())
Alex Lorenz37146432018-08-14 22:21:40 +0000524 LSPDiag["category"] = Diag.category;
Alex Lorenz8626d362018-08-10 17:25:07 +0000525 DiagnosticsJSON.push_back(std::move(LSPDiag));
Ilya Biryukov71028b82018-03-12 15:28:22 +0000526
527 auto &FixItsForDiagnostic = LocalFixIts[Diag];
528 std::copy(Fixes.begin(), Fixes.end(),
529 std::back_inserter(FixItsForDiagnostic));
Sam McCalldd0566b2017-11-06 15:40:30 +0000530 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000531 }
532
533 // Cache FixIts
534 {
535 // FIXME(ibiryukov): should be deleted when documents are removed
536 std::lock_guard<std::mutex> Lock(FixItsMutex);
537 FixItsMap[File] = LocalFixIts;
538 }
539
540 // Publish diagnostics.
Sam McCalld20d7982018-07-09 14:25:59 +0000541 Out.writeMessage(json::Object{
Sam McCalldd0566b2017-11-06 15:40:30 +0000542 {"jsonrpc", "2.0"},
543 {"method", "textDocument/publishDiagnostics"},
544 {"params",
Sam McCalld20d7982018-07-09 14:25:59 +0000545 json::Object{
Eric Liu78ed91a72018-01-29 15:37:46 +0000546 {"uri", URIForFile{File}},
Sam McCalldd0566b2017-11-06 15:40:30 +0000547 {"diagnostics", std::move(DiagnosticsJSON)},
548 }},
549 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000550}
Simon Marchi9569fd52018-03-16 14:30:42 +0000551
552void ClangdLSPServer::reparseOpenedFiles() {
553 for (const Path &FilePath : DraftMgr.getActiveFiles())
554 Server.addDocument(FilePath, *DraftMgr.getDraft(FilePath),
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000555 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +0000556}
Alex Lorenzf8087862018-08-01 17:39:29 +0000557
558ClangdLSPServer::CompilationDB ClangdLSPServer::CompilationDB::makeInMemory() {
559 return CompilationDB(llvm::make_unique<InMemoryCompilationDb>(), nullptr,
560 /*IsDirectoryBased=*/false);
561}
562
563ClangdLSPServer::CompilationDB
564ClangdLSPServer::CompilationDB::makeDirectoryBased(
565 llvm::Optional<Path> CompileCommandsDir) {
566 auto CDB = llvm::make_unique<DirectoryBasedGlobalCompilationDatabase>(
567 std::move(CompileCommandsDir));
568 auto CachingCDB = llvm::make_unique<CachingCompilationDb>(*CDB);
569 return CompilationDB(std::move(CDB), std::move(CachingCDB),
570 /*IsDirectoryBased=*/true);
571}
572
573void ClangdLSPServer::CompilationDB::invalidate(PathRef File) {
574 if (!IsDirectoryBased)
575 static_cast<InMemoryCompilationDb *>(CDB.get())->invalidate(File);
576 else
577 CachingCDB->invalidate(File);
578}
579
580bool ClangdLSPServer::CompilationDB::setCompilationCommandForFile(
581 PathRef File, tooling::CompileCommand CompilationCommand) {
582 if (IsDirectoryBased) {
583 elog("Trying to set compile command for {0} while using directory-based "
584 "compilation database",
585 File);
586 return false;
587 }
588 return static_cast<InMemoryCompilationDb *>(CDB.get())
589 ->setCompilationCommandForFile(File, std::move(CompilationCommand));
590}
591
592void ClangdLSPServer::CompilationDB::setExtraFlagsForFile(
593 PathRef File, std::vector<std::string> ExtraFlags) {
594 if (!IsDirectoryBased) {
595 elog("Trying to set extra flags for {0} while using in-memory compilation "
596 "database",
597 File);
598 return;
599 }
600 static_cast<DirectoryBasedGlobalCompilationDatabase *>(CDB.get())
601 ->setExtraFlagsForFile(File, std::move(ExtraFlags));
602 CachingCDB->invalidate(File);
603}
604
605void ClangdLSPServer::CompilationDB::setCompileCommandsDir(Path P) {
606 if (!IsDirectoryBased) {
607 elog("Trying to set compile commands dir while using in-memory compilation "
608 "database");
609 return;
610 }
611 static_cast<DirectoryBasedGlobalCompilationDatabase *>(CDB.get())
612 ->setCompileCommandsDir(P);
613 CachingCDB->clear();
614}
615
616GlobalCompilationDatabase &ClangdLSPServer::CompilationDB::getCDB() {
617 if (CachingCDB)
618 return *CachingCDB;
619 return *CDB;
620}