blob: 00b51fc426ecd1dcea8d28cfe93b6f1c0f6c64eb [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
Raoul Wols212bcf82017-12-12 20:25:06 +000020TextEdit replacementToEdit(StringRef Code, const tooling::Replacement &R) {
21 Range ReplacementRange = {
22 offsetToPosition(Code, R.getOffset()),
23 offsetToPosition(Code, R.getOffset() + R.getLength())};
24 return {ReplacementRange, R.getReplacementText()};
25}
26
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000027std::vector<TextEdit>
Ilya Biryukovafb55542017-05-16 14:40:30 +000028replacementsToEdits(StringRef Code,
29 const std::vector<tooling::Replacement> &Replacements) {
30 // Turn the replacements into the format specified by the Language Server
Sam McCalldd0566b2017-11-06 15:40:30 +000031 // Protocol. Fuse them into one big JSON array.
32 std::vector<TextEdit> Edits;
Raoul Wols212bcf82017-12-12 20:25:06 +000033 for (const auto &R : Replacements)
34 Edits.push_back(replacementToEdit(Code, R));
35 return Edits;
36}
37
38std::vector<TextEdit> replacementsToEdits(StringRef Code,
39 const tooling::Replacements &Repls) {
40 std::vector<TextEdit> Edits;
41 for (const auto &R : Repls)
42 Edits.push_back(replacementToEdit(Code, R));
Ilya Biryukovafb55542017-05-16 14:40:30 +000043 return Edits;
44}
45
46} // namespace
47
Sam McCall8a5dded2017-10-12 13:29:58 +000048void ClangdLSPServer::onInitialize(Ctx C, InitializeParams &Params) {
Sam McCalldd0566b2017-11-06 15:40:30 +000049 C.reply(json::obj{
Sam McCall0930ab02017-11-07 15:49:35 +000050 {{"capabilities",
51 json::obj{
52 {"textDocumentSync", 1},
53 {"documentFormattingProvider", true},
54 {"documentRangeFormattingProvider", true},
55 {"documentOnTypeFormattingProvider",
56 json::obj{
57 {"firstTriggerCharacter", "}"},
58 {"moreTriggerCharacter", {}},
59 }},
60 {"codeActionProvider", true},
61 {"completionProvider",
62 json::obj{
63 {"resolveProvider", false},
64 {"triggerCharacters", {".", ">", ":"}},
65 }},
66 {"signatureHelpProvider",
67 json::obj{
68 {"triggerCharacters", {"(", ","}},
69 }},
70 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +000071 {"documentHighlightProvider", true},
Haojian Wu345099c2017-11-09 11:30:04 +000072 {"renameProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +000073 {"executeCommandProvider",
74 json::obj{
75 {"commands", {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND}},
76 }},
77 }}}});
Sam McCall8a5dded2017-10-12 13:29:58 +000078 if (Params.rootUri && !Params.rootUri->file.empty())
79 Server.setRootPath(Params.rootUri->file);
80 else if (Params.rootPath && !Params.rootPath->empty())
81 Server.setRootPath(*Params.rootPath);
Ilya Biryukovafb55542017-05-16 14:40:30 +000082}
83
Sam McCall8a5dded2017-10-12 13:29:58 +000084void ClangdLSPServer::onShutdown(Ctx C, ShutdownParams &Params) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +000085 // Do essentially nothing, just say we're ready to exit.
86 ShutdownRequestReceived = true;
Sam McCalldd0566b2017-11-06 15:40:30 +000087 C.reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +000088}
Ilya Biryukovafb55542017-05-16 14:40:30 +000089
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +000090void ClangdLSPServer::onExit(Ctx C, ExitParams &Params) { IsDone = true; }
91
Sam McCall8a5dded2017-10-12 13:29:58 +000092void ClangdLSPServer::onDocumentDidOpen(Ctx C,
93 DidOpenTextDocumentParams &Params) {
Krasimir Georgievc2a16a32017-07-06 08:44:54 +000094 if (Params.metadata && !Params.metadata->extraFlags.empty())
Sam McCall4db732a2017-09-30 10:08:52 +000095 CDB.setExtraFlagsForFile(Params.textDocument.uri.file,
96 std::move(Params.metadata->extraFlags));
97 Server.addDocument(Params.textDocument.uri.file, Params.textDocument.text);
Ilya Biryukovafb55542017-05-16 14:40:30 +000098}
99
Sam McCall8a5dded2017-10-12 13:29:58 +0000100void ClangdLSPServer::onDocumentDidChange(Ctx C,
101 DidChangeTextDocumentParams &Params) {
Benjamin Kramerb560a9a2017-10-26 10:36:20 +0000102 if (Params.contentChanges.size() != 1)
Haojian Wu2375c922017-11-07 10:21:02 +0000103 return C.replyError(ErrorCode::InvalidParams,
104 "can only apply one change at a time");
Ilya Biryukovafb55542017-05-16 14:40:30 +0000105 // We only support full syncing right now.
Sam McCall4db732a2017-09-30 10:08:52 +0000106 Server.addDocument(Params.textDocument.uri.file,
107 Params.contentChanges[0].text);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000108}
109
Sam McCall8a5dded2017-10-12 13:29:58 +0000110void ClangdLSPServer::onFileEvent(Ctx C, DidChangeWatchedFilesParams &Params) {
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000111 Server.onFileEvent(Params);
112}
113
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000114void ClangdLSPServer::onCommand(Ctx C, ExecuteCommandParams &Params) {
115 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
116 Params.workspaceEdit) {
117 // The flow for "apply-fix" :
118 // 1. We publish a diagnostic, including fixits
119 // 2. The user clicks on the diagnostic, the editor asks us for code actions
120 // 3. We send code actions, with the fixit embedded as context
121 // 4. The user selects the fixit, the editor asks us to apply it
122 // 5. We unwrap the changes and send them back to the editor
123 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
124 // we ignore it)
125
126 ApplyWorkspaceEditParams ApplyEdit;
127 ApplyEdit.edit = *Params.workspaceEdit;
Sam McCalldd0566b2017-11-06 15:40:30 +0000128 C.reply("Fix applied.");
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000129 // We don't need the response so id == 1 is OK.
130 // Ideally, we would wait for the response and if there is no error, we
131 // would reply success/failure to the original RPC.
Sam McCallff8b8742017-11-30 21:32:29 +0000132 C.call("workspace/applyEdit", ApplyEdit);
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000133 } else {
134 // We should not get here because ExecuteCommandParams would not have
135 // parsed in the first place and this handler should not be called. But if
136 // more commands are added, this will be here has a safe guard.
137 C.replyError(
Haojian Wu2375c922017-11-07 10:21:02 +0000138 ErrorCode::InvalidParams,
139 llvm::formatv("Unsupported command \"{0}\".", Params.command).str());
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000140 }
141}
142
Haojian Wu345099c2017-11-09 11:30:04 +0000143void ClangdLSPServer::onRename(Ctx C, RenameParams &Params) {
144 auto File = Params.textDocument.uri.file;
145 auto Replacements = Server.rename(File, Params.position, Params.newName);
146 if (!Replacements) {
Ilya Biryukov9e11c4c2017-11-15 18:04:56 +0000147 C.replyError(ErrorCode::InternalError,
148 llvm::toString(Replacements.takeError()));
Haojian Wu345099c2017-11-09 11:30:04 +0000149 return;
150 }
151 std::string Code = Server.getDocument(File);
152 std::vector<TextEdit> Edits = replacementsToEdits(Code, *Replacements);
153 WorkspaceEdit WE;
Sam McCallec109022017-11-28 09:37:43 +0000154 WE.changes = {{Params.textDocument.uri.uri, Edits}};
Sam McCallff8b8742017-11-30 21:32:29 +0000155 C.reply(WE);
Haojian Wu345099c2017-11-09 11:30:04 +0000156}
157
Sam McCall8a5dded2017-10-12 13:29:58 +0000158void ClangdLSPServer::onDocumentDidClose(Ctx C,
159 DidCloseTextDocumentParams &Params) {
Sam McCall4db732a2017-09-30 10:08:52 +0000160 Server.removeDocument(Params.textDocument.uri.file);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000161}
162
Sam McCall4db732a2017-09-30 10:08:52 +0000163void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall8a5dded2017-10-12 13:29:58 +0000164 Ctx C, DocumentOnTypeFormattingParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000165 auto File = Params.textDocument.uri.file;
Sam McCall4db732a2017-09-30 10:08:52 +0000166 std::string Code = Server.getDocument(File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000167 auto ReplacementsOrError = Server.formatOnType(Code, File, Params.position);
168 if (ReplacementsOrError)
169 C.reply(json::ary(replacementsToEdits(Code, ReplacementsOrError.get())));
170 else
171 C.replyError(ErrorCode::UnknownErrorCode,
172 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000173}
174
Sam McCall4db732a2017-09-30 10:08:52 +0000175void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall8a5dded2017-10-12 13:29:58 +0000176 Ctx C, DocumentRangeFormattingParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000177 auto File = Params.textDocument.uri.file;
Sam McCall4db732a2017-09-30 10:08:52 +0000178 std::string Code = Server.getDocument(File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000179 auto ReplacementsOrError = Server.formatRange(Code, File, Params.range);
180 if (ReplacementsOrError)
181 C.reply(json::ary(replacementsToEdits(Code, ReplacementsOrError.get())));
182 else
183 C.replyError(ErrorCode::UnknownErrorCode,
184 llvm::toString(ReplacementsOrError.takeError()));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000185}
186
Sam McCall8a5dded2017-10-12 13:29:58 +0000187void ClangdLSPServer::onDocumentFormatting(Ctx C,
188 DocumentFormattingParams &Params) {
Sam McCall4db732a2017-09-30 10:08:52 +0000189 auto File = Params.textDocument.uri.file;
190 std::string Code = Server.getDocument(File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000191 auto ReplacementsOrError = Server.formatFile(Code, File);
192 if (ReplacementsOrError)
193 C.reply(json::ary(replacementsToEdits(Code, ReplacementsOrError.get())));
194 else
195 C.replyError(ErrorCode::UnknownErrorCode,
196 llvm::toString(ReplacementsOrError.takeError()));
Sam McCall4db732a2017-09-30 10:08:52 +0000197}
198
Sam McCall8a5dded2017-10-12 13:29:58 +0000199void ClangdLSPServer::onCodeAction(Ctx C, CodeActionParams &Params) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000200 // We provide a code action for each diagnostic at the requested location
201 // which has FixIts available.
Sam McCall4db732a2017-09-30 10:08:52 +0000202 std::string Code = Server.getDocument(Params.textDocument.uri.file);
Sam McCalldd0566b2017-11-06 15:40:30 +0000203 json::ary Commands;
Ilya Biryukovafb55542017-05-16 14:40:30 +0000204 for (Diagnostic &D : Params.context.diagnostics) {
Sam McCall8111d3b2017-12-13 08:48:42 +0000205 auto Edits = getFixIts(Params.textDocument.uri.file, D);
Sam McCalldd0566b2017-11-06 15:40:30 +0000206 if (!Edits.empty()) {
207 WorkspaceEdit WE;
208 WE.changes = {{Params.textDocument.uri.uri, std::move(Edits)}};
209 Commands.push_back(json::obj{
210 {"title", llvm::formatv("Apply FixIt {0}", D.message)},
211 {"command", ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND},
212 {"arguments", {WE}},
213 });
214 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000215 }
Sam McCalldd0566b2017-11-06 15:40:30 +0000216 C.reply(std::move(Commands));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000217}
218
Sam McCall8a5dded2017-10-12 13:29:58 +0000219void ClangdLSPServer::onCompletion(Ctx C, TextDocumentPositionParams &Params) {
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000220 auto List =
221 Server
222 .codeComplete(
223 Params.textDocument.uri.file,
224 Position{Params.position.line, Params.position.character}, CCOpts)
225 .get() // FIXME(ibiryukov): This could be made async if we
226 // had an API that would allow to attach callbacks to
227 // futures returned by ClangdServer.
228 .Value;
Sam McCalla40371b2017-11-15 09:16:29 +0000229 C.reply(List);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000230}
231
Sam McCall8a5dded2017-10-12 13:29:58 +0000232void ClangdLSPServer::onSignatureHelp(Ctx C,
233 TextDocumentPositionParams &Params) {
Benjamin Krameree19f162017-10-26 12:28:13 +0000234 auto SignatureHelp = Server.signatureHelp(
235 Params.textDocument.uri.file,
236 Position{Params.position.line, Params.position.character});
237 if (!SignatureHelp)
Haojian Wu2375c922017-11-07 10:21:02 +0000238 return C.replyError(ErrorCode::InvalidParams,
239 llvm::toString(SignatureHelp.takeError()));
Sam McCalldd0566b2017-11-06 15:40:30 +0000240 C.reply(SignatureHelp->Value);
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000241}
242
Sam McCall8a5dded2017-10-12 13:29:58 +0000243void ClangdLSPServer::onGoToDefinition(Ctx C,
244 TextDocumentPositionParams &Params) {
Benjamin Krameree19f162017-10-26 12:28:13 +0000245 auto Items = Server.findDefinitions(
246 Params.textDocument.uri.file,
247 Position{Params.position.line, Params.position.character});
248 if (!Items)
Haojian Wu2375c922017-11-07 10:21:02 +0000249 return C.replyError(ErrorCode::InvalidParams,
250 llvm::toString(Items.takeError()));
Sam McCalldd0566b2017-11-06 15:40:30 +0000251 C.reply(json::ary(Items->Value));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000252}
253
Sam McCall8a5dded2017-10-12 13:29:58 +0000254void ClangdLSPServer::onSwitchSourceHeader(Ctx C,
255 TextDocumentIdentifier &Params) {
Sam McCall4db732a2017-09-30 10:08:52 +0000256 llvm::Optional<Path> Result = Server.switchSourceHeader(Params.uri.file);
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000257 std::string ResultUri;
Sam McCalldd0566b2017-11-06 15:40:30 +0000258 C.reply(Result ? URI::fromFile(*Result).uri : "");
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000259}
260
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000261void ClangdLSPServer::onDocumentHighlight(Ctx C,
262 TextDocumentPositionParams &Params) {
263
264 auto Highlights = Server.findDocumentHighlights(
265 Params.textDocument.uri.file,
266 Position{Params.position.line, Params.position.character});
267
268 if (!Highlights) {
269 C.replyError(ErrorCode::InternalError,
270 llvm::toString(Highlights.takeError()));
271 return;
272 }
273
274 C.reply(json::ary(Highlights->Value));
275}
276
Ilya Biryukovdb8b2d72017-08-14 08:45:47 +0000277ClangdLSPServer::ClangdLSPServer(JSONOutput &Out, unsigned AsyncThreadsCount,
Ilya Biryukove9eb7f02017-11-16 16:25:18 +0000278 bool StorePreamblesInMemory,
Sam McCalladccab62017-11-23 16:58:22 +0000279 const clangd::CodeCompleteOptions &CCOpts,
Ilya Biryukov0c1ca6b2017-10-02 15:13:20 +0000280 llvm::Optional<StringRef> ResourceDir,
281 llvm::Optional<Path> CompileCommandsDir)
282 : Out(Out), CDB(/*Logger=*/Out, std::move(CompileCommandsDir)),
Ilya Biryukovd3b04e32017-12-05 10:42:57 +0000283 CCOpts(CCOpts), Server(CDB, /*DiagConsumer=*/*this, FSProvider,
284 AsyncThreadsCount, StorePreamblesInMemory,
285 /*Logger=*/Out, ResourceDir) {}
Ilya Biryukov38d79772017-05-16 09:38:59 +0000286
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000287bool ClangdLSPServer::run(std::istream &In) {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000288 assert(!IsDone && "Run was called before");
Ilya Biryukov38d79772017-05-16 09:38:59 +0000289
Ilya Biryukovafb55542017-05-16 14:40:30 +0000290 // Set up JSONRPCDispatcher.
Sam McCall8a5dded2017-10-12 13:29:58 +0000291 JSONRPCDispatcher Dispatcher(
Sam McCallec109022017-11-28 09:37:43 +0000292 [](RequestContext Ctx, const json::Expr &Params) {
Haojian Wu2375c922017-11-07 10:21:02 +0000293 Ctx.replyError(ErrorCode::MethodNotFound, "method not found");
Sam McCall8a5dded2017-10-12 13:29:58 +0000294 });
Sam McCall4db732a2017-09-30 10:08:52 +0000295 registerCallbackHandlers(Dispatcher, Out, /*Callbacks=*/*this);
Ilya Biryukov38d79772017-05-16 09:38:59 +0000296
Ilya Biryukovafb55542017-05-16 14:40:30 +0000297 // Run the Language Server loop.
298 runLanguageServerLoop(In, Out, Dispatcher, IsDone);
299
300 // Make sure IsDone is set to true after this method exits to ensure assertion
301 // at the start of the method fires if it's ever executed again.
302 IsDone = true;
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000303
304 return ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000305}
306
Sam McCall8111d3b2017-12-13 08:48:42 +0000307std::vector<TextEdit> ClangdLSPServer::getFixIts(StringRef File,
308 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000309 std::lock_guard<std::mutex> Lock(FixItsMutex);
310 auto DiagToFixItsIter = FixItsMap.find(File);
311 if (DiagToFixItsIter == FixItsMap.end())
312 return {};
313
314 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
315 auto FixItsIter = DiagToFixItsMap.find(D);
316 if (FixItsIter == DiagToFixItsMap.end())
317 return {};
318
319 return FixItsIter->second;
320}
321
Sam McCall4db732a2017-09-30 10:08:52 +0000322void ClangdLSPServer::onDiagnosticsReady(
323 PathRef File, Tagged<std::vector<DiagWithFixIts>> Diagnostics) {
Sam McCalldd0566b2017-11-06 15:40:30 +0000324 json::ary DiagnosticsJSON;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000325
326 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCall4db732a2017-09-30 10:08:52 +0000327 for (auto &DiagWithFixes : Diagnostics.Value) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000328 auto Diag = DiagWithFixes.Diag;
Sam McCalldd0566b2017-11-06 15:40:30 +0000329 DiagnosticsJSON.push_back(json::obj{
330 {"range", Diag.range},
331 {"severity", Diag.severity},
332 {"message", Diag.message},
333 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000334 // We convert to Replacements to become independent of the SourceManager.
335 auto &FixItsForDiagnostic = LocalFixIts[Diag];
336 std::copy(DiagWithFixes.FixIts.begin(), DiagWithFixes.FixIts.end(),
337 std::back_inserter(FixItsForDiagnostic));
338 }
339
340 // Cache FixIts
341 {
342 // FIXME(ibiryukov): should be deleted when documents are removed
343 std::lock_guard<std::mutex> Lock(FixItsMutex);
344 FixItsMap[File] = LocalFixIts;
345 }
346
347 // Publish diagnostics.
Sam McCalldd0566b2017-11-06 15:40:30 +0000348 Out.writeMessage(json::obj{
349 {"jsonrpc", "2.0"},
350 {"method", "textDocument/publishDiagnostics"},
351 {"params",
352 json::obj{
353 {"uri", URI::fromFile(File)},
354 {"diagnostics", std::move(DiagnosticsJSON)},
355 }},
356 });
Ilya Biryukov38d79772017-05-16 09:38:59 +0000357}