blob: 0a0c1ead04f976f2fdda43645a488e9705dbceba [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"
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;
Alex Lorenz8626d362018-08-10 17:25:07 +000085 DiagOpts.EmbedFixesInDiagnostics =
86 Params.capabilities.textDocument.publishDiagnostics.clangdFixSupport;
Alex Lorenz0ce8a7a2018-08-22 20:30:06 +000087 DiagOpts.SendDiagnosticCategory =
88 Params.capabilities.textDocument.publishDiagnostics.categorySupport;
Ilya Biryukov23bc73b2018-02-15 14:32:57 +000089
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000090 if (Params.capabilities.workspace && Params.capabilities.workspace->symbol &&
91 Params.capabilities.workspace->symbol->symbolKind) {
92 for (SymbolKind Kind :
93 *Params.capabilities.workspace->symbol->symbolKind->valueSet) {
94 SupportedSymbolKinds.set(static_cast<size_t>(Kind));
95 }
96 }
97
Sam McCalld20d7982018-07-09 14:25:59 +000098 reply(json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +000099 {{"capabilities",
Sam McCalld20d7982018-07-09 14:25:59 +0000100 json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000101 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000102 {"documentFormattingProvider", true},
103 {"documentRangeFormattingProvider", true},
104 {"documentOnTypeFormattingProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000105 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000106 {"firstTriggerCharacter", "}"},
107 {"moreTriggerCharacter", {}},
108 }},
109 {"codeActionProvider", true},
110 {"completionProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000111 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000112 {"resolveProvider", false},
113 {"triggerCharacters", {".", ">", ":"}},
114 }},
115 {"signatureHelpProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000116 json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000117 {"triggerCharacters", {"(", ","}},
118 }},
119 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000120 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000121 {"hoverProvider", true},
Haojian Wu345099c2017-11-09 11:30:04 +0000122 {"renameProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000123 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000124 {"workspaceSymbolProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000125 {"executeCommandProvider",
Sam McCalld20d7982018-07-09 14:25:59 +0000126 json::Object{
Eric Liu2c190532018-05-15 15:23:53 +0000127 {"commands", {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND}},
Sam McCall0930ab02017-11-07 15:49:35 +0000128 }},
129 }}}});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000130}
131
Sam McCalld1a7a372018-01-31 13:40:48 +0000132void ClangdLSPServer::onShutdown(ShutdownParams &Params) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000133 // Do essentially nothing, just say we're ready to exit.
134 ShutdownRequestReceived = true;
Sam McCalld1a7a372018-01-31 13:40:48 +0000135 reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000136}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000137
Sam McCalld1a7a372018-01-31 13:40:48 +0000138void ClangdLSPServer::onExit(ExitParams &Params) { IsDone = true; }
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000139
Sam McCalld1a7a372018-01-31 13:40:48 +0000140void ClangdLSPServer::onDocumentDidOpen(DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000141 PathRef File = Params.textDocument.uri.file();
Alex Lorenzf8087862018-08-01 17:39:29 +0000142 if (Params.metadata && !Params.metadata->extraFlags.empty())
143 CDB.setExtraFlagsForFile(File, std::move(Params.metadata->extraFlags));
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000144
Simon Marchi9569fd52018-03-16 14:30:42 +0000145 std::string &Contents = Params.textDocument.text;
146
Simon Marchi98082622018-03-26 14:41:40 +0000147 DraftMgr.addDraft(File, Contents);
Simon Marchi9569fd52018-03-16 14:30:42 +0000148 Server.addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000149}
150
Sam McCalld1a7a372018-01-31 13:40:48 +0000151void ClangdLSPServer::onDocumentDidChange(DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000152 auto WantDiags = WantDiagnostics::Auto;
153 if (Params.wantDiagnostics.hasValue())
154 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
155 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000156
157 PathRef File = Params.textDocument.uri.file();
Simon Marchi98082622018-03-26 14:41:40 +0000158 llvm::Expected<std::string> Contents =
159 DraftMgr.updateDraft(File, Params.contentChanges);
160 if (!Contents) {
161 // If this fails, we are most likely going to be not in sync anymore with
162 // the client. It is better to remove the draft and let further operations
163 // fail rather than giving wrong results.
164 DraftMgr.removeDraft(File);
165 Server.removeDocument(File);
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000166 CDB.invalidate(File);
Sam McCallbed58852018-07-11 10:35:11 +0000167 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000168 return;
169 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000170
Simon Marchi98082622018-03-26 14:41:40 +0000171 Server.addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000172}
173
Sam McCalld1a7a372018-01-31 13:40:48 +0000174void ClangdLSPServer::onFileEvent(DidChangeWatchedFilesParams &Params) {
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000175 Server.onFileEvent(Params);
176}
177
Sam McCalld1a7a372018-01-31 13:40:48 +0000178void ClangdLSPServer::onCommand(ExecuteCommandParams &Params) {
Eric Liuc5105f92018-02-16 14:15:55 +0000179 auto ApplyEdit = [](WorkspaceEdit WE) {
180 ApplyWorkspaceEditParams Edit;
181 Edit.edit = std::move(WE);
182 // We don't need the response so id == 1 is OK.
183 // Ideally, we would wait for the response and if there is no error, we
184 // would reply success/failure to the original RPC.
185 call("workspace/applyEdit", Edit);
186 };
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000187 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
188 Params.workspaceEdit) {
189 // The flow for "apply-fix" :
190 // 1. We publish a diagnostic, including fixits
191 // 2. The user clicks on the diagnostic, the editor asks us for code actions
192 // 3. We send code actions, with the fixit embedded as context
193 // 4. The user selects the fixit, the editor asks us to apply it
194 // 5. We unwrap the changes and send them back to the editor
195 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
196 // we ignore it)
197
Sam McCalld1a7a372018-01-31 13:40:48 +0000198 reply("Fix applied.");
Eric Liuc5105f92018-02-16 14:15:55 +0000199 ApplyEdit(*Params.workspaceEdit);
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000200 } else {
201 // We should not get here because ExecuteCommandParams would not have
202 // parsed in the first place and this handler should not be called. But if
203 // more commands are added, this will be here has a safe guard.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000204 replyError(
Sam McCalld1a7a372018-01-31 13:40:48 +0000205 ErrorCode::InvalidParams,
Haojian Wu2375c922017-11-07 10:21:02 +0000206 llvm::formatv("Unsupported command \"{0}\".", Params.command).str());
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000207 }
208}
209
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000210void ClangdLSPServer::onWorkspaceSymbol(WorkspaceSymbolParams &Params) {
211 Server.workspaceSymbols(
212 Params.query, CCOpts.Limit,
213 [this](llvm::Expected<std::vector<SymbolInformation>> Items) {
214 if (!Items)
215 return replyError(ErrorCode::InternalError,
216 llvm::toString(Items.takeError()));
217 for (auto &Sym : *Items)
218 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
219
Sam McCalld20d7982018-07-09 14:25:59 +0000220 reply(json::Array(*Items));
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000221 });
222}
223
Sam McCalld1a7a372018-01-31 13:40:48 +0000224void ClangdLSPServer::onRename(RenameParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000225 Path File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000226 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000227 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000228 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000229 "onRename called for non-added file");
230
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000231 Server.rename(
232 File, Params.position, Params.newName,
233 [File, Code,
234 Params](llvm::Expected<std::vector<tooling::Replacement>> Replacements) {
235 if (!Replacements)
236 return replyError(ErrorCode::InternalError,
237 llvm::toString(Replacements.takeError()));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000238
Eric Liu9133ecd2018-05-11 12:12:08 +0000239 // Turn the replacements into the format specified by the Language
240 // Server Protocol. Fuse them into one big JSON array.
241 std::vector<TextEdit> Edits;
242 for (const auto &R : *Replacements)
243 Edits.push_back(replacementToEdit(*Code, R));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000244 WorkspaceEdit WE;
245 WE.changes = {{Params.textDocument.uri.uri(), Edits}};
246 reply(WE);
247 });
Haojian Wu345099c2017-11-09 11:30:04 +0000248}
249
Sam McCalld1a7a372018-01-31 13:40:48 +0000250void ClangdLSPServer::onDocumentDidClose(DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000251 PathRef File = Params.textDocument.uri.file();
252 DraftMgr.removeDraft(File);
253 Server.removeDocument(File);
Alex Lorenzf8087862018-08-01 17:39:29 +0000254 CDB.invalidate(File);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000255}
256
Sam McCall4db732a2017-09-30 10:08:52 +0000257void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCalld1a7a372018-01-31 13:40:48 +0000258 DocumentOnTypeFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000259 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000260 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000261 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000262 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000263 "onDocumentOnTypeFormatting called for non-added file");
264
265 auto ReplacementsOrError = Server.formatOnType(*Code, File, Params.position);
Raoul Wols212bcf82017-12-12 20:25:06 +0000266 if (ReplacementsOrError)
Sam McCalld20d7982018-07-09 14:25:59 +0000267 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000268 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000269 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000270 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000271}
272
Sam McCall4db732a2017-09-30 10:08:52 +0000273void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCalld1a7a372018-01-31 13:40:48 +0000274 DocumentRangeFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000275 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000276 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000277 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000278 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000279 "onDocumentRangeFormatting called for non-added file");
280
281 auto ReplacementsOrError = Server.formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000282 if (ReplacementsOrError)
Sam McCalld20d7982018-07-09 14:25:59 +0000283 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000284 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000285 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000286 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000287}
288
Sam McCalld1a7a372018-01-31 13:40:48 +0000289void ClangdLSPServer::onDocumentFormatting(DocumentFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000290 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000291 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000292 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000293 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000294 "onDocumentFormatting called for non-added file");
295
296 auto ReplacementsOrError = Server.formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000297 if (ReplacementsOrError)
Sam McCalld20d7982018-07-09 14:25:59 +0000298 reply(json::Array(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000299 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000300 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000301 llvm::toString(ReplacementsOrError.takeError()));
Sam McCall4db732a2017-09-30 10:08:52 +0000302}
303
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000304void ClangdLSPServer::onDocumentSymbol(DocumentSymbolParams &Params) {
305 Server.documentSymbols(
306 Params.textDocument.uri.file(),
307 [this](llvm::Expected<std::vector<SymbolInformation>> Items) {
308 if (!Items)
309 return replyError(ErrorCode::InvalidParams,
310 llvm::toString(Items.takeError()));
311 for (auto &Sym : *Items)
312 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Sam McCalld20d7982018-07-09 14:25:59 +0000313 reply(json::Array(*Items));
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000314 });
315}
316
Sam McCalld1a7a372018-01-31 13:40:48 +0000317void ClangdLSPServer::onCodeAction(CodeActionParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000318 // We provide a code action for each diagnostic at the requested location
319 // which has FixIts available.
Simon Marchi9569fd52018-03-16 14:30:42 +0000320 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000321 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000322 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000323 "onCodeAction called for non-added file");
324
Sam McCalld20d7982018-07-09 14:25:59 +0000325 json::Array Commands;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000326 for (Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000327 for (auto &F : getFixes(Params.textDocument.uri.file(), D)) {
Sam McCalldd0566b2017-11-06 15:40:30 +0000328 WorkspaceEdit WE;
Ilya Biryukov71028b82018-03-12 15:28:22 +0000329 std::vector<TextEdit> Edits(F.Edits.begin(), F.Edits.end());
Eric Liu78ed91a72018-01-29 15:37:46 +0000330 WE.changes = {{Params.textDocument.uri.uri(), std::move(Edits)}};
Sam McCalld20d7982018-07-09 14:25:59 +0000331 Commands.push_back(json::Object{
Ilya Biryukov71028b82018-03-12 15:28:22 +0000332 {"title", llvm::formatv("Apply fix: {0}", F.Message)},
Sam McCalldd0566b2017-11-06 15:40:30 +0000333 {"command", ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND},
334 {"arguments", {WE}},
335 });
336 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000337 }
Sam McCalld1a7a372018-01-31 13:40:48 +0000338 reply(std::move(Commands));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000339}
340
Sam McCalld1a7a372018-01-31 13:40:48 +0000341void ClangdLSPServer::onCompletion(TextDocumentPositionParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000342 Server.codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
Sam McCalle746a2b2018-07-02 11:13:16 +0000343 [this](llvm::Expected<CodeCompleteResult> List) {
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000344 if (!List)
345 return replyError(ErrorCode::InvalidParams,
346 llvm::toString(List.takeError()));
Sam McCalle746a2b2018-07-02 11:13:16 +0000347 CompletionList LSPList;
348 LSPList.isIncomplete = List->HasMore;
349 for (const auto &R : List->Completions)
350 LSPList.items.push_back(R.render(CCOpts));
351 reply(std::move(LSPList));
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000352 });
Ilya Biryukovafb55542017-05-16 14:40:30 +0000353}
354
Sam McCalld1a7a372018-01-31 13:40:48 +0000355void ClangdLSPServer::onSignatureHelp(TextDocumentPositionParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000356 Server.signatureHelp(Params.textDocument.uri.file(), Params.position,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000357 [](llvm::Expected<SignatureHelp> SignatureHelp) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000358 if (!SignatureHelp)
359 return replyError(
360 ErrorCode::InvalidParams,
361 llvm::toString(SignatureHelp.takeError()));
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000362 reply(*SignatureHelp);
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000363 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000364}
365
Sam McCalld1a7a372018-01-31 13:40:48 +0000366void ClangdLSPServer::onGoToDefinition(TextDocumentPositionParams &Params) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000367 Server.findDefinitions(
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000368 Params.textDocument.uri.file(), Params.position,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000369 [](llvm::Expected<std::vector<Location>> Items) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000370 if (!Items)
371 return replyError(ErrorCode::InvalidParams,
372 llvm::toString(Items.takeError()));
Sam McCalld20d7982018-07-09 14:25:59 +0000373 reply(json::Array(*Items));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000374 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000375}
376
Sam McCalld1a7a372018-01-31 13:40:48 +0000377void ClangdLSPServer::onSwitchSourceHeader(TextDocumentIdentifier &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000378 llvm::Optional<Path> Result = Server.switchSourceHeader(Params.uri.file());
Sam McCalld1a7a372018-01-31 13:40:48 +0000379 reply(Result ? URI::createFile(*Result).toString() : "");
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000380}
381
Sam McCalld1a7a372018-01-31 13:40:48 +0000382void ClangdLSPServer::onDocumentHighlight(TextDocumentPositionParams &Params) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000383 Server.findDocumentHighlights(
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000384 Params.textDocument.uri.file(), Params.position,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000385 [](llvm::Expected<std::vector<DocumentHighlight>> Highlights) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000386 if (!Highlights)
387 return replyError(ErrorCode::InternalError,
388 llvm::toString(Highlights.takeError()));
Sam McCalld20d7982018-07-09 14:25:59 +0000389 reply(json::Array(*Highlights));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000390 });
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000391}
392
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000393void ClangdLSPServer::onHover(TextDocumentPositionParams &Params) {
394 Server.findHover(Params.textDocument.uri.file(), Params.position,
Sam McCall682cfe72018-06-04 10:37:16 +0000395 [](llvm::Expected<llvm::Optional<Hover>> H) {
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000396 if (!H) {
397 replyError(ErrorCode::InternalError,
398 llvm::toString(H.takeError()));
399 return;
400 }
401
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000402 reply(*H);
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000403 });
404}
405
Simon Marchi88016782018-08-01 11:28:49 +0000406void ClangdLSPServer::applyConfiguration(
407 const ClangdConfigurationParamsChange &Settings) {
Simon Marchi5178f922018-02-22 14:00:39 +0000408 // Compilation database change.
409 if (Settings.compilationDatabasePath.hasValue()) {
Alex Lorenzf8087862018-08-01 17:39:29 +0000410 CDB.setCompileCommandsDir(Settings.compilationDatabasePath.getValue());
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000411
Simon Marchi9569fd52018-03-16 14:30:42 +0000412 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +0000413 }
Alex Lorenzf8087862018-08-01 17:39:29 +0000414
415 // Update to the compilation database.
416 if (Settings.compilationDatabaseChanges) {
417 const auto &CompileCommandUpdates = *Settings.compilationDatabaseChanges;
418 bool ShouldReparseOpenFiles = false;
419 for (auto &Entry : CompileCommandUpdates) {
420 /// The opened files need to be reparsed only when some existing
421 /// entries are changed.
422 PathRef File = Entry.first;
423 if (!CDB.setCompilationCommandForFile(
424 File, tooling::CompileCommand(
425 std::move(Entry.second.workingDirectory), File,
426 std::move(Entry.second.compilationCommand),
427 /*Output=*/"")))
428 ShouldReparseOpenFiles = true;
429 }
430 if (ShouldReparseOpenFiles)
431 reparseOpenedFiles();
432 }
Simon Marchi5178f922018-02-22 14:00:39 +0000433}
434
Simon Marchi88016782018-08-01 11:28:49 +0000435// FIXME: This function needs to be properly tested.
436void ClangdLSPServer::onChangeConfiguration(
437 DidChangeConfigurationParams &Params) {
438 applyConfiguration(Params.settings);
439}
440
Sam McCall7363a2f2018-03-05 17:28:54 +0000441ClangdLSPServer::ClangdLSPServer(JSONOutput &Out,
Sam McCalladccab62017-11-23 16:58:22 +0000442 const clangd::CodeCompleteOptions &CCOpts,
Eric Liubfac8f72017-12-19 18:00:37 +0000443 llvm::Optional<Path> CompileCommandsDir,
Alex Lorenzf8087862018-08-01 17:39:29 +0000444 bool ShouldUseInMemoryCDB,
Sam McCall7363a2f2018-03-05 17:28:54 +0000445 const ClangdServer::Options &Opts)
Alex Lorenzf8087862018-08-01 17:39:29 +0000446 : Out(Out), CDB(ShouldUseInMemoryCDB ? CompilationDB::makeInMemory()
447 : CompilationDB::makeDirectoryBased(
448 std::move(CompileCommandsDir))),
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000449 CCOpts(CCOpts), SupportedSymbolKinds(defaultSymbolKinds()),
Alex Lorenzf8087862018-08-01 17:39:29 +0000450 Server(CDB.getCDB(), FSProvider, /*DiagConsumer=*/*this, Opts) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000451
Sam McCall27a07cf2018-06-05 09:34:46 +0000452bool ClangdLSPServer::run(std::FILE *In, JSONStreamStyle InputStyle) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000453 assert(!IsDone && "Run was called before");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000454
Ilya Biryukovafb55542017-05-16 14:40:30 +0000455 // Set up JSONRPCDispatcher.
Sam McCalld20d7982018-07-09 14:25:59 +0000456 JSONRPCDispatcher Dispatcher([](const json::Value &Params) {
Sam McCalld1a7a372018-01-31 13:40:48 +0000457 replyError(ErrorCode::MethodNotFound, "method not found");
Ilya Biryukov940901e2017-12-13 12:51:22 +0000458 });
Simon Marchi6e8eb9d2018-03-07 21:47:25 +0000459 registerCallbackHandlers(Dispatcher, /*Callbacks=*/*this);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000460
Ilya Biryukovafb55542017-05-16 14:40:30 +0000461 // Run the Language Server loop.
Sam McCall5ed599e2018-02-06 10:47:30 +0000462 runLanguageServerLoop(In, Out, InputStyle, Dispatcher, IsDone);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000463
464 // Make sure IsDone is set to true after this method exits to ensure assertion
465 // at the start of the method fires if it's ever executed again.
466 IsDone = true;
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000467
468 return ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000469}
470
Ilya Biryukov71028b82018-03-12 15:28:22 +0000471std::vector<Fix> ClangdLSPServer::getFixes(StringRef File,
472 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000473 std::lock_guard<std::mutex> Lock(FixItsMutex);
474 auto DiagToFixItsIter = FixItsMap.find(File);
475 if (DiagToFixItsIter == FixItsMap.end())
476 return {};
477
478 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
479 auto FixItsIter = DiagToFixItsMap.find(D);
480 if (FixItsIter == DiagToFixItsMap.end())
481 return {};
482
483 return FixItsIter->second;
484}
485
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000486void ClangdLSPServer::onDiagnosticsReady(PathRef File,
487 std::vector<Diag> Diagnostics) {
Sam McCalld20d7982018-07-09 14:25:59 +0000488 json::Array DiagnosticsJSON;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000489
490 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000491 for (auto &Diag : Diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000492 toLSPDiags(Diag, [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Alex Lorenz8626d362018-08-10 17:25:07 +0000493 json::Object LSPDiag({
Ilya Biryukov71028b82018-03-12 15:28:22 +0000494 {"range", Diag.range},
495 {"severity", Diag.severity},
496 {"message", Diag.message},
497 });
Alex Lorenz8626d362018-08-10 17:25:07 +0000498 // LSP extension: embed the fixes in the diagnostic.
499 if (DiagOpts.EmbedFixesInDiagnostics && !Fixes.empty()) {
500 json::Array ClangdFixes;
501 for (const auto &Fix : Fixes) {
502 WorkspaceEdit WE;
503 URIForFile URI{File};
504 WE.changes = {{URI.uri(), std::vector<TextEdit>(Fix.Edits.begin(),
505 Fix.Edits.end())}};
506 ClangdFixes.push_back(
507 json::Object{{"edit", toJSON(WE)}, {"title", Fix.Message}});
508 }
509 LSPDiag["clangd_fixes"] = std::move(ClangdFixes);
510 }
Alex Lorenz0ce8a7a2018-08-22 20:30:06 +0000511 if (DiagOpts.SendDiagnosticCategory && !Diag.category.empty())
Alex Lorenz37146432018-08-14 22:21:40 +0000512 LSPDiag["category"] = Diag.category;
Alex Lorenz8626d362018-08-10 17:25:07 +0000513 DiagnosticsJSON.push_back(std::move(LSPDiag));
Ilya Biryukov71028b82018-03-12 15:28:22 +0000514
515 auto &FixItsForDiagnostic = LocalFixIts[Diag];
516 std::copy(Fixes.begin(), Fixes.end(),
517 std::back_inserter(FixItsForDiagnostic));
Sam McCalldd0566b2017-11-06 15:40:30 +0000518 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000519 }
520
521 // Cache FixIts
522 {
523 // FIXME(ibiryukov): should be deleted when documents are removed
524 std::lock_guard<std::mutex> Lock(FixItsMutex);
525 FixItsMap[File] = LocalFixIts;
526 }
527
528 // Publish diagnostics.
Sam McCalld20d7982018-07-09 14:25:59 +0000529 Out.writeMessage(json::Object{
Sam McCalldd0566b2017-11-06 15:40:30 +0000530 {"jsonrpc", "2.0"},
531 {"method", "textDocument/publishDiagnostics"},
532 {"params",
Sam McCalld20d7982018-07-09 14:25:59 +0000533 json::Object{
Eric Liu78ed91a72018-01-29 15:37:46 +0000534 {"uri", URIForFile{File}},
Sam McCalldd0566b2017-11-06 15:40:30 +0000535 {"diagnostics", std::move(DiagnosticsJSON)},
536 }},
537 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000538}
Simon Marchi9569fd52018-03-16 14:30:42 +0000539
540void ClangdLSPServer::reparseOpenedFiles() {
541 for (const Path &FilePath : DraftMgr.getActiveFiles())
542 Server.addDocument(FilePath, *DraftMgr.getDraft(FilePath),
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000543 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +0000544}
Alex Lorenzf8087862018-08-01 17:39:29 +0000545
546ClangdLSPServer::CompilationDB ClangdLSPServer::CompilationDB::makeInMemory() {
547 return CompilationDB(llvm::make_unique<InMemoryCompilationDb>(), nullptr,
548 /*IsDirectoryBased=*/false);
549}
550
551ClangdLSPServer::CompilationDB
552ClangdLSPServer::CompilationDB::makeDirectoryBased(
553 llvm::Optional<Path> CompileCommandsDir) {
554 auto CDB = llvm::make_unique<DirectoryBasedGlobalCompilationDatabase>(
555 std::move(CompileCommandsDir));
556 auto CachingCDB = llvm::make_unique<CachingCompilationDb>(*CDB);
557 return CompilationDB(std::move(CDB), std::move(CachingCDB),
558 /*IsDirectoryBased=*/true);
559}
560
561void ClangdLSPServer::CompilationDB::invalidate(PathRef File) {
562 if (!IsDirectoryBased)
563 static_cast<InMemoryCompilationDb *>(CDB.get())->invalidate(File);
564 else
565 CachingCDB->invalidate(File);
566}
567
568bool ClangdLSPServer::CompilationDB::setCompilationCommandForFile(
569 PathRef File, tooling::CompileCommand CompilationCommand) {
570 if (IsDirectoryBased) {
571 elog("Trying to set compile command for {0} while using directory-based "
572 "compilation database",
573 File);
574 return false;
575 }
576 return static_cast<InMemoryCompilationDb *>(CDB.get())
577 ->setCompilationCommandForFile(File, std::move(CompilationCommand));
578}
579
580void ClangdLSPServer::CompilationDB::setExtraFlagsForFile(
581 PathRef File, std::vector<std::string> ExtraFlags) {
582 if (!IsDirectoryBased) {
583 elog("Trying to set extra flags for {0} while using in-memory compilation "
584 "database",
585 File);
586 return;
587 }
588 static_cast<DirectoryBasedGlobalCompilationDatabase *>(CDB.get())
589 ->setExtraFlagsForFile(File, std::move(ExtraFlags));
590 CachingCDB->invalidate(File);
591}
592
593void ClangdLSPServer::CompilationDB::setCompileCommandsDir(Path P) {
594 if (!IsDirectoryBased) {
595 elog("Trying to set compile commands dir while using in-memory compilation "
596 "database");
597 return;
598 }
599 static_cast<DirectoryBasedGlobalCompilationDatabase *>(CDB.get())
600 ->setCompileCommandsDir(P);
601 CachingCDB->clear();
602}
603
604GlobalCompilationDatabase &ClangdLSPServer::CompilationDB::getCDB() {
605 if (CachingCDB)
606 return *CachingCDB;
607 return *CDB;
608}