blob: c916d5371cb56f2ff6e4f9862f4649fd511ae513 [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{
39 {"textDocumentSync", 1},
40 {"documentFormattingProvider", true},
41 {"documentRangeFormattingProvider", true},
42 {"documentOnTypeFormattingProvider",
43 json::obj{
44 {"firstTriggerCharacter", "}"},
45 {"moreTriggerCharacter", {}},
46 }},
47 {"codeActionProvider", true},
48 {"completionProvider",
49 json::obj{
50 {"resolveProvider", false},
51 {"triggerCharacters", {".", ">", ":"}},
52 }},
53 {"signatureHelpProvider",
54 json::obj{
55 {"triggerCharacters", {"(", ","}},
56 }},
57 {"definitionProvider", true},
58 {"executeCommandProvider",
59 json::obj{
60 {"commands", {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND}},
61 }},
62 });
Sam McCall8a5dded2017-10-12 13:29:58 +000063 if (Params.rootUri && !Params.rootUri->file.empty())
64 Server.setRootPath(Params.rootUri->file);
65 else if (Params.rootPath && !Params.rootPath->empty())
66 Server.setRootPath(*Params.rootPath);
Ilya Biryukovafb55542017-05-16 14:40:30 +000067}
68
Sam McCall8a5dded2017-10-12 13:29:58 +000069void ClangdLSPServer::onShutdown(Ctx C, ShutdownParams &Params) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +000070 // Do essentially nothing, just say we're ready to exit.
71 ShutdownRequestReceived = true;
Sam McCalldd0566b2017-11-06 15:40:30 +000072 C.reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +000073}
Ilya Biryukovafb55542017-05-16 14:40:30 +000074
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +000075void ClangdLSPServer::onExit(Ctx C, ExitParams &Params) { IsDone = true; }
76
Sam McCall8a5dded2017-10-12 13:29:58 +000077void ClangdLSPServer::onDocumentDidOpen(Ctx C,
78 DidOpenTextDocumentParams &Params) {
Krasimir Georgievc2a16a32017-07-06 08:44:54 +000079 if (Params.metadata && !Params.metadata->extraFlags.empty())
Sam McCall4db732a2017-09-30 10:08:52 +000080 CDB.setExtraFlagsForFile(Params.textDocument.uri.file,
81 std::move(Params.metadata->extraFlags));
82 Server.addDocument(Params.textDocument.uri.file, Params.textDocument.text);
Ilya Biryukovafb55542017-05-16 14:40:30 +000083}
84
Sam McCall8a5dded2017-10-12 13:29:58 +000085void ClangdLSPServer::onDocumentDidChange(Ctx C,
86 DidChangeTextDocumentParams &Params) {
Benjamin Kramerb560a9a2017-10-26 10:36:20 +000087 if (Params.contentChanges.size() != 1)
88 return C.replyError(-32602, "can only apply one change at a time");
Ilya Biryukovafb55542017-05-16 14:40:30 +000089 // We only support full syncing right now.
Sam McCall4db732a2017-09-30 10:08:52 +000090 Server.addDocument(Params.textDocument.uri.file,
91 Params.contentChanges[0].text);
Ilya Biryukovafb55542017-05-16 14:40:30 +000092}
93
Sam McCall8a5dded2017-10-12 13:29:58 +000094void ClangdLSPServer::onFileEvent(Ctx C, DidChangeWatchedFilesParams &Params) {
Marc-Andre Laperlebf114242017-10-02 18:00:37 +000095 Server.onFileEvent(Params);
96}
97
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000098void ClangdLSPServer::onCommand(Ctx C, ExecuteCommandParams &Params) {
99 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
100 Params.workspaceEdit) {
101 // The flow for "apply-fix" :
102 // 1. We publish a diagnostic, including fixits
103 // 2. The user clicks on the diagnostic, the editor asks us for code actions
104 // 3. We send code actions, with the fixit embedded as context
105 // 4. The user selects the fixit, the editor asks us to apply it
106 // 5. We unwrap the changes and send them back to the editor
107 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
108 // we ignore it)
109
110 ApplyWorkspaceEditParams ApplyEdit;
111 ApplyEdit.edit = *Params.workspaceEdit;
Sam McCalldd0566b2017-11-06 15:40:30 +0000112 C.reply("Fix applied.");
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000113 // We don't need the response so id == 1 is OK.
114 // Ideally, we would wait for the response and if there is no error, we
115 // would reply success/failure to the original RPC.
116 C.call("workspace/applyEdit", ApplyWorkspaceEditParams::unparse(ApplyEdit));
117 } else {
118 // We should not get here because ExecuteCommandParams would not have
119 // parsed in the first place and this handler should not be called. But if
120 // more commands are added, this will be here has a safe guard.
121 C.replyError(
122 1, llvm::formatv("Unsupported command \"{0}\".", Params.command).str());
123 }
124}
125
Sam McCall8a5dded2017-10-12 13:29:58 +0000126void ClangdLSPServer::onDocumentDidClose(Ctx C,
127 DidCloseTextDocumentParams &Params) {
Sam McCall4db732a2017-09-30 10:08:52 +0000128 Server.removeDocument(Params.textDocument.uri.file);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000129}
130
Sam McCall4db732a2017-09-30 10:08:52 +0000131void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall8a5dded2017-10-12 13:29:58 +0000132 Ctx C, DocumentOnTypeFormattingParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000133 auto File = Params.textDocument.uri.file;
Sam McCall4db732a2017-09-30 10:08:52 +0000134 std::string Code = Server.getDocument(File);
Sam McCalldd0566b2017-11-06 15:40:30 +0000135 C.reply(json::ary(
136 replacementsToEdits(Code, Server.formatOnType(File, Params.position))));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000137}
138
Sam McCall4db732a2017-09-30 10:08:52 +0000139void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall8a5dded2017-10-12 13:29:58 +0000140 Ctx C, DocumentRangeFormattingParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000141 auto File = Params.textDocument.uri.file;
Sam McCall4db732a2017-09-30 10:08:52 +0000142 std::string Code = Server.getDocument(File);
Sam McCalldd0566b2017-11-06 15:40:30 +0000143 C.reply(json::ary(
144 replacementsToEdits(Code, Server.formatRange(File, Params.range))));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000145}
146
Sam McCall8a5dded2017-10-12 13:29:58 +0000147void ClangdLSPServer::onDocumentFormatting(Ctx C,
148 DocumentFormattingParams &Params) {
Sam McCall4db732a2017-09-30 10:08:52 +0000149 auto File = Params.textDocument.uri.file;
150 std::string Code = Server.getDocument(File);
Sam McCalldd0566b2017-11-06 15:40:30 +0000151 C.reply(json::ary(replacementsToEdits(Code, Server.formatFile(File))));
Sam McCall4db732a2017-09-30 10:08:52 +0000152}
153
Sam McCall8a5dded2017-10-12 13:29:58 +0000154void ClangdLSPServer::onCodeAction(Ctx C, CodeActionParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000155 // We provide a code action for each diagnostic at the requested location
156 // which has FixIts available.
Sam McCall4db732a2017-09-30 10:08:52 +0000157 std::string Code = Server.getDocument(Params.textDocument.uri.file);
Sam McCalldd0566b2017-11-06 15:40:30 +0000158 json::ary Commands;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000159 for (Diagnostic &D : Params.context.diagnostics) {
160 std::vector<clang::tooling::Replacement> Fixes =
Sam McCall4db732a2017-09-30 10:08:52 +0000161 getFixIts(Params.textDocument.uri.file, D);
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000162 auto Edits = replacementsToEdits(Code, Fixes);
Sam McCalldd0566b2017-11-06 15:40:30 +0000163 if (!Edits.empty()) {
164 WorkspaceEdit WE;
165 WE.changes = {{Params.textDocument.uri.uri, std::move(Edits)}};
166 Commands.push_back(json::obj{
167 {"title", llvm::formatv("Apply FixIt {0}", D.message)},
168 {"command", ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND},
169 {"arguments", {WE}},
170 });
171 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000172 }
Sam McCalldd0566b2017-11-06 15:40:30 +0000173 C.reply(std::move(Commands));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000174}
175
Sam McCall8a5dded2017-10-12 13:29:58 +0000176void ClangdLSPServer::onCompletion(Ctx C, TextDocumentPositionParams &Params) {
Sam McCall4db732a2017-09-30 10:08:52 +0000177 auto Items = Server
Ilya Biryukov574b7532017-08-02 09:08:39 +0000178 .codeComplete(Params.textDocument.uri.file,
179 Position{Params.position.line,
180 Params.position.character})
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000181 .get() // FIXME(ibiryukov): This could be made async if we
182 // had an API that would allow to attach callbacks to
183 // futures returned by ClangdServer.
Ilya Biryukov574b7532017-08-02 09:08:39 +0000184 .Value;
Sam McCalldd0566b2017-11-06 15:40:30 +0000185 C.reply(json::ary(Items));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000186}
187
Sam McCall8a5dded2017-10-12 13:29:58 +0000188void ClangdLSPServer::onSignatureHelp(Ctx C,
189 TextDocumentPositionParams &Params) {
Benjamin Krameree19f162017-10-26 12:28:13 +0000190 auto SignatureHelp = Server.signatureHelp(
191 Params.textDocument.uri.file,
192 Position{Params.position.line, Params.position.character});
193 if (!SignatureHelp)
194 return C.replyError(-32602, llvm::toString(SignatureHelp.takeError()));
Sam McCalldd0566b2017-11-06 15:40:30 +0000195 C.reply(SignatureHelp->Value);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000196}
197
Sam McCall8a5dded2017-10-12 13:29:58 +0000198void ClangdLSPServer::onGoToDefinition(Ctx C,
199 TextDocumentPositionParams &Params) {
Benjamin Krameree19f162017-10-26 12:28:13 +0000200 auto Items = Server.findDefinitions(
201 Params.textDocument.uri.file,
202 Position{Params.position.line, Params.position.character});
203 if (!Items)
204 return C.replyError(-32602, llvm::toString(Items.takeError()));
Sam McCalldd0566b2017-11-06 15:40:30 +0000205 C.reply(json::ary(Items->Value));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000206}
207
Sam McCall8a5dded2017-10-12 13:29:58 +0000208void ClangdLSPServer::onSwitchSourceHeader(Ctx C,
209 TextDocumentIdentifier &Params) {
Sam McCall4db732a2017-09-30 10:08:52 +0000210 llvm::Optional<Path> Result = Server.switchSourceHeader(Params.uri.file);
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000211 std::string ResultUri;
Sam McCalldd0566b2017-11-06 15:40:30 +0000212 C.reply(Result ? URI::fromFile(*Result).uri : "");
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000213}
214
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000215ClangdLSPServer::ClangdLSPServer(JSONOutput &Out, unsigned AsyncThreadsCount,
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000216 bool SnippetCompletions,
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +0000217 llvm::Optional<StringRef> ResourceDir,
218 llvm::Optional<Path> CompileCommandsDir)
219 : Out(Out), CDB(/*Logger=*/Out, std::move(CompileCommandsDir)),
Sam McCall4db732a2017-09-30 10:08:52 +0000220 Server(CDB, /*DiagConsumer=*/*this, FSProvider, AsyncThreadsCount,
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000221 clangd::CodeCompleteOptions(
222 /*EnableSnippetsAndCodePatterns=*/SnippetCompletions),
223 /*Logger=*/Out, ResourceDir) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000224
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000225bool ClangdLSPServer::run(std::istream &In) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000226 assert(!IsDone && "Run was called before");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000227
Ilya Biryukovafb55542017-05-16 14:40:30 +0000228 // Set up JSONRPCDispatcher.
Sam McCall8a5dded2017-10-12 13:29:58 +0000229 JSONRPCDispatcher Dispatcher(
230 [](RequestContext Ctx, llvm::yaml::MappingNode *Params) {
231 Ctx.replyError(-32601, "method not found");
232 });
Sam McCall4db732a2017-09-30 10:08:52 +0000233 registerCallbackHandlers(Dispatcher, Out, /*Callbacks=*/*this);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000234
Ilya Biryukovafb55542017-05-16 14:40:30 +0000235 // Run the Language Server loop.
236 runLanguageServerLoop(In, Out, Dispatcher, IsDone);
237
238 // Make sure IsDone is set to true after this method exits to ensure assertion
239 // at the start of the method fires if it's ever executed again.
240 IsDone = true;
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000241
242 return ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000243}
244
245std::vector<clang::tooling::Replacement>
246ClangdLSPServer::getFixIts(StringRef File, const clangd::Diagnostic &D) {
247 std::lock_guard<std::mutex> Lock(FixItsMutex);
248 auto DiagToFixItsIter = FixItsMap.find(File);
249 if (DiagToFixItsIter == FixItsMap.end())
250 return {};
251
252 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
253 auto FixItsIter = DiagToFixItsMap.find(D);
254 if (FixItsIter == DiagToFixItsMap.end())
255 return {};
256
257 return FixItsIter->second;
258}
259
Sam McCall4db732a2017-09-30 10:08:52 +0000260void ClangdLSPServer::onDiagnosticsReady(
261 PathRef File, Tagged<std::vector<DiagWithFixIts>> Diagnostics) {
Sam McCalldd0566b2017-11-06 15:40:30 +0000262 json::ary DiagnosticsJSON;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000263
264 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCall4db732a2017-09-30 10:08:52 +0000265 for (auto &DiagWithFixes : Diagnostics.Value) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000266 auto Diag = DiagWithFixes.Diag;
Sam McCalldd0566b2017-11-06 15:40:30 +0000267 DiagnosticsJSON.push_back(json::obj{
268 {"range", Diag.range},
269 {"severity", Diag.severity},
270 {"message", Diag.message},
271 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000272 // We convert to Replacements to become independent of the SourceManager.
273 auto &FixItsForDiagnostic = LocalFixIts[Diag];
274 std::copy(DiagWithFixes.FixIts.begin(), DiagWithFixes.FixIts.end(),
275 std::back_inserter(FixItsForDiagnostic));
276 }
277
278 // Cache FixIts
279 {
280 // FIXME(ibiryukov): should be deleted when documents are removed
281 std::lock_guard<std::mutex> Lock(FixItsMutex);
282 FixItsMap[File] = LocalFixIts;
283 }
284
285 // Publish diagnostics.
Sam McCalldd0566b2017-11-06 15:40:30 +0000286 Out.writeMessage(json::obj{
287 {"jsonrpc", "2.0"},
288 {"method", "textDocument/publishDiagnostics"},
289 {"params",
290 json::obj{
291 {"uri", URI::fromFile(File)},
292 {"diagnostics", std::move(DiagnosticsJSON)},
293 }},
294 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000295}