blob: 3e0e4f6d4978e413944c25fcbb794eab47e71e74 [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;
21
Ilya Biryukovafb55542017-05-16 14:40:30 +000022namespace {
23
Eric Liu5740ff52018-01-31 16:26:27 +000024/// \brief Supports a test URI scheme with relaxed constraints for lit tests.
25/// The path in a test URI will be combined with a platform-specific fake
26/// directory to form an absolute path. For example, test:///a.cpp is resolved
27/// C:\clangd-test\a.cpp on Windows and /clangd-test/a.cpp on Unix.
28class TestScheme : public URIScheme {
29public:
30 llvm::Expected<std::string>
31 getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,
32 llvm::StringRef /*HintPath*/) const override {
33 using namespace llvm::sys;
34 // Still require "/" in body to mimic file scheme, as we want lengths of an
35 // equivalent URI in both schemes to be the same.
36 if (!Body.startswith("/"))
37 return llvm::make_error<llvm::StringError>(
38 "Expect URI body to be an absolute path starting with '/': " + Body,
39 llvm::inconvertibleErrorCode());
40 Body = Body.ltrim('/');
Nico Weber0da22902018-04-10 13:14:03 +000041#ifdef _WIN32
Eric Liu5740ff52018-01-31 16:26:27 +000042 constexpr char TestDir[] = "C:\\clangd-test";
43#else
44 constexpr char TestDir[] = "/clangd-test";
45#endif
46 llvm::SmallVector<char, 16> Path(Body.begin(), Body.end());
47 path::native(Path);
48 auto Err = fs::make_absolute(TestDir, Path);
Eric Liucda25262018-02-01 12:44:52 +000049 if (Err)
50 llvm_unreachable("Failed to make absolute path in test scheme.");
Eric Liu5740ff52018-01-31 16:26:27 +000051 return std::string(Path.begin(), Path.end());
52 }
53
54 llvm::Expected<URI>
55 uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
56 llvm_unreachable("Clangd must never create a test URI.");
57 }
58};
59
60static URISchemeRegistry::Add<TestScheme>
61 X("test", "Test scheme for clangd lit tests.");
62
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000063SymbolKindBitset defaultSymbolKinds() {
64 SymbolKindBitset Defaults;
65 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
66 ++I)
67 Defaults.set(I);
68 return Defaults;
69}
70
Ilya Biryukovafb55542017-05-16 14:40:30 +000071} // namespace
72
Sam McCalld1a7a372018-01-31 13:40:48 +000073void ClangdLSPServer::onInitialize(InitializeParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +000074 if (Params.rootUri && *Params.rootUri)
75 Server.setRootPath(Params.rootUri->file());
Ilya Biryukov23bc73b2018-02-15 14:32:57 +000076 else if (Params.rootPath && !Params.rootPath->empty())
77 Server.setRootPath(*Params.rootPath);
78
79 CCOpts.EnableSnippets =
80 Params.capabilities.textDocument.completion.completionItem.snippetSupport;
81
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000082 if (Params.capabilities.workspace && Params.capabilities.workspace->symbol &&
83 Params.capabilities.workspace->symbol->symbolKind) {
84 for (SymbolKind Kind :
85 *Params.capabilities.workspace->symbol->symbolKind->valueSet) {
86 SupportedSymbolKinds.set(static_cast<size_t>(Kind));
87 }
88 }
89
Sam McCalld1a7a372018-01-31 13:40:48 +000090 reply(json::obj{
Sam McCall0930ab02017-11-07 15:49:35 +000091 {{"capabilities",
92 json::obj{
Simon Marchi98082622018-03-26 14:41:40 +000093 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +000094 {"documentFormattingProvider", true},
95 {"documentRangeFormattingProvider", true},
96 {"documentOnTypeFormattingProvider",
97 json::obj{
98 {"firstTriggerCharacter", "}"},
99 {"moreTriggerCharacter", {}},
100 }},
101 {"codeActionProvider", true},
102 {"completionProvider",
103 json::obj{
104 {"resolveProvider", false},
105 {"triggerCharacters", {".", ">", ":"}},
106 }},
107 {"signatureHelpProvider",
108 json::obj{
109 {"triggerCharacters", {"(", ","}},
110 }},
111 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000112 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000113 {"hoverProvider", true},
Haojian Wu345099c2017-11-09 11:30:04 +0000114 {"renameProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000115 {"workspaceSymbolProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000116 {"executeCommandProvider",
117 json::obj{
Eric Liu2c190532018-05-15 15:23:53 +0000118 {"commands", {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND}},
Sam McCall0930ab02017-11-07 15:49:35 +0000119 }},
120 }}}});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000121}
122
Sam McCalld1a7a372018-01-31 13:40:48 +0000123void ClangdLSPServer::onShutdown(ShutdownParams &Params) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000124 // Do essentially nothing, just say we're ready to exit.
125 ShutdownRequestReceived = true;
Sam McCalld1a7a372018-01-31 13:40:48 +0000126 reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000127}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000128
Sam McCalld1a7a372018-01-31 13:40:48 +0000129void ClangdLSPServer::onExit(ExitParams &Params) { IsDone = true; }
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000130
Sam McCalld1a7a372018-01-31 13:40:48 +0000131void ClangdLSPServer::onDocumentDidOpen(DidOpenTextDocumentParams &Params) {
Krasimir Georgievc2a16a32017-07-06 08:44:54 +0000132 if (Params.metadata && !Params.metadata->extraFlags.empty())
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000133 CDB.setExtraFlagsForFile(Params.textDocument.uri.file(),
Sam McCall4db732a2017-09-30 10:08:52 +0000134 std::move(Params.metadata->extraFlags));
Simon Marchi9569fd52018-03-16 14:30:42 +0000135
136 PathRef File = Params.textDocument.uri.file();
137 std::string &Contents = Params.textDocument.text;
138
Simon Marchi98082622018-03-26 14:41:40 +0000139 DraftMgr.addDraft(File, Contents);
Simon Marchi9569fd52018-03-16 14:30:42 +0000140 Server.addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000141}
142
Sam McCalld1a7a372018-01-31 13:40:48 +0000143void ClangdLSPServer::onDocumentDidChange(DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000144 auto WantDiags = WantDiagnostics::Auto;
145 if (Params.wantDiagnostics.hasValue())
146 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
147 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000148
149 PathRef File = Params.textDocument.uri.file();
Simon Marchi98082622018-03-26 14:41:40 +0000150 llvm::Expected<std::string> Contents =
151 DraftMgr.updateDraft(File, Params.contentChanges);
152 if (!Contents) {
153 // If this fails, we are most likely going to be not in sync anymore with
154 // the client. It is better to remove the draft and let further operations
155 // fail rather than giving wrong results.
156 DraftMgr.removeDraft(File);
157 Server.removeDocument(File);
158 log(llvm::toString(Contents.takeError()));
159 return;
160 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000161
Simon Marchi98082622018-03-26 14:41:40 +0000162 Server.addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000163}
164
Sam McCalld1a7a372018-01-31 13:40:48 +0000165void ClangdLSPServer::onFileEvent(DidChangeWatchedFilesParams &Params) {
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000166 Server.onFileEvent(Params);
167}
168
Sam McCalld1a7a372018-01-31 13:40:48 +0000169void ClangdLSPServer::onCommand(ExecuteCommandParams &Params) {
Eric Liuc5105f92018-02-16 14:15:55 +0000170 auto ApplyEdit = [](WorkspaceEdit WE) {
171 ApplyWorkspaceEditParams Edit;
172 Edit.edit = std::move(WE);
173 // We don't need the response so id == 1 is OK.
174 // Ideally, we would wait for the response and if there is no error, we
175 // would reply success/failure to the original RPC.
176 call("workspace/applyEdit", Edit);
177 };
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000178 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
179 Params.workspaceEdit) {
180 // The flow for "apply-fix" :
181 // 1. We publish a diagnostic, including fixits
182 // 2. The user clicks on the diagnostic, the editor asks us for code actions
183 // 3. We send code actions, with the fixit embedded as context
184 // 4. The user selects the fixit, the editor asks us to apply it
185 // 5. We unwrap the changes and send them back to the editor
186 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
187 // we ignore it)
188
Sam McCalld1a7a372018-01-31 13:40:48 +0000189 reply("Fix applied.");
Eric Liuc5105f92018-02-16 14:15:55 +0000190 ApplyEdit(*Params.workspaceEdit);
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000191 } else {
192 // We should not get here because ExecuteCommandParams would not have
193 // parsed in the first place and this handler should not be called. But if
194 // more commands are added, this will be here has a safe guard.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000195 replyError(
Sam McCalld1a7a372018-01-31 13:40:48 +0000196 ErrorCode::InvalidParams,
Haojian Wu2375c922017-11-07 10:21:02 +0000197 llvm::formatv("Unsupported command \"{0}\".", Params.command).str());
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000198 }
199}
200
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000201void ClangdLSPServer::onWorkspaceSymbol(WorkspaceSymbolParams &Params) {
202 Server.workspaceSymbols(
203 Params.query, CCOpts.Limit,
204 [this](llvm::Expected<std::vector<SymbolInformation>> Items) {
205 if (!Items)
206 return replyError(ErrorCode::InternalError,
207 llvm::toString(Items.takeError()));
208 for (auto &Sym : *Items)
209 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
210
211 reply(json::ary(*Items));
212 });
213}
214
Sam McCalld1a7a372018-01-31 13:40:48 +0000215void ClangdLSPServer::onRename(RenameParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000216 Path File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000217 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000218 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000219 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000220 "onRename called for non-added file");
221
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000222 Server.rename(
223 File, Params.position, Params.newName,
224 [File, Code,
225 Params](llvm::Expected<std::vector<tooling::Replacement>> Replacements) {
226 if (!Replacements)
227 return replyError(ErrorCode::InternalError,
228 llvm::toString(Replacements.takeError()));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000229
Eric Liu9133ecd2018-05-11 12:12:08 +0000230 // Turn the replacements into the format specified by the Language
231 // Server Protocol. Fuse them into one big JSON array.
232 std::vector<TextEdit> Edits;
233 for (const auto &R : *Replacements)
234 Edits.push_back(replacementToEdit(*Code, R));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000235 WorkspaceEdit WE;
236 WE.changes = {{Params.textDocument.uri.uri(), Edits}};
237 reply(WE);
238 });
Haojian Wu345099c2017-11-09 11:30:04 +0000239}
240
Sam McCalld1a7a372018-01-31 13:40:48 +0000241void ClangdLSPServer::onDocumentDidClose(DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000242 PathRef File = Params.textDocument.uri.file();
243 DraftMgr.removeDraft(File);
244 Server.removeDocument(File);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000245}
246
Sam McCall4db732a2017-09-30 10:08:52 +0000247void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCalld1a7a372018-01-31 13:40:48 +0000248 DocumentOnTypeFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000249 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000250 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000251 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000252 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000253 "onDocumentOnTypeFormatting called for non-added file");
254
255 auto ReplacementsOrError = Server.formatOnType(*Code, File, Params.position);
Raoul Wols212bcf82017-12-12 20:25:06 +0000256 if (ReplacementsOrError)
Sam McCalld1a7a372018-01-31 13:40:48 +0000257 reply(json::ary(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000258 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000259 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000260 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000261}
262
Sam McCall4db732a2017-09-30 10:08:52 +0000263void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCalld1a7a372018-01-31 13:40:48 +0000264 DocumentRangeFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000265 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000266 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000267 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000268 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000269 "onDocumentRangeFormatting called for non-added file");
270
271 auto ReplacementsOrError = Server.formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000272 if (ReplacementsOrError)
Sam McCalld1a7a372018-01-31 13:40:48 +0000273 reply(json::ary(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000274 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000275 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000276 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000277}
278
Sam McCalld1a7a372018-01-31 13:40:48 +0000279void ClangdLSPServer::onDocumentFormatting(DocumentFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000280 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000281 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000282 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000283 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000284 "onDocumentFormatting called for non-added file");
285
286 auto ReplacementsOrError = Server.formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000287 if (ReplacementsOrError)
Sam McCalld1a7a372018-01-31 13:40:48 +0000288 reply(json::ary(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000289 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000290 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000291 llvm::toString(ReplacementsOrError.takeError()));
Sam McCall4db732a2017-09-30 10:08:52 +0000292}
293
Sam McCalld1a7a372018-01-31 13:40:48 +0000294void ClangdLSPServer::onCodeAction(CodeActionParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000295 // We provide a code action for each diagnostic at the requested location
296 // which has FixIts available.
Simon Marchi9569fd52018-03-16 14:30:42 +0000297 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000298 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000299 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000300 "onCodeAction called for non-added file");
301
Sam McCalldd0566b2017-11-06 15:40:30 +0000302 json::ary Commands;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000303 for (Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000304 for (auto &F : getFixes(Params.textDocument.uri.file(), D)) {
Sam McCalldd0566b2017-11-06 15:40:30 +0000305 WorkspaceEdit WE;
Ilya Biryukov71028b82018-03-12 15:28:22 +0000306 std::vector<TextEdit> Edits(F.Edits.begin(), F.Edits.end());
Eric Liu78ed91a72018-01-29 15:37:46 +0000307 WE.changes = {{Params.textDocument.uri.uri(), std::move(Edits)}};
Sam McCalldd0566b2017-11-06 15:40:30 +0000308 Commands.push_back(json::obj{
Ilya Biryukov71028b82018-03-12 15:28:22 +0000309 {"title", llvm::formatv("Apply fix: {0}", F.Message)},
Sam McCalldd0566b2017-11-06 15:40:30 +0000310 {"command", ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND},
311 {"arguments", {WE}},
312 });
313 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000314 }
Sam McCalld1a7a372018-01-31 13:40:48 +0000315 reply(std::move(Commands));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000316}
317
Sam McCalld1a7a372018-01-31 13:40:48 +0000318void ClangdLSPServer::onCompletion(TextDocumentPositionParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000319 Server.codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000320 [](llvm::Expected<CompletionList> List) {
321 if (!List)
322 return replyError(ErrorCode::InvalidParams,
323 llvm::toString(List.takeError()));
324 reply(*List);
325 });
Ilya Biryukovafb55542017-05-16 14:40:30 +0000326}
327
Sam McCalld1a7a372018-01-31 13:40:48 +0000328void ClangdLSPServer::onSignatureHelp(TextDocumentPositionParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000329 Server.signatureHelp(Params.textDocument.uri.file(), Params.position,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000330 [](llvm::Expected<SignatureHelp> SignatureHelp) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000331 if (!SignatureHelp)
332 return replyError(
333 ErrorCode::InvalidParams,
334 llvm::toString(SignatureHelp.takeError()));
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000335 reply(*SignatureHelp);
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000336 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000337}
338
Sam McCalld1a7a372018-01-31 13:40:48 +0000339void ClangdLSPServer::onGoToDefinition(TextDocumentPositionParams &Params) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000340 Server.findDefinitions(
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000341 Params.textDocument.uri.file(), Params.position,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000342 [](llvm::Expected<std::vector<Location>> Items) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000343 if (!Items)
344 return replyError(ErrorCode::InvalidParams,
345 llvm::toString(Items.takeError()));
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000346 reply(json::ary(*Items));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000347 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000348}
349
Sam McCalld1a7a372018-01-31 13:40:48 +0000350void ClangdLSPServer::onSwitchSourceHeader(TextDocumentIdentifier &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000351 llvm::Optional<Path> Result = Server.switchSourceHeader(Params.uri.file());
Sam McCalld1a7a372018-01-31 13:40:48 +0000352 reply(Result ? URI::createFile(*Result).toString() : "");
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000353}
354
Sam McCalld1a7a372018-01-31 13:40:48 +0000355void ClangdLSPServer::onDocumentHighlight(TextDocumentPositionParams &Params) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000356 Server.findDocumentHighlights(
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000357 Params.textDocument.uri.file(), Params.position,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000358 [](llvm::Expected<std::vector<DocumentHighlight>> Highlights) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000359 if (!Highlights)
360 return replyError(ErrorCode::InternalError,
361 llvm::toString(Highlights.takeError()));
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000362 reply(json::ary(*Highlights));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000363 });
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000364}
365
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000366void ClangdLSPServer::onHover(TextDocumentPositionParams &Params) {
367 Server.findHover(Params.textDocument.uri.file(), Params.position,
Sam McCall682cfe72018-06-04 10:37:16 +0000368 [](llvm::Expected<llvm::Optional<Hover>> H) {
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000369 if (!H) {
370 replyError(ErrorCode::InternalError,
371 llvm::toString(H.takeError()));
372 return;
373 }
374
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000375 reply(*H);
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000376 });
377}
378
Simon Marchi5178f922018-02-22 14:00:39 +0000379// FIXME: This function needs to be properly tested.
380void ClangdLSPServer::onChangeConfiguration(
381 DidChangeConfigurationParams &Params) {
382 ClangdConfigurationParamsChange &Settings = Params.settings;
383
384 // Compilation database change.
385 if (Settings.compilationDatabasePath.hasValue()) {
386 CDB.setCompileCommandsDir(Settings.compilationDatabasePath.getValue());
Simon Marchi9569fd52018-03-16 14:30:42 +0000387 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +0000388 }
389}
390
Sam McCall7363a2f2018-03-05 17:28:54 +0000391ClangdLSPServer::ClangdLSPServer(JSONOutput &Out,
Sam McCalladccab62017-11-23 16:58:22 +0000392 const clangd::CodeCompleteOptions &CCOpts,
Eric Liubfac8f72017-12-19 18:00:37 +0000393 llvm::Optional<Path> CompileCommandsDir,
Sam McCall7363a2f2018-03-05 17:28:54 +0000394 const ClangdServer::Options &Opts)
Ilya Biryukov940901e2017-12-13 12:51:22 +0000395 : Out(Out), CDB(std::move(CompileCommandsDir)), CCOpts(CCOpts),
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000396 SupportedSymbolKinds(defaultSymbolKinds()),
Sam McCall7363a2f2018-03-05 17:28:54 +0000397 Server(CDB, FSProvider, /*DiagConsumer=*/*this, Opts) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000398
Sam McCall27a07cf2018-06-05 09:34:46 +0000399bool ClangdLSPServer::run(std::FILE *In, JSONStreamStyle InputStyle) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000400 assert(!IsDone && "Run was called before");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000401
Ilya Biryukovafb55542017-05-16 14:40:30 +0000402 // Set up JSONRPCDispatcher.
Sam McCalld1a7a372018-01-31 13:40:48 +0000403 JSONRPCDispatcher Dispatcher([](const json::Expr &Params) {
404 replyError(ErrorCode::MethodNotFound, "method not found");
Ilya Biryukov940901e2017-12-13 12:51:22 +0000405 });
Simon Marchi6e8eb9d2018-03-07 21:47:25 +0000406 registerCallbackHandlers(Dispatcher, /*Callbacks=*/*this);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000407
Ilya Biryukovafb55542017-05-16 14:40:30 +0000408 // Run the Language Server loop.
Sam McCall5ed599e2018-02-06 10:47:30 +0000409 runLanguageServerLoop(In, Out, InputStyle, Dispatcher, IsDone);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000410
411 // Make sure IsDone is set to true after this method exits to ensure assertion
412 // at the start of the method fires if it's ever executed again.
413 IsDone = true;
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000414
415 return ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000416}
417
Ilya Biryukov71028b82018-03-12 15:28:22 +0000418std::vector<Fix> ClangdLSPServer::getFixes(StringRef File,
419 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000420 std::lock_guard<std::mutex> Lock(FixItsMutex);
421 auto DiagToFixItsIter = FixItsMap.find(File);
422 if (DiagToFixItsIter == FixItsMap.end())
423 return {};
424
425 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
426 auto FixItsIter = DiagToFixItsMap.find(D);
427 if (FixItsIter == DiagToFixItsMap.end())
428 return {};
429
430 return FixItsIter->second;
431}
432
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000433void ClangdLSPServer::onDiagnosticsReady(PathRef File,
434 std::vector<Diag> Diagnostics) {
Sam McCalldd0566b2017-11-06 15:40:30 +0000435 json::ary DiagnosticsJSON;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000436
437 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000438 for (auto &Diag : Diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000439 toLSPDiags(Diag, [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
440 DiagnosticsJSON.push_back(json::obj{
441 {"range", Diag.range},
442 {"severity", Diag.severity},
443 {"message", Diag.message},
444 });
445
446 auto &FixItsForDiagnostic = LocalFixIts[Diag];
447 std::copy(Fixes.begin(), Fixes.end(),
448 std::back_inserter(FixItsForDiagnostic));
Sam McCalldd0566b2017-11-06 15:40:30 +0000449 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000450 }
451
452 // Cache FixIts
453 {
454 // FIXME(ibiryukov): should be deleted when documents are removed
455 std::lock_guard<std::mutex> Lock(FixItsMutex);
456 FixItsMap[File] = LocalFixIts;
457 }
458
459 // Publish diagnostics.
Sam McCalldd0566b2017-11-06 15:40:30 +0000460 Out.writeMessage(json::obj{
461 {"jsonrpc", "2.0"},
462 {"method", "textDocument/publishDiagnostics"},
463 {"params",
464 json::obj{
Eric Liu78ed91a72018-01-29 15:37:46 +0000465 {"uri", URIForFile{File}},
Sam McCalldd0566b2017-11-06 15:40:30 +0000466 {"diagnostics", std::move(DiagnosticsJSON)},
467 }},
468 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000469}
Simon Marchi9569fd52018-03-16 14:30:42 +0000470
471void ClangdLSPServer::reparseOpenedFiles() {
472 for (const Path &FilePath : DraftMgr.getActiveFiles())
473 Server.addDocument(FilePath, *DraftMgr.getDraft(FilePath),
474 WantDiagnostics::Auto,
475 /*SkipCache=*/true);
476}