blob: 3e5f79231f519ab2093098a8e9442b2f0efac76f [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 Biryukov23bc73b2018-02-15 14:32:57 +000090 if (Params.rootUri && !Params.rootUri->file.empty())
91 Server.setRootPath(Params.rootUri->file);
92 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},
Haojian Wu345099c2017-11-09 11:30:04 +0000121 {"renameProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000122 {"executeCommandProvider",
123 json::obj{
124 {"commands", {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND}},
125 }},
126 }}}});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000127}
128
Sam McCalld1a7a372018-01-31 13:40:48 +0000129void ClangdLSPServer::onShutdown(ShutdownParams &Params) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000130 // Do essentially nothing, just say we're ready to exit.
131 ShutdownRequestReceived = true;
Sam McCalld1a7a372018-01-31 13:40:48 +0000132 reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000133}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000134
Sam McCalld1a7a372018-01-31 13:40:48 +0000135void ClangdLSPServer::onExit(ExitParams &Params) { IsDone = true; }
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000136
Sam McCalld1a7a372018-01-31 13:40:48 +0000137void ClangdLSPServer::onDocumentDidOpen(DidOpenTextDocumentParams &Params) {
Krasimir Georgievc2a16a32017-07-06 08:44:54 +0000138 if (Params.metadata && !Params.metadata->extraFlags.empty())
Sam McCall4db732a2017-09-30 10:08:52 +0000139 CDB.setExtraFlagsForFile(Params.textDocument.uri.file,
140 std::move(Params.metadata->extraFlags));
Sam McCalld1a7a372018-01-31 13:40:48 +0000141 Server.addDocument(Params.textDocument.uri.file, Params.textDocument.text);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000142}
143
Sam McCalld1a7a372018-01-31 13:40:48 +0000144void ClangdLSPServer::onDocumentDidChange(DidChangeTextDocumentParams &Params) {
Benjamin Kramerb560a9a2017-10-26 10:36:20 +0000145 if (Params.contentChanges.size() != 1)
Sam McCalld1a7a372018-01-31 13:40:48 +0000146 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000147 "can only apply one change at a time");
Ilya Biryukovafb55542017-05-16 14:40:30 +0000148 // We only support full syncing right now.
Sam McCalld1a7a372018-01-31 13:40:48 +0000149 Server.addDocument(Params.textDocument.uri.file,
Sam McCall4db732a2017-09-30 10:08:52 +0000150 Params.contentChanges[0].text);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000151}
152
Sam McCalld1a7a372018-01-31 13:40:48 +0000153void ClangdLSPServer::onFileEvent(DidChangeWatchedFilesParams &Params) {
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000154 Server.onFileEvent(Params);
155}
156
Sam McCalld1a7a372018-01-31 13:40:48 +0000157void ClangdLSPServer::onCommand(ExecuteCommandParams &Params) {
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000158 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
159 Params.workspaceEdit) {
160 // The flow for "apply-fix" :
161 // 1. We publish a diagnostic, including fixits
162 // 2. The user clicks on the diagnostic, the editor asks us for code actions
163 // 3. We send code actions, with the fixit embedded as context
164 // 4. The user selects the fixit, the editor asks us to apply it
165 // 5. We unwrap the changes and send them back to the editor
166 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
167 // we ignore it)
168
169 ApplyWorkspaceEditParams ApplyEdit;
170 ApplyEdit.edit = *Params.workspaceEdit;
Sam McCalld1a7a372018-01-31 13:40:48 +0000171 reply("Fix applied.");
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000172 // We don't need the response so id == 1 is OK.
173 // Ideally, we would wait for the response and if there is no error, we
174 // would reply success/failure to the original RPC.
Sam McCalld1a7a372018-01-31 13:40:48 +0000175 call("workspace/applyEdit", ApplyEdit);
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000176 } else {
177 // We should not get here because ExecuteCommandParams would not have
178 // parsed in the first place and this handler should not be called. But if
179 // more commands are added, this will be here has a safe guard.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000180 replyError(
Sam McCalld1a7a372018-01-31 13:40:48 +0000181 ErrorCode::InvalidParams,
Haojian Wu2375c922017-11-07 10:21:02 +0000182 llvm::formatv("Unsupported command \"{0}\".", Params.command).str());
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000183 }
184}
185
Sam McCalld1a7a372018-01-31 13:40:48 +0000186void ClangdLSPServer::onRename(RenameParams &Params) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000187 Path File = Params.textDocument.uri.file;
188 llvm::Optional<std::string> Code = Server.getDocument(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000189 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000190 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000191 "onRename called for non-added file");
192
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000193 Server.rename(
194 File, Params.position, Params.newName,
195 [File, Code,
196 Params](llvm::Expected<std::vector<tooling::Replacement>> Replacements) {
197 if (!Replacements)
198 return replyError(ErrorCode::InternalError,
199 llvm::toString(Replacements.takeError()));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000200
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000201 std::vector<TextEdit> Edits = replacementsToEdits(*Code, *Replacements);
202 WorkspaceEdit WE;
203 WE.changes = {{Params.textDocument.uri.uri(), Edits}};
204 reply(WE);
205 });
Haojian Wu345099c2017-11-09 11:30:04 +0000206}
207
Sam McCalld1a7a372018-01-31 13:40:48 +0000208void ClangdLSPServer::onDocumentDidClose(DidCloseTextDocumentParams &Params) {
209 Server.removeDocument(Params.textDocument.uri.file);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000210}
211
Sam McCall4db732a2017-09-30 10:08:52 +0000212void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCalld1a7a372018-01-31 13:40:48 +0000213 DocumentOnTypeFormattingParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000214 auto File = Params.textDocument.uri.file;
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000215 auto Code = Server.getDocument(File);
216 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000217 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000218 "onDocumentOnTypeFormatting called for non-added file");
219
220 auto ReplacementsOrError = Server.formatOnType(*Code, File, Params.position);
Raoul Wols212bcf82017-12-12 20:25:06 +0000221 if (ReplacementsOrError)
Sam McCalld1a7a372018-01-31 13:40:48 +0000222 reply(json::ary(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000223 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000224 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000225 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000226}
227
Sam McCall4db732a2017-09-30 10:08:52 +0000228void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCalld1a7a372018-01-31 13:40:48 +0000229 DocumentRangeFormattingParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000230 auto File = Params.textDocument.uri.file;
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000231 auto Code = Server.getDocument(File);
232 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000233 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000234 "onDocumentRangeFormatting called for non-added file");
235
236 auto ReplacementsOrError = Server.formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000237 if (ReplacementsOrError)
Sam McCalld1a7a372018-01-31 13:40:48 +0000238 reply(json::ary(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000239 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000240 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000241 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000242}
243
Sam McCalld1a7a372018-01-31 13:40:48 +0000244void ClangdLSPServer::onDocumentFormatting(DocumentFormattingParams &Params) {
Sam McCall4db732a2017-09-30 10:08:52 +0000245 auto File = Params.textDocument.uri.file;
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000246 auto Code = Server.getDocument(File);
247 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000248 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000249 "onDocumentFormatting called for non-added file");
250
251 auto ReplacementsOrError = Server.formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000252 if (ReplacementsOrError)
Sam McCalld1a7a372018-01-31 13:40:48 +0000253 reply(json::ary(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000254 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000255 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000256 llvm::toString(ReplacementsOrError.takeError()));
Sam McCall4db732a2017-09-30 10:08:52 +0000257}
258
Sam McCalld1a7a372018-01-31 13:40:48 +0000259void ClangdLSPServer::onCodeAction(CodeActionParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000260 // We provide a code action for each diagnostic at the requested location
261 // which has FixIts available.
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000262 auto Code = Server.getDocument(Params.textDocument.uri.file);
263 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000264 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000265 "onCodeAction called for non-added file");
266
Sam McCalldd0566b2017-11-06 15:40:30 +0000267 json::ary Commands;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000268 for (Diagnostic &D : Params.context.diagnostics) {
Sam McCall8111d3b2017-12-13 08:48:42 +0000269 auto Edits = getFixIts(Params.textDocument.uri.file, D);
Sam McCalldd0566b2017-11-06 15:40:30 +0000270 if (!Edits.empty()) {
271 WorkspaceEdit WE;
Eric Liu78ed91a72018-01-29 15:37:46 +0000272 WE.changes = {{Params.textDocument.uri.uri(), std::move(Edits)}};
Sam McCalldd0566b2017-11-06 15:40:30 +0000273 Commands.push_back(json::obj{
274 {"title", llvm::formatv("Apply FixIt {0}", D.message)},
275 {"command", ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND},
276 {"arguments", {WE}},
277 });
278 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000279 }
Sam McCalld1a7a372018-01-31 13:40:48 +0000280 reply(std::move(Commands));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000281}
282
Sam McCalld1a7a372018-01-31 13:40:48 +0000283void ClangdLSPServer::onCompletion(TextDocumentPositionParams &Params) {
Ilya Biryukov7beea3a2018-02-14 10:52:04 +0000284 Server.codeComplete(Params.textDocument.uri.file, Params.position, CCOpts,
Sam McCalld1a7a372018-01-31 13:40:48 +0000285 [](Tagged<CompletionList> List) { reply(List.Value); });
Ilya Biryukovafb55542017-05-16 14:40:30 +0000286}
287
Sam McCalld1a7a372018-01-31 13:40:48 +0000288void ClangdLSPServer::onSignatureHelp(TextDocumentPositionParams &Params) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000289 Server.signatureHelp(Params.textDocument.uri.file, Params.position,
290 [](llvm::Expected<Tagged<SignatureHelp>> SignatureHelp) {
291 if (!SignatureHelp)
292 return replyError(
293 ErrorCode::InvalidParams,
294 llvm::toString(SignatureHelp.takeError()));
295 reply(SignatureHelp->Value);
296 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000297}
298
Sam McCalld1a7a372018-01-31 13:40:48 +0000299void ClangdLSPServer::onGoToDefinition(TextDocumentPositionParams &Params) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000300 Server.findDefinitions(
301 Params.textDocument.uri.file, Params.position,
302 [](llvm::Expected<Tagged<std::vector<Location>>> Items) {
303 if (!Items)
304 return replyError(ErrorCode::InvalidParams,
305 llvm::toString(Items.takeError()));
306 reply(json::ary(Items->Value));
307 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000308}
309
Sam McCalld1a7a372018-01-31 13:40:48 +0000310void ClangdLSPServer::onSwitchSourceHeader(TextDocumentIdentifier &Params) {
Sam McCall4db732a2017-09-30 10:08:52 +0000311 llvm::Optional<Path> Result = Server.switchSourceHeader(Params.uri.file);
Sam McCalld1a7a372018-01-31 13:40:48 +0000312 reply(Result ? URI::createFile(*Result).toString() : "");
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000313}
314
Sam McCalld1a7a372018-01-31 13:40:48 +0000315void ClangdLSPServer::onDocumentHighlight(TextDocumentPositionParams &Params) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000316 Server.findDocumentHighlights(
317 Params.textDocument.uri.file, Params.position,
318 [](llvm::Expected<Tagged<std::vector<DocumentHighlight>>> Highlights) {
319 if (!Highlights)
320 return replyError(ErrorCode::InternalError,
321 llvm::toString(Highlights.takeError()));
322 reply(json::ary(Highlights->Value));
323 });
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000324}
325
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000326ClangdLSPServer::ClangdLSPServer(JSONOutput &Out, unsigned AsyncThreadsCount,
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000327 bool StorePreamblesInMemory,
Sam McCalladccab62017-11-23 16:58:22 +0000328 const clangd::CodeCompleteOptions &CCOpts,
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +0000329 llvm::Optional<StringRef> ResourceDir,
Eric Liubfac8f72017-12-19 18:00:37 +0000330 llvm::Optional<Path> CompileCommandsDir,
Haojian Wuba28e9a2018-01-10 14:44:34 +0000331 bool BuildDynamicSymbolIndex,
332 SymbolIndex *StaticIdx)
Ilya Biryukov940901e2017-12-13 12:51:22 +0000333 : Out(Out), CDB(std::move(CompileCommandsDir)), CCOpts(CCOpts),
334 Server(CDB, /*DiagConsumer=*/*this, FSProvider, AsyncThreadsCount,
Haojian Wuba28e9a2018-01-10 14:44:34 +0000335 StorePreamblesInMemory, BuildDynamicSymbolIndex, StaticIdx,
336 ResourceDir) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000337
Sam McCall5ed599e2018-02-06 10:47:30 +0000338bool ClangdLSPServer::run(std::istream &In, JSONStreamStyle InputStyle) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000339 assert(!IsDone && "Run was called before");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000340
Ilya Biryukovafb55542017-05-16 14:40:30 +0000341 // Set up JSONRPCDispatcher.
Sam McCalld1a7a372018-01-31 13:40:48 +0000342 JSONRPCDispatcher Dispatcher([](const json::Expr &Params) {
343 replyError(ErrorCode::MethodNotFound, "method not found");
Ilya Biryukov940901e2017-12-13 12:51:22 +0000344 });
Sam McCall4db732a2017-09-30 10:08:52 +0000345 registerCallbackHandlers(Dispatcher, Out, /*Callbacks=*/*this);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000346
Ilya Biryukovafb55542017-05-16 14:40:30 +0000347 // Run the Language Server loop.
Sam McCall5ed599e2018-02-06 10:47:30 +0000348 runLanguageServerLoop(In, Out, InputStyle, Dispatcher, IsDone);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000349
350 // Make sure IsDone is set to true after this method exits to ensure assertion
351 // at the start of the method fires if it's ever executed again.
352 IsDone = true;
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000353
354 return ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000355}
356
Sam McCall8111d3b2017-12-13 08:48:42 +0000357std::vector<TextEdit> ClangdLSPServer::getFixIts(StringRef File,
358 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000359 std::lock_guard<std::mutex> Lock(FixItsMutex);
360 auto DiagToFixItsIter = FixItsMap.find(File);
361 if (DiagToFixItsIter == FixItsMap.end())
362 return {};
363
364 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
365 auto FixItsIter = DiagToFixItsMap.find(D);
366 if (FixItsIter == DiagToFixItsMap.end())
367 return {};
368
369 return FixItsIter->second;
370}
371
Sam McCall4db732a2017-09-30 10:08:52 +0000372void ClangdLSPServer::onDiagnosticsReady(
Sam McCalld1a7a372018-01-31 13:40:48 +0000373 PathRef File, Tagged<std::vector<DiagWithFixIts>> Diagnostics) {
Sam McCalldd0566b2017-11-06 15:40:30 +0000374 json::ary DiagnosticsJSON;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000375
376 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCall4db732a2017-09-30 10:08:52 +0000377 for (auto &DiagWithFixes : Diagnostics.Value) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000378 auto Diag = DiagWithFixes.Diag;
Sam McCalldd0566b2017-11-06 15:40:30 +0000379 DiagnosticsJSON.push_back(json::obj{
380 {"range", Diag.range},
381 {"severity", Diag.severity},
382 {"message", Diag.message},
383 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000384 // We convert to Replacements to become independent of the SourceManager.
385 auto &FixItsForDiagnostic = LocalFixIts[Diag];
386 std::copy(DiagWithFixes.FixIts.begin(), DiagWithFixes.FixIts.end(),
387 std::back_inserter(FixItsForDiagnostic));
388 }
389
390 // Cache FixIts
391 {
392 // FIXME(ibiryukov): should be deleted when documents are removed
393 std::lock_guard<std::mutex> Lock(FixItsMutex);
394 FixItsMap[File] = LocalFixIts;
395 }
396
397 // Publish diagnostics.
Sam McCalldd0566b2017-11-06 15:40:30 +0000398 Out.writeMessage(json::obj{
399 {"jsonrpc", "2.0"},
400 {"method", "textDocument/publishDiagnostics"},
401 {"params",
402 json::obj{
Eric Liu78ed91a72018-01-29 15:37:46 +0000403 {"uri", URIForFile{File}},
Sam McCalldd0566b2017-11-06 15:40:30 +0000404 {"diagnostics", std::move(DiagnosticsJSON)},
405 }},
406 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000407}