blob: aa73e737f22fb770243d78a1af0689de49351bf7 [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},
60 {"executeCommandProvider",
61 json::obj{
62 {"commands", {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND}},
63 }},
64 }}}});
Sam McCall8a5dded2017-10-12 13:29:58 +000065 if (Params.rootUri && !Params.rootUri->file.empty())
66 Server.setRootPath(Params.rootUri->file);
67 else if (Params.rootPath && !Params.rootPath->empty())
68 Server.setRootPath(*Params.rootPath);
Ilya Biryukovafb55542017-05-16 14:40:30 +000069}
70
Sam McCall8a5dded2017-10-12 13:29:58 +000071void ClangdLSPServer::onShutdown(Ctx C, ShutdownParams &Params) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +000072 // Do essentially nothing, just say we're ready to exit.
73 ShutdownRequestReceived = true;
Sam McCalldd0566b2017-11-06 15:40:30 +000074 C.reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +000075}
Ilya Biryukovafb55542017-05-16 14:40:30 +000076
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +000077void ClangdLSPServer::onExit(Ctx C, ExitParams &Params) { IsDone = true; }
78
Sam McCall8a5dded2017-10-12 13:29:58 +000079void ClangdLSPServer::onDocumentDidOpen(Ctx C,
80 DidOpenTextDocumentParams &Params) {
Krasimir Georgievc2a16a32017-07-06 08:44:54 +000081 if (Params.metadata && !Params.metadata->extraFlags.empty())
Sam McCall4db732a2017-09-30 10:08:52 +000082 CDB.setExtraFlagsForFile(Params.textDocument.uri.file,
83 std::move(Params.metadata->extraFlags));
84 Server.addDocument(Params.textDocument.uri.file, Params.textDocument.text);
Ilya Biryukovafb55542017-05-16 14:40:30 +000085}
86
Sam McCall8a5dded2017-10-12 13:29:58 +000087void ClangdLSPServer::onDocumentDidChange(Ctx C,
88 DidChangeTextDocumentParams &Params) {
Benjamin Kramerb560a9a2017-10-26 10:36:20 +000089 if (Params.contentChanges.size() != 1)
Haojian Wu2375c922017-11-07 10:21:02 +000090 return C.replyError(ErrorCode::InvalidParams,
91 "can only apply one change at a time");
Ilya Biryukovafb55542017-05-16 14:40:30 +000092 // We only support full syncing right now.
Sam McCall4db732a2017-09-30 10:08:52 +000093 Server.addDocument(Params.textDocument.uri.file,
94 Params.contentChanges[0].text);
Ilya Biryukovafb55542017-05-16 14:40:30 +000095}
96
Sam McCall8a5dded2017-10-12 13:29:58 +000097void ClangdLSPServer::onFileEvent(Ctx C, DidChangeWatchedFilesParams &Params) {
Marc-Andre Laperlebf114242017-10-02 18:00:37 +000098 Server.onFileEvent(Params);
99}
100
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000101void ClangdLSPServer::onCommand(Ctx C, ExecuteCommandParams &Params) {
102 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
103 Params.workspaceEdit) {
104 // The flow for "apply-fix" :
105 // 1. We publish a diagnostic, including fixits
106 // 2. The user clicks on the diagnostic, the editor asks us for code actions
107 // 3. We send code actions, with the fixit embedded as context
108 // 4. The user selects the fixit, the editor asks us to apply it
109 // 5. We unwrap the changes and send them back to the editor
110 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
111 // we ignore it)
112
113 ApplyWorkspaceEditParams ApplyEdit;
114 ApplyEdit.edit = *Params.workspaceEdit;
Sam McCalldd0566b2017-11-06 15:40:30 +0000115 C.reply("Fix applied.");
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000116 // We don't need the response so id == 1 is OK.
117 // Ideally, we would wait for the response and if there is no error, we
118 // would reply success/failure to the original RPC.
119 C.call("workspace/applyEdit", ApplyWorkspaceEditParams::unparse(ApplyEdit));
120 } else {
121 // We should not get here because ExecuteCommandParams would not have
122 // parsed in the first place and this handler should not be called. But if
123 // more commands are added, this will be here has a safe guard.
124 C.replyError(
Haojian Wu2375c922017-11-07 10:21:02 +0000125 ErrorCode::InvalidParams,
126 llvm::formatv("Unsupported command \"{0}\".", Params.command).str());
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000127 }
128}
129
Sam McCall8a5dded2017-10-12 13:29:58 +0000130void ClangdLSPServer::onDocumentDidClose(Ctx C,
131 DidCloseTextDocumentParams &Params) {
Sam McCall4db732a2017-09-30 10:08:52 +0000132 Server.removeDocument(Params.textDocument.uri.file);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000133}
134
Sam McCall4db732a2017-09-30 10:08:52 +0000135void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall8a5dded2017-10-12 13:29:58 +0000136 Ctx C, DocumentOnTypeFormattingParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000137 auto File = Params.textDocument.uri.file;
Sam McCall4db732a2017-09-30 10:08:52 +0000138 std::string Code = Server.getDocument(File);
Sam McCalldd0566b2017-11-06 15:40:30 +0000139 C.reply(json::ary(
140 replacementsToEdits(Code, Server.formatOnType(File, Params.position))));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000141}
142
Sam McCall4db732a2017-09-30 10:08:52 +0000143void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall8a5dded2017-10-12 13:29:58 +0000144 Ctx C, DocumentRangeFormattingParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000145 auto File = Params.textDocument.uri.file;
Sam McCall4db732a2017-09-30 10:08:52 +0000146 std::string Code = Server.getDocument(File);
Sam McCalldd0566b2017-11-06 15:40:30 +0000147 C.reply(json::ary(
148 replacementsToEdits(Code, Server.formatRange(File, Params.range))));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000149}
150
Sam McCall8a5dded2017-10-12 13:29:58 +0000151void ClangdLSPServer::onDocumentFormatting(Ctx C,
152 DocumentFormattingParams &Params) {
Sam McCall4db732a2017-09-30 10:08:52 +0000153 auto File = Params.textDocument.uri.file;
154 std::string Code = Server.getDocument(File);
Sam McCalldd0566b2017-11-06 15:40:30 +0000155 C.reply(json::ary(replacementsToEdits(Code, Server.formatFile(File))));
Sam McCall4db732a2017-09-30 10:08:52 +0000156}
157
Sam McCall8a5dded2017-10-12 13:29:58 +0000158void ClangdLSPServer::onCodeAction(Ctx C, CodeActionParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000159 // We provide a code action for each diagnostic at the requested location
160 // which has FixIts available.
Sam McCall4db732a2017-09-30 10:08:52 +0000161 std::string Code = Server.getDocument(Params.textDocument.uri.file);
Sam McCalldd0566b2017-11-06 15:40:30 +0000162 json::ary Commands;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000163 for (Diagnostic &D : Params.context.diagnostics) {
164 std::vector<clang::tooling::Replacement> Fixes =
Sam McCall4db732a2017-09-30 10:08:52 +0000165 getFixIts(Params.textDocument.uri.file, D);
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000166 auto Edits = replacementsToEdits(Code, Fixes);
Sam McCalldd0566b2017-11-06 15:40:30 +0000167 if (!Edits.empty()) {
168 WorkspaceEdit WE;
169 WE.changes = {{Params.textDocument.uri.uri, std::move(Edits)}};
170 Commands.push_back(json::obj{
171 {"title", llvm::formatv("Apply FixIt {0}", D.message)},
172 {"command", ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND},
173 {"arguments", {WE}},
174 });
175 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000176 }
Sam McCalldd0566b2017-11-06 15:40:30 +0000177 C.reply(std::move(Commands));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000178}
179
Sam McCall8a5dded2017-10-12 13:29:58 +0000180void ClangdLSPServer::onCompletion(Ctx C, TextDocumentPositionParams &Params) {
Sam McCall4db732a2017-09-30 10:08:52 +0000181 auto Items = Server
Ilya Biryukov574b7532017-08-02 09:08:39 +0000182 .codeComplete(Params.textDocument.uri.file,
183 Position{Params.position.line,
184 Params.position.character})
Ilya Biryukovdcd21692017-10-05 17:04:13 +0000185 .get() // FIXME(ibiryukov): This could be made async if we
186 // had an API that would allow to attach callbacks to
187 // futures returned by ClangdServer.
Ilya Biryukov574b7532017-08-02 09:08:39 +0000188 .Value;
Sam McCalldd0566b2017-11-06 15:40:30 +0000189 C.reply(json::ary(Items));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000190}
191
Sam McCall8a5dded2017-10-12 13:29:58 +0000192void ClangdLSPServer::onSignatureHelp(Ctx C,
193 TextDocumentPositionParams &Params) {
Benjamin Krameree19f162017-10-26 12:28:13 +0000194 auto SignatureHelp = Server.signatureHelp(
195 Params.textDocument.uri.file,
196 Position{Params.position.line, Params.position.character});
197 if (!SignatureHelp)
Haojian Wu2375c922017-11-07 10:21:02 +0000198 return C.replyError(ErrorCode::InvalidParams,
199 llvm::toString(SignatureHelp.takeError()));
Sam McCalldd0566b2017-11-06 15:40:30 +0000200 C.reply(SignatureHelp->Value);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000201}
202
Sam McCall8a5dded2017-10-12 13:29:58 +0000203void ClangdLSPServer::onGoToDefinition(Ctx C,
204 TextDocumentPositionParams &Params) {
Benjamin Krameree19f162017-10-26 12:28:13 +0000205 auto Items = Server.findDefinitions(
206 Params.textDocument.uri.file,
207 Position{Params.position.line, Params.position.character});
208 if (!Items)
Haojian Wu2375c922017-11-07 10:21:02 +0000209 return C.replyError(ErrorCode::InvalidParams,
210 llvm::toString(Items.takeError()));
Sam McCalldd0566b2017-11-06 15:40:30 +0000211 C.reply(json::ary(Items->Value));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000212}
213
Sam McCall8a5dded2017-10-12 13:29:58 +0000214void ClangdLSPServer::onSwitchSourceHeader(Ctx C,
215 TextDocumentIdentifier &Params) {
Sam McCall4db732a2017-09-30 10:08:52 +0000216 llvm::Optional<Path> Result = Server.switchSourceHeader(Params.uri.file);
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000217 std::string ResultUri;
Sam McCalldd0566b2017-11-06 15:40:30 +0000218 C.reply(Result ? URI::fromFile(*Result).uri : "");
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000219}
220
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000221ClangdLSPServer::ClangdLSPServer(JSONOutput &Out, unsigned AsyncThreadsCount,
Ilya Biryukovb33c1572017-09-12 13:57:14 +0000222 bool SnippetCompletions,
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +0000223 llvm::Optional<StringRef> ResourceDir,
224 llvm::Optional<Path> CompileCommandsDir)
225 : Out(Out), CDB(/*Logger=*/Out, std::move(CompileCommandsDir)),
Sam McCall4db732a2017-09-30 10:08:52 +0000226 Server(CDB, /*DiagConsumer=*/*this, FSProvider, AsyncThreadsCount,
Ilya Biryukovb080cb12017-10-23 14:46:48 +0000227 clangd::CodeCompleteOptions(
228 /*EnableSnippetsAndCodePatterns=*/SnippetCompletions),
229 /*Logger=*/Out, ResourceDir) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000230
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000231bool ClangdLSPServer::run(std::istream &In) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000232 assert(!IsDone && "Run was called before");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000233
Ilya Biryukovafb55542017-05-16 14:40:30 +0000234 // Set up JSONRPCDispatcher.
Sam McCall8a5dded2017-10-12 13:29:58 +0000235 JSONRPCDispatcher Dispatcher(
236 [](RequestContext Ctx, llvm::yaml::MappingNode *Params) {
Haojian Wu2375c922017-11-07 10:21:02 +0000237 Ctx.replyError(ErrorCode::MethodNotFound, "method not found");
Sam McCall8a5dded2017-10-12 13:29:58 +0000238 });
Sam McCall4db732a2017-09-30 10:08:52 +0000239 registerCallbackHandlers(Dispatcher, Out, /*Callbacks=*/*this);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000240
Ilya Biryukovafb55542017-05-16 14:40:30 +0000241 // Run the Language Server loop.
242 runLanguageServerLoop(In, Out, Dispatcher, IsDone);
243
244 // Make sure IsDone is set to true after this method exits to ensure assertion
245 // at the start of the method fires if it's ever executed again.
246 IsDone = true;
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000247
248 return ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000249}
250
251std::vector<clang::tooling::Replacement>
252ClangdLSPServer::getFixIts(StringRef File, const clangd::Diagnostic &D) {
253 std::lock_guard<std::mutex> Lock(FixItsMutex);
254 auto DiagToFixItsIter = FixItsMap.find(File);
255 if (DiagToFixItsIter == FixItsMap.end())
256 return {};
257
258 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
259 auto FixItsIter = DiagToFixItsMap.find(D);
260 if (FixItsIter == DiagToFixItsMap.end())
261 return {};
262
263 return FixItsIter->second;
264}
265
Sam McCall4db732a2017-09-30 10:08:52 +0000266void ClangdLSPServer::onDiagnosticsReady(
267 PathRef File, Tagged<std::vector<DiagWithFixIts>> Diagnostics) {
Sam McCalldd0566b2017-11-06 15:40:30 +0000268 json::ary DiagnosticsJSON;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000269
270 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCall4db732a2017-09-30 10:08:52 +0000271 for (auto &DiagWithFixes : Diagnostics.Value) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000272 auto Diag = DiagWithFixes.Diag;
Sam McCalldd0566b2017-11-06 15:40:30 +0000273 DiagnosticsJSON.push_back(json::obj{
274 {"range", Diag.range},
275 {"severity", Diag.severity},
276 {"message", Diag.message},
277 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000278 // We convert to Replacements to become independent of the SourceManager.
279 auto &FixItsForDiagnostic = LocalFixIts[Diag];
280 std::copy(DiagWithFixes.FixIts.begin(), DiagWithFixes.FixIts.end(),
281 std::back_inserter(FixItsForDiagnostic));
282 }
283
284 // Cache FixIts
285 {
286 // FIXME(ibiryukov): should be deleted when documents are removed
287 std::lock_guard<std::mutex> Lock(FixItsMutex);
288 FixItsMap[File] = LocalFixIts;
289 }
290
291 // Publish diagnostics.
Sam McCalldd0566b2017-11-06 15:40:30 +0000292 Out.writeMessage(json::obj{
293 {"jsonrpc", "2.0"},
294 {"method", "textDocument/publishDiagnostics"},
295 {"params",
296 json::obj{
297 {"uri", URI::fromFile(File)},
298 {"diagnostics", std::move(DiagnosticsJSON)},
299 }},
300 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000301}