blob: 7d6f54e7aa587b1fae7a1052d653f3ea85b67d6c [file] [log] [blame]
Ilya Biryukov38d79772017-05-16 09:38:59 +00001//===--- ClangdLSPServer.cpp - LSP server ------------------------*- C++-*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Ilya Biryukov38d79772017-05-16 09:38:59 +00006//
Kirill Bobyrev8e35f1e2018-08-14 16:03:32 +00007//===----------------------------------------------------------------------===//
Ilya Biryukov38d79772017-05-16 09:38:59 +00008
9#include "ClangdLSPServer.h"
Ilya Biryukov71028b82018-03-12 15:28:22 +000010#include "Diagnostics.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000011#include "Protocol.h"
Sam McCallb536a2a2017-12-19 12:23:48 +000012#include "SourceCode.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000013#include "Trace.h"
Eric Liu78ed91a72018-01-29 15:37:46 +000014#include "URI.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000015#include "clang/Tooling/Core/Replacement.h"
Sam McCalla69698f2019-03-27 17:47:49 +000016#include "llvm/ADT/Optional.h"
Kadir Cetinkaya689bf932018-08-24 13:09:41 +000017#include "llvm/ADT/ScopeExit.h"
Simon Marchi9569fd52018-03-16 14:30:42 +000018#include "llvm/Support/Errc.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000019#include "llvm/Support/Error.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000020#include "llvm/Support/FormatVariadic.h"
Eric Liu5740ff52018-01-31 16:26:27 +000021#include "llvm/Support/Path.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000022#include "llvm/Support/ScopedPrinter.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000023
Sam McCallc008af62018-10-20 15:30:37 +000024namespace clang {
25namespace clangd {
Ilya Biryukovafb55542017-05-16 14:40:30 +000026namespace {
Ilya Biryukovb0826bd2019-01-03 13:37:12 +000027class IgnoreCompletionError : public llvm::ErrorInfo<CancelledError> {
28public:
29 void log(llvm::raw_ostream &OS) const override {
30 OS << "ignored auto-triggered completion, preceding char did not match";
31 }
32 std::error_code convertToErrorCode() const override {
33 return std::make_error_code(std::errc::operation_canceled);
34 }
35};
Ilya Biryukovafb55542017-05-16 14:40:30 +000036
Ilya Biryukovcce67a32019-01-29 14:17:36 +000037/// Transforms a tweak into a code action that would apply it if executed.
38/// EXPECTS: T.prepare() was called and returned true.
39CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File,
40 Range Selection) {
41 CodeAction CA;
42 CA.title = T.Title;
43 CA.kind = CodeAction::REFACTOR_KIND;
44 // This tweak may have an expensive second stage, we only run it if the user
45 // actually chooses it in the UI. We reply with a command that would run the
46 // corresponding tweak.
47 // FIXME: for some tweaks, computing the edits is cheap and we could send them
48 // directly.
49 CA.command.emplace();
50 CA.command->title = T.Title;
51 CA.command->command = Command::CLANGD_APPLY_TWEAK;
52 CA.command->tweakArgs.emplace();
53 CA.command->tweakArgs->file = File;
54 CA.command->tweakArgs->tweakID = T.ID;
55 CA.command->tweakArgs->selection = Selection;
56 return CA;
Simon Pilgrime9a136b2019-02-03 14:08:30 +000057}
Ilya Biryukovcce67a32019-01-29 14:17:36 +000058
Ilya Biryukov19d75602018-11-23 15:21:19 +000059void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
60 SymbolKindBitset Kinds) {
61 for (auto &S : Syms) {
62 S.kind = adjustKindToCapability(S.kind, Kinds);
63 adjustSymbolKinds(S.children, Kinds);
64 }
65}
66
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000067SymbolKindBitset defaultSymbolKinds() {
68 SymbolKindBitset Defaults;
69 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
70 ++I)
71 Defaults.set(I);
72 return Defaults;
73}
74
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +000075CompletionItemKindBitset defaultCompletionItemKinds() {
76 CompletionItemKindBitset Defaults;
77 for (size_t I = CompletionItemKindMin;
78 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
79 Defaults.set(I);
80 return Defaults;
81}
82
Ilya Biryukovafb55542017-05-16 14:40:30 +000083} // namespace
84
Sam McCall2c30fbc2018-10-18 12:32:04 +000085// MessageHandler dispatches incoming LSP messages.
86// It handles cross-cutting concerns:
87// - serializes/deserializes protocol objects to JSON
88// - logging of inbound messages
89// - cancellation handling
90// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +000091// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +000092class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
93public:
94 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
95
Ilya Biryukovf2001aa2019-01-07 15:45:19 +000096 bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
Sam McCalla69698f2019-03-27 17:47:49 +000097 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +000098 log("<-- {0}", Method);
99 if (Method == "exit")
100 return false;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000101 if (!Server.Server)
102 elog("Notification {0} before initialization", Method);
103 else if (Method == "$/cancelRequest")
Sam McCall2c30fbc2018-10-18 12:32:04 +0000104 onCancel(std::move(Params));
105 else if (auto Handler = Notifications.lookup(Method))
106 Handler(std::move(Params));
107 else
108 log("unhandled notification {0}", Method);
109 return true;
110 }
111
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000112 bool onCall(llvm::StringRef Method, llvm::json::Value Params,
113 llvm::json::Value ID) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000114 WithContext HandlerContext(handlerContext());
Sam McCalle2f3a732018-10-24 14:26:26 +0000115 // Calls can be canceled by the client. Add cancellation context.
116 WithContext WithCancel(cancelableRequestContext(ID));
117 trace::Span Tracer(Method);
118 SPAN_ATTACH(Tracer, "Params", Params);
119 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000120 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +0000121 if (!Server.Server && Method != "initialize") {
122 elog("Call {0} before initialization.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000123 Reply(llvm::make_error<LSPError>("server not initialized",
124 ErrorCode::ServerNotInitialized));
Sam McCall3d0adbe2018-10-18 14:41:50 +0000125 } else if (auto Handler = Calls.lookup(Method))
Sam McCalle2f3a732018-10-24 14:26:26 +0000126 Handler(std::move(Params), std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000127 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000128 Reply(llvm::make_error<LSPError>("method not found",
129 ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000130 return true;
131 }
132
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000133 bool onReply(llvm::json::Value ID,
134 llvm::Expected<llvm::json::Value> Result) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000135 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000136 // We ignore replies, just log them.
137 if (Result)
138 log("<-- reply({0})", ID);
139 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000140 log("<-- reply({0}) error: {1}", ID, llvm::toString(Result.takeError()));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000141 return true;
142 }
143
144 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000145 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000146 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000147 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000148 Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000149 ReplyOnce Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000150 Param P;
Sam McCalle2f3a732018-10-24 14:26:26 +0000151 if (fromJSON(RawParams, P)) {
152 (Server.*Handler)(P, std::move(Reply));
153 } else {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000154 elog("Failed to decode {0} request.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000155 Reply(llvm::make_error<LSPError>("failed to decode request",
156 ErrorCode::InvalidRequest));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000157 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000158 };
159 }
160
161 // Bind an LSP method name to a notification.
162 template <typename Param>
163 void bind(const char *Method,
164 void (ClangdLSPServer::*Handler)(const Param &)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000165 Notifications[Method] = [Method, Handler,
166 this](llvm::json::Value RawParams) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000167 Param P;
168 if (!fromJSON(RawParams, P)) {
169 elog("Failed to decode {0} request.", Method);
170 return;
171 }
172 trace::Span Tracer(Method);
173 SPAN_ATTACH(Tracer, "Params", RawParams);
174 (Server.*Handler)(P);
175 };
176 }
177
178private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000179 // Function object to reply to an LSP call.
180 // Each instance must be called exactly once, otherwise:
181 // - the bug is logged, and (in debug mode) an assert will fire
182 // - if there was no reply, an error reply is sent
183 // - if there were multiple replies, only the first is sent
184 class ReplyOnce {
185 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000186 std::chrono::steady_clock::time_point Start;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000187 llvm::json::Value ID;
Sam McCalle2f3a732018-10-24 14:26:26 +0000188 std::string Method;
189 ClangdLSPServer *Server; // Null when moved-from.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000190 llvm::json::Object *TraceArgs;
Sam McCalle2f3a732018-10-24 14:26:26 +0000191
192 public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000193 ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
194 ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000195 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
196 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000197 assert(Server);
198 }
199 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000200 : Replied(Other.Replied.load()), Start(Other.Start),
201 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
202 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000203 Other.Server = nullptr;
204 }
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000205 ReplyOnce &operator=(ReplyOnce &&) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000206 ReplyOnce(const ReplyOnce &) = delete;
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000207 ReplyOnce &operator=(const ReplyOnce &) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000208
209 ~ReplyOnce() {
210 if (Server && !Replied) {
211 elog("No reply to message {0}({1})", Method, ID);
212 assert(false && "must reply to all calls!");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000213 (*this)(llvm::make_error<LSPError>("server failed to reply",
214 ErrorCode::InternalError));
Sam McCalle2f3a732018-10-24 14:26:26 +0000215 }
216 }
217
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000218 void operator()(llvm::Expected<llvm::json::Value> Reply) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000219 assert(Server && "moved-from!");
220 if (Replied.exchange(true)) {
221 elog("Replied twice to message {0}({1})", Method, ID);
222 assert(false && "must reply to each call only once!");
223 return;
224 }
Sam McCalld7babe42018-10-24 15:18:40 +0000225 auto Duration = std::chrono::steady_clock::now() - Start;
226 if (Reply) {
227 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
228 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000229 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000230 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
231 Server->Transp.reply(std::move(ID), std::move(Reply));
232 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000233 llvm::Error Err = Reply.takeError();
Sam McCalld7babe42018-10-24 15:18:40 +0000234 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
235 if (TraceArgs)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000236 (*TraceArgs)["Error"] = llvm::to_string(Err);
Sam McCalld7babe42018-10-24 15:18:40 +0000237 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
238 Server->Transp.reply(std::move(ID), std::move(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000239 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000240 }
241 };
242
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000243 llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
244 llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000245
246 // Method calls may be cancelled by ID, so keep track of their state.
247 // This needs a mutex: handlers may finish on a different thread, and that's
248 // when we clean up entries in the map.
249 mutable std::mutex RequestCancelersMutex;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000250 llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000251 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000252 void onCancel(const llvm::json::Value &Params) {
253 const llvm::json::Value *ID = nullptr;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000254 if (auto *O = Params.getAsObject())
255 ID = O->get("id");
256 if (!ID) {
257 elog("Bad cancellation request: {0}", Params);
258 return;
259 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000260 auto StrID = llvm::to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000261 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
262 auto It = RequestCancelers.find(StrID);
263 if (It != RequestCancelers.end())
264 It->second.first(); // Invoke the canceler.
265 }
Sam McCalla69698f2019-03-27 17:47:49 +0000266
267 Context handlerContext() const {
268 return Context::current().derive(
269 kCurrentOffsetEncoding,
270 Server.NegotiatedOffsetEncoding.getValueOr(OffsetEncoding::UTF16));
271 }
272
Sam McCall2c30fbc2018-10-18 12:32:04 +0000273 // We run cancelable requests in a context that does two things:
274 // - allows cancellation using RequestCancelers[ID]
275 // - cleans up the entry in RequestCancelers when it's no longer needed
276 // If a client reuses an ID, the last wins and the first cannot be canceled.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000277 Context cancelableRequestContext(const llvm::json::Value &ID) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000278 auto Task = cancelableTask();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000279 auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000280 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
281 {
282 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
283 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
284 }
285 // When the request ends, we can clean up the entry we just added.
286 // The cookie lets us check that it hasn't been overwritten due to ID
287 // reuse.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000288 return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000289 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
290 auto It = RequestCancelers.find(StrID);
291 if (It != RequestCancelers.end() && It->second.second == Cookie)
292 RequestCancelers.erase(It);
293 }));
294 }
295
296 ClangdLSPServer &Server;
297};
298
299// call(), notify(), and reply() wrap the Transport, adding logging and locking.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000300void ClangdLSPServer::call(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000301 auto ID = NextCallID++;
302 log("--> {0}({1})", Method, ID);
303 // We currently don't handle responses, so no need to store ID anywhere.
304 std::lock_guard<std::mutex> Lock(TranspWriter);
305 Transp.call(Method, std::move(Params), ID);
306}
307
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000308void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000309 log("--> {0}", Method);
310 std::lock_guard<std::mutex> Lock(TranspWriter);
311 Transp.notify(Method, std::move(Params));
312}
313
Sam McCall2c30fbc2018-10-18 12:32:04 +0000314void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000315 Callback<llvm::json::Value> Reply) {
Sam McCalla69698f2019-03-27 17:47:49 +0000316 // Determine character encoding first as it affects constructed ClangdServer.
317 if (Params.capabilities.offsetEncoding && !NegotiatedOffsetEncoding) {
318 NegotiatedOffsetEncoding = OffsetEncoding::UTF16; // fallback
319 for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
320 if (Supported != OffsetEncoding::UnsupportedEncoding) {
321 NegotiatedOffsetEncoding = Supported;
322 break;
323 }
324 }
325 llvm::Optional<WithContextValue> WithOffsetEncoding;
326 if (NegotiatedOffsetEncoding)
327 WithOffsetEncoding.emplace(kCurrentOffsetEncoding,
328 *NegotiatedOffsetEncoding);
329
Sam McCall0d9b40f2018-10-19 15:42:23 +0000330 if (Params.rootUri && *Params.rootUri)
331 ClangdServerOpts.WorkspaceRoot = Params.rootUri->file();
332 else if (Params.rootPath && !Params.rootPath->empty())
333 ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000334 if (Server)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000335 return Reply(llvm::make_error<LSPError>("server already initialized",
336 ErrorCode::InvalidRequest));
Sam McCallbc904612018-10-25 04:22:52 +0000337 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
338 CompileCommandsDir = Dir;
Sam McCallc55d09a2018-11-02 13:09:36 +0000339 if (UseDirBasedCDB)
340 BaseCDB = llvm::make_unique<DirectoryBasedGlobalCompilationDatabase>(
341 CompileCommandsDir);
Kadir Cetinkayabe6b35d2019-01-22 09:10:20 +0000342 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
343 ClangdServerOpts.ResourceDir);
Sam McCallc55d09a2018-11-02 13:09:36 +0000344 Server.emplace(*CDB, FSProvider, static_cast<DiagnosticsConsumer &>(*this),
345 ClangdServerOpts);
Sam McCallbc904612018-10-25 04:22:52 +0000346 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000347
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000348 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
349 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
350 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
351 if (Params.capabilities.WorkspaceSymbolKinds)
352 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
353 if (Params.capabilities.CompletionItemKinds)
354 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
355 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000356 SupportsHierarchicalDocumentSymbol =
357 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000358 SupportFileStatus = Params.initializationOptions.FileStatus;
Sam McCalla69698f2019-03-27 17:47:49 +0000359 llvm::json::Object Result{
Sam McCall0930ab02017-11-07 15:49:35 +0000360 {{"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000361 llvm::json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000362 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000363 {"documentFormattingProvider", true},
364 {"documentRangeFormattingProvider", true},
365 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000366 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000367 {"firstTriggerCharacter", "}"},
368 {"moreTriggerCharacter", {}},
369 }},
370 {"codeActionProvider", true},
371 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000372 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000373 {"resolveProvider", false},
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000374 // We do extra checks for '>' and ':' in completion to only
375 // trigger on '->' and '::'.
Sam McCall0930ab02017-11-07 15:49:35 +0000376 {"triggerCharacters", {".", ">", ":"}},
377 }},
378 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000379 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000380 {"triggerCharacters", {"(", ","}},
381 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000382 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000383 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000384 {"documentHighlightProvider", true},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000385 {"hoverProvider", true},
Haojian Wu345099c2017-11-09 11:30:04 +0000386 {"renameProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000387 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000388 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000389 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000390 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000391 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000392 {"commands",
393 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
394 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000395 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000396 {"typeHierarchyProvider", true},
Sam McCalla69698f2019-03-27 17:47:49 +0000397 }}}};
398 if (NegotiatedOffsetEncoding)
399 Result["offsetEncoding"] = *NegotiatedOffsetEncoding;
400 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000401}
402
Sam McCall2c30fbc2018-10-18 12:32:04 +0000403void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
404 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000405 // Do essentially nothing, just say we're ready to exit.
406 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000407 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000408}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000409
Sam McCall422c8282018-11-26 16:00:11 +0000410// sync is a clangd extension: it blocks until all background work completes.
411// It blocks the calling thread, so no messages are processed until it returns!
412void ClangdLSPServer::onSync(const NoParams &Params,
413 Callback<std::nullptr_t> Reply) {
414 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
415 Reply(nullptr);
416 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000417 Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
418 "Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000419}
420
Sam McCall2c30fbc2018-10-18 12:32:04 +0000421void ClangdLSPServer::onDocumentDidOpen(
422 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000423 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000424
Sam McCall2c30fbc2018-10-18 12:32:04 +0000425 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000426
Simon Marchi98082622018-03-26 14:41:40 +0000427 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000428 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000429}
430
Sam McCall2c30fbc2018-10-18 12:32:04 +0000431void ClangdLSPServer::onDocumentDidChange(
432 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000433 auto WantDiags = WantDiagnostics::Auto;
434 if (Params.wantDiagnostics.hasValue())
435 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
436 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000437
438 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000439 llvm::Expected<std::string> Contents =
Simon Marchi98082622018-03-26 14:41:40 +0000440 DraftMgr.updateDraft(File, Params.contentChanges);
441 if (!Contents) {
442 // If this fails, we are most likely going to be not in sync anymore with
443 // the client. It is better to remove the draft and let further operations
444 // fail rather than giving wrong results.
445 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000446 Server->removeDocument(File);
Sam McCallbed58852018-07-11 10:35:11 +0000447 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000448 return;
449 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000450
Ilya Biryukov652364b2018-09-26 05:48:29 +0000451 Server->addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000452}
453
Sam McCall2c30fbc2018-10-18 12:32:04 +0000454void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000455 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000456}
457
Sam McCall2c30fbc2018-10-18 12:32:04 +0000458void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000459 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000460 auto ApplyEdit = [this](WorkspaceEdit WE) {
Eric Liuc5105f92018-02-16 14:15:55 +0000461 ApplyWorkspaceEditParams Edit;
462 Edit.edit = std::move(WE);
Eric Liuc5105f92018-02-16 14:15:55 +0000463 // Ideally, we would wait for the response and if there is no error, we
464 // would reply success/failure to the original RPC.
465 call("workspace/applyEdit", Edit);
466 };
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000467 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
468 Params.workspaceEdit) {
469 // The flow for "apply-fix" :
470 // 1. We publish a diagnostic, including fixits
471 // 2. The user clicks on the diagnostic, the editor asks us for code actions
472 // 3. We send code actions, with the fixit embedded as context
473 // 4. The user selects the fixit, the editor asks us to apply it
474 // 5. We unwrap the changes and send them back to the editor
475 // 6. The editor applies the changes (applyEdit), and sends us a reply (but
476 // we ignore it)
477
Sam McCall2c30fbc2018-10-18 12:32:04 +0000478 Reply("Fix applied.");
Eric Liuc5105f92018-02-16 14:15:55 +0000479 ApplyEdit(*Params.workspaceEdit);
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000480 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
481 Params.tweakArgs) {
482 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
483 if (!Code)
484 return Reply(llvm::createStringError(
485 llvm::inconvertibleErrorCode(),
486 "trying to apply a code action for a non-added file"));
487
488 auto Action = [ApplyEdit](decltype(Reply) Reply, URIForFile File,
489 std::string Code,
490 llvm::Expected<tooling::Replacements> R) {
491 if (!R)
492 return Reply(R.takeError());
493
494 WorkspaceEdit WE;
495 WE.changes.emplace();
496 (*WE.changes)[File.uri()] = replacementsToEdits(Code, *R);
497
498 Reply("Fix applied.");
499 ApplyEdit(std::move(WE));
500 };
501 Server->applyTweak(Params.tweakArgs->file.file(),
502 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
503 Bind(Action, std::move(Reply), Params.tweakArgs->file,
504 std::move(*Code)));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000505 } else {
506 // We should not get here because ExecuteCommandParams would not have
507 // parsed in the first place and this handler should not be called. But if
508 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000509 Reply(llvm::make_error<LSPError>(
510 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000511 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000512 }
513}
514
Sam McCall2c30fbc2018-10-18 12:32:04 +0000515void ClangdLSPServer::onWorkspaceSymbol(
516 const WorkspaceSymbolParams &Params,
517 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000518 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000519 Params.query, CCOpts.Limit,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000520 Bind(
521 [this](decltype(Reply) Reply,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000522 llvm::Expected<std::vector<SymbolInformation>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000523 if (!Items)
524 return Reply(Items.takeError());
525 for (auto &Sym : *Items)
526 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000527
Sam McCall2c30fbc2018-10-18 12:32:04 +0000528 Reply(std::move(*Items));
529 },
530 std::move(Reply)));
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000531}
532
Sam McCall2c30fbc2018-10-18 12:32:04 +0000533void ClangdLSPServer::onRename(const RenameParams &Params,
534 Callback<WorkspaceEdit> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000535 Path File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000536 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000537 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000538 return Reply(llvm::make_error<LSPError>(
539 "onRename called for non-added file", ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000540
Ilya Biryukov652364b2018-09-26 05:48:29 +0000541 Server->rename(
Ilya Biryukov2c5e8e82018-02-15 13:15:47 +0000542 File, Params.position, Params.newName,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000543 Bind(
Ilya Biryukovd9c24dc2019-04-03 07:18:43 +0000544 [File, Code, Params](decltype(Reply) Reply,
545 llvm::Expected<std::vector<TextEdit>> Edits) {
546 if (!Edits)
547 return Reply(Edits.takeError());
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000548
Sam McCall2c30fbc2018-10-18 12:32:04 +0000549 WorkspaceEdit WE;
Ilya Biryukovd9c24dc2019-04-03 07:18:43 +0000550 WE.changes = {{Params.textDocument.uri.uri(), *Edits}};
Sam McCall2c30fbc2018-10-18 12:32:04 +0000551 Reply(WE);
552 },
553 std::move(Reply)));
Haojian Wu345099c2017-11-09 11:30:04 +0000554}
555
Sam McCall2c30fbc2018-10-18 12:32:04 +0000556void ClangdLSPServer::onDocumentDidClose(
557 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000558 PathRef File = Params.textDocument.uri.file();
559 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000560 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000561
562 {
563 std::lock_guard<std::mutex> Lock(FixItsMutex);
564 FixItsMap.erase(File);
565 }
566 // clangd will not send updates for this file anymore, so we empty out the
567 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
568 // VSCode). Note that this cannot race with actual diagnostics responses
569 // because removeDocument() guarantees no diagnostic callbacks will be
570 // executed after it returns.
571 publishDiagnostics(URIForFile::canonicalize(File, /*TUPath=*/File), {});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000572}
573
Sam McCall4db732a2017-09-30 10:08:52 +0000574void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000575 const DocumentOnTypeFormattingParams &Params,
576 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000577 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000578 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000579 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000580 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000581 "onDocumentOnTypeFormatting called for non-added file",
582 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000583
Ilya Biryukov652364b2018-09-26 05:48:29 +0000584 auto ReplacementsOrError = Server->formatOnType(*Code, File, Params.position);
Raoul Wols212bcf82017-12-12 20:25:06 +0000585 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000586 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000587 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000588 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000589}
590
Sam McCall4db732a2017-09-30 10:08:52 +0000591void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000592 const DocumentRangeFormattingParams &Params,
593 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000594 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000595 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000596 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000597 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000598 "onDocumentRangeFormatting called for non-added file",
599 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000600
Ilya Biryukov652364b2018-09-26 05:48:29 +0000601 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000602 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000603 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000604 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000605 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000606}
607
Sam McCall2c30fbc2018-10-18 12:32:04 +0000608void ClangdLSPServer::onDocumentFormatting(
609 const DocumentFormattingParams &Params,
610 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000611 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000612 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000613 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000614 return Reply(llvm::make_error<LSPError>(
615 "onDocumentFormatting called for non-added file",
616 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000617
Ilya Biryukov652364b2018-09-26 05:48:29 +0000618 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000619 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000620 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000621 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000622 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000623}
624
Ilya Biryukov19d75602018-11-23 15:21:19 +0000625/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
626/// Used by the clients that do not support the hierarchical view.
627static std::vector<SymbolInformation>
628flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
629 const URIForFile &FileURI) {
630
631 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000632 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
633 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000634 SymbolInformation SI;
635 SI.containerName = ParentName ? "" : *ParentName;
636 SI.name = S.name;
637 SI.kind = S.kind;
638 SI.location.range = S.range;
639 SI.location.uri = FileURI;
640
641 Results.push_back(std::move(SI));
642 std::string FullName =
643 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
644 for (auto &C : S.children)
645 Process(C, /*ParentName=*/FullName);
646 };
647 for (auto &S : Symbols)
648 Process(S, /*ParentName=*/"");
649 return Results;
650}
651
652void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000653 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000654 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000655 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000656 Params.textDocument.uri.file(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000657 Bind(
Ilya Biryukov19d75602018-11-23 15:21:19 +0000658 [this, FileURI](decltype(Reply) Reply,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000659 llvm::Expected<std::vector<DocumentSymbol>> Items) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000660 if (!Items)
661 return Reply(Items.takeError());
Ilya Biryukov19d75602018-11-23 15:21:19 +0000662 adjustSymbolKinds(*Items, SupportedSymbolKinds);
663 if (SupportsHierarchicalDocumentSymbol)
664 return Reply(std::move(*Items));
665 else
666 return Reply(flattenSymbolHierarchy(*Items, FileURI));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000667 },
668 std::move(Reply)));
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000669}
670
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000671static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000672 Command Cmd;
673 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000674 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000675 if (Action.command) {
676 Cmd = *Action.command;
677 } else if (Action.edit) {
678 Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
679 Cmd.workspaceEdit = *Action.edit;
680 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000681 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000682 }
683 Cmd.title = Action.title;
684 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
685 Cmd.title = "Apply fix: " + Cmd.title;
686 return Cmd;
687}
688
Sam McCall2c30fbc2018-10-18 12:32:04 +0000689void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000690 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000691 URIForFile File = Params.textDocument.uri;
692 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000693 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000694 return Reply(llvm::make_error<LSPError>(
695 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000696 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000697 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000698 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000699 for (auto &F : getFixes(File.file(), D)) {
700 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
701 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000702 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000703 }
Sam McCall20841d42018-10-16 16:29:41 +0000704
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000705 // Now enumerate the semantic code actions.
706 auto ConsumeActions =
707 [this](decltype(Reply) Reply, URIForFile File, std::string Code,
708 Range Selection, std::vector<CodeAction> FixIts,
709 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +0000710 if (!Tweaks)
711 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000712
713 std::vector<CodeAction> Actions = std::move(FixIts);
714 Actions.reserve(Actions.size() + Tweaks->size());
715 for (const auto &T : *Tweaks)
716 Actions.push_back(toCodeAction(T, File, Selection));
717
718 if (SupportsCodeAction)
719 return Reply(llvm::json::Array(Actions));
720 std::vector<Command> Commands;
721 for (const auto &Action : Actions) {
722 if (auto Command = asCommand(Action))
723 Commands.push_back(std::move(*Command));
724 }
725 return Reply(llvm::json::Array(Commands));
726 };
727
728 Server->enumerateTweaks(File.file(), Params.range,
Ilya Biryukovc9409c62019-01-30 09:39:01 +0000729 Bind(ConsumeActions, std::move(Reply), File,
730 std::move(*Code), Params.range,
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000731 std::move(FixIts)));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000732}
733
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000734void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000735 Callback<CompletionList> Reply) {
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000736 if (!shouldRunCompletion(Params))
737 return Reply(llvm::make_error<IgnoreCompletionError>());
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000738 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
739 Bind(
740 [this](decltype(Reply) Reply,
741 llvm::Expected<CodeCompleteResult> List) {
742 if (!List)
743 return Reply(List.takeError());
744 CompletionList LSPList;
745 LSPList.isIncomplete = List->HasMore;
746 for (const auto &R : List->Completions) {
747 CompletionItem C = R.render(CCOpts);
748 C.kind = adjustKindToCapability(
749 C.kind, SupportedCompletionItemKinds);
750 LSPList.items.push_back(std::move(C));
751 }
752 return Reply(std::move(LSPList));
753 },
754 std::move(Reply)));
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000755}
756
Sam McCall2c30fbc2018-10-18 12:32:04 +0000757void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
758 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000759 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000760 std::move(Reply));
Ilya Biryukov652364b2018-09-26 05:48:29 +0000761}
762
Sam McCall0dbab7f2019-02-02 05:56:00 +0000763// Go to definition has a toggle function: if def and decl are distinct, then
764// the first press gives you the def, the second gives you the matching def.
765// getToggle() returns the counterpart location that under the cursor.
766//
767// We return the toggled location alone (ignoring other symbols) to encourage
768// editors to "bounce" quickly between locations, without showing a menu.
769static Location *getToggle(const TextDocumentPositionParams &Point,
770 LocatedSymbol &Sym) {
771 // Toggle only makes sense with two distinct locations.
772 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
773 return nullptr;
774 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
775 Sym.Definition->range.contains(Point.position))
776 return &Sym.PreferredDeclaration;
777 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
778 Sym.PreferredDeclaration.range.contains(Point.position))
779 return &*Sym.Definition;
780 return nullptr;
781}
782
Sam McCall2c30fbc2018-10-18 12:32:04 +0000783void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
784 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000785 Server->locateSymbolAt(
786 Params.textDocument.uri.file(), Params.position,
787 Bind(
Sam McCall0dbab7f2019-02-02 05:56:00 +0000788 [&, Params](decltype(Reply) Reply,
789 llvm::Expected<std::vector<LocatedSymbol>> Symbols) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000790 if (!Symbols)
791 return Reply(Symbols.takeError());
792 std::vector<Location> Defs;
Sam McCall0dbab7f2019-02-02 05:56:00 +0000793 for (auto &S : *Symbols) {
794 if (Location *Toggle = getToggle(Params, S))
795 return Reply(std::vector<Location>{std::move(*Toggle)});
Sam McCall866ba2c2019-02-01 11:26:13 +0000796 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
Sam McCall0dbab7f2019-02-02 05:56:00 +0000797 }
Sam McCall866ba2c2019-02-01 11:26:13 +0000798 Reply(std::move(Defs));
799 },
800 std::move(Reply)));
801}
802
803void ClangdLSPServer::onGoToDeclaration(
804 const TextDocumentPositionParams &Params,
805 Callback<std::vector<Location>> Reply) {
806 Server->locateSymbolAt(
807 Params.textDocument.uri.file(), Params.position,
808 Bind(
Sam McCall0dbab7f2019-02-02 05:56:00 +0000809 [&, Params](decltype(Reply) Reply,
810 llvm::Expected<std::vector<LocatedSymbol>> Symbols) {
Sam McCall866ba2c2019-02-01 11:26:13 +0000811 if (!Symbols)
812 return Reply(Symbols.takeError());
813 std::vector<Location> Decls;
Sam McCall0dbab7f2019-02-02 05:56:00 +0000814 for (auto &S : *Symbols) {
815 if (Location *Toggle = getToggle(Params, S))
816 return Reply(std::vector<Location>{std::move(*Toggle)});
817 Decls.push_back(std::move(S.PreferredDeclaration));
818 }
Sam McCall866ba2c2019-02-01 11:26:13 +0000819 Reply(std::move(Decls));
820 },
821 std::move(Reply)));
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +0000822}
823
Sam McCall2c30fbc2018-10-18 12:32:04 +0000824void ClangdLSPServer::onSwitchSourceHeader(const TextDocumentIdentifier &Params,
825 Callback<std::string> Reply) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000826 llvm::Optional<Path> Result = Server->switchSourceHeader(Params.uri.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000827 Reply(Result ? URI::createFile(*Result).toString() : "");
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +0000828}
829
Sam McCall2c30fbc2018-10-18 12:32:04 +0000830void ClangdLSPServer::onDocumentHighlight(
831 const TextDocumentPositionParams &Params,
832 Callback<std::vector<DocumentHighlight>> Reply) {
833 Server->findDocumentHighlights(Params.textDocument.uri.file(),
834 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000835}
836
Sam McCall2c30fbc2018-10-18 12:32:04 +0000837void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000838 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000839 Server->findHover(Params.textDocument.uri.file(), Params.position,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000840 std::move(Reply));
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000841}
842
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000843void ClangdLSPServer::onTypeHierarchy(
844 const TypeHierarchyParams &Params,
845 Callback<Optional<TypeHierarchyItem>> Reply) {
846 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
847 Params.resolve, Params.direction, std::move(Reply));
848}
849
Simon Marchi88016782018-08-01 11:28:49 +0000850void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +0000851 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +0000852 // Per-file update to the compilation database.
Sam McCallbc904612018-10-25 04:22:52 +0000853 bool ShouldReparseOpenFiles = false;
854 for (auto &Entry : Settings.compilationDatabaseChanges) {
855 /// The opened files need to be reparsed only when some existing
856 /// entries are changed.
857 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +0000858 auto Old = CDB->getCompileCommand(File);
859 auto New =
860 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
861 std::move(Entry.second.compilationCommand),
862 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +0000863 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +0000864 CDB->setCompileCommand(File, std::move(New));
Sam McCall6980edb2018-11-02 14:07:51 +0000865 ShouldReparseOpenFiles = true;
866 }
Alex Lorenzf8087862018-08-01 17:39:29 +0000867 }
Sam McCallbc904612018-10-25 04:22:52 +0000868 if (ShouldReparseOpenFiles)
869 reparseOpenedFiles();
Simon Marchi5178f922018-02-22 14:00:39 +0000870}
871
Ilya Biryukov49c10712019-03-25 10:15:11 +0000872void ClangdLSPServer::publishDiagnostics(
873 const URIForFile &File, std::vector<clangd::Diagnostic> Diagnostics) {
874 // Publish diagnostics.
875 notify("textDocument/publishDiagnostics",
876 llvm::json::Object{
877 {"uri", File},
878 {"diagnostics", std::move(Diagnostics)},
879 });
880}
881
Simon Marchi88016782018-08-01 11:28:49 +0000882// FIXME: This function needs to be properly tested.
883void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000884 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +0000885 applyConfiguration(Params.settings);
886}
887
Sam McCall2c30fbc2018-10-18 12:32:04 +0000888void ClangdLSPServer::onReference(const ReferenceParams &Params,
889 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000890 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wuc34f0222019-01-14 18:11:09 +0000891 CCOpts.Limit, std::move(Reply));
Sam McCall1ad142f2018-09-05 11:53:07 +0000892}
893
Jan Korousb4067012018-11-27 16:40:46 +0000894void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
895 Callback<std::vector<SymbolDetails>> Reply) {
896 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
897 std::move(Reply));
898}
899
Sam McCalla69698f2019-03-27 17:47:49 +0000900ClangdLSPServer::ClangdLSPServer(
901 class Transport &Transp, const FileSystemProvider &FSProvider,
902 const clangd::CodeCompleteOptions &CCOpts,
903 llvm::Optional<Path> CompileCommandsDir, bool UseDirBasedCDB,
904 llvm::Optional<OffsetEncoding> ForcedOffsetEncoding,
905 const ClangdServer::Options &Opts)
Haojian Wu1ca0c582019-01-22 09:39:05 +0000906 : Transp(Transp), MsgHandler(new MessageHandler(*this)),
907 FSProvider(FSProvider), CCOpts(CCOpts),
Sam McCalld1c9d112018-10-23 14:19:54 +0000908 SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000909 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +0000910 UseDirBasedCDB(UseDirBasedCDB),
Sam McCalla69698f2019-03-27 17:47:49 +0000911 CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts),
912 NegotiatedOffsetEncoding(ForcedOffsetEncoding) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000913 // clang-format off
914 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
915 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +0000916 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000917 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
918 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
919 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
920 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
921 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
922 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
923 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +0000924 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000925 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
926 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
927 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
928 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
929 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
930 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
931 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
932 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
933 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
934 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
935 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
936 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
937 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +0000938 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000939 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000940 // clang-format on
941}
942
943ClangdLSPServer::~ClangdLSPServer() = default;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000944
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000945bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +0000946 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000947 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000948 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000949 elog("Transport error: {0}", std::move(Err));
950 CleanExit = false;
951 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000952
Ilya Biryukov652364b2018-09-26 05:48:29 +0000953 // Destroy ClangdServer to ensure all worker threads finish.
954 Server.reset();
Sam McCalldc8f3cf2018-10-17 07:32:05 +0000955 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +0000956}
957
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000958std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +0000959 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +0000960 std::lock_guard<std::mutex> Lock(FixItsMutex);
961 auto DiagToFixItsIter = FixItsMap.find(File);
962 if (DiagToFixItsIter == FixItsMap.end())
963 return {};
964
965 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
966 auto FixItsIter = DiagToFixItsMap.find(D);
967 if (FixItsIter == DiagToFixItsMap.end())
968 return {};
969
970 return FixItsIter->second;
971}
972
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000973bool ClangdLSPServer::shouldRunCompletion(
974 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000975 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000976 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
977 (Trigger != ">" && Trigger != ":"))
978 return true;
979
980 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
981 if (!Code)
982 return true; // completion code will log the error for untracked doc.
983
984 // A completion request is sent when the user types '>' or ':', but we only
985 // want to trigger on '->' and '::'. We check the preceeding character to make
986 // sure it matches what we expected.
987 // Running the lexer here would be more robust (e.g. we can detect comments
988 // and avoid triggering completion there), but we choose to err on the side
989 // of simplicity here.
990 auto Offset = positionToOffset(*Code, Params.position,
991 /*AllowColumnsBeyondLineLength=*/false);
992 if (!Offset) {
993 vlog("could not convert position '{0}' to offset for file '{1}'",
994 Params.position, Params.textDocument.uri.file());
995 return true;
996 }
997 if (*Offset < 2)
998 return false;
999
1000 if (Trigger == ">")
1001 return (*Code)[*Offset - 2] == '-'; // trigger only on '->'.
1002 if (Trigger == ":")
1003 return (*Code)[*Offset - 2] == ':'; // trigger only on '::'.
1004 assert(false && "unhandled trigger character");
1005 return true;
1006}
1007
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001008void ClangdLSPServer::onDiagnosticsReady(PathRef File,
1009 std::vector<Diag> Diagnostics) {
Eric Liu4d814a92018-11-28 10:30:42 +00001010 auto URI = URIForFile::canonicalize(File, /*TUPath=*/File);
Sam McCall16e70702018-10-24 07:59:38 +00001011 std::vector<Diagnostic> LSPDiagnostics;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001012 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001013 for (auto &Diag : Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +00001014 toLSPDiags(Diag, URI, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001015 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001016 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1017 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
1018 LSPDiagnostics.push_back(std::move(Diag));
1019 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001020 }
1021
1022 // Cache FixIts
1023 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001024 std::lock_guard<std::mutex> Lock(FixItsMutex);
1025 FixItsMap[File] = LocalFixIts;
1026 }
1027
Ilya Biryukov49c10712019-03-25 10:15:11 +00001028 // Send a notification to the LSP client.
1029 publishDiagnostics(URI, std::move(LSPDiagnostics));
Ilya Biryukov38d79772017-05-16 09:38:59 +00001030}
Simon Marchi9569fd52018-03-16 14:30:42 +00001031
Haojian Wub6188492018-12-20 15:39:12 +00001032void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1033 if (!SupportFileStatus)
1034 return;
1035 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1036 // two statuses are running faster in practice, which leads the UI constantly
1037 // changing, and doesn't provide much value. We may want to emit status at a
1038 // reasonable time interval (e.g. 0.5s).
1039 if (Status.Action.S == TUAction::BuildingFile ||
1040 Status.Action.S == TUAction::RunningAction)
1041 return;
1042 notify("textDocument/clangd.fileStatus", Status.render(File));
1043}
1044
Simon Marchi9569fd52018-03-16 14:30:42 +00001045void ClangdLSPServer::reparseOpenedFiles() {
1046 for (const Path &FilePath : DraftMgr.getActiveFiles())
Ilya Biryukov652364b2018-09-26 05:48:29 +00001047 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
1048 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001049}
Alex Lorenzf8087862018-08-01 17:39:29 +00001050
Sam McCallc008af62018-10-20 15:30:37 +00001051} // namespace clangd
1052} // namespace clang