blob: 7374c6d354be3b585fe7d7db011772ccdd688256 [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//
8//===---------------------------------------------------------------------===//
9
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"
Simon Marchi9569fd52018-03-16 14:30:42 +000015#include "llvm/Support/Errc.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000016#include "llvm/Support/FormatVariadic.h"
Eric Liu5740ff52018-01-31 16:26:27 +000017#include "llvm/Support/Path.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000018
Ilya Biryukov38d79772017-05-16 09:38:59 +000019using namespace clang::clangd;
20using namespace clang;
Sam McCalld20d7982018-07-09 14:25:59 +000021using namespace llvm;
Ilya Biryukov38d79772017-05-16 09:38:59 +000022
Ilya Biryukovafb55542017-05-16 14:40:30 +000023namespace {
24
Eric Liu5740ff52018-01-31 16:26:27 +000025/// \brief Supports a test URI scheme with relaxed constraints for lit tests.
26/// The path in a test URI will be combined with a platform-specific fake
27/// directory to form an absolute path. For example, test:///a.cpp is resolved
28/// C:\clangd-test\a.cpp on Windows and /clangd-test/a.cpp on Unix.
29class TestScheme : public URIScheme {
30public:
31 llvm::Expected<std::string>
32 getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,
33 llvm::StringRef /*HintPath*/) const override {
34 using namespace llvm::sys;
35 // Still require "/" in body to mimic file scheme, as we want lengths of an
36 // equivalent URI in both schemes to be the same.
37 if (!Body.startswith("/"))
38 return llvm::make_error<llvm::StringError>(
39 "Expect URI body to be an absolute path starting with '/': " + Body,
40 llvm::inconvertibleErrorCode());
41 Body = Body.ltrim('/');
Nico Weber0da22902018-04-10 13:14:03 +000042#ifdef _WIN32
Eric Liu5740ff52018-01-31 16:26:27 +000043 constexpr char TestDir[] = "C:\\clangd-test";
44#else
45 constexpr char TestDir[] = "/clangd-test";
46#endif
47 llvm::SmallVector<char, 16> Path(Body.begin(), Body.end());
48 path::native(Path);
49 auto Err = fs::make_absolute(TestDir, Path);
Eric Liucda25262018-02-01 12:44:52 +000050 if (Err)
51 llvm_unreachable("Failed to make absolute path in test scheme.");
Eric Liu5740ff52018-01-31 16:26:27 +000052 return std::string(Path.begin(), Path.end());
53 }
54
55 llvm::Expected<URI>
56 uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
57 llvm_unreachable("Clangd must never create a test URI.");
58 }
59};
60
61static URISchemeRegistry::Add<TestScheme>
62 X("test", "Test scheme for clangd lit tests.");
63
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000064SymbolKindBitset defaultSymbolKinds() {
65 SymbolKindBitset Defaults;
66 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
67 ++I)
68 Defaults.set(I);
69 return Defaults;
70}
71
Ilya Biryukovafb55542017-05-16 14:40:30 +000072} // namespace
73
Sam McCalld1a7a372018-01-31 13:40:48 +000074void ClangdLSPServer::onInitialize(InitializeParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +000075 if (Params.initializationOptions)
76 applyConfiguration(*Params.initializationOptions);
77
Ilya Biryukov7d60d202018-02-16 12:20:47 +000078 if (Params.rootUri && *Params.rootUri)
79 Server.setRootPath(Params.rootUri->file());
Ilya Biryukov23bc73b2018-02-15 14:32:57 +000080 else if (Params.rootPath && !Params.rootPath->empty())
81 Server.setRootPath(*Params.rootPath);
82
83 CCOpts.EnableSnippets =
84 Params.capabilities.textDocument.completion.completionItem.snippetSupport;
85
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000086 if (Params.capabilities.workspace && Params.capabilities.workspace->symbol &&
87 Params.capabilities.workspace->symbol->symbolKind) {
88 for (SymbolKind Kind :
89 *Params.capabilities.workspace->symbol->symbolKind->valueSet) {
90 SupportedSymbolKinds.set(static_cast<size_t>(Kind));
91 }
92 }
93
Sam McCalld20d7982018-07-09 14:25:59 +000094 reply(json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +000095 {{"capabilities",
Sam McCalld20d7982018-07-09 14:25:59 +000096 json::Object{
Simon Marchi98082622018-03-26 14:41:40 +000097 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +000098 {"documentFormattingProvider", true},
99 {"documentRangeFormattingProvider", true},
100 {"documentOnTypeFormattingProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000101 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000102 {"firstTriggerCharacter", "}"},
103 {"moreTriggerCharacter", {}},
104 }},
105 {"codeActionProvider", true},
106 {"completionProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000107 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000108 {"resolveProvider", false},
109 {"triggerCharacters", {".", ">", ":"}},
110 }},
111 {"signatureHelpProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000112 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000113 {"triggerCharacters", {"(", ","}},
114 }},
115 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000116 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000117 {"hoverProvider", true},
Haojian Wu345099c2017-11-09 11:30:04 +0000118 {"renameProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000119 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000120 {"workspaceSymbolProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000121 {"executeCommandProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000122 json::Object{
Eric Liu2c190532018-05-15 15:23:53 +0000123 {"commands", {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND}},
Sam McCall0930ab02017-11-07 15:49:35 +0000124 }},
125 }}}});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000126}
127
Sam McCalld1a7a372018-01-31 13:40:48 +0000128void ClangdLSPServer::onShutdown(ShutdownParams &Params) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000129 // Do essentially nothing, just say we're ready to exit.
130 ShutdownRequestReceived = true;
Sam McCalld1a7a372018-01-31 13:40:48 +0000131 reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000132}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000133
Sam McCalld1a7a372018-01-31 13:40:48 +0000134void ClangdLSPServer::onExit(ExitParams &Params) { IsDone = true; }
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000135
Sam McCalld1a7a372018-01-31 13:40:48 +0000136void ClangdLSPServer::onDocumentDidOpen(DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000137 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000138 if (Params.metadata && !Params.metadata->extraFlags.empty()) {
139 NonCachedCDB.setExtraFlagsForFile(File,
140 std::move(Params.metadata->extraFlags));
141 CDB.invalidate(File);
142 }
143
Simon Marchi9569fd52018-03-16 14:30:42 +0000144 std::string &Contents = Params.textDocument.text;
145
Simon Marchi98082622018-03-26 14:41:40 +0000146 DraftMgr.addDraft(File, Contents);
Simon Marchi9569fd52018-03-16 14:30:42 +0000147 Server.addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000148}
149
Sam McCalld1a7a372018-01-31 13:40:48 +0000150void ClangdLSPServer::onDocumentDidChange(DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000151 auto WantDiags = WantDiagnostics::Auto;
152 if (Params.wantDiagnostics.hasValue())
153 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
154 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000155
156 PathRef File = Params.textDocument.uri.file();
Simon Marchi98082622018-03-26 14:41:40 +0000157 llvm::Expected<std::string> Contents =
158 DraftMgr.updateDraft(File, Params.contentChanges);
159 if (!Contents) {
160 // If this fails, we are most likely going to be not in sync anymore with
161 // the client. It is better to remove the draft and let further operations
162 // fail rather than giving wrong results.
163 DraftMgr.removeDraft(File);
164 Server.removeDocument(File);
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000165 CDB.invalidate(File);
Sam McCallbed58852018-07-11 10:35:11 +0000166 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000167 return;
168 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000169
Simon Marchi98082622018-03-26 14:41:40 +0000170 Server.addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000171}
172
Sam McCalld1a7a372018-01-31 13:40:48 +0000173void ClangdLSPServer::onFileEvent(DidChangeWatchedFilesParams &Params) {
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000174 Server.onFileEvent(Params);
175}
176
Sam McCalld1a7a372018-01-31 13:40:48 +0000177void ClangdLSPServer::onCommand(ExecuteCommandParams &Params) {
Eric Liuc5105f92018-02-16 14:15:55 +0000178 auto ApplyEdit = [](WorkspaceEdit WE) {
179 ApplyWorkspaceEditParams Edit;
180 Edit.edit = std::move(WE);
181 // We don't need the response so id == 1 is OK.
182 // Ideally, we would wait for the response and if there is no error, we
183 // would reply success/failure to the original RPC.
184 call("workspace/applyEdit", Edit);
185 };
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000186 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
187 Params.workspaceEdit) {
188 // The flow for "apply-fix" :
189 // 1. We publish a diagnostic, including fixits
190 // 2. The user clicks on the diagnostic, the editor asks us for code actions
191 // 3. We send code actions, with the fixit embedded as context
192 // 4. The user selects the fixit, the editor asks us to apply it
193 // 5. We unwrap the changes and send them back to the editor
194 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
195 // we ignore it)
196
Sam McCalld1a7a372018-01-31 13:40:48 +0000197 reply("Fix applied.");
Eric Liuc5105f92018-02-16 14:15:55 +0000198 ApplyEdit(*Params.workspaceEdit);
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000199 } else {
200 // We should not get here because ExecuteCommandParams would not have
201 // parsed in the first place and this handler should not be called. But if
202 // more commands are added, this will be here has a safe guard.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000203 replyError(
Sam McCalld1a7a372018-01-31 13:40:48 +0000204 ErrorCode::InvalidParams,
Haojian Wu2375c922017-11-07 10:21:02 +0000205 llvm::formatv("Unsupported command \"{0}\".", Params.command).str());
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000206 }
207}
208
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000209void ClangdLSPServer::onWorkspaceSymbol(WorkspaceSymbolParams &Params) {
210 Server.workspaceSymbols(
211 Params.query, CCOpts.Limit,
212 [this](llvm::Expected<std::vector<SymbolInformation>> Items) {
213 if (!Items)
214 return replyError(ErrorCode::InternalError,
215 llvm::toString(Items.takeError()));
216 for (auto &Sym : *Items)
217 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
218
Sam McCalld20d7982018-07-09 14:25:59 +0000219 reply(json::Array(*Items));
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000220 });
221}
222
Sam McCalld1a7a372018-01-31 13:40:48 +0000223void ClangdLSPServer::onRename(RenameParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000224 Path File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000225 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000226 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000227 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000228 "onRename called for non-added file");
229
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000230 Server.rename(
231 File, Params.position, Params.newName,
232 [File, Code,
233 Params](llvm::Expected<std::vector<tooling::Replacement>> Replacements) {
234 if (!Replacements)
235 return replyError(ErrorCode::InternalError,
236 llvm::toString(Replacements.takeError()));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000237
Eric Liu9133ecd2018-05-11 12:12:08 +0000238 // Turn the replacements into the format specified by the Language
239 // Server Protocol. Fuse them into one big JSON array.
240 std::vector<TextEdit> Edits;
241 for (const auto &R : *Replacements)
242 Edits.push_back(replacementToEdit(*Code, R));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000243 WorkspaceEdit WE;
244 WE.changes = {{Params.textDocument.uri.uri(), Edits}};
245 reply(WE);
246 });
Haojian Wu345099c2017-11-09 11:30:04 +0000247}
248
Sam McCalld1a7a372018-01-31 13:40:48 +0000249void ClangdLSPServer::onDocumentDidClose(DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000250 PathRef File = Params.textDocument.uri.file();
251 DraftMgr.removeDraft(File);
252 Server.removeDocument(File);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000253}
254
Sam McCall4db732a2017-09-30 10:08:52 +0000255void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCalld1a7a372018-01-31 13:40:48 +0000256 DocumentOnTypeFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000257 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000258 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000259 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000260 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000261 "onDocumentOnTypeFormatting called for non-added file");
262
263 auto ReplacementsOrError = Server.formatOnType(*Code, File, Params.position);
Raoul Wols212bcf82017-12-12 20:25:06 +0000264 if (ReplacementsOrError)
Sam McCalld20d7982018-07-09 14:25:59 +0000265 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000266 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000267 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000268 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000269}
270
Sam McCall4db732a2017-09-30 10:08:52 +0000271void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCalld1a7a372018-01-31 13:40:48 +0000272 DocumentRangeFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000273 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000274 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000275 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000276 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000277 "onDocumentRangeFormatting called for non-added file");
278
279 auto ReplacementsOrError = Server.formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000280 if (ReplacementsOrError)
Sam McCalld20d7982018-07-09 14:25:59 +0000281 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000282 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000283 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000284 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000285}
286
Sam McCalld1a7a372018-01-31 13:40:48 +0000287void ClangdLSPServer::onDocumentFormatting(DocumentFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000288 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000289 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000290 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000291 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000292 "onDocumentFormatting called for non-added file");
293
294 auto ReplacementsOrError = Server.formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000295 if (ReplacementsOrError)
Sam McCalld20d7982018-07-09 14:25:59 +0000296 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000297 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000298 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000299 llvm::toString(ReplacementsOrError.takeError()));
Sam McCall4db732a2017-09-30 10:08:52 +0000300}
301
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000302void ClangdLSPServer::onDocumentSymbol(DocumentSymbolParams &Params) {
303 Server.documentSymbols(
304 Params.textDocument.uri.file(),
305 [this](llvm::Expected<std::vector<SymbolInformation>> Items) {
306 if (!Items)
307 return replyError(ErrorCode::InvalidParams,
308 llvm::toString(Items.takeError()));
309 for (auto &Sym : *Items)
310 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Sam McCalld20d7982018-07-09 14:25:59 +0000311 reply(json::Array(*Items));
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000312 });
313}
314
Sam McCalld1a7a372018-01-31 13:40:48 +0000315void ClangdLSPServer::onCodeAction(CodeActionParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000316 // We provide a code action for each diagnostic at the requested location
317 // which has FixIts available.
Simon Marchi9569fd52018-03-16 14:30:42 +0000318 auto Code = DraftMgr.getDraft(Params.textDocument.uri.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 "onCodeAction called for non-added file");
322
Sam McCalld20d7982018-07-09 14:25:59 +0000323 json::Array Commands;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000324 for (Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000325 for (auto &F : getFixes(Params.textDocument.uri.file(), D)) {
Sam McCalldd0566b2017-11-06 15:40:30 +0000326 WorkspaceEdit WE;
Ilya Biryukov71028b82018-03-12 15:28:22 +0000327 std::vector<TextEdit> Edits(F.Edits.begin(), F.Edits.end());
Eric Liu78ed91a72018-01-29 15:37:46 +0000328 WE.changes = {{Params.textDocument.uri.uri(), std::move(Edits)}};
Sam McCalld20d7982018-07-09 14:25:59 +0000329 Commands.push_back(json::Object{
Ilya Biryukov71028b82018-03-12 15:28:22 +0000330 {"title", llvm::formatv("Apply fix: {0}", F.Message)},
Sam McCalldd0566b2017-11-06 15:40:30 +0000331 {"command", ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND},
332 {"arguments", {WE}},
333 });
334 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000335 }
Sam McCalld1a7a372018-01-31 13:40:48 +0000336 reply(std::move(Commands));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000337}
338
Sam McCalld1a7a372018-01-31 13:40:48 +0000339void ClangdLSPServer::onCompletion(TextDocumentPositionParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000340 Server.codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
Sam McCalle746a2b2018-07-02 11:13:16 +0000341 [this](llvm::Expected<CodeCompleteResult> List) {
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000342 if (!List)
343 return replyError(ErrorCode::InvalidParams,
344 llvm::toString(List.takeError()));
Sam McCalle746a2b2018-07-02 11:13:16 +0000345 CompletionList LSPList;
346 LSPList.isIncomplete = List->HasMore;
347 for (const auto &R : List->Completions)
348 LSPList.items.push_back(R.render(CCOpts));
349 reply(std::move(LSPList));
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000350 });
Ilya Biryukovafb55542017-05-16 14:40:30 +0000351}
352
Sam McCalld1a7a372018-01-31 13:40:48 +0000353void ClangdLSPServer::onSignatureHelp(TextDocumentPositionParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000354 Server.signatureHelp(Params.textDocument.uri.file(), Params.position,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000355 [](llvm::Expected<SignatureHelp> SignatureHelp) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000356 if (!SignatureHelp)
357 return replyError(
358 ErrorCode::InvalidParams,
359 llvm::toString(SignatureHelp.takeError()));
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000360 reply(*SignatureHelp);
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000361 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000362}
363
Sam McCalld1a7a372018-01-31 13:40:48 +0000364void ClangdLSPServer::onGoToDefinition(TextDocumentPositionParams &Params) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000365 Server.findDefinitions(
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000366 Params.textDocument.uri.file(), Params.position,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000367 [](llvm::Expected<std::vector<Location>> Items) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000368 if (!Items)
369 return replyError(ErrorCode::InvalidParams,
370 llvm::toString(Items.takeError()));
Sam McCalld20d7982018-07-09 14:25:59 +0000371 reply(json::Array(*Items));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000372 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000373}
374
Sam McCalld1a7a372018-01-31 13:40:48 +0000375void ClangdLSPServer::onSwitchSourceHeader(TextDocumentIdentifier &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000376 llvm::Optional<Path> Result = Server.switchSourceHeader(Params.uri.file());
Sam McCalld1a7a372018-01-31 13:40:48 +0000377 reply(Result ? URI::createFile(*Result).toString() : "");
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000378}
379
Sam McCalld1a7a372018-01-31 13:40:48 +0000380void ClangdLSPServer::onDocumentHighlight(TextDocumentPositionParams &Params) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000381 Server.findDocumentHighlights(
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000382 Params.textDocument.uri.file(), Params.position,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000383 [](llvm::Expected<std::vector<DocumentHighlight>> Highlights) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000384 if (!Highlights)
385 return replyError(ErrorCode::InternalError,
386 llvm::toString(Highlights.takeError()));
Sam McCalld20d7982018-07-09 14:25:59 +0000387 reply(json::Array(*Highlights));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000388 });
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000389}
390
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000391void ClangdLSPServer::onHover(TextDocumentPositionParams &Params) {
392 Server.findHover(Params.textDocument.uri.file(), Params.position,
Sam McCall682cfe72018-06-04 10:37:16 +0000393 [](llvm::Expected<llvm::Optional<Hover>> H) {
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000394 if (!H) {
395 replyError(ErrorCode::InternalError,
396 llvm::toString(H.takeError()));
397 return;
398 }
399
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000400 reply(*H);
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000401 });
402}
403
Simon Marchi88016782018-08-01 11:28:49 +0000404void ClangdLSPServer::applyConfiguration(
405 const ClangdConfigurationParamsChange &Settings) {
Simon Marchi5178f922018-02-22 14:00:39 +0000406 // Compilation database change.
407 if (Settings.compilationDatabasePath.hasValue()) {
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000408 NonCachedCDB.setCompileCommandsDir(
409 Settings.compilationDatabasePath.getValue());
410 CDB.clear();
411
Simon Marchi9569fd52018-03-16 14:30:42 +0000412 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +0000413 }
414}
415
Simon Marchi88016782018-08-01 11:28:49 +0000416// FIXME: This function needs to be properly tested.
417void ClangdLSPServer::onChangeConfiguration(
418 DidChangeConfigurationParams &Params) {
419 applyConfiguration(Params.settings);
420}
421
Sam McCall7363a2f2018-03-05 17:28:54 +0000422ClangdLSPServer::ClangdLSPServer(JSONOutput &Out,
Sam McCalladccab62017-11-23 16:58:22 +0000423 const clangd::CodeCompleteOptions &CCOpts,
Eric Liubfac8f72017-12-19 18:00:37 +0000424 llvm::Optional<Path> CompileCommandsDir,
Sam McCall7363a2f2018-03-05 17:28:54 +0000425 const ClangdServer::Options &Opts)
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000426 : Out(Out), NonCachedCDB(std::move(CompileCommandsDir)), CDB(NonCachedCDB),
427 CCOpts(CCOpts), SupportedSymbolKinds(defaultSymbolKinds()),
Sam McCall7363a2f2018-03-05 17:28:54 +0000428 Server(CDB, FSProvider, /*DiagConsumer=*/*this, Opts) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000429
Sam McCall27a07cf2018-06-05 09:34:46 +0000430bool ClangdLSPServer::run(std::FILE *In, JSONStreamStyle InputStyle) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000431 assert(!IsDone && "Run was called before");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000432
Ilya Biryukovafb55542017-05-16 14:40:30 +0000433 // Set up JSONRPCDispatcher.
Sam McCalld20d7982018-07-09 14:25:59 +0000434 JSONRPCDispatcher Dispatcher([](const json::Value &Params) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000435 replyError(ErrorCode::MethodNotFound, "method not found");
Ilya Biryukov940901e2017-12-13 12:51:22 +0000436 });
Simon Marchi6e8eb9d2018-03-07 21:47:25 +0000437 registerCallbackHandlers(Dispatcher, /*Callbacks=*/*this);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000438
Ilya Biryukovafb55542017-05-16 14:40:30 +0000439 // Run the Language Server loop.
Sam McCall5ed599e2018-02-06 10:47:30 +0000440 runLanguageServerLoop(In, Out, InputStyle, Dispatcher, IsDone);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000441
442 // Make sure IsDone is set to true after this method exits to ensure assertion
443 // at the start of the method fires if it's ever executed again.
444 IsDone = true;
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000445
446 return ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000447}
448
Ilya Biryukov71028b82018-03-12 15:28:22 +0000449std::vector<Fix> ClangdLSPServer::getFixes(StringRef File,
450 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000451 std::lock_guard<std::mutex> Lock(FixItsMutex);
452 auto DiagToFixItsIter = FixItsMap.find(File);
453 if (DiagToFixItsIter == FixItsMap.end())
454 return {};
455
456 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
457 auto FixItsIter = DiagToFixItsMap.find(D);
458 if (FixItsIter == DiagToFixItsMap.end())
459 return {};
460
461 return FixItsIter->second;
462}
463
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000464void ClangdLSPServer::onDiagnosticsReady(PathRef File,
465 std::vector<Diag> Diagnostics) {
Sam McCalld20d7982018-07-09 14:25:59 +0000466 json::Array DiagnosticsJSON;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000467
468 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000469 for (auto &Diag : Diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000470 toLSPDiags(Diag, [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCalld20d7982018-07-09 14:25:59 +0000471 DiagnosticsJSON.push_back(json::Object{
Ilya Biryukov71028b82018-03-12 15:28:22 +0000472 {"range", Diag.range},
473 {"severity", Diag.severity},
474 {"message", Diag.message},
475 });
476
477 auto &FixItsForDiagnostic = LocalFixIts[Diag];
478 std::copy(Fixes.begin(), Fixes.end(),
479 std::back_inserter(FixItsForDiagnostic));
Sam McCalldd0566b2017-11-06 15:40:30 +0000480 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000481 }
482
483 // Cache FixIts
484 {
485 // FIXME(ibiryukov): should be deleted when documents are removed
486 std::lock_guard<std::mutex> Lock(FixItsMutex);
487 FixItsMap[File] = LocalFixIts;
488 }
489
490 // Publish diagnostics.
Sam McCalld20d7982018-07-09 14:25:59 +0000491 Out.writeMessage(json::Object{
Sam McCalldd0566b2017-11-06 15:40:30 +0000492 {"jsonrpc", "2.0"},
493 {"method", "textDocument/publishDiagnostics"},
494 {"params",
Sam McCalld20d7982018-07-09 14:25:59 +0000495 json::Object{
Eric Liu78ed91a72018-01-29 15:37:46 +0000496 {"uri", URIForFile{File}},
Sam McCalldd0566b2017-11-06 15:40:30 +0000497 {"diagnostics", std::move(DiagnosticsJSON)},
498 }},
499 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000500}
Simon Marchi9569fd52018-03-16 14:30:42 +0000501
502void ClangdLSPServer::reparseOpenedFiles() {
503 for (const Path &FilePath : DraftMgr.getActiveFiles())
504 Server.addDocument(FilePath, *DraftMgr.getDraft(FilePath),
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000505 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +0000506}