blob: dbce7c87d4b15573a682bd9734d75bf019320134 [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"
12
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000013#include "llvm/Support/FormatVariadic.h"
14
Ilya Biryukov38d79772017-05-16 09:38:59 +000015using namespace clang::clangd;
16using namespace clang;
17
Ilya Biryukovafb55542017-05-16 14:40:30 +000018namespace {
19
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000020std::vector<TextEdit>
Ilya Biryukovafb55542017-05-16 14:40:30 +000021replacementsToEdits(StringRef Code,
22 const std::vector<tooling::Replacement> &Replacements) {
23 // Turn the replacements into the format specified by the Language Server
Sam McCalldd0566b2017-11-06 15:40:30 +000024 // Protocol. Fuse them into one big JSON array.
25 std::vector<TextEdit> Edits;
Ilya Biryukovafb55542017-05-16 14:40:30 +000026 for (auto &R : Replacements) {
27 Range ReplacementRange = {
28 offsetToPosition(Code, R.getOffset()),
29 offsetToPosition(Code, R.getOffset() + R.getLength())};
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000030 Edits.push_back({ReplacementRange, R.getReplacementText()});
Ilya Biryukovafb55542017-05-16 14:40:30 +000031 }
Ilya Biryukovafb55542017-05-16 14:40:30 +000032 return Edits;
33}
34
35} // namespace
36
Sam McCall8a5dded2017-10-12 13:29:58 +000037void ClangdLSPServer::onInitialize(Ctx C, InitializeParams &Params) {
Sam McCalldd0566b2017-11-06 15:40:30 +000038 C.reply(json::obj{
Sam McCall0930ab02017-11-07 15:49:35 +000039 {{"capabilities",
40 json::obj{
41 {"textDocumentSync", 1},
42 {"documentFormattingProvider", true},
43 {"documentRangeFormattingProvider", true},
44 {"documentOnTypeFormattingProvider",
45 json::obj{
46 {"firstTriggerCharacter", "}"},
47 {"moreTriggerCharacter", {}},
48 }},
49 {"codeActionProvider", true},
50 {"completionProvider",
51 json::obj{
52 {"resolveProvider", false},
53 {"triggerCharacters", {".", ">", ":"}},
54 }},
55 {"signatureHelpProvider",
56 json::obj{
57 {"triggerCharacters", {"(", ","}},
58 }},
59 {"definitionProvider", true},
Haojian Wu345099c2017-11-09 11:30:04 +000060 {"renameProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +000061 {"executeCommandProvider",
62 json::obj{
63 {"commands", {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND}},
64 }},
65 }}}});
Sam McCall8a5dded2017-10-12 13:29:58 +000066 if (Params.rootUri && !Params.rootUri->file.empty())
67 Server.setRootPath(Params.rootUri->file);
68 else if (Params.rootPath && !Params.rootPath->empty())
69 Server.setRootPath(*Params.rootPath);
Ilya Biryukovafb55542017-05-16 14:40:30 +000070}
71
Sam McCall8a5dded2017-10-12 13:29:58 +000072void ClangdLSPServer::onShutdown(Ctx C, ShutdownParams &Params) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +000073 // Do essentially nothing, just say we're ready to exit.
74 ShutdownRequestReceived = true;
Sam McCalldd0566b2017-11-06 15:40:30 +000075 C.reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +000076}
Ilya Biryukovafb55542017-05-16 14:40:30 +000077
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +000078void ClangdLSPServer::onExit(Ctx C, ExitParams &Params) { IsDone = true; }
79
Sam McCall8a5dded2017-10-12 13:29:58 +000080void ClangdLSPServer::onDocumentDidOpen(Ctx C,
81 DidOpenTextDocumentParams &Params) {
Krasimir Georgievc2a16a32017-07-06 08:44:54 +000082 if (Params.metadata && !Params.metadata->extraFlags.empty())
Sam McCall4db732a2017-09-30 10:08:52 +000083 CDB.setExtraFlagsForFile(Params.textDocument.uri.file,
84 std::move(Params.metadata->extraFlags));
85 Server.addDocument(Params.textDocument.uri.file, Params.textDocument.text);
Ilya Biryukovafb55542017-05-16 14:40:30 +000086}
87
Sam McCall8a5dded2017-10-12 13:29:58 +000088void ClangdLSPServer::onDocumentDidChange(Ctx C,
89 DidChangeTextDocumentParams &Params) {
Benjamin Kramerb560a9a2017-10-26 10:36:20 +000090 if (Params.contentChanges.size() != 1)
Haojian Wu2375c922017-11-07 10:21:02 +000091 return C.replyError(ErrorCode::InvalidParams,
92 "can only apply one change at a time");
Ilya Biryukovafb55542017-05-16 14:40:30 +000093 // We only support full syncing right now.
Sam McCall4db732a2017-09-30 10:08:52 +000094 Server.addDocument(Params.textDocument.uri.file,
95 Params.contentChanges[0].text);
Ilya Biryukovafb55542017-05-16 14:40:30 +000096}
97
Sam McCall8a5dded2017-10-12 13:29:58 +000098void ClangdLSPServer::onFileEvent(Ctx C, DidChangeWatchedFilesParams &Params) {
Marc-Andre Laperlebf114242017-10-02 18:00:37 +000099 Server.onFileEvent(Params);
100}
101
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000102void ClangdLSPServer::onCommand(Ctx C, ExecuteCommandParams &Params) {
103 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
104 Params.workspaceEdit) {
105 // The flow for "apply-fix" :
106 // 1. We publish a diagnostic, including fixits
107 // 2. The user clicks on the diagnostic, the editor asks us for code actions
108 // 3. We send code actions, with the fixit embedded as context
109 // 4. The user selects the fixit, the editor asks us to apply it
110 // 5. We unwrap the changes and send them back to the editor
111 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
112 // we ignore it)
113
114 ApplyWorkspaceEditParams ApplyEdit;
115 ApplyEdit.edit = *Params.workspaceEdit;
Sam McCalldd0566b2017-11-06 15:40:30 +0000116 C.reply("Fix applied.");
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000117 // We don't need the response so id == 1 is OK.
118 // Ideally, we would wait for the response and if there is no error, we
119 // would reply success/failure to the original RPC.
Sam McCallff8b8742017-11-30 21:32:29 +0000120 C.call("workspace/applyEdit", ApplyEdit);
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000121 } else {
122 // We should not get here because ExecuteCommandParams would not have
123 // parsed in the first place and this handler should not be called. But if
124 // more commands are added, this will be here has a safe guard.
125 C.replyError(
Haojian Wu2375c922017-11-07 10:21:02 +0000126 ErrorCode::InvalidParams,
127 llvm::formatv("Unsupported command \"{0}\".", Params.command).str());
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000128 }
129}
130
Haojian Wu345099c2017-11-09 11:30:04 +0000131void ClangdLSPServer::onRename(Ctx C, RenameParams &Params) {
132 auto File = Params.textDocument.uri.file;
133 auto Replacements = Server.rename(File, Params.position, Params.newName);
134 if (!Replacements) {
Ilya Biryukov9e11c4c2017-11-15 18:04:56 +0000135 C.replyError(ErrorCode::InternalError,
136 llvm::toString(Replacements.takeError()));
Haojian Wu345099c2017-11-09 11:30:04 +0000137 return;
138 }
139 std::string Code = Server.getDocument(File);
140 std::vector<TextEdit> Edits = replacementsToEdits(Code, *Replacements);
141 WorkspaceEdit WE;
Sam McCallec109022017-11-28 09:37:43 +0000142 WE.changes = {{Params.textDocument.uri.uri, Edits}};
Sam McCallff8b8742017-11-30 21:32:29 +0000143 C.reply(WE);
Haojian Wu345099c2017-11-09 11:30:04 +0000144}
145
Sam McCall8a5dded2017-10-12 13:29:58 +0000146void ClangdLSPServer::onDocumentDidClose(Ctx C,
147 DidCloseTextDocumentParams &Params) {
Sam McCall4db732a2017-09-30 10:08:52 +0000148 Server.removeDocument(Params.textDocument.uri.file);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000149}
150
Sam McCall4db732a2017-09-30 10:08:52 +0000151void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall8a5dded2017-10-12 13:29:58 +0000152 Ctx C, DocumentOnTypeFormattingParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000153 auto File = Params.textDocument.uri.file;
Sam McCall4db732a2017-09-30 10:08:52 +0000154 std::string Code = Server.getDocument(File);
Sam McCalldd0566b2017-11-06 15:40:30 +0000155 C.reply(json::ary(
156 replacementsToEdits(Code, Server.formatOnType(File, Params.position))));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000157}
158
Sam McCall4db732a2017-09-30 10:08:52 +0000159void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall8a5dded2017-10-12 13:29:58 +0000160 Ctx C, DocumentRangeFormattingParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000161 auto File = Params.textDocument.uri.file;
Sam McCall4db732a2017-09-30 10:08:52 +0000162 std::string Code = Server.getDocument(File);
Sam McCalldd0566b2017-11-06 15:40:30 +0000163 C.reply(json::ary(
164 replacementsToEdits(Code, Server.formatRange(File, Params.range))));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000165}
166
Sam McCall8a5dded2017-10-12 13:29:58 +0000167void ClangdLSPServer::onDocumentFormatting(Ctx C,
168 DocumentFormattingParams &Params) {
Sam McCall4db732a2017-09-30 10:08:52 +0000169 auto File = Params.textDocument.uri.file;
170 std::string Code = Server.getDocument(File);
Sam McCalldd0566b2017-11-06 15:40:30 +0000171 C.reply(json::ary(replacementsToEdits(Code, Server.formatFile(File))));
Sam McCall4db732a2017-09-30 10:08:52 +0000172}
173
Sam McCall8a5dded2017-10-12 13:29:58 +0000174void ClangdLSPServer::onCodeAction(Ctx C, CodeActionParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000175 // We provide a code action for each diagnostic at the requested location
176 // which has FixIts available.
Sam McCall4db732a2017-09-30 10:08:52 +0000177 std::string Code = Server.getDocument(Params.textDocument.uri.file);
Sam McCalldd0566b2017-11-06 15:40:30 +0000178 json::ary Commands;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000179 for (Diagnostic &D : Params.context.diagnostics) {
180 std::vector<clang::tooling::Replacement> Fixes =
Sam McCall4db732a2017-09-30 10:08:52 +0000181 getFixIts(Params.textDocument.uri.file, D);
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000182 auto Edits = replacementsToEdits(Code, Fixes);
Sam McCalldd0566b2017-11-06 15:40:30 +0000183 if (!Edits.empty()) {
184 WorkspaceEdit WE;
185 WE.changes = {{Params.textDocument.uri.uri, std::move(Edits)}};
186 Commands.push_back(json::obj{
187 {"title", llvm::formatv("Apply FixIt {0}", D.message)},
188 {"command", ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND},
189 {"arguments", {WE}},
190 });
191 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000192 }
Sam McCalldd0566b2017-11-06 15:40:30 +0000193 C.reply(std::move(Commands));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000194}
195
Sam McCall8a5dded2017-10-12 13:29:58 +0000196void ClangdLSPServer::onCompletion(Ctx C, TextDocumentPositionParams &Params) {
Sam McCalla40371b2017-11-15 09:16:29 +0000197 auto List = Server
198 .codeComplete(
199 Params.textDocument.uri.file,
200 Position{Params.position.line, Params.position.character})
201 .get() // FIXME(ibiryukov): This could be made async if we
202 // had an API that would allow to attach callbacks to
203 // futures returned by ClangdServer.
204 .Value;
205 C.reply(List);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000206}
207
Sam McCall8a5dded2017-10-12 13:29:58 +0000208void ClangdLSPServer::onSignatureHelp(Ctx C,
209 TextDocumentPositionParams &Params) {
Benjamin Krameree19f162017-10-26 12:28:13 +0000210 auto SignatureHelp = Server.signatureHelp(
211 Params.textDocument.uri.file,
212 Position{Params.position.line, Params.position.character});
213 if (!SignatureHelp)
Haojian Wu2375c922017-11-07 10:21:02 +0000214 return C.replyError(ErrorCode::InvalidParams,
215 llvm::toString(SignatureHelp.takeError()));
Sam McCalldd0566b2017-11-06 15:40:30 +0000216 C.reply(SignatureHelp->Value);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000217}
218
Sam McCall8a5dded2017-10-12 13:29:58 +0000219void ClangdLSPServer::onGoToDefinition(Ctx C,
220 TextDocumentPositionParams &Params) {
Benjamin Krameree19f162017-10-26 12:28:13 +0000221 auto Items = Server.findDefinitions(
222 Params.textDocument.uri.file,
223 Position{Params.position.line, Params.position.character});
224 if (!Items)
Haojian Wu2375c922017-11-07 10:21:02 +0000225 return C.replyError(ErrorCode::InvalidParams,
226 llvm::toString(Items.takeError()));
Sam McCalldd0566b2017-11-06 15:40:30 +0000227 C.reply(json::ary(Items->Value));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000228}
229
Sam McCall8a5dded2017-10-12 13:29:58 +0000230void ClangdLSPServer::onSwitchSourceHeader(Ctx C,
231 TextDocumentIdentifier &Params) {
Sam McCall4db732a2017-09-30 10:08:52 +0000232 llvm::Optional<Path> Result = Server.switchSourceHeader(Params.uri.file);
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000233 std::string ResultUri;
Sam McCalldd0566b2017-11-06 15:40:30 +0000234 C.reply(Result ? URI::fromFile(*Result).uri : "");
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000235}
236
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000237ClangdLSPServer::ClangdLSPServer(JSONOutput &Out, unsigned AsyncThreadsCount,
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000238 bool StorePreamblesInMemory,
Sam McCalladccab62017-11-23 16:58:22 +0000239 const clangd::CodeCompleteOptions &CCOpts,
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +0000240 llvm::Optional<StringRef> ResourceDir,
241 llvm::Optional<Path> CompileCommandsDir)
242 : Out(Out), CDB(/*Logger=*/Out, std::move(CompileCommandsDir)),
Sam McCall4db732a2017-09-30 10:08:52 +0000243 Server(CDB, /*DiagConsumer=*/*this, FSProvider, AsyncThreadsCount,
Sam McCalladccab62017-11-23 16:58:22 +0000244 StorePreamblesInMemory, CCOpts,
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000245 /*Logger=*/Out, ResourceDir) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000246
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000247bool ClangdLSPServer::run(std::istream &In) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000248 assert(!IsDone && "Run was called before");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000249
Ilya Biryukovafb55542017-05-16 14:40:30 +0000250 // Set up JSONRPCDispatcher.
Sam McCall8a5dded2017-10-12 13:29:58 +0000251 JSONRPCDispatcher Dispatcher(
Sam McCallec109022017-11-28 09:37:43 +0000252 [](RequestContext Ctx, const json::Expr &Params) {
Haojian Wu2375c922017-11-07 10:21:02 +0000253 Ctx.replyError(ErrorCode::MethodNotFound, "method not found");
Sam McCall8a5dded2017-10-12 13:29:58 +0000254 });
Sam McCall4db732a2017-09-30 10:08:52 +0000255 registerCallbackHandlers(Dispatcher, Out, /*Callbacks=*/*this);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000256
Ilya Biryukovafb55542017-05-16 14:40:30 +0000257 // Run the Language Server loop.
258 runLanguageServerLoop(In, Out, Dispatcher, IsDone);
259
260 // Make sure IsDone is set to true after this method exits to ensure assertion
261 // at the start of the method fires if it's ever executed again.
262 IsDone = true;
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000263
264 return ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000265}
266
267std::vector<clang::tooling::Replacement>
268ClangdLSPServer::getFixIts(StringRef File, const clangd::Diagnostic &D) {
269 std::lock_guard<std::mutex> Lock(FixItsMutex);
270 auto DiagToFixItsIter = FixItsMap.find(File);
271 if (DiagToFixItsIter == FixItsMap.end())
272 return {};
273
274 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
275 auto FixItsIter = DiagToFixItsMap.find(D);
276 if (FixItsIter == DiagToFixItsMap.end())
277 return {};
278
279 return FixItsIter->second;
280}
281
Sam McCall4db732a2017-09-30 10:08:52 +0000282void ClangdLSPServer::onDiagnosticsReady(
283 PathRef File, Tagged<std::vector<DiagWithFixIts>> Diagnostics) {
Sam McCalldd0566b2017-11-06 15:40:30 +0000284 json::ary DiagnosticsJSON;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000285
286 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCall4db732a2017-09-30 10:08:52 +0000287 for (auto &DiagWithFixes : Diagnostics.Value) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000288 auto Diag = DiagWithFixes.Diag;
Sam McCalldd0566b2017-11-06 15:40:30 +0000289 DiagnosticsJSON.push_back(json::obj{
290 {"range", Diag.range},
291 {"severity", Diag.severity},
292 {"message", Diag.message},
293 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000294 // We convert to Replacements to become independent of the SourceManager.
295 auto &FixItsForDiagnostic = LocalFixIts[Diag];
296 std::copy(DiagWithFixes.FixIts.begin(), DiagWithFixes.FixIts.end(),
297 std::back_inserter(FixItsForDiagnostic));
298 }
299
300 // Cache FixIts
301 {
302 // FIXME(ibiryukov): should be deleted when documents are removed
303 std::lock_guard<std::mutex> Lock(FixItsMutex);
304 FixItsMap[File] = LocalFixIts;
305 }
306
307 // Publish diagnostics.
Sam McCalldd0566b2017-11-06 15:40:30 +0000308 Out.writeMessage(json::obj{
309 {"jsonrpc", "2.0"},
310 {"method", "textDocument/publishDiagnostics"},
311 {"params",
312 json::obj{
313 {"uri", URI::fromFile(File)},
314 {"diagnostics", std::move(DiagnosticsJSON)},
315 }},
316 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000317}