blob: 465bbde67e0cf90996cabaf22641a9d86df3e96e [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.
120 C.call("workspace/applyEdit", ApplyWorkspaceEditParams::unparse(ApplyEdit));
121 } 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) {
135 C.replyError(
136 ErrorCode::InternalError,
137 llvm::toString(Replacements.takeError()));
138 return;
139 }
140 std::string Code = Server.getDocument(File);
141 std::vector<TextEdit> Edits = replacementsToEdits(Code, *Replacements);
142 WorkspaceEdit WE;
143 WE.changes = {{llvm::yaml::escape(Params.textDocument.uri.uri), Edits}};
144 C.reply(WorkspaceEdit::unparse(WE));
145}
146
Sam McCall8a5dded2017-10-12 13:29:58 +0000147void ClangdLSPServer::onDocumentDidClose(Ctx C,
148 DidCloseTextDocumentParams &Params) {
Sam McCall4db732a2017-09-30 10:08:52 +0000149 Server.removeDocument(Params.textDocument.uri.file);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000150}
151
Sam McCall4db732a2017-09-30 10:08:52 +0000152void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall8a5dded2017-10-12 13:29:58 +0000153 Ctx C, DocumentOnTypeFormattingParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000154 auto File = Params.textDocument.uri.file;
Sam McCall4db732a2017-09-30 10:08:52 +0000155 std::string Code = Server.getDocument(File);
Sam McCalldd0566b2017-11-06 15:40:30 +0000156 C.reply(json::ary(
157 replacementsToEdits(Code, Server.formatOnType(File, Params.position))));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000158}
159
Sam McCall4db732a2017-09-30 10:08:52 +0000160void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall8a5dded2017-10-12 13:29:58 +0000161 Ctx C, DocumentRangeFormattingParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000162 auto File = Params.textDocument.uri.file;
Sam McCall4db732a2017-09-30 10:08:52 +0000163 std::string Code = Server.getDocument(File);
Sam McCalldd0566b2017-11-06 15:40:30 +0000164 C.reply(json::ary(
165 replacementsToEdits(Code, Server.formatRange(File, Params.range))));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000166}
167
Sam McCall8a5dded2017-10-12 13:29:58 +0000168void ClangdLSPServer::onDocumentFormatting(Ctx C,
169 DocumentFormattingParams &Params) {
Sam McCall4db732a2017-09-30 10:08:52 +0000170 auto File = Params.textDocument.uri.file;
171 std::string Code = Server.getDocument(File);
Sam McCalldd0566b2017-11-06 15:40:30 +0000172 C.reply(json::ary(replacementsToEdits(Code, Server.formatFile(File))));
Sam McCall4db732a2017-09-30 10:08:52 +0000173}
174
Sam McCall8a5dded2017-10-12 13:29:58 +0000175void ClangdLSPServer::onCodeAction(Ctx C, CodeActionParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000176 // We provide a code action for each diagnostic at the requested location
177 // which has FixIts available.
Sam McCall4db732a2017-09-30 10:08:52 +0000178 std::string Code = Server.getDocument(Params.textDocument.uri.file);
Sam McCalldd0566b2017-11-06 15:40:30 +0000179 json::ary Commands;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000180 for (Diagnostic &D : Params.context.diagnostics) {
181 std::vector<clang::tooling::Replacement> Fixes =
Sam McCall4db732a2017-09-30 10:08:52 +0000182 getFixIts(Params.textDocument.uri.file, D);
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000183 auto Edits = replacementsToEdits(Code, Fixes);
Sam McCalldd0566b2017-11-06 15:40:30 +0000184 if (!Edits.empty()) {
185 WorkspaceEdit WE;
186 WE.changes = {{Params.textDocument.uri.uri, std::move(Edits)}};
187 Commands.push_back(json::obj{
188 {"title", llvm::formatv("Apply FixIt {0}", D.message)},
189 {"command", ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND},
190 {"arguments", {WE}},
191 });
192 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000193 }
Sam McCalldd0566b2017-11-06 15:40:30 +0000194 C.reply(std::move(Commands));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000195}
196
Sam McCall8a5dded2017-10-12 13:29:58 +0000197void ClangdLSPServer::onCompletion(Ctx C, TextDocumentPositionParams &Params) {
Sam McCalla40371b2017-11-15 09:16:29 +0000198 auto List = Server
199 .codeComplete(
200 Params.textDocument.uri.file,
201 Position{Params.position.line, Params.position.character})
202 .get() // FIXME(ibiryukov): This could be made async if we
203 // had an API that would allow to attach callbacks to
204 // futures returned by ClangdServer.
205 .Value;
206 C.reply(List);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000207}
208
Sam McCall8a5dded2017-10-12 13:29:58 +0000209void ClangdLSPServer::onSignatureHelp(Ctx C,
210 TextDocumentPositionParams &Params) {
Benjamin Krameree19f162017-10-26 12:28:13 +0000211 auto SignatureHelp = Server.signatureHelp(
212 Params.textDocument.uri.file,
213 Position{Params.position.line, Params.position.character});
214 if (!SignatureHelp)
Haojian Wu2375c922017-11-07 10:21:02 +0000215 return C.replyError(ErrorCode::InvalidParams,
216 llvm::toString(SignatureHelp.takeError()));
Sam McCalldd0566b2017-11-06 15:40:30 +0000217 C.reply(SignatureHelp->Value);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000218}
219
Sam McCall8a5dded2017-10-12 13:29:58 +0000220void ClangdLSPServer::onGoToDefinition(Ctx C,
221 TextDocumentPositionParams &Params) {
Benjamin Krameree19f162017-10-26 12:28:13 +0000222 auto Items = Server.findDefinitions(
223 Params.textDocument.uri.file,
224 Position{Params.position.line, Params.position.character});
225 if (!Items)
Haojian Wu2375c922017-11-07 10:21:02 +0000226 return C.replyError(ErrorCode::InvalidParams,
227 llvm::toString(Items.takeError()));
Sam McCalldd0566b2017-11-06 15:40:30 +0000228 C.reply(json::ary(Items->Value));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000229}
230
Sam McCall8a5dded2017-10-12 13:29:58 +0000231void ClangdLSPServer::onSwitchSourceHeader(Ctx C,
232 TextDocumentIdentifier &Params) {
Sam McCall4db732a2017-09-30 10:08:52 +0000233 llvm::Optional<Path> Result = Server.switchSourceHeader(Params.uri.file);
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000234 std::string ResultUri;
Sam McCalldd0566b2017-11-06 15:40:30 +0000235 C.reply(Result ? URI::fromFile(*Result).uri : "");
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000236}
237
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000238ClangdLSPServer::ClangdLSPServer(JSONOutput &Out, unsigned AsyncThreadsCount,
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000239 bool SnippetCompletions,
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,
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000244 clangd::CodeCompleteOptions(
245 /*EnableSnippetsAndCodePatterns=*/SnippetCompletions),
246 /*Logger=*/Out, ResourceDir) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000247
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000248bool ClangdLSPServer::run(std::istream &In) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000249 assert(!IsDone && "Run was called before");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000250
Ilya Biryukovafb55542017-05-16 14:40:30 +0000251 // Set up JSONRPCDispatcher.
Sam McCall8a5dded2017-10-12 13:29:58 +0000252 JSONRPCDispatcher Dispatcher(
253 [](RequestContext Ctx, llvm::yaml::MappingNode *Params) {
Haojian Wu2375c922017-11-07 10:21:02 +0000254 Ctx.replyError(ErrorCode::MethodNotFound, "method not found");
Sam McCall8a5dded2017-10-12 13:29:58 +0000255 });
Sam McCall4db732a2017-09-30 10:08:52 +0000256 registerCallbackHandlers(Dispatcher, Out, /*Callbacks=*/*this);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000257
Ilya Biryukovafb55542017-05-16 14:40:30 +0000258 // Run the Language Server loop.
259 runLanguageServerLoop(In, Out, Dispatcher, IsDone);
260
261 // Make sure IsDone is set to true after this method exits to ensure assertion
262 // at the start of the method fires if it's ever executed again.
263 IsDone = true;
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000264
265 return ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000266}
267
268std::vector<clang::tooling::Replacement>
269ClangdLSPServer::getFixIts(StringRef File, const clangd::Diagnostic &D) {
270 std::lock_guard<std::mutex> Lock(FixItsMutex);
271 auto DiagToFixItsIter = FixItsMap.find(File);
272 if (DiagToFixItsIter == FixItsMap.end())
273 return {};
274
275 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
276 auto FixItsIter = DiagToFixItsMap.find(D);
277 if (FixItsIter == DiagToFixItsMap.end())
278 return {};
279
280 return FixItsIter->second;
281}
282
Sam McCall4db732a2017-09-30 10:08:52 +0000283void ClangdLSPServer::onDiagnosticsReady(
284 PathRef File, Tagged<std::vector<DiagWithFixIts>> Diagnostics) {
Sam McCalldd0566b2017-11-06 15:40:30 +0000285 json::ary DiagnosticsJSON;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000286
287 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCall4db732a2017-09-30 10:08:52 +0000288 for (auto &DiagWithFixes : Diagnostics.Value) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000289 auto Diag = DiagWithFixes.Diag;
Sam McCalldd0566b2017-11-06 15:40:30 +0000290 DiagnosticsJSON.push_back(json::obj{
291 {"range", Diag.range},
292 {"severity", Diag.severity},
293 {"message", Diag.message},
294 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000295 // We convert to Replacements to become independent of the SourceManager.
296 auto &FixItsForDiagnostic = LocalFixIts[Diag];
297 std::copy(DiagWithFixes.FixIts.begin(), DiagWithFixes.FixIts.end(),
298 std::back_inserter(FixItsForDiagnostic));
299 }
300
301 // Cache FixIts
302 {
303 // FIXME(ibiryukov): should be deleted when documents are removed
304 std::lock_guard<std::mutex> Lock(FixItsMutex);
305 FixItsMap[File] = LocalFixIts;
306 }
307
308 // Publish diagnostics.
Sam McCalldd0566b2017-11-06 15:40:30 +0000309 Out.writeMessage(json::obj{
310 {"jsonrpc", "2.0"},
311 {"method", "textDocument/publishDiagnostics"},
312 {"params",
313 json::obj{
314 {"uri", URI::fromFile(File)},
315 {"diagnostics", std::move(DiagnosticsJSON)},
316 }},
317 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000318}