blob: 7e708a29665d02aad7dd7af2bc9d8025c6c602a4 [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) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000132 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000133 if (Params.metadata && !Params.metadata->extraFlags.empty()) {
134 NonCachedCDB.setExtraFlagsForFile(File,
135 std::move(Params.metadata->extraFlags));
136 CDB.invalidate(File);
137 }
138
Simon Marchi9569fd52018-03-16 14:30:42 +0000139 std::string &Contents = Params.textDocument.text;
140
Simon Marchi98082622018-03-26 14:41:40 +0000141 DraftMgr.addDraft(File, Contents);
Simon Marchi9569fd52018-03-16 14:30:42 +0000142 Server.addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000143}
144
Sam McCalld1a7a372018-01-31 13:40:48 +0000145void ClangdLSPServer::onDocumentDidChange(DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000146 auto WantDiags = WantDiagnostics::Auto;
147 if (Params.wantDiagnostics.hasValue())
148 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
149 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000150
151 PathRef File = Params.textDocument.uri.file();
Simon Marchi98082622018-03-26 14:41:40 +0000152 llvm::Expected<std::string> Contents =
153 DraftMgr.updateDraft(File, Params.contentChanges);
154 if (!Contents) {
155 // If this fails, we are most likely going to be not in sync anymore with
156 // the client. It is better to remove the draft and let further operations
157 // fail rather than giving wrong results.
158 DraftMgr.removeDraft(File);
159 Server.removeDocument(File);
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000160 CDB.invalidate(File);
Simon Marchi98082622018-03-26 14:41:40 +0000161 log(llvm::toString(Contents.takeError()));
162 return;
163 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000164
Simon Marchi98082622018-03-26 14:41:40 +0000165 Server.addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000166}
167
Sam McCalld1a7a372018-01-31 13:40:48 +0000168void ClangdLSPServer::onFileEvent(DidChangeWatchedFilesParams &Params) {
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000169 Server.onFileEvent(Params);
170}
171
Sam McCalld1a7a372018-01-31 13:40:48 +0000172void ClangdLSPServer::onCommand(ExecuteCommandParams &Params) {
Eric Liuc5105f92018-02-16 14:15:55 +0000173 auto ApplyEdit = [](WorkspaceEdit WE) {
174 ApplyWorkspaceEditParams Edit;
175 Edit.edit = std::move(WE);
176 // We don't need the response so id == 1 is OK.
177 // Ideally, we would wait for the response and if there is no error, we
178 // would reply success/failure to the original RPC.
179 call("workspace/applyEdit", Edit);
180 };
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000181 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
182 Params.workspaceEdit) {
183 // The flow for "apply-fix" :
184 // 1. We publish a diagnostic, including fixits
185 // 2. The user clicks on the diagnostic, the editor asks us for code actions
186 // 3. We send code actions, with the fixit embedded as context
187 // 4. The user selects the fixit, the editor asks us to apply it
188 // 5. We unwrap the changes and send them back to the editor
189 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
190 // we ignore it)
191
Sam McCalld1a7a372018-01-31 13:40:48 +0000192 reply("Fix applied.");
Eric Liuc5105f92018-02-16 14:15:55 +0000193 ApplyEdit(*Params.workspaceEdit);
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000194 } else {
195 // We should not get here because ExecuteCommandParams would not have
196 // parsed in the first place and this handler should not be called. But if
197 // more commands are added, this will be here has a safe guard.
Ilya Biryukov940901e2017-12-13 12:51:22 +0000198 replyError(
Sam McCalld1a7a372018-01-31 13:40:48 +0000199 ErrorCode::InvalidParams,
Haojian Wu2375c922017-11-07 10:21:02 +0000200 llvm::formatv("Unsupported command \"{0}\".", Params.command).str());
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000201 }
202}
203
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000204void ClangdLSPServer::onWorkspaceSymbol(WorkspaceSymbolParams &Params) {
205 Server.workspaceSymbols(
206 Params.query, CCOpts.Limit,
207 [this](llvm::Expected<std::vector<SymbolInformation>> Items) {
208 if (!Items)
209 return replyError(ErrorCode::InternalError,
210 llvm::toString(Items.takeError()));
211 for (auto &Sym : *Items)
212 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
213
214 reply(json::ary(*Items));
215 });
216}
217
Sam McCalld1a7a372018-01-31 13:40:48 +0000218void ClangdLSPServer::onRename(RenameParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000219 Path File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000220 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000221 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000222 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000223 "onRename called for non-added file");
224
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000225 Server.rename(
226 File, Params.position, Params.newName,
227 [File, Code,
228 Params](llvm::Expected<std::vector<tooling::Replacement>> Replacements) {
229 if (!Replacements)
230 return replyError(ErrorCode::InternalError,
231 llvm::toString(Replacements.takeError()));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000232
Eric Liu9133ecd2018-05-11 12:12:08 +0000233 // Turn the replacements into the format specified by the Language
234 // Server Protocol. Fuse them into one big JSON array.
235 std::vector<TextEdit> Edits;
236 for (const auto &R : *Replacements)
237 Edits.push_back(replacementToEdit(*Code, R));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000238 WorkspaceEdit WE;
239 WE.changes = {{Params.textDocument.uri.uri(), Edits}};
240 reply(WE);
241 });
Haojian Wu345099c2017-11-09 11:30:04 +0000242}
243
Sam McCalld1a7a372018-01-31 13:40:48 +0000244void ClangdLSPServer::onDocumentDidClose(DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000245 PathRef File = Params.textDocument.uri.file();
246 DraftMgr.removeDraft(File);
247 Server.removeDocument(File);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000248}
249
Sam McCall4db732a2017-09-30 10:08:52 +0000250void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCalld1a7a372018-01-31 13:40:48 +0000251 DocumentOnTypeFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000252 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000253 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000254 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000255 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000256 "onDocumentOnTypeFormatting called for non-added file");
257
258 auto ReplacementsOrError = Server.formatOnType(*Code, File, Params.position);
Raoul Wols212bcf82017-12-12 20:25:06 +0000259 if (ReplacementsOrError)
Sam McCalld1a7a372018-01-31 13:40:48 +0000260 reply(json::ary(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000261 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000262 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000263 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000264}
265
Sam McCall4db732a2017-09-30 10:08:52 +0000266void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCalld1a7a372018-01-31 13:40:48 +0000267 DocumentRangeFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000268 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000269 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000270 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000271 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000272 "onDocumentRangeFormatting called for non-added file");
273
274 auto ReplacementsOrError = Server.formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000275 if (ReplacementsOrError)
Sam McCalld1a7a372018-01-31 13:40:48 +0000276 reply(json::ary(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000277 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000278 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000279 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000280}
281
Sam McCalld1a7a372018-01-31 13:40:48 +0000282void ClangdLSPServer::onDocumentFormatting(DocumentFormattingParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000283 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000284 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000285 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000286 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000287 "onDocumentFormatting called for non-added file");
288
289 auto ReplacementsOrError = Server.formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000290 if (ReplacementsOrError)
Sam McCalld1a7a372018-01-31 13:40:48 +0000291 reply(json::ary(replacementsToEdits(*Code, ReplacementsOrError.get())));
Raoul Wols212bcf82017-12-12 20:25:06 +0000292 else
Sam McCalld1a7a372018-01-31 13:40:48 +0000293 replyError(ErrorCode::UnknownErrorCode,
Ilya Biryukov940901e2017-12-13 12:51:22 +0000294 llvm::toString(ReplacementsOrError.takeError()));
Sam McCall4db732a2017-09-30 10:08:52 +0000295}
296
Sam McCalld1a7a372018-01-31 13:40:48 +0000297void ClangdLSPServer::onCodeAction(CodeActionParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000298 // We provide a code action for each diagnostic at the requested location
299 // which has FixIts available.
Simon Marchi9569fd52018-03-16 14:30:42 +0000300 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000301 if (!Code)
Sam McCalld1a7a372018-01-31 13:40:48 +0000302 return replyError(ErrorCode::InvalidParams,
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000303 "onCodeAction called for non-added file");
304
Sam McCalldd0566b2017-11-06 15:40:30 +0000305 json::ary Commands;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000306 for (Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000307 for (auto &F : getFixes(Params.textDocument.uri.file(), D)) {
Sam McCalldd0566b2017-11-06 15:40:30 +0000308 WorkspaceEdit WE;
Ilya Biryukov71028b82018-03-12 15:28:22 +0000309 std::vector<TextEdit> Edits(F.Edits.begin(), F.Edits.end());
Eric Liu78ed91a72018-01-29 15:37:46 +0000310 WE.changes = {{Params.textDocument.uri.uri(), std::move(Edits)}};
Sam McCalldd0566b2017-11-06 15:40:30 +0000311 Commands.push_back(json::obj{
Ilya Biryukov71028b82018-03-12 15:28:22 +0000312 {"title", llvm::formatv("Apply fix: {0}", F.Message)},
Sam McCalldd0566b2017-11-06 15:40:30 +0000313 {"command", ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND},
314 {"arguments", {WE}},
315 });
316 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000317 }
Sam McCalld1a7a372018-01-31 13:40:48 +0000318 reply(std::move(Commands));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000319}
320
Sam McCalld1a7a372018-01-31 13:40:48 +0000321void ClangdLSPServer::onCompletion(TextDocumentPositionParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000322 Server.codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000323 [](llvm::Expected<CompletionList> List) {
324 if (!List)
325 return replyError(ErrorCode::InvalidParams,
326 llvm::toString(List.takeError()));
327 reply(*List);
328 });
Ilya Biryukovafb55542017-05-16 14:40:30 +0000329}
330
Sam McCalld1a7a372018-01-31 13:40:48 +0000331void ClangdLSPServer::onSignatureHelp(TextDocumentPositionParams &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000332 Server.signatureHelp(Params.textDocument.uri.file(), Params.position,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000333 [](llvm::Expected<SignatureHelp> SignatureHelp) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000334 if (!SignatureHelp)
335 return replyError(
336 ErrorCode::InvalidParams,
337 llvm::toString(SignatureHelp.takeError()));
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000338 reply(*SignatureHelp);
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000339 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000340}
341
Sam McCalld1a7a372018-01-31 13:40:48 +0000342void ClangdLSPServer::onGoToDefinition(TextDocumentPositionParams &Params) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000343 Server.findDefinitions(
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000344 Params.textDocument.uri.file(), Params.position,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000345 [](llvm::Expected<std::vector<Location>> Items) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000346 if (!Items)
347 return replyError(ErrorCode::InvalidParams,
348 llvm::toString(Items.takeError()));
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000349 reply(json::ary(*Items));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000350 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000351}
352
Sam McCalld1a7a372018-01-31 13:40:48 +0000353void ClangdLSPServer::onSwitchSourceHeader(TextDocumentIdentifier &Params) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000354 llvm::Optional<Path> Result = Server.switchSourceHeader(Params.uri.file());
Sam McCalld1a7a372018-01-31 13:40:48 +0000355 reply(Result ? URI::createFile(*Result).toString() : "");
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000356}
357
Sam McCalld1a7a372018-01-31 13:40:48 +0000358void ClangdLSPServer::onDocumentHighlight(TextDocumentPositionParams &Params) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000359 Server.findDocumentHighlights(
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000360 Params.textDocument.uri.file(), Params.position,
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000361 [](llvm::Expected<std::vector<DocumentHighlight>> Highlights) {
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000362 if (!Highlights)
363 return replyError(ErrorCode::InternalError,
364 llvm::toString(Highlights.takeError()));
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000365 reply(json::ary(*Highlights));
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000366 });
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000367}
368
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000369void ClangdLSPServer::onHover(TextDocumentPositionParams &Params) {
370 Server.findHover(Params.textDocument.uri.file(), Params.position,
Sam McCall682cfe72018-06-04 10:37:16 +0000371 [](llvm::Expected<llvm::Optional<Hover>> H) {
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000372 if (!H) {
373 replyError(ErrorCode::InternalError,
374 llvm::toString(H.takeError()));
375 return;
376 }
377
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000378 reply(*H);
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000379 });
380}
381
Simon Marchi5178f922018-02-22 14:00:39 +0000382// FIXME: This function needs to be properly tested.
383void ClangdLSPServer::onChangeConfiguration(
384 DidChangeConfigurationParams &Params) {
385 ClangdConfigurationParamsChange &Settings = Params.settings;
386
387 // Compilation database change.
388 if (Settings.compilationDatabasePath.hasValue()) {
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000389 NonCachedCDB.setCompileCommandsDir(
390 Settings.compilationDatabasePath.getValue());
391 CDB.clear();
392
Simon Marchi9569fd52018-03-16 14:30:42 +0000393 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +0000394 }
395}
396
Sam McCall7363a2f2018-03-05 17:28:54 +0000397ClangdLSPServer::ClangdLSPServer(JSONOutput &Out,
Sam McCalladccab62017-11-23 16:58:22 +0000398 const clangd::CodeCompleteOptions &CCOpts,
Eric Liubfac8f72017-12-19 18:00:37 +0000399 llvm::Optional<Path> CompileCommandsDir,
Sam McCall7363a2f2018-03-05 17:28:54 +0000400 const ClangdServer::Options &Opts)
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000401 : Out(Out), NonCachedCDB(std::move(CompileCommandsDir)), CDB(NonCachedCDB),
402 CCOpts(CCOpts), SupportedSymbolKinds(defaultSymbolKinds()),
Sam McCall7363a2f2018-03-05 17:28:54 +0000403 Server(CDB, FSProvider, /*DiagConsumer=*/*this, Opts) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000404
Sam McCall27a07cf2018-06-05 09:34:46 +0000405bool ClangdLSPServer::run(std::FILE *In, JSONStreamStyle InputStyle) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000406 assert(!IsDone && "Run was called before");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000407
Ilya Biryukovafb55542017-05-16 14:40:30 +0000408 // Set up JSONRPCDispatcher.
Sam McCalld1a7a372018-01-31 13:40:48 +0000409 JSONRPCDispatcher Dispatcher([](const json::Expr &Params) {
410 replyError(ErrorCode::MethodNotFound, "method not found");
Ilya Biryukov940901e2017-12-13 12:51:22 +0000411 });
Simon Marchi6e8eb9d2018-03-07 21:47:25 +0000412 registerCallbackHandlers(Dispatcher, /*Callbacks=*/*this);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000413
Ilya Biryukovafb55542017-05-16 14:40:30 +0000414 // Run the Language Server loop.
Sam McCall5ed599e2018-02-06 10:47:30 +0000415 runLanguageServerLoop(In, Out, InputStyle, Dispatcher, IsDone);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000416
417 // Make sure IsDone is set to true after this method exits to ensure assertion
418 // at the start of the method fires if it's ever executed again.
419 IsDone = true;
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000420
421 return ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000422}
423
Ilya Biryukov71028b82018-03-12 15:28:22 +0000424std::vector<Fix> ClangdLSPServer::getFixes(StringRef File,
425 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000426 std::lock_guard<std::mutex> Lock(FixItsMutex);
427 auto DiagToFixItsIter = FixItsMap.find(File);
428 if (DiagToFixItsIter == FixItsMap.end())
429 return {};
430
431 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
432 auto FixItsIter = DiagToFixItsMap.find(D);
433 if (FixItsIter == DiagToFixItsMap.end())
434 return {};
435
436 return FixItsIter->second;
437}
438
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000439void ClangdLSPServer::onDiagnosticsReady(PathRef File,
440 std::vector<Diag> Diagnostics) {
Sam McCalldd0566b2017-11-06 15:40:30 +0000441 json::ary DiagnosticsJSON;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000442
443 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +0000444 for (auto &Diag : Diagnostics) {
Ilya Biryukov71028b82018-03-12 15:28:22 +0000445 toLSPDiags(Diag, [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
446 DiagnosticsJSON.push_back(json::obj{
447 {"range", Diag.range},
448 {"severity", Diag.severity},
449 {"message", Diag.message},
450 });
451
452 auto &FixItsForDiagnostic = LocalFixIts[Diag];
453 std::copy(Fixes.begin(), Fixes.end(),
454 std::back_inserter(FixItsForDiagnostic));
Sam McCalldd0566b2017-11-06 15:40:30 +0000455 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000456 }
457
458 // Cache FixIts
459 {
460 // FIXME(ibiryukov): should be deleted when documents are removed
461 std::lock_guard<std::mutex> Lock(FixItsMutex);
462 FixItsMap[File] = LocalFixIts;
463 }
464
465 // Publish diagnostics.
Sam McCalldd0566b2017-11-06 15:40:30 +0000466 Out.writeMessage(json::obj{
467 {"jsonrpc", "2.0"},
468 {"method", "textDocument/publishDiagnostics"},
469 {"params",
470 json::obj{
Eric Liu78ed91a72018-01-29 15:37:46 +0000471 {"uri", URIForFile{File}},
Sam McCalldd0566b2017-11-06 15:40:30 +0000472 {"diagnostics", std::move(DiagnosticsJSON)},
473 }},
474 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000475}
Simon Marchi9569fd52018-03-16 14:30:42 +0000476
477void ClangdLSPServer::reparseOpenedFiles() {
478 for (const Path &FilePath : DraftMgr.getActiveFiles())
479 Server.addDocument(FilePath, *DraftMgr.getDraft(FilePath),
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000480 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +0000481}