blob: 21c69632f01098a4d3c2253269b2d8a181d96033 [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"
11#include "JSONRPCDispatcher.h"
Sam McCallb536a2a2017-12-19 12:23:48 +000012#include "SourceCode.h"
Eric Liu78ed91a72018-01-29 15:37:46 +000013#include "URI.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000014#include "llvm/Support/FormatVariadic.h"
Eric Liu5740ff52018-01-31 16:26:27 +000015#include "llvm/Support/Path.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000016
Ilya Biryukov38d79772017-05-16 09:38:59 +000017using namespace clang::clangd;
18using namespace clang;
19
Ilya Biryukovafb55542017-05-16 14:40:30 +000020namespace {
21
Eric Liu5740ff52018-01-31 16:26:27 +000022/// \brief Supports a test URI scheme with relaxed constraints for lit tests.
23/// The path in a test URI will be combined with a platform-specific fake
24/// directory to form an absolute path. For example, test:///a.cpp is resolved
25/// C:\clangd-test\a.cpp on Windows and /clangd-test/a.cpp on Unix.
26class TestScheme : public URIScheme {
27public:
28 llvm::Expected<std::string>
29 getAbsolutePath(llvm::StringRef /*Authority*/, llvm::StringRef Body,
30 llvm::StringRef /*HintPath*/) const override {
31 using namespace llvm::sys;
32 // Still require "/" in body to mimic file scheme, as we want lengths of an
33 // equivalent URI in both schemes to be the same.
34 if (!Body.startswith("/"))
35 return llvm::make_error<llvm::StringError>(
36 "Expect URI body to be an absolute path starting with '/': " + Body,
37 llvm::inconvertibleErrorCode());
38 Body = Body.ltrim('/');
39#ifdef LLVM_ON_WIN32
40 constexpr char TestDir[] = "C:\\clangd-test";
41#else
42 constexpr char TestDir[] = "/clangd-test";
43#endif
44 llvm::SmallVector<char, 16> Path(Body.begin(), Body.end());
45 path::native(Path);
46 auto Err = fs::make_absolute(TestDir, Path);
Eric Liucda25262018-02-01 12:44:52 +000047 if (Err)
48 llvm_unreachable("Failed to make absolute path in test scheme.");
Eric Liu5740ff52018-01-31 16:26:27 +000049 return std::string(Path.begin(), Path.end());
50 }
51
52 llvm::Expected<URI>
53 uriFromAbsolutePath(llvm::StringRef AbsolutePath) const override {
54 llvm_unreachable("Clangd must never create a test URI.");
55 }
56};
57
58static URISchemeRegistry::Add<TestScheme>
59 X("test", "Test scheme for clangd lit tests.");
60
Raoul Wols212bcf82017-12-12 20:25:06 +000061TextEdit replacementToEdit(StringRef Code, const tooling::Replacement &R) {
62 Range ReplacementRange = {
63 offsetToPosition(Code, R.getOffset()),
64 offsetToPosition(Code, R.getOffset() + R.getLength())};
65 return {ReplacementRange, R.getReplacementText()};
66}
67
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000068std::vector<TextEdit>
Ilya Biryukovafb55542017-05-16 14:40:30 +000069replacementsToEdits(StringRef Code,
70 const std::vector<tooling::Replacement> &Replacements) {
71 // Turn the replacements into the format specified by the Language Server
Sam McCalldd0566b2017-11-06 15:40:30 +000072 // Protocol. Fuse them into one big JSON array.
73 std::vector<TextEdit> Edits;
Raoul Wols212bcf82017-12-12 20:25:06 +000074 for (const auto &R : Replacements)
75 Edits.push_back(replacementToEdit(Code, R));
76 return Edits;
77}
78
79std::vector<TextEdit> replacementsToEdits(StringRef Code,
80 const tooling::Replacements &Repls) {
81 std::vector<TextEdit> Edits;
82 for (const auto &R : Repls)
83 Edits.push_back(replacementToEdit(Code, R));
Ilya Biryukovafb55542017-05-16 14:40:30 +000084 return Edits;
85}
86
87} // namespace
88
Sam McCalld1a7a372018-01-31 13:40:48 +000089void ClangdLSPServer::onInitialize(InitializeParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +000090 if (Params.rootUri && *Params.rootUri)
91 Server.setRootPath(Params.rootUri->file());
Ilya Biryukov23bc73b2018-02-15 14:32:57 +000092 else if (Params.rootPath && !Params.rootPath->empty())
93 Server.setRootPath(*Params.rootPath);
94
95 CCOpts.EnableSnippets =
96 Params.capabilities.textDocument.completion.completionItem.snippetSupport;
97
Sam McCalld1a7a372018-01-31 13:40:48 +000098 reply(json::obj{
Sam McCall0930ab02017-11-07 15:49:35 +000099 {{"capabilities",
100 json::obj{
101 {"textDocumentSync", 1},
102 {"documentFormattingProvider", true},
103 {"documentRangeFormattingProvider", true},
104 {"documentOnTypeFormattingProvider",
105 json::obj{
106 {"firstTriggerCharacter", "}"},
107 {"moreTriggerCharacter", {}},
108 }},
109 {"codeActionProvider", true},
110 {"completionProvider",
111 json::obj{
112 {"resolveProvider", false},
113 {"triggerCharacters", {".", ">", ":"}},
114 }},
115 {"signatureHelpProvider",
116 json::obj{
117 {"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},
Sam McCall0930ab02017-11-07 15:49:35 +0000123 {"executeCommandProvider",
124 json::obj{
Eric Liuc5105f92018-02-16 14:15:55 +0000125 {"commands",
126 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
127 ExecuteCommandParams::CLANGD_INSERT_HEADER_INCLUDE}},
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) {
Krasimir Georgievc2a16a32017-07-06 08:44:54 +0000141 if (Params.metadata && !Params.metadata->extraFlags.empty())
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000142 CDB.setExtraFlagsForFile(Params.textDocument.uri.file(),
Sam McCall4db732a2017-09-30 10:08:52 +0000143 std::move(Params.metadata->extraFlags));
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000144 Server.addDocument(Params.textDocument.uri.file(), Params.textDocument.text);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000145}
146
Sam McCalld1a7a372018-01-31 13:40:48 +0000147void ClangdLSPServer::onDocumentDidChange(DidChangeTextDocumentParams &Params) {
Benjamin Kramerb560a9a2017-10-26 10:36:20 +0000148 if (Params.contentChanges.size() != 1)
Sam McCalld1a7a372018-01-31 13:40:48 +0000149 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000150 "can only apply one change at a time");
Ilya Biryukovafb55542017-05-16 14:40:30 +0000151 // We only support full syncing right now.
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000152 Server.addDocument(Params.textDocument.uri.file(),
Sam McCall4db732a2017-09-30 10:08:52 +0000153 Params.contentChanges[0].text);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000154}
155
Sam McCalld1a7a372018-01-31 13:40:48 +0000156void ClangdLSPServer::onFileEvent(DidChangeWatchedFilesParams &Params) {
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000157 Server.onFileEvent(Params);
158}
159
Sam McCalld1a7a372018-01-31 13:40:48 +0000160void ClangdLSPServer::onCommand(ExecuteCommandParams &Params) {
Eric Liuc5105f92018-02-16 14:15:55 +0000161 auto ApplyEdit = [](WorkspaceEdit WE) {
162 ApplyWorkspaceEditParams Edit;
163 Edit.edit = std::move(WE);
164 // We don't need the response so id == 1 is OK.
165 // Ideally, we would wait for the response and if there is no error, we
166 // would reply success/failure to the original RPC.
167 call("workspace/applyEdit", Edit);
168 };
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000169 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
170 Params.workspaceEdit) {
171 // The flow for "apply-fix" :
172 // 1. We publish a diagnostic, including fixits
173 // 2. The user clicks on the diagnostic, the editor asks us for code actions
174 // 3. We send code actions, with the fixit embedded as context
175 // 4. The user selects the fixit, the editor asks us to apply it
176 // 5. We unwrap the changes and send them back to the editor
177 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
178 // we ignore it)
179
Sam McCalld1a7a372018-01-31 13:40:48 +0000180 reply("Fix applied.");
Eric Liuc5105f92018-02-16 14:15:55 +0000181 ApplyEdit(*Params.workspaceEdit);
182 } else if (Params.command ==
183 ExecuteCommandParams::CLANGD_INSERT_HEADER_INCLUDE) {
184 auto &FileURI = Params.includeInsertion->textDocument.uri;
185 auto Code = Server.getDocument(FileURI.file());
186 if (!Code)
187 return replyError(ErrorCode::InvalidParams,
188 ("command " +
189 ExecuteCommandParams::CLANGD_INSERT_HEADER_INCLUDE +
190 " called on non-added file " + FileURI.file())
191 .str());
192 auto Replaces = Server.insertInclude(FileURI.file(), *Code,
193 Params.includeInsertion->header);
194 if (!Replaces) {
195 std::string ErrMsg =
196 ("Failed to generate include insertion edits for adding " +
197 Params.includeInsertion->header + " into " + FileURI.file())
198 .str();
199 log(ErrMsg + ":" + llvm::toString(Replaces.takeError()));
200 replyError(ErrorCode::InternalError, ErrMsg);
201 return;
202 }
203 auto Edits = replacementsToEdits(*Code, *Replaces);
204 WorkspaceEdit WE;
205 WE.changes = {{FileURI.uri(), Edits}};
206
207 reply("Inserted header " + Params.includeInsertion->header);
208 ApplyEdit(std::move(WE));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000209 } else {
210 // We should not get here because ExecuteCommandParams would not have
211 // parsed in the first place and this handler should not be called. But if
212 // more commands are added, this will be here has a safe guard.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000213 replyError(
Sam McCalld1a7a372018-01-31 13:40:48 +0000214 ErrorCode::InvalidParams,
Haojian Wu2375c922017-11-07 10:21:02 +0000215 llvm::formatv("Unsupported command \"{0}\".", Params.command).str());
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000216 }
217}
218
Sam McCalld1a7a372018-01-31 13:40:48 +0000219void ClangdLSPServer::onRename(RenameParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000220 Path File = Params.textDocument.uri.file();
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000221 llvm::Optional<std::string> Code = Server.getDocument(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000222 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000223 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000224 "onRename called for non-added file");
225
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000226 Server.rename(
227 File, Params.position, Params.newName,
228 [File, Code,
229 Params](llvm::Expected<std::vector<tooling::Replacement>> Replacements) {
230 if (!Replacements)
231 return replyError(ErrorCode::InternalError,
232 llvm::toString(Replacements.takeError()));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000233
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000234 std::vector<TextEdit> Edits = replacementsToEdits(*Code, *Replacements);
235 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) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000242 Server.removeDocument(Params.textDocument.uri.file());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000243}
244
Sam McCall4db732a2017-09-30 10:08:52 +0000245void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCalld1a7a372018-01-31 13:40:48 +0000246 DocumentOnTypeFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000247 auto File = Params.textDocument.uri.file();
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000248 auto Code = Server.getDocument(File);
249 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000250 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000251 "onDocumentOnTypeFormatting called for non-added file");
252
253 auto ReplacementsOrError = Server.formatOnType(*Code, File, Params.position);
Raoul Wols212bcf82017-12-12 20:25:06 +0000254 if (ReplacementsOrError)
Sam McCalld1a7a372018-01-31 13:40:48 +0000255 reply(json::ary(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000256 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000257 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000258 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000259}
260
Sam McCall4db732a2017-09-30 10:08:52 +0000261void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCalld1a7a372018-01-31 13:40:48 +0000262 DocumentRangeFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000263 auto File = Params.textDocument.uri.file();
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000264 auto Code = Server.getDocument(File);
265 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000266 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000267 "onDocumentRangeFormatting called for non-added file");
268
269 auto ReplacementsOrError = Server.formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000270 if (ReplacementsOrError)
Sam McCalld1a7a372018-01-31 13:40:48 +0000271 reply(json::ary(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000272 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000273 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000274 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000275}
276
Sam McCalld1a7a372018-01-31 13:40:48 +0000277void ClangdLSPServer::onDocumentFormatting(DocumentFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000278 auto File = Params.textDocument.uri.file();
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000279 auto Code = Server.getDocument(File);
280 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000281 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000282 "onDocumentFormatting called for non-added file");
283
284 auto ReplacementsOrError = Server.formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000285 if (ReplacementsOrError)
Sam McCalld1a7a372018-01-31 13:40:48 +0000286 reply(json::ary(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000287 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000288 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000289 llvm::toString(ReplacementsOrError.takeError()));
Sam McCall4db732a2017-09-30 10:08:52 +0000290}
291
Sam McCalld1a7a372018-01-31 13:40:48 +0000292void ClangdLSPServer::onCodeAction(CodeActionParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000293 // We provide a code action for each diagnostic at the requested location
294 // which has FixIts available.
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000295 auto Code = Server.getDocument(Params.textDocument.uri.file());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000296 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000297 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000298 "onCodeAction called for non-added file");
299
Sam McCalldd0566b2017-11-06 15:40:30 +0000300 json::ary Commands;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000301 for (Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000302 auto Edits = getFixIts(Params.textDocument.uri.file(), D);
Sam McCalldd0566b2017-11-06 15:40:30 +0000303 if (!Edits.empty()) {
304 WorkspaceEdit WE;
Eric Liu78ed91a72018-01-29 15:37:46 +0000305 WE.changes = {{Params.textDocument.uri.uri(), std::move(Edits)}};
Sam McCalldd0566b2017-11-06 15:40:30 +0000306 Commands.push_back(json::obj{
307 {"title", llvm::formatv("Apply FixIt {0}", D.message)},
308 {"command", ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND},
309 {"arguments", {WE}},
310 });
311 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000312 }
Sam McCalld1a7a372018-01-31 13:40:48 +0000313 reply(std::move(Commands));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000314}
315
Sam McCalld1a7a372018-01-31 13:40:48 +0000316void ClangdLSPServer::onCompletion(TextDocumentPositionParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000317 Server.codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
Sam McCalld1a7a372018-01-31 13:40:48 +0000318 [](Tagged<CompletionList> List) { reply(List.Value); });
Ilya Biryukovafb55542017-05-16 14:40:30 +0000319}
320
Sam McCalld1a7a372018-01-31 13:40:48 +0000321void ClangdLSPServer::onSignatureHelp(TextDocumentPositionParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000322 Server.signatureHelp(Params.textDocument.uri.file(), Params.position,
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000323 [](llvm::Expected<Tagged<SignatureHelp>> SignatureHelp) {
324 if (!SignatureHelp)
325 return replyError(
326 ErrorCode::InvalidParams,
327 llvm::toString(SignatureHelp.takeError()));
328 reply(SignatureHelp->Value);
329 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000330}
331
Sam McCalld1a7a372018-01-31 13:40:48 +0000332void ClangdLSPServer::onGoToDefinition(TextDocumentPositionParams &Params) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000333 Server.findDefinitions(
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000334 Params.textDocument.uri.file(), Params.position,
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000335 [](llvm::Expected<Tagged<std::vector<Location>>> Items) {
336 if (!Items)
337 return replyError(ErrorCode::InvalidParams,
338 llvm::toString(Items.takeError()));
339 reply(json::ary(Items->Value));
340 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000341}
342
Sam McCalld1a7a372018-01-31 13:40:48 +0000343void ClangdLSPServer::onSwitchSourceHeader(TextDocumentIdentifier &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000344 llvm::Optional<Path> Result = Server.switchSourceHeader(Params.uri.file());
Sam McCalld1a7a372018-01-31 13:40:48 +0000345 reply(Result ? URI::createFile(*Result).toString() : "");
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000346}
347
Sam McCalld1a7a372018-01-31 13:40:48 +0000348void ClangdLSPServer::onDocumentHighlight(TextDocumentPositionParams &Params) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000349 Server.findDocumentHighlights(
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000350 Params.textDocument.uri.file(), Params.position,
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000351 [](llvm::Expected<Tagged<std::vector<DocumentHighlight>>> Highlights) {
352 if (!Highlights)
353 return replyError(ErrorCode::InternalError,
354 llvm::toString(Highlights.takeError()));
355 reply(json::ary(Highlights->Value));
356 });
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000357}
358
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000359void ClangdLSPServer::onHover(TextDocumentPositionParams &Params) {
360 Server.findHover(Params.textDocument.uri.file(), Params.position,
361 [](llvm::Expected<Tagged<Hover>> H) {
362 if (!H) {
363 replyError(ErrorCode::InternalError,
364 llvm::toString(H.takeError()));
365 return;
366 }
367
368 reply(H->Value);
369 });
370}
371
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000372ClangdLSPServer::ClangdLSPServer(JSONOutput &Out, unsigned AsyncThreadsCount,
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000373 bool StorePreamblesInMemory,
Sam McCalladccab62017-11-23 16:58:22 +0000374 const clangd::CodeCompleteOptions &CCOpts,
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +0000375 llvm::Optional<StringRef> ResourceDir,
Eric Liubfac8f72017-12-19 18:00:37 +0000376 llvm::Optional<Path> CompileCommandsDir,
Haojian Wuba28e9a2018-01-10 14:44:34 +0000377 bool BuildDynamicSymbolIndex,
378 SymbolIndex *StaticIdx)
Ilya Biryukov940901e2017-12-13 12:51:22 +0000379 : Out(Out), CDB(std::move(CompileCommandsDir)), CCOpts(CCOpts),
380 Server(CDB, /*DiagConsumer=*/*this, FSProvider, AsyncThreadsCount,
Haojian Wuba28e9a2018-01-10 14:44:34 +0000381 StorePreamblesInMemory, BuildDynamicSymbolIndex, StaticIdx,
382 ResourceDir) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000383
Sam McCall5ed599e2018-02-06 10:47:30 +0000384bool ClangdLSPServer::run(std::istream &In, JSONStreamStyle InputStyle) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000385 assert(!IsDone && "Run was called before");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000386
Ilya Biryukovafb55542017-05-16 14:40:30 +0000387 // Set up JSONRPCDispatcher.
Sam McCalld1a7a372018-01-31 13:40:48 +0000388 JSONRPCDispatcher Dispatcher([](const json::Expr &Params) {
389 replyError(ErrorCode::MethodNotFound, "method not found");
Ilya Biryukov940901e2017-12-13 12:51:22 +0000390 });
Sam McCall4db732a2017-09-30 10:08:52 +0000391 registerCallbackHandlers(Dispatcher, Out, /*Callbacks=*/*this);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000392
Ilya Biryukovafb55542017-05-16 14:40:30 +0000393 // Run the Language Server loop.
Sam McCall5ed599e2018-02-06 10:47:30 +0000394 runLanguageServerLoop(In, Out, InputStyle, Dispatcher, IsDone);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000395
396 // Make sure IsDone is set to true after this method exits to ensure assertion
397 // at the start of the method fires if it's ever executed again.
398 IsDone = true;
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000399
400 return ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000401}
402
Sam McCall8111d3b2017-12-13 08:48:42 +0000403std::vector<TextEdit> ClangdLSPServer::getFixIts(StringRef File,
404 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000405 std::lock_guard<std::mutex> Lock(FixItsMutex);
406 auto DiagToFixItsIter = FixItsMap.find(File);
407 if (DiagToFixItsIter == FixItsMap.end())
408 return {};
409
410 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
411 auto FixItsIter = DiagToFixItsMap.find(D);
412 if (FixItsIter == DiagToFixItsMap.end())
413 return {};
414
415 return FixItsIter->second;
416}
417
Sam McCall4db732a2017-09-30 10:08:52 +0000418void ClangdLSPServer::onDiagnosticsReady(
Sam McCalld1a7a372018-01-31 13:40:48 +0000419 PathRef File, Tagged<std::vector<DiagWithFixIts>> Diagnostics) {
Sam McCalldd0566b2017-11-06 15:40:30 +0000420 json::ary DiagnosticsJSON;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000421
422 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCall4db732a2017-09-30 10:08:52 +0000423 for (auto &DiagWithFixes : Diagnostics.Value) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000424 auto Diag = DiagWithFixes.Diag;
Sam McCalldd0566b2017-11-06 15:40:30 +0000425 DiagnosticsJSON.push_back(json::obj{
426 {"range", Diag.range},
427 {"severity", Diag.severity},
428 {"message", Diag.message},
429 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000430 // We convert to Replacements to become independent of the SourceManager.
431 auto &FixItsForDiagnostic = LocalFixIts[Diag];
432 std::copy(DiagWithFixes.FixIts.begin(), DiagWithFixes.FixIts.end(),
433 std::back_inserter(FixItsForDiagnostic));
434 }
435
436 // Cache FixIts
437 {
438 // FIXME(ibiryukov): should be deleted when documents are removed
439 std::lock_guard<std::mutex> Lock(FixItsMutex);
440 FixItsMap[File] = LocalFixIts;
441 }
442
443 // Publish diagnostics.
Sam McCalldd0566b2017-11-06 15:40:30 +0000444 Out.writeMessage(json::obj{
445 {"jsonrpc", "2.0"},
446 {"method", "textDocument/publishDiagnostics"},
447 {"params",
448 json::obj{
Eric Liu78ed91a72018-01-29 15:37:46 +0000449 {"uri", URIForFile{File}},
Sam McCalldd0566b2017-11-06 15:40:30 +0000450 {"diagnostics", std::move(DiagnosticsJSON)},
451 }},
452 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000453}