blob: 99c2465a579c01ee5ec621b5ba7b9441fd41399b [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"
Kadir Cetinkaya35871fd2020-09-28 15:09:55 +020010#include "ClangdServer.h"
Sam McCall032727f2020-05-06 01:39:59 +020011#include "CodeComplete.h"
Ilya Biryukov71028b82018-03-12 15:28:22 +000012#include "Diagnostics.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000013#include "DraftStore.h"
Kadir Cetinkaya256247c2019-06-26 07:45:27 +000014#include "GlobalCompilationDatabase.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000015#include "Protocol.h"
Johan Vikstroma848dab2019-07-04 07:53:12 +000016#include "SemanticHighlighting.h"
Sam McCallb536a2a2017-12-19 12:23:48 +000017#include "SourceCode.h"
Kadir Cetinkaya6b850322020-03-17 19:08:23 +010018#include "TUScheduler.h"
Eric Liu78ed91a72018-01-29 15:37:46 +000019#include "URI.h"
Sam McCall395fde72019-06-18 13:37:54 +000020#include "refactor/Tweak.h"
Sam McCallad97ccf2020-04-28 17:49:17 +020021#include "support/Context.h"
Kadir Cetinkaya35871fd2020-09-28 15:09:55 +020022#include "support/MemoryTree.h"
Sam McCallad97ccf2020-04-28 17:49:17 +020023#include "support/Trace.h"
Sam McCall6f7dca92020-03-03 12:25:46 +010024#include "clang/Basic/Version.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000025#include "clang/Tooling/Core/Replacement.h"
Kadir Cetinkaya256247c2019-06-26 07:45:27 +000026#include "llvm/ADT/ArrayRef.h"
Sam McCalla69698f2019-03-27 17:47:49 +000027#include "llvm/ADT/Optional.h"
Kadir Cetinkaya689bf932018-08-24 13:09:41 +000028#include "llvm/ADT/ScopeExit.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000029#include "llvm/ADT/StringRef.h"
Utkarsh Saxena55925da2019-09-24 13:38:33 +000030#include "llvm/ADT/iterator_range.h"
Kadir Cetinkaya35871fd2020-09-28 15:09:55 +020031#include "llvm/Support/Allocator.h"
Simon Marchi9569fd52018-03-16 14:30:42 +000032#include "llvm/Support/Errc.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000033#include "llvm/Support/Error.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000034#include "llvm/Support/FormatVariadic.h"
Utkarsh Saxena55925da2019-09-24 13:38:33 +000035#include "llvm/Support/JSON.h"
Eric Liu5740ff52018-01-31 16:26:27 +000036#include "llvm/Support/Path.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000037#include "llvm/Support/SHA1.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000038#include "llvm/Support/ScopedPrinter.h"
Kadir Cetinkayad0f28742020-10-13 00:10:04 +020039#include "llvm/Support/raw_ostream.h"
Kadir Cetinkaya35871fd2020-09-28 15:09:55 +020040#include <chrono>
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000041#include <cstddef>
Kadir Cetinkayad0f28742020-10-13 00:10:04 +020042#include <cstdint>
43#include <functional>
Utkarsh Saxena55925da2019-09-24 13:38:33 +000044#include <memory>
Sam McCall7d20e802020-01-22 19:41:45 +010045#include <mutex>
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000046#include <string>
Utkarsh Saxena55925da2019-09-24 13:38:33 +000047#include <vector>
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000048
Sam McCallc008af62018-10-20 15:30:37 +000049namespace clang {
50namespace clangd {
Ilya Biryukovafb55542017-05-16 14:40:30 +000051namespace {
Sam McCall2cd33e62020-03-04 00:33:29 +010052
Kadir Cetinkayae64f99c2020-04-16 23:12:09 +020053// Tracks end-to-end latency of high level lsp calls. Measurements are in
54// seconds.
55constexpr trace::Metric LSPLatency("lsp_latency", trace::Metric::Distribution,
56 "method_name");
57
Sam McCall2cd33e62020-03-04 00:33:29 +010058// LSP defines file versions as numbers that increase.
59// ClangdServer treats them as opaque and therefore uses strings instead.
60std::string encodeVersion(int64_t LSPVersion) {
61 return llvm::to_string(LSPVersion);
62}
63llvm::Optional<int64_t> decodeVersion(llvm::StringRef Encoded) {
64 int64_t Result;
65 if (llvm::to_integer(Encoded, Result, 10))
66 return Result;
Kadir Cetinkayabceca7a2020-09-11 11:30:06 +020067 if (!Encoded.empty()) // Empty can be e.g. diagnostics on close.
Sam McCall2cd33e62020-03-04 00:33:29 +010068 elog("unexpected non-numeric version {0}", Encoded);
69 return llvm::None;
70}
71
Ilya Biryukovcce67a32019-01-29 14:17:36 +000072/// Transforms a tweak into a code action that would apply it if executed.
73/// EXPECTS: T.prepare() was called and returned true.
74CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File,
75 Range Selection) {
76 CodeAction CA;
77 CA.title = T.Title;
Sam McCall17747d22020-09-28 18:12:37 +020078 CA.kind = T.Kind.str();
Ilya Biryukovcce67a32019-01-29 14:17:36 +000079 // This tweak may have an expensive second stage, we only run it if the user
80 // actually chooses it in the UI. We reply with a command that would run the
81 // corresponding tweak.
82 // FIXME: for some tweaks, computing the edits is cheap and we could send them
83 // directly.
84 CA.command.emplace();
85 CA.command->title = T.Title;
Benjamin Krameradcd0262020-01-28 20:23:46 +010086 CA.command->command = std::string(Command::CLANGD_APPLY_TWEAK);
Ilya Biryukovcce67a32019-01-29 14:17:36 +000087 CA.command->tweakArgs.emplace();
88 CA.command->tweakArgs->file = File;
89 CA.command->tweakArgs->tweakID = T.ID;
90 CA.command->tweakArgs->selection = Selection;
91 return CA;
Simon Pilgrime9a136b2019-02-03 14:08:30 +000092}
Ilya Biryukovcce67a32019-01-29 14:17:36 +000093
Ilya Biryukov19d75602018-11-23 15:21:19 +000094void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
95 SymbolKindBitset Kinds) {
96 for (auto &S : Syms) {
97 S.kind = adjustKindToCapability(S.kind, Kinds);
98 adjustSymbolKinds(S.children, Kinds);
99 }
100}
101
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000102SymbolKindBitset defaultSymbolKinds() {
103 SymbolKindBitset Defaults;
104 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
105 ++I)
106 Defaults.set(I);
107 return Defaults;
108}
109
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +0000110CompletionItemKindBitset defaultCompletionItemKinds() {
111 CompletionItemKindBitset Defaults;
112 for (size_t I = CompletionItemKindMin;
113 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
114 Defaults.set(I);
115 return Defaults;
116}
117
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000118// Build a lookup table (HighlightingKind => {TextMate Scopes}), which is sent
119// to the LSP client.
120std::vector<std::vector<std::string>> buildHighlightScopeLookupTable() {
121 std::vector<std::vector<std::string>> LookupTable;
122 // HighlightingKind is using as the index.
Ilya Biryukov63d5d162019-09-09 08:57:17 +0000123 for (int KindValue = 0; KindValue <= (int)HighlightingKind::LastKind;
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000124 ++KindValue)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100125 LookupTable.push_back(
126 {std::string(toTextMateScope((HighlightingKind)(KindValue)))});
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000127 return LookupTable;
128}
129
Haojian Wu852bafa2019-10-23 14:40:20 +0200130// Makes sure edits in \p FE are applicable to latest file contents reported by
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000131// editor. If not generates an error message containing information about files
132// that needs to be saved.
Haojian Wu852bafa2019-10-23 14:40:20 +0200133llvm::Error validateEdits(const DraftStore &DraftMgr, const FileEdits &FE) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000134 size_t InvalidFileCount = 0;
135 llvm::StringRef LastInvalidFile;
Haojian Wu852bafa2019-10-23 14:40:20 +0200136 for (const auto &It : FE) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000137 if (auto Draft = DraftMgr.getDraft(It.first())) {
138 // If the file is open in user's editor, make sure the version we
139 // saw and current version are compatible as this is the text that
140 // will be replaced by editors.
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100141 if (!It.second.canApplyTo(Draft->Contents)) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000142 ++InvalidFileCount;
143 LastInvalidFile = It.first();
144 }
145 }
146 }
147 if (!InvalidFileCount)
148 return llvm::Error::success();
149 if (InvalidFileCount == 1)
Sam McCall30667c92020-07-08 21:49:38 +0200150 return error("File must be saved first: {0}", LastInvalidFile);
151 return error("Files must be saved first: {0} (and {1} others)",
152 LastInvalidFile, InvalidFileCount - 1);
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000153}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000154} // namespace
155
Sam McCall2c30fbc2018-10-18 12:32:04 +0000156// MessageHandler dispatches incoming LSP messages.
157// It handles cross-cutting concerns:
158// - serializes/deserializes protocol objects to JSON
159// - logging of inbound messages
160// - cancellation handling
161// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +0000162// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000163class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
164public:
165 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
166
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000167 bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000168 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000169 log("<-- {0}", Method);
170 if (Method == "exit")
171 return false;
Kadir Cetinkaya35871fd2020-09-28 15:09:55 +0200172 if (!Server.Server) {
Sam McCall3d0adbe2018-10-18 14:41:50 +0000173 elog("Notification {0} before initialization", Method);
Kadir Cetinkaya35871fd2020-09-28 15:09:55 +0200174 } else if (Method == "$/cancelRequest") {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000175 onCancel(std::move(Params));
Kadir Cetinkaya35871fd2020-09-28 15:09:55 +0200176 } else if (auto Handler = Notifications.lookup(Method)) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000177 Handler(std::move(Params));
Kadir Cetinkaya35871fd2020-09-28 15:09:55 +0200178 Server.maybeExportMemoryProfile();
179 } else {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000180 log("unhandled notification {0}", Method);
Kadir Cetinkaya35871fd2020-09-28 15:09:55 +0200181 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000182 return true;
183 }
184
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000185 bool onCall(llvm::StringRef Method, llvm::json::Value Params,
186 llvm::json::Value ID) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000187 WithContext HandlerContext(handlerContext());
Sam McCalle2f3a732018-10-24 14:26:26 +0000188 // Calls can be canceled by the client. Add cancellation context.
189 WithContext WithCancel(cancelableRequestContext(ID));
Kadir Cetinkayae64f99c2020-04-16 23:12:09 +0200190 trace::Span Tracer(Method, LSPLatency);
Sam McCalle2f3a732018-10-24 14:26:26 +0000191 SPAN_ATTACH(Tracer, "Params", Params);
192 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000193 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +0000194 if (!Server.Server && Method != "initialize") {
195 elog("Call {0} before initialization.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000196 Reply(llvm::make_error<LSPError>("server not initialized",
197 ErrorCode::ServerNotInitialized));
Sam McCall3d0adbe2018-10-18 14:41:50 +0000198 } else if (auto Handler = Calls.lookup(Method))
Sam McCalle2f3a732018-10-24 14:26:26 +0000199 Handler(std::move(Params), std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000200 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000201 Reply(llvm::make_error<LSPError>("method not found",
202 ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000203 return true;
204 }
205
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000206 bool onReply(llvm::json::Value ID,
207 llvm::Expected<llvm::json::Value> Result) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000208 WithContext HandlerContext(handlerContext());
Haojian Wuf2516342019-08-05 12:48:09 +0000209
210 Callback<llvm::json::Value> ReplyHandler = nullptr;
211 if (auto IntID = ID.getAsInteger()) {
212 std::lock_guard<std::mutex> Mutex(CallMutex);
213 // Find a corresponding callback for the request ID;
214 for (size_t Index = 0; Index < ReplyCallbacks.size(); ++Index) {
215 if (ReplyCallbacks[Index].first == *IntID) {
216 ReplyHandler = std::move(ReplyCallbacks[Index].second);
217 ReplyCallbacks.erase(ReplyCallbacks.begin() +
218 Index); // remove the entry
219 break;
220 }
221 }
222 }
223
224 if (!ReplyHandler) {
225 // No callback being found, use a default log callback.
226 ReplyHandler = [&ID](llvm::Expected<llvm::json::Value> Result) {
227 elog("received a reply with ID {0}, but there was no such call", ID);
228 if (!Result)
229 llvm::consumeError(Result.takeError());
230 };
231 }
232
233 // Log and run the reply handler.
234 if (Result) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000235 log("<-- reply({0})", ID);
Haojian Wuf2516342019-08-05 12:48:09 +0000236 ReplyHandler(std::move(Result));
237 } else {
238 auto Err = Result.takeError();
239 log("<-- reply({0}) error: {1}", ID, Err);
240 ReplyHandler(std::move(Err));
241 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000242 return true;
243 }
244
245 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000246 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000247 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000248 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000249 Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000250 ReplyOnce Reply) {
Sam McCallfa69b602020-09-24 01:14:12 +0200251 auto P = parse<Param>(RawParams, Method, "request");
252 if (!P)
253 return Reply(P.takeError());
254 (Server.*Handler)(*P, std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000255 };
256 }
257
Haojian Wuf2516342019-08-05 12:48:09 +0000258 // Bind a reply callback to a request. The callback will be invoked when
259 // clangd receives the reply from the LSP client.
260 // Return a call id of the request.
261 llvm::json::Value bindReply(Callback<llvm::json::Value> Reply) {
262 llvm::Optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB;
263 int ID;
264 {
265 std::lock_guard<std::mutex> Mutex(CallMutex);
266 ID = NextCallID++;
267 ReplyCallbacks.emplace_back(ID, std::move(Reply));
268
269 // If the queue overflows, we assume that the client didn't reply the
270 // oldest request, and run the corresponding callback which replies an
271 // error to the client.
272 if (ReplyCallbacks.size() > MaxReplayCallbacks) {
273 elog("more than {0} outstanding LSP calls, forgetting about {1}",
274 MaxReplayCallbacks, ReplyCallbacks.front().first);
275 OldestCB = std::move(ReplyCallbacks.front());
276 ReplyCallbacks.pop_front();
277 }
278 }
279 if (OldestCB)
Sam McCall30667c92020-07-08 21:49:38 +0200280 OldestCB->second(
281 error("failed to receive a client reply for request ({0})",
282 OldestCB->first));
Haojian Wuf2516342019-08-05 12:48:09 +0000283 return ID;
284 }
285
Sam McCall2c30fbc2018-10-18 12:32:04 +0000286 // Bind an LSP method name to a notification.
287 template <typename Param>
288 void bind(const char *Method,
289 void (ClangdLSPServer::*Handler)(const Param &)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000290 Notifications[Method] = [Method, Handler,
291 this](llvm::json::Value RawParams) {
Sam McCallfa69b602020-09-24 01:14:12 +0200292 llvm::Expected<Param> P = parse<Param>(RawParams, Method, "request");
293 if (!P)
294 return llvm::consumeError(P.takeError());
Kadir Cetinkayae64f99c2020-04-16 23:12:09 +0200295 trace::Span Tracer(Method, LSPLatency);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000296 SPAN_ATTACH(Tracer, "Params", RawParams);
Sam McCallfa69b602020-09-24 01:14:12 +0200297 (Server.*Handler)(*P);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000298 };
299 }
300
301private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000302 // Function object to reply to an LSP call.
303 // Each instance must be called exactly once, otherwise:
304 // - the bug is logged, and (in debug mode) an assert will fire
305 // - if there was no reply, an error reply is sent
306 // - if there were multiple replies, only the first is sent
307 class ReplyOnce {
308 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000309 std::chrono::steady_clock::time_point Start;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000310 llvm::json::Value ID;
Sam McCalle2f3a732018-10-24 14:26:26 +0000311 std::string Method;
312 ClangdLSPServer *Server; // Null when moved-from.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000313 llvm::json::Object *TraceArgs;
Sam McCalle2f3a732018-10-24 14:26:26 +0000314
315 public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000316 ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
317 ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000318 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
319 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000320 assert(Server);
321 }
322 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000323 : Replied(Other.Replied.load()), Start(Other.Start),
324 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
325 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000326 Other.Server = nullptr;
327 }
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000328 ReplyOnce &operator=(ReplyOnce &&) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000329 ReplyOnce(const ReplyOnce &) = delete;
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000330 ReplyOnce &operator=(const ReplyOnce &) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000331
332 ~ReplyOnce() {
Haojian Wuf2516342019-08-05 12:48:09 +0000333 // There's one legitimate reason to never reply to a request: clangd's
334 // request handler send a call to the client (e.g. applyEdit) and the
335 // client never replied. In this case, the ReplyOnce is owned by
336 // ClangdLSPServer's reply callback table and is destroyed along with the
337 // server. We don't attempt to send a reply in this case, there's little
338 // to be gained from doing so.
339 if (Server && !Server->IsBeingDestroyed && !Replied) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000340 elog("No reply to message {0}({1})", Method, ID);
341 assert(false && "must reply to all calls!");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000342 (*this)(llvm::make_error<LSPError>("server failed to reply",
343 ErrorCode::InternalError));
Sam McCalle2f3a732018-10-24 14:26:26 +0000344 }
345 }
346
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000347 void operator()(llvm::Expected<llvm::json::Value> Reply) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000348 assert(Server && "moved-from!");
349 if (Replied.exchange(true)) {
350 elog("Replied twice to message {0}({1})", Method, ID);
351 assert(false && "must reply to each call only once!");
352 return;
353 }
Sam McCalld7babe42018-10-24 15:18:40 +0000354 auto Duration = std::chrono::steady_clock::now() - Start;
355 if (Reply) {
356 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
357 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000358 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000359 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
360 Server->Transp.reply(std::move(ID), std::move(Reply));
361 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000362 llvm::Error Err = Reply.takeError();
Sam McCalld7babe42018-10-24 15:18:40 +0000363 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
364 if (TraceArgs)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000365 (*TraceArgs)["Error"] = llvm::to_string(Err);
Sam McCalld7babe42018-10-24 15:18:40 +0000366 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
367 Server->Transp.reply(std::move(ID), std::move(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000368 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000369 }
370 };
371
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000372 llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
373 llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000374
375 // Method calls may be cancelled by ID, so keep track of their state.
376 // This needs a mutex: handlers may finish on a different thread, and that's
377 // when we clean up entries in the map.
378 mutable std::mutex RequestCancelersMutex;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000379 llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000380 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000381 void onCancel(const llvm::json::Value &Params) {
382 const llvm::json::Value *ID = nullptr;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000383 if (auto *O = Params.getAsObject())
384 ID = O->get("id");
385 if (!ID) {
386 elog("Bad cancellation request: {0}", Params);
387 return;
388 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000389 auto StrID = llvm::to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000390 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
391 auto It = RequestCancelers.find(StrID);
392 if (It != RequestCancelers.end())
393 It->second.first(); // Invoke the canceler.
394 }
Sam McCalla69698f2019-03-27 17:47:49 +0000395
396 Context handlerContext() const {
397 return Context::current().derive(
398 kCurrentOffsetEncoding,
Sam McCall6342b382020-09-30 10:56:43 +0200399 Server.Opts.Encoding.getValueOr(OffsetEncoding::UTF16));
Sam McCalla69698f2019-03-27 17:47:49 +0000400 }
401
Sam McCall2c30fbc2018-10-18 12:32:04 +0000402 // We run cancelable requests in a context that does two things:
403 // - allows cancellation using RequestCancelers[ID]
404 // - cleans up the entry in RequestCancelers when it's no longer needed
405 // If a client reuses an ID, the last wins and the first cannot be canceled.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000406 Context cancelableRequestContext(const llvm::json::Value &ID) {
Sam McCall31db1e02020-04-11 18:19:50 +0200407 auto Task = cancelableTask(
408 /*Reason=*/static_cast<int>(ErrorCode::RequestCancelled));
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000409 auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000410 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
411 {
412 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
413 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
414 }
415 // When the request ends, we can clean up the entry we just added.
416 // The cookie lets us check that it hasn't been overwritten due to ID
417 // reuse.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000418 return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000419 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
420 auto It = RequestCancelers.find(StrID);
421 if (It != RequestCancelers.end() && It->second.second == Cookie)
422 RequestCancelers.erase(It);
423 }));
424 }
425
Kadir Cetinkaya9a3a87d2019-10-09 13:59:31 +0000426 // The maximum number of callbacks held in clangd.
427 //
428 // We bound the maximum size to the pending map to prevent memory leakage
429 // for cases where LSP clients don't reply for the request.
430 // This has to go after RequestCancellers and RequestCancellersMutex since it
431 // can contain a callback that has a cancelable context.
432 static constexpr int MaxReplayCallbacks = 100;
433 mutable std::mutex CallMutex;
434 int NextCallID = 0; /* GUARDED_BY(CallMutex) */
435 std::deque<std::pair</*RequestID*/ int,
436 /*ReplyHandler*/ Callback<llvm::json::Value>>>
437 ReplyCallbacks; /* GUARDED_BY(CallMutex) */
438
Sam McCall2c30fbc2018-10-18 12:32:04 +0000439 ClangdLSPServer &Server;
440};
Haojian Wuf2516342019-08-05 12:48:09 +0000441constexpr int ClangdLSPServer::MessageHandler::MaxReplayCallbacks;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000442
443// call(), notify(), and reply() wrap the Transport, adding logging and locking.
Haojian Wuf2516342019-08-05 12:48:09 +0000444void ClangdLSPServer::callRaw(StringRef Method, llvm::json::Value Params,
445 Callback<llvm::json::Value> CB) {
446 auto ID = MsgHandler->bindReply(std::move(CB));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000447 log("--> {0}({1})", Method, ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000448 std::lock_guard<std::mutex> Lock(TranspWriter);
449 Transp.call(Method, std::move(Params), ID);
450}
451
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000452void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000453 log("--> {0}", Method);
454 std::lock_guard<std::mutex> Lock(TranspWriter);
455 Transp.notify(Method, std::move(Params));
456}
457
Sam McCall71177ac2020-03-24 02:24:47 +0100458static std::vector<llvm::StringRef> semanticTokenTypes() {
459 std::vector<llvm::StringRef> Types;
460 for (unsigned I = 0; I <= static_cast<unsigned>(HighlightingKind::LastKind);
461 ++I)
462 Types.push_back(toSemanticTokenType(static_cast<HighlightingKind>(I)));
463 return Types;
464}
465
Sam McCall2c30fbc2018-10-18 12:32:04 +0000466void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000467 Callback<llvm::json::Value> Reply) {
Sam McCalla69698f2019-03-27 17:47:49 +0000468 // Determine character encoding first as it affects constructed ClangdServer.
Sam McCall6342b382020-09-30 10:56:43 +0200469 if (Params.capabilities.offsetEncoding && !Opts.Encoding) {
470 Opts.Encoding = OffsetEncoding::UTF16; // fallback
Sam McCalla69698f2019-03-27 17:47:49 +0000471 for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
472 if (Supported != OffsetEncoding::UnsupportedEncoding) {
Sam McCall6342b382020-09-30 10:56:43 +0200473 Opts.Encoding = Supported;
Sam McCalla69698f2019-03-27 17:47:49 +0000474 break;
475 }
476 }
Sam McCalla69698f2019-03-27 17:47:49 +0000477
Sam McCall7ba07792020-09-29 10:37:46 +0200478 Opts.TheiaSemanticHighlighting =
Sam McCalledf6a192020-03-24 00:31:14 +0100479 Params.capabilities.TheiaSemanticHighlighting;
Sam McCallfc830102020-04-01 12:02:28 +0200480 if (Params.capabilities.TheiaSemanticHighlighting &&
481 Params.capabilities.SemanticTokens) {
482 log("Client supports legacy semanticHighlights notification and standard "
483 "semanticTokens request, choosing the latter (no notifications).");
Sam McCall7ba07792020-09-29 10:37:46 +0200484 Opts.TheiaSemanticHighlighting = false;
Sam McCallfc830102020-04-01 12:02:28 +0200485 }
486
Sam McCall0d9b40f2018-10-19 15:42:23 +0000487 if (Params.rootUri && *Params.rootUri)
Sam McCall7ba07792020-09-29 10:37:46 +0200488 Opts.WorkspaceRoot = std::string(Params.rootUri->file());
Sam McCall0d9b40f2018-10-19 15:42:23 +0000489 else if (Params.rootPath && !Params.rootPath->empty())
Sam McCall7ba07792020-09-29 10:37:46 +0200490 Opts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000491 if (Server)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000492 return Reply(llvm::make_error<LSPError>("server already initialized",
493 ErrorCode::InvalidRequest));
Sam McCallbc904612018-10-25 04:22:52 +0000494 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
Sam McCall7ba07792020-09-29 10:37:46 +0200495 Opts.CompileCommandsDir = Dir;
496 if (Opts.UseDirBasedCDB) {
Jonas Devlieghere1c705d92019-08-14 23:52:23 +0000497 BaseCDB = std::make_unique<DirectoryBasedGlobalCompilationDatabase>(
Sam McCall7ba07792020-09-29 10:37:46 +0200498 Opts.CompileCommandsDir);
499 BaseCDB = getQueryDriverDatabase(llvm::makeArrayRef(Opts.QueryDriverGlobs),
500 std::move(BaseCDB));
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000501 }
Sam McCall99768b22019-11-29 19:37:48 +0100502 auto Mangler = CommandMangler::detect();
Sam McCall7ba07792020-09-29 10:37:46 +0200503 if (Opts.ResourceDir)
504 Mangler.ResourceDir = *Opts.ResourceDir;
Kadir Cetinkayabe6b35d2019-01-22 09:10:20 +0000505 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
Sam McCall2a3ac012020-06-09 22:54:42 +0200506 tooling::ArgumentsAdjuster(std::move(Mangler)));
Kadir Cetinkaya9d662472019-10-15 14:20:52 +0000507 {
508 // Switch caller's context with LSPServer's background context. Since we
509 // rather want to propagate information from LSPServer's context into the
510 // Server, CDB, etc.
511 WithContext MainContext(BackgroundContext.clone());
512 llvm::Optional<WithContextValue> WithOffsetEncoding;
Sam McCall6342b382020-09-30 10:56:43 +0200513 if (Opts.Encoding)
514 WithOffsetEncoding.emplace(kCurrentOffsetEncoding, *Opts.Encoding);
Sam McCall7ba07792020-09-29 10:37:46 +0200515 Server.emplace(*CDB, TFS, Opts,
Sam McCall6ef1cce2020-01-24 14:08:56 +0100516 static_cast<ClangdServer::Callbacks *>(this));
Kadir Cetinkaya9d662472019-10-15 14:20:52 +0000517 }
Sam McCallbc904612018-10-25 04:22:52 +0000518 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000519
Sam McCall7ba07792020-09-29 10:37:46 +0200520 Opts.CodeComplete.EnableSnippets = Params.capabilities.CompletionSnippets;
521 Opts.CodeComplete.IncludeFixIts = Params.capabilities.CompletionFixes;
522 if (!Opts.CodeComplete.BundleOverloads.hasValue())
523 Opts.CodeComplete.BundleOverloads = Params.capabilities.HasSignatureHelp;
524 Opts.CodeComplete.DocumentationFormat =
Sam McCalla3a27a72020-04-30 10:49:32 +0200525 Params.capabilities.CompletionDocumentationFormat;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000526 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
527 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
Sam McCallc9e4ee92019-04-18 15:17:07 +0000528 DiagOpts.EmitRelatedLocations =
529 Params.capabilities.DiagnosticRelatedInformation;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000530 if (Params.capabilities.WorkspaceSymbolKinds)
531 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
532 if (Params.capabilities.CompletionItemKinds)
533 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
534 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000535 SupportsHierarchicalDocumentSymbol =
536 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000537 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000538 HoverContentFormat = Params.capabilities.HoverContentFormat;
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000539 SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
Sam McCall7d20e802020-01-22 19:41:45 +0100540 if (Params.capabilities.WorkDoneProgress)
541 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
542 BackgroundIndexSkipCreate = Params.capabilities.ImplicitProgressCreation;
Haojian Wuf429ab62019-07-24 07:49:23 +0000543
544 // Per LSP, renameProvider can be either boolean or RenameOptions.
545 // RenameOptions will be specified if the client states it supports prepare.
546 llvm::json::Value RenameProvider =
547 llvm::json::Object{{"prepareProvider", true}};
548 if (!Params.capabilities.RenamePrepareSupport) // Only boolean allowed per LSP
549 RenameProvider = true;
550
Haojian Wu08d93f12019-08-22 14:53:45 +0000551 // Per LSP, codeActionProvide can be either boolean or CodeActionOptions.
552 // CodeActionOptions is only valid if the client supports action literal
553 // via textDocument.codeAction.codeActionLiteralSupport.
554 llvm::json::Value CodeActionProvider = true;
555 if (Params.capabilities.CodeActionStructure)
556 CodeActionProvider = llvm::json::Object{
557 {"codeActionKinds",
558 {CodeAction::QUICKFIX_KIND, CodeAction::REFACTOR_KIND,
559 CodeAction::INFO_KIND}}};
560
Sam McCalla69698f2019-03-27 17:47:49 +0000561 llvm::json::Object Result{
Sam McCall6f7dca92020-03-03 12:25:46 +0100562 {{"serverInfo",
563 llvm::json::Object{{"name", "clangd"},
564 {"version", getClangToolFullVersion("clangd")}}},
565 {"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000566 llvm::json::Object{
Sam McCall596b63a2020-04-10 03:27:37 +0200567 {"textDocumentSync",
568 llvm::json::Object{
569 {"openClose", true},
570 {"change", (int)TextDocumentSyncKind::Incremental},
571 {"save", true},
572 }},
Sam McCall0930ab02017-11-07 15:49:35 +0000573 {"documentFormattingProvider", true},
574 {"documentRangeFormattingProvider", true},
575 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000576 llvm::json::Object{
Sam McCall25c62572019-06-10 14:26:21 +0000577 {"firstTriggerCharacter", "\n"},
Sam McCall0930ab02017-11-07 15:49:35 +0000578 {"moreTriggerCharacter", {}},
579 }},
Haojian Wu08d93f12019-08-22 14:53:45 +0000580 {"codeActionProvider", std::move(CodeActionProvider)},
Sam McCall0930ab02017-11-07 15:49:35 +0000581 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000582 llvm::json::Object{
Kirill Bobyrev9d11e672020-08-26 17:08:00 +0200583 {"allCommitCharacters",
584 {" ", "\t", "(", ")", "[", "]", "{", "}", "<",
585 ">", ":", ";", ",", "+", "-", "/", "*", "%",
586 "^", "&", "#", "?", ".", "=", "\"", "'", "|"}},
Sam McCall0930ab02017-11-07 15:49:35 +0000587 {"resolveProvider", false},
Sam McCall032727f2020-05-06 01:39:59 +0200588 // We do extra checks, e.g. that > is part of ->.
589 {"triggerCharacters", {".", "<", ">", ":", "\"", "/"}},
Sam McCall0930ab02017-11-07 15:49:35 +0000590 }},
Sam McCall71177ac2020-03-24 02:24:47 +0100591 {"semanticTokensProvider",
592 llvm::json::Object{
Sam McCall5fea54b2020-07-10 16:08:14 +0200593 {"full", llvm::json::Object{{"delta", true}}},
594 {"range", false},
Sam McCall71177ac2020-03-24 02:24:47 +0100595 {"legend",
596 llvm::json::Object{{"tokenTypes", semanticTokenTypes()},
597 {"tokenModifiers", llvm::json::Array()}}},
598 }},
Sam McCall0930ab02017-11-07 15:49:35 +0000599 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000600 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000601 {"triggerCharacters", {"(", ","}},
602 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000603 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000604 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000605 {"documentHighlightProvider", true},
Sam McCall8d7ecc12019-12-16 19:08:51 +0100606 {"documentLinkProvider",
607 llvm::json::Object{
608 {"resolveProvider", false},
609 }},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000610 {"hoverProvider", true},
Haojian Wuf429ab62019-07-24 07:49:23 +0000611 {"renameProvider", std::move(RenameProvider)},
Utkarsh Saxena55925da2019-09-24 13:38:33 +0000612 {"selectionRangeProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000613 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000614 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000615 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000616 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000617 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000618 {"commands",
619 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
620 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000621 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000622 {"typeHierarchyProvider", true},
Kadir Cetinkayad0f28742020-10-13 00:10:04 +0200623 {"memoryUsageProvider", true}, // clangd extension.
Sam McCalla69698f2019-03-27 17:47:49 +0000624 }}}};
Sam McCall6342b382020-09-30 10:56:43 +0200625 if (Opts.Encoding)
626 Result["offsetEncoding"] = *Opts.Encoding;
Sam McCall7ba07792020-09-29 10:37:46 +0200627 if (Opts.TheiaSemanticHighlighting)
Johan Vikstroma848dab2019-07-04 07:53:12 +0000628 Result.getObject("capabilities")
629 ->insert(
630 {"semanticHighlighting",
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000631 llvm::json::Object{{"scopes", buildHighlightScopeLookupTable()}}});
Sam McCall7ba07792020-09-29 10:37:46 +0200632 if (Opts.FoldingRanges)
Kirill Bobyrev7a514c92020-07-14 09:28:38 +0200633 Result.getObject("capabilities")->insert({"foldingRangeProvider", true});
Sam McCalla69698f2019-03-27 17:47:49 +0000634 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000635}
636
Sam McCall8a2d2942020-03-03 12:12:14 +0100637void ClangdLSPServer::onInitialized(const InitializedParams &Params) {}
638
Sam McCall2c30fbc2018-10-18 12:32:04 +0000639void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
640 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000641 // Do essentially nothing, just say we're ready to exit.
642 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000643 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000644}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000645
Sam McCall422c8282018-11-26 16:00:11 +0000646// sync is a clangd extension: it blocks until all background work completes.
647// It blocks the calling thread, so no messages are processed until it returns!
648void ClangdLSPServer::onSync(const NoParams &Params,
649 Callback<std::nullptr_t> Reply) {
650 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
651 Reply(nullptr);
652 else
Sam McCall30667c92020-07-08 21:49:38 +0200653 Reply(error("Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000654}
655
Sam McCall2c30fbc2018-10-18 12:32:04 +0000656void ClangdLSPServer::onDocumentDidOpen(
657 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000658 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000659
Sam McCall2c30fbc2018-10-18 12:32:04 +0000660 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000661
Sam McCall2cd33e62020-03-04 00:33:29 +0100662 auto Version = DraftMgr.addDraft(File, Params.textDocument.version, Contents);
663 Server->addDocument(File, Contents, encodeVersion(Version),
664 WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000665}
666
Sam McCall2c30fbc2018-10-18 12:32:04 +0000667void ClangdLSPServer::onDocumentDidChange(
668 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000669 auto WantDiags = WantDiagnostics::Auto;
670 if (Params.wantDiagnostics.hasValue())
671 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
672 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000673
674 PathRef File = Params.textDocument.uri.file();
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100675 llvm::Expected<DraftStore::Draft> Draft = DraftMgr.updateDraft(
676 File, Params.textDocument.version, Params.contentChanges);
677 if (!Draft) {
Simon Marchi98082622018-03-26 14:41:40 +0000678 // If this fails, we are most likely going to be not in sync anymore with
679 // the client. It is better to remove the draft and let further operations
680 // fail rather than giving wrong results.
681 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000682 Server->removeDocument(File);
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100683 elog("Failed to update {0}: {1}", File, Draft.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000684 return;
685 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000686
Sam McCall2cd33e62020-03-04 00:33:29 +0100687 Server->addDocument(File, Draft->Contents, encodeVersion(Draft->Version),
688 WantDiags, Params.forceRebuild);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000689}
690
Sam McCall596b63a2020-04-10 03:27:37 +0200691void ClangdLSPServer::onDocumentDidSave(
692 const DidSaveTextDocumentParams &Params) {
693 reparseOpenFilesIfNeeded([](llvm::StringRef) { return true; });
694}
695
Sam McCall2c30fbc2018-10-18 12:32:04 +0000696void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Sam McCall596b63a2020-04-10 03:27:37 +0200697 // We could also reparse all open files here. However:
698 // - this could be frequent, and revalidating all the preambles isn't free
699 // - this is useful e.g. when switching git branches, but we're likely to see
700 // fresh headers but still have the old-branch main-file content
Ilya Biryukov652364b2018-09-26 05:48:29 +0000701 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000702}
703
Sam McCall2c30fbc2018-10-18 12:32:04 +0000704void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000705 Callback<llvm::json::Value> Reply) {
Ilya Biryukov12864002019-08-16 12:46:41 +0000706 auto ApplyEdit = [this](WorkspaceEdit WE, std::string SuccessMessage,
707 decltype(Reply) Reply) {
Eric Liuc5105f92018-02-16 14:15:55 +0000708 ApplyWorkspaceEditParams Edit;
709 Edit.edit = std::move(WE);
Ilya Biryukov12864002019-08-16 12:46:41 +0000710 call<ApplyWorkspaceEditResponse>(
711 "workspace/applyEdit", std::move(Edit),
712 [Reply = std::move(Reply), SuccessMessage = std::move(SuccessMessage)](
713 llvm::Expected<ApplyWorkspaceEditResponse> Response) mutable {
714 if (!Response)
715 return Reply(Response.takeError());
716 if (!Response->applied) {
717 std::string Reason = Response->failureReason
718 ? *Response->failureReason
719 : "unknown reason";
Sam McCall30667c92020-07-08 21:49:38 +0200720 return Reply(error("edits were not applied: {0}", Reason));
Ilya Biryukov12864002019-08-16 12:46:41 +0000721 }
722 return Reply(SuccessMessage);
723 });
Eric Liuc5105f92018-02-16 14:15:55 +0000724 };
Ilya Biryukov12864002019-08-16 12:46:41 +0000725
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000726 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
727 Params.workspaceEdit) {
728 // The flow for "apply-fix" :
729 // 1. We publish a diagnostic, including fixits
730 // 2. The user clicks on the diagnostic, the editor asks us for code actions
731 // 3. We send code actions, with the fixit embedded as context
732 // 4. The user selects the fixit, the editor asks us to apply it
733 // 5. We unwrap the changes and send them back to the editor
Haojian Wuf2516342019-08-05 12:48:09 +0000734 // 6. The editor applies the changes (applyEdit), and sends us a reply
735 // 7. We unwrap the reply and send a reply to the editor.
Ilya Biryukov12864002019-08-16 12:46:41 +0000736 ApplyEdit(*Params.workspaceEdit, "Fix applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000737 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
738 Params.tweakArgs) {
739 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
740 if (!Code)
Sam McCall30667c92020-07-08 21:49:38 +0200741 return Reply(error("trying to apply a code action for a non-added file"));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000742
Ilya Biryukov12864002019-08-16 12:46:41 +0000743 auto Action = [this, ApplyEdit, Reply = std::move(Reply),
744 File = Params.tweakArgs->file, Code = std::move(*Code)](
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000745 llvm::Expected<Tweak::Effect> R) mutable {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000746 if (!R)
747 return Reply(R.takeError());
748
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000749 assert(R->ShowMessage ||
750 (!R->ApplyEdits.empty() && "tweak has no effect"));
Ilya Biryukov12864002019-08-16 12:46:41 +0000751
Sam McCall395fde72019-06-18 13:37:54 +0000752 if (R->ShowMessage) {
753 ShowMessageParams Msg;
754 Msg.message = *R->ShowMessage;
755 Msg.type = MessageType::Info;
756 notify("window/showMessage", Msg);
757 }
Ilya Biryukov12864002019-08-16 12:46:41 +0000758 // When no edit is specified, make sure we Reply().
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000759 if (R->ApplyEdits.empty())
760 return Reply("Tweak applied.");
761
Haojian Wu852bafa2019-10-23 14:40:20 +0200762 if (auto Err = validateEdits(DraftMgr, R->ApplyEdits))
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000763 return Reply(std::move(Err));
764
765 WorkspaceEdit WE;
766 WE.changes.emplace();
767 for (const auto &It : R->ApplyEdits) {
Kadir Cetinkayae95e5162019-10-02 09:12:01 +0000768 (*WE.changes)[URI::createFile(It.first()).toString()] =
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000769 It.second.asTextEdits();
770 }
771 // ApplyEdit will take care of calling Reply().
772 return ApplyEdit(std::move(WE), "Tweak applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000773 };
774 Server->applyTweak(Params.tweakArgs->file.file(),
775 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000776 std::move(Action));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000777 } else {
778 // We should not get here because ExecuteCommandParams would not have
779 // parsed in the first place and this handler should not be called. But if
780 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000781 Reply(llvm::make_error<LSPError>(
782 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000783 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000784 }
785}
786
Sam McCall2c30fbc2018-10-18 12:32:04 +0000787void ClangdLSPServer::onWorkspaceSymbol(
788 const WorkspaceSymbolParams &Params,
789 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000790 Server->workspaceSymbols(
Sam McCall7ba07792020-09-29 10:37:46 +0200791 Params.query, Opts.CodeComplete.Limit,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000792 [Reply = std::move(Reply),
793 this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable {
794 if (!Items)
795 return Reply(Items.takeError());
796 for (auto &Sym : *Items)
797 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000798
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000799 Reply(std::move(*Items));
800 });
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000801}
802
Haojian Wuf429ab62019-07-24 07:49:23 +0000803void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params,
804 Callback<llvm::Optional<Range>> Reply) {
Haojian Wu0f0cbcc2020-10-02 16:01:25 +0200805 Server->prepareRename(
Haojian Wu9c09e202020-10-07 21:16:45 +0200806 Params.textDocument.uri.file(), Params.position, /*NewName*/ llvm::None,
807 Opts.Rename,
Haojian Wu0f0cbcc2020-10-02 16:01:25 +0200808 [Reply = std::move(Reply)](llvm::Expected<RenameResult> Result) mutable {
809 if (!Result)
810 return Reply(Result.takeError());
811 return Reply(std::move(Result->Target));
812 });
Haojian Wuf429ab62019-07-24 07:49:23 +0000813}
814
Sam McCall2c30fbc2018-10-18 12:32:04 +0000815void ClangdLSPServer::onRename(const RenameParams &Params,
816 Callback<WorkspaceEdit> Reply) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100817 Path File = std::string(Params.textDocument.uri.file());
Sam McCallcaf5a4d2020-03-03 15:57:39 +0100818 if (!DraftMgr.getDraft(File))
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000819 return Reply(llvm::make_error<LSPError>(
820 "onRename called for non-added file", ErrorCode::InvalidParams));
Haojian Wu852bafa2019-10-23 14:40:20 +0200821 Server->rename(
Sam McCall7ba07792020-09-29 10:37:46 +0200822 File, Params.position, Params.newName, Opts.Rename,
Haojian Wu852bafa2019-10-23 14:40:20 +0200823 [File, Params, Reply = std::move(Reply),
Haojian Wu0f0cbcc2020-10-02 16:01:25 +0200824 this](llvm::Expected<RenameResult> R) mutable {
825 if (!R)
826 return Reply(R.takeError());
827 if (auto Err = validateEdits(DraftMgr, R->GlobalChanges))
Haojian Wu852bafa2019-10-23 14:40:20 +0200828 return Reply(std::move(Err));
829 WorkspaceEdit Result;
830 Result.changes.emplace();
Haojian Wu0f0cbcc2020-10-02 16:01:25 +0200831 for (const auto &Rep : R->GlobalChanges) {
Haojian Wu852bafa2019-10-23 14:40:20 +0200832 (*Result.changes)[URI::createFile(Rep.first()).toString()] =
833 Rep.second.asTextEdits();
834 }
835 Reply(Result);
836 });
Haojian Wu345099c2017-11-09 11:30:04 +0000837}
838
Sam McCall2c30fbc2018-10-18 12:32:04 +0000839void ClangdLSPServer::onDocumentDidClose(
840 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000841 PathRef File = Params.textDocument.uri.file();
842 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000843 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000844
845 {
846 std::lock_guard<std::mutex> Lock(FixItsMutex);
847 FixItsMap.erase(File);
848 }
Johan Vikstromc2653ef22019-08-01 08:08:44 +0000849 {
850 std::lock_guard<std::mutex> HLock(HighlightingsMutex);
851 FileToHighlightings.erase(File);
852 }
Sam McCall9e3063e2020-04-01 16:21:44 +0200853 {
854 std::lock_guard<std::mutex> HLock(SemanticTokensMutex);
855 LastSemanticTokens.erase(File);
856 }
Ilya Biryukov49c10712019-03-25 10:15:11 +0000857 // clangd will not send updates for this file anymore, so we empty out the
858 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
859 // VSCode). Note that this cannot race with actual diagnostics responses
860 // because removeDocument() guarantees no diagnostic callbacks will be
861 // executed after it returns.
Sam McCall6525a6b2020-03-03 12:44:40 +0100862 PublishDiagnosticsParams Notification;
863 Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File);
864 publishDiagnostics(Notification);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000865}
866
Sam McCall4db732a2017-09-30 10:08:52 +0000867void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000868 const DocumentOnTypeFormattingParams &Params,
869 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000870 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000871 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000872 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000873 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000874 "onDocumentOnTypeFormatting called for non-added file",
875 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000876
Sam McCallffa63dd2020-06-26 12:57:29 +0200877 Server->formatOnType(File, Code->Contents, Params.position, Params.ch,
878 std::move(Reply));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000879}
880
Sam McCall4db732a2017-09-30 10:08:52 +0000881void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000882 const DocumentRangeFormattingParams &Params,
883 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000884 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000885 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000886 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000887 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000888 "onDocumentRangeFormatting called for non-added file",
889 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000890
Sam McCallffa63dd2020-06-26 12:57:29 +0200891 Server->formatRange(
892 File, Code->Contents, Params.range,
893 [Code = Code->Contents, Reply = std::move(Reply)](
894 llvm::Expected<tooling::Replacements> Result) mutable {
895 if (Result)
896 Reply(replacementsToEdits(Code, Result.get()));
897 else
898 Reply(Result.takeError());
899 });
Ilya Biryukovafb55542017-05-16 14:40:30 +0000900}
901
Sam McCall2c30fbc2018-10-18 12:32:04 +0000902void ClangdLSPServer::onDocumentFormatting(
903 const DocumentFormattingParams &Params,
904 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000905 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000906 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000907 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000908 return Reply(llvm::make_error<LSPError>(
909 "onDocumentFormatting called for non-added file",
910 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000911
Sam McCallffa63dd2020-06-26 12:57:29 +0200912 Server->formatFile(File, Code->Contents,
913 [Code = Code->Contents, Reply = std::move(Reply)](
914 llvm::Expected<tooling::Replacements> Result) mutable {
915 if (Result)
916 Reply(replacementsToEdits(Code, Result.get()));
917 else
918 Reply(Result.takeError());
919 });
Sam McCall4db732a2017-09-30 10:08:52 +0000920}
921
Ilya Biryukov19d75602018-11-23 15:21:19 +0000922/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
923/// Used by the clients that do not support the hierarchical view.
924static std::vector<SymbolInformation>
925flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
926 const URIForFile &FileURI) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000927 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000928 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
929 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000930 SymbolInformation SI;
Benjamin Krameradcd0262020-01-28 20:23:46 +0100931 SI.containerName = std::string(ParentName ? "" : *ParentName);
Ilya Biryukov19d75602018-11-23 15:21:19 +0000932 SI.name = S.name;
933 SI.kind = S.kind;
934 SI.location.range = S.range;
935 SI.location.uri = FileURI;
936
937 Results.push_back(std::move(SI));
938 std::string FullName =
939 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
940 for (auto &C : S.children)
941 Process(C, /*ParentName=*/FullName);
942 };
943 for (auto &S : Symbols)
944 Process(S, /*ParentName=*/"");
945 return Results;
946}
947
948void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000949 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000950 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000951 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000952 Params.textDocument.uri.file(),
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000953 [this, FileURI, Reply = std::move(Reply)](
954 llvm::Expected<std::vector<DocumentSymbol>> Items) mutable {
955 if (!Items)
956 return Reply(Items.takeError());
957 adjustSymbolKinds(*Items, SupportedSymbolKinds);
958 if (SupportsHierarchicalDocumentSymbol)
959 return Reply(std::move(*Items));
960 else
961 return Reply(flattenSymbolHierarchy(*Items, FileURI));
962 });
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000963}
964
Kirill Bobyrev7a514c92020-07-14 09:28:38 +0200965void ClangdLSPServer::onFoldingRange(
966 const FoldingRangeParams &Params,
967 Callback<std::vector<FoldingRange>> Reply) {
968 Server->foldingRanges(Params.textDocument.uri.file(), std::move(Reply));
969}
970
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000971static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000972 Command Cmd;
973 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000974 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000975 if (Action.command) {
976 Cmd = *Action.command;
977 } else if (Action.edit) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100978 Cmd.command = std::string(Command::CLANGD_APPLY_FIX_COMMAND);
Sam McCall20841d42018-10-16 16:29:41 +0000979 Cmd.workspaceEdit = *Action.edit;
980 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000981 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000982 }
983 Cmd.title = Action.title;
984 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
985 Cmd.title = "Apply fix: " + Cmd.title;
986 return Cmd;
987}
988
Sam McCall2c30fbc2018-10-18 12:32:04 +0000989void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000990 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000991 URIForFile File = Params.textDocument.uri;
992 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000993 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000994 return Reply(llvm::make_error<LSPError>(
995 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000996 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000997 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000998 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000999 for (auto &F : getFixes(File.file(), D)) {
1000 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
1001 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +00001002 }
Ilya Biryukovafb55542017-05-16 14:40:30 +00001003 }
Sam McCall20841d42018-10-16 16:29:41 +00001004
Ilya Biryukovcce67a32019-01-29 14:17:36 +00001005 // Now enumerate the semantic code actions.
1006 auto ConsumeActions =
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001007 [Reply = std::move(Reply), File, Code = std::move(*Code),
1008 Selection = Params.range, FixIts = std::move(FixIts), this](
1009 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +00001010 if (!Tweaks)
1011 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +00001012
1013 std::vector<CodeAction> Actions = std::move(FixIts);
1014 Actions.reserve(Actions.size() + Tweaks->size());
1015 for (const auto &T : *Tweaks)
1016 Actions.push_back(toCodeAction(T, File, Selection));
1017
Sam McCall83926852020-09-29 16:28:50 +02001018 // If there's exactly one quick-fix, call it "preferred".
1019 // We never consider refactorings etc as preferred.
1020 CodeAction *OnlyFix = nullptr;
1021 for (auto &Action : Actions) {
1022 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND) {
1023 if (OnlyFix) {
1024 OnlyFix->isPreferred = false;
1025 break;
1026 }
1027 Action.isPreferred = true;
1028 OnlyFix = &Action;
1029 }
1030 }
1031
Ilya Biryukovcce67a32019-01-29 14:17:36 +00001032 if (SupportsCodeAction)
1033 return Reply(llvm::json::Array(Actions));
1034 std::vector<Command> Commands;
1035 for (const auto &Action : Actions) {
1036 if (auto Command = asCommand(Action))
1037 Commands.push_back(std::move(*Command));
1038 }
1039 return Reply(llvm::json::Array(Commands));
1040 };
1041
Sam McCall7530b252020-10-02 11:34:40 +02001042 Server->enumerateTweaks(
1043 File.file(), Params.range,
1044 [&](const Tweak &T) {
1045 if (!Opts.TweakFilter(T))
1046 return false;
1047 // FIXME: also consider CodeActionContext.only
1048 return true;
1049 },
1050 std::move(ConsumeActions));
Ilya Biryukovafb55542017-05-16 14:40:30 +00001051}
1052
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001053void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +00001054 Callback<CompletionList> Reply) {
Ilya Biryukova7a11472019-06-07 16:24:38 +00001055 if (!shouldRunCompletion(Params)) {
1056 // Clients sometimes auto-trigger completions in undesired places (e.g.
1057 // 'a >^ '), we return empty results in those cases.
1058 vlog("ignored auto-triggered completion, preceding char did not match");
1059 return Reply(CompletionList());
1060 }
Kadir Cetinkaya94076862020-10-12 14:24:05 +02001061 Server->codeComplete(
1062 Params.textDocument.uri.file(), Params.position, Opts.CodeComplete,
1063 [Reply = std::move(Reply),
1064 this](llvm::Expected<CodeCompleteResult> List) mutable {
1065 if (!List)
1066 return Reply(List.takeError());
1067 CompletionList LSPList;
1068 LSPList.isIncomplete = List->HasMore;
1069 for (const auto &R : List->Completions) {
1070 CompletionItem C = R.render(Opts.CodeComplete);
1071 C.kind = adjustKindToCapability(C.kind, SupportedCompletionItemKinds);
1072 LSPList.items.push_back(std::move(C));
1073 }
1074 return Reply(std::move(LSPList));
1075 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +00001076}
1077
Sam McCall2c30fbc2018-10-18 12:32:04 +00001078void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
1079 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001080 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001081 [Reply = std::move(Reply), this](
1082 llvm::Expected<SignatureHelp> Signature) mutable {
1083 if (!Signature)
1084 return Reply(Signature.takeError());
1085 if (SupportsOffsetsInSignatureHelp)
1086 return Reply(std::move(*Signature));
1087 // Strip out the offsets from signature help for
1088 // clients that only support string labels.
1089 for (auto &SigInfo : Signature->signatures) {
1090 for (auto &Param : SigInfo.parameters)
1091 Param.labelOffsets.reset();
1092 }
1093 return Reply(std::move(*Signature));
1094 });
Ilya Biryukov652364b2018-09-26 05:48:29 +00001095}
1096
Sam McCall0dbab7f2019-02-02 05:56:00 +00001097// Go to definition has a toggle function: if def and decl are distinct, then
1098// the first press gives you the def, the second gives you the matching def.
1099// getToggle() returns the counterpart location that under the cursor.
1100//
1101// We return the toggled location alone (ignoring other symbols) to encourage
1102// editors to "bounce" quickly between locations, without showing a menu.
1103static Location *getToggle(const TextDocumentPositionParams &Point,
1104 LocatedSymbol &Sym) {
1105 // Toggle only makes sense with two distinct locations.
1106 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
1107 return nullptr;
1108 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
1109 Sym.Definition->range.contains(Point.position))
1110 return &Sym.PreferredDeclaration;
1111 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
1112 Sym.PreferredDeclaration.range.contains(Point.position))
1113 return &*Sym.Definition;
1114 return nullptr;
1115}
1116
Sam McCall2c30fbc2018-10-18 12:32:04 +00001117void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
1118 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +00001119 Server->locateSymbolAt(
1120 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001121 [Params, Reply = std::move(Reply)](
1122 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1123 if (!Symbols)
1124 return Reply(Symbols.takeError());
1125 std::vector<Location> Defs;
1126 for (auto &S : *Symbols) {
1127 if (Location *Toggle = getToggle(Params, S))
1128 return Reply(std::vector<Location>{std::move(*Toggle)});
1129 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
1130 }
1131 Reply(std::move(Defs));
1132 });
Sam McCall866ba2c2019-02-01 11:26:13 +00001133}
1134
1135void ClangdLSPServer::onGoToDeclaration(
1136 const TextDocumentPositionParams &Params,
1137 Callback<std::vector<Location>> Reply) {
1138 Server->locateSymbolAt(
1139 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001140 [Params, Reply = std::move(Reply)](
1141 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1142 if (!Symbols)
1143 return Reply(Symbols.takeError());
1144 std::vector<Location> Decls;
1145 for (auto &S : *Symbols) {
1146 if (Location *Toggle = getToggle(Params, S))
1147 return Reply(std::vector<Location>{std::move(*Toggle)});
1148 Decls.push_back(std::move(S.PreferredDeclaration));
1149 }
1150 Reply(std::move(Decls));
1151 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001152}
1153
Sam McCall111fe842019-05-07 07:55:35 +00001154void ClangdLSPServer::onSwitchSourceHeader(
1155 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +00001156 Callback<llvm::Optional<URIForFile>> Reply) {
Haojian Wud6d5edd2019-10-01 10:21:15 +00001157 Server->switchSourceHeader(
1158 Params.uri.file(),
1159 [Reply = std::move(Reply),
1160 Params](llvm::Expected<llvm::Optional<clangd::Path>> Path) mutable {
1161 if (!Path)
1162 return Reply(Path.takeError());
1163 if (*Path)
Haojian Wu77c97002019-10-07 11:37:25 +00001164 return Reply(URIForFile::canonicalize(**Path, Params.uri.file()));
Haojian Wud6d5edd2019-10-01 10:21:15 +00001165 return Reply(llvm::None);
1166 });
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +00001167}
1168
Sam McCall2c30fbc2018-10-18 12:32:04 +00001169void ClangdLSPServer::onDocumentHighlight(
1170 const TextDocumentPositionParams &Params,
1171 Callback<std::vector<DocumentHighlight>> Reply) {
1172 Server->findDocumentHighlights(Params.textDocument.uri.file(),
1173 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +00001174}
1175
Sam McCall2c30fbc2018-10-18 12:32:04 +00001176void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001177 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001178 Server->findHover(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001179 [Reply = std::move(Reply), this](
1180 llvm::Expected<llvm::Optional<HoverInfo>> H) mutable {
1181 if (!H)
1182 return Reply(H.takeError());
1183 if (!*H)
1184 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +00001185
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001186 Hover R;
1187 R.contents.kind = HoverContentFormat;
1188 R.range = (*H)->SymRange;
1189 switch (HoverContentFormat) {
1190 case MarkupKind::PlainText:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001191 R.contents.value = (*H)->present().asPlainText();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001192 return Reply(std::move(R));
1193 case MarkupKind::Markdown:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001194 R.contents.value = (*H)->present().asMarkdown();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001195 return Reply(std::move(R));
1196 };
1197 llvm_unreachable("unhandled MarkupKind");
1198 });
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +00001199}
1200
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001201void ClangdLSPServer::onTypeHierarchy(
1202 const TypeHierarchyParams &Params,
1203 Callback<Optional<TypeHierarchyItem>> Reply) {
1204 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
1205 Params.resolve, Params.direction, std::move(Reply));
1206}
1207
Nathan Ridge087b0442019-07-13 03:24:48 +00001208void ClangdLSPServer::onResolveTypeHierarchy(
1209 const ResolveTypeHierarchyItemParams &Params,
1210 Callback<Optional<TypeHierarchyItem>> Reply) {
1211 Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
1212 std::move(Reply));
1213}
1214
Simon Marchi88016782018-08-01 11:28:49 +00001215void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +00001216 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +00001217 // Per-file update to the compilation database.
David Goldman60249c22020-01-13 17:01:10 -05001218 llvm::StringSet<> ModifiedFiles;
Sam McCallbc904612018-10-25 04:22:52 +00001219 for (auto &Entry : Settings.compilationDatabaseChanges) {
Sam McCallbc904612018-10-25 04:22:52 +00001220 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +00001221 auto Old = CDB->getCompileCommand(File);
1222 auto New =
1223 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
1224 std::move(Entry.second.compilationCommand),
1225 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +00001226 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +00001227 CDB->setCompileCommand(File, std::move(New));
David Goldman60249c22020-01-13 17:01:10 -05001228 ModifiedFiles.insert(File);
Sam McCall6980edb2018-11-02 14:07:51 +00001229 }
Alex Lorenzf8087862018-08-01 17:39:29 +00001230 }
David Goldman60249c22020-01-13 17:01:10 -05001231
Sam McCall596b63a2020-04-10 03:27:37 +02001232 reparseOpenFilesIfNeeded(
1233 [&](llvm::StringRef File) { return ModifiedFiles.count(File) != 0; });
Simon Marchi5178f922018-02-22 14:00:39 +00001234}
1235
Sam McCalledf6a192020-03-24 00:31:14 +01001236void ClangdLSPServer::publishTheiaSemanticHighlighting(
1237 const TheiaSemanticHighlightingParams &Params) {
Johan Vikstroma848dab2019-07-04 07:53:12 +00001238 notify("textDocument/semanticHighlighting", Params);
1239}
1240
Ilya Biryukov49c10712019-03-25 10:15:11 +00001241void ClangdLSPServer::publishDiagnostics(
Sam McCall6525a6b2020-03-03 12:44:40 +01001242 const PublishDiagnosticsParams &Params) {
1243 notify("textDocument/publishDiagnostics", Params);
Ilya Biryukov49c10712019-03-25 10:15:11 +00001244}
1245
Kadir Cetinkaya35871fd2020-09-28 15:09:55 +02001246void ClangdLSPServer::maybeExportMemoryProfile() {
1247 if (!trace::enabled())
1248 return;
1249 // Profiling might be expensive, so we throttle it to happen once every 5
1250 // minutes.
1251 static constexpr auto ProfileInterval = std::chrono::minutes(5);
1252 auto Now = std::chrono::steady_clock::now();
1253 if (Now < NextProfileTime)
1254 return;
1255
1256 static constexpr trace::Metric MemoryUsage(
1257 "memory_usage", trace::Metric::Value, "component_name");
1258 trace::Span Tracer("ProfileBrief");
1259 MemoryTree MT;
1260 profile(MT);
1261 record(MT, "clangd_lsp_server", MemoryUsage);
1262 NextProfileTime = Now + ProfileInterval;
1263}
1264
Simon Marchi88016782018-08-01 11:28:49 +00001265// FIXME: This function needs to be properly tested.
1266void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +00001267 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +00001268 applyConfiguration(Params.settings);
1269}
1270
Sam McCall2c30fbc2018-10-18 12:32:04 +00001271void ClangdLSPServer::onReference(const ReferenceParams &Params,
1272 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001273 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Sam McCall7ba07792020-09-29 10:37:46 +02001274 Opts.CodeComplete.Limit,
Haojian Wu5181ada2019-11-18 11:35:00 +01001275 [Reply = std::move(Reply)](
1276 llvm::Expected<ReferencesResult> Refs) mutable {
1277 if (!Refs)
1278 return Reply(Refs.takeError());
1279 return Reply(std::move(Refs->References));
1280 });
Sam McCall1ad142f2018-09-05 11:53:07 +00001281}
1282
Jan Korousb4067012018-11-27 16:40:46 +00001283void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
1284 Callback<std::vector<SymbolDetails>> Reply) {
1285 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
1286 std::move(Reply));
1287}
1288
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001289void ClangdLSPServer::onSelectionRange(
1290 const SelectionRangeParams &Params,
1291 Callback<std::vector<SelectionRange>> Reply) {
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001292 Server->semanticRanges(
Sam McCall8f237f92020-03-25 00:51:50 +01001293 Params.textDocument.uri.file(), Params.positions,
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001294 [Reply = std::move(Reply)](
Sam McCall8f237f92020-03-25 00:51:50 +01001295 llvm::Expected<std::vector<SelectionRange>> Ranges) mutable {
1296 if (!Ranges)
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001297 return Reply(Ranges.takeError());
Sam McCall8f237f92020-03-25 00:51:50 +01001298 return Reply(std::move(*Ranges));
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001299 });
1300}
1301
Sam McCall8d7ecc12019-12-16 19:08:51 +01001302void ClangdLSPServer::onDocumentLink(
1303 const DocumentLinkParams &Params,
1304 Callback<std::vector<DocumentLink>> Reply) {
1305
1306 // TODO(forster): This currently resolves all targets eagerly. This is slow,
1307 // because it blocks on the preamble/AST being built. We could respond to the
1308 // request faster by using string matching or the lexer to find the includes
1309 // and resolving the targets lazily.
1310 Server->documentLinks(
1311 Params.textDocument.uri.file(),
1312 [Reply = std::move(Reply)](
1313 llvm::Expected<std::vector<DocumentLink>> Links) mutable {
1314 if (!Links) {
1315 return Reply(Links.takeError());
1316 }
1317 return Reply(std::move(Links));
1318 });
1319}
1320
Sam McCall9e3063e2020-04-01 16:21:44 +02001321// Increment a numeric string: "" -> 1 -> 2 -> ... -> 9 -> 10 -> 11 ...
1322static void increment(std::string &S) {
1323 for (char &C : llvm::reverse(S)) {
1324 if (C != '9') {
1325 ++C;
1326 return;
1327 }
1328 C = '0';
1329 }
1330 S.insert(S.begin(), '1');
1331}
1332
Sam McCall71177ac2020-03-24 02:24:47 +01001333void ClangdLSPServer::onSemanticTokens(const SemanticTokensParams &Params,
1334 Callback<SemanticTokens> CB) {
1335 Server->semanticHighlights(
1336 Params.textDocument.uri.file(),
Sam McCall9e3063e2020-04-01 16:21:44 +02001337 [this, File(Params.textDocument.uri.file().str()), CB(std::move(CB))](
1338 llvm::Expected<std::vector<HighlightingToken>> HT) mutable {
1339 if (!HT)
1340 return CB(HT.takeError());
Sam McCall71177ac2020-03-24 02:24:47 +01001341 SemanticTokens Result;
Sam McCall9e3063e2020-04-01 16:21:44 +02001342 Result.tokens = toSemanticTokens(*HT);
1343 {
1344 std::lock_guard<std::mutex> Lock(SemanticTokensMutex);
Kadir Cetinkayae64f99c2020-04-16 23:12:09 +02001345 auto &Last = LastSemanticTokens[File];
Sam McCall9e3063e2020-04-01 16:21:44 +02001346
1347 Last.tokens = Result.tokens;
1348 increment(Last.resultId);
1349 Result.resultId = Last.resultId;
1350 }
1351 CB(std::move(Result));
1352 });
1353}
1354
Sam McCall5fea54b2020-07-10 16:08:14 +02001355void ClangdLSPServer::onSemanticTokensDelta(
1356 const SemanticTokensDeltaParams &Params,
1357 Callback<SemanticTokensOrDelta> CB) {
Sam McCall9e3063e2020-04-01 16:21:44 +02001358 Server->semanticHighlights(
1359 Params.textDocument.uri.file(),
1360 [this, PrevResultID(Params.previousResultId),
1361 File(Params.textDocument.uri.file().str()), CB(std::move(CB))](
1362 llvm::Expected<std::vector<HighlightingToken>> HT) mutable {
1363 if (!HT)
1364 return CB(HT.takeError());
1365 std::vector<SemanticToken> Toks = toSemanticTokens(*HT);
1366
Sam McCall5fea54b2020-07-10 16:08:14 +02001367 SemanticTokensOrDelta Result;
Sam McCall9e3063e2020-04-01 16:21:44 +02001368 {
1369 std::lock_guard<std::mutex> Lock(SemanticTokensMutex);
Kadir Cetinkayae64f99c2020-04-16 23:12:09 +02001370 auto &Last = LastSemanticTokens[File];
Sam McCall9e3063e2020-04-01 16:21:44 +02001371
1372 if (PrevResultID == Last.resultId) {
1373 Result.edits = diffTokens(Last.tokens, Toks);
1374 } else {
Sam McCall5fea54b2020-07-10 16:08:14 +02001375 vlog("semanticTokens/full/delta: wanted edits vs {0} but last "
1376 "result had ID {1}. Returning full token list.",
Sam McCall9e3063e2020-04-01 16:21:44 +02001377 PrevResultID, Last.resultId);
1378 Result.tokens = Toks;
1379 }
1380
1381 Last.tokens = std::move(Toks);
1382 increment(Last.resultId);
1383 Result.resultId = Last.resultId;
1384 }
1385
Sam McCall71177ac2020-03-24 02:24:47 +01001386 CB(std::move(Result));
1387 });
1388}
1389
Kadir Cetinkayad0f28742020-10-13 00:10:04 +02001390void ClangdLSPServer::onMemoryUsage(const NoParams &,
1391 Callback<MemoryTree> Reply) {
1392 llvm::BumpPtrAllocator DetailAlloc;
1393 MemoryTree MT(&DetailAlloc);
1394 profile(MT);
1395 Reply(std::move(MT));
1396}
1397
Sam McCall7ba07792020-09-29 10:37:46 +02001398ClangdLSPServer::ClangdLSPServer(class Transport &Transp,
1399 const ThreadsafeFS &TFS,
1400 const ClangdLSPServer::Options &Opts)
Kadir Cetinkaya9d662472019-10-15 14:20:52 +00001401 : BackgroundContext(Context::current().clone()), Transp(Transp),
Sam McCall7ba07792020-09-29 10:37:46 +02001402 MsgHandler(new MessageHandler(*this)), TFS(TFS),
1403 SupportedSymbolKinds(defaultSymbolKinds()),
1404 SupportedCompletionItemKinds(defaultCompletionItemKinds()), Opts(Opts) {
Sam McCall2c30fbc2018-10-18 12:32:04 +00001405 // clang-format off
1406 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
Sam McCall8a2d2942020-03-03 12:12:14 +01001407 MsgHandler->bind("initialized", &ClangdLSPServer::onInitialized);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001408 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +00001409 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001410 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
1411 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
1412 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
1413 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
1414 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
1415 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
1416 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +00001417 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001418 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
1419 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
Haojian Wuf429ab62019-07-24 07:49:23 +00001420 MsgHandler->bind("textDocument/prepareRename", &ClangdLSPServer::onPrepareRename);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001421 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
1422 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
1423 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
1424 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
1425 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
1426 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
1427 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
1428 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
1429 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
Sam McCall596b63a2020-04-10 03:27:37 +02001430 MsgHandler->bind("textDocument/didSave", &ClangdLSPServer::onDocumentDidSave);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001431 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
1432 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +00001433 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001434 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Nathan Ridge087b0442019-07-13 03:24:48 +00001435 MsgHandler->bind("typeHierarchy/resolve", &ClangdLSPServer::onResolveTypeHierarchy);
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001436 MsgHandler->bind("textDocument/selectionRange", &ClangdLSPServer::onSelectionRange);
Sam McCall8d7ecc12019-12-16 19:08:51 +01001437 MsgHandler->bind("textDocument/documentLink", &ClangdLSPServer::onDocumentLink);
Sam McCall5fea54b2020-07-10 16:08:14 +02001438 MsgHandler->bind("textDocument/semanticTokens/full", &ClangdLSPServer::onSemanticTokens);
1439 MsgHandler->bind("textDocument/semanticTokens/full/delta", &ClangdLSPServer::onSemanticTokensDelta);
Kadir Cetinkayad0f28742020-10-13 00:10:04 +02001440 MsgHandler->bind("$/memoryUsage", &ClangdLSPServer::onMemoryUsage);
Kirill Bobyrev7a514c92020-07-14 09:28:38 +02001441 if (Opts.FoldingRanges)
1442 MsgHandler->bind("textDocument/foldingRange", &ClangdLSPServer::onFoldingRange);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001443 // clang-format on
Kadir Cetinkaya35871fd2020-09-28 15:09:55 +02001444
1445 // Delay first profile until we've finished warming up.
1446 NextProfileTime = std::chrono::steady_clock::now() + std::chrono::minutes(1);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001447}
1448
Kadir Cetinkaya6b850322020-03-17 19:08:23 +01001449ClangdLSPServer::~ClangdLSPServer() {
1450 IsBeingDestroyed = true;
Sam McCall8bda5f22019-10-23 11:11:18 +02001451 // Explicitly destroy ClangdServer first, blocking on threads it owns.
1452 // This ensures they don't access any other members.
1453 Server.reset();
1454}
Ilya Biryukov38d79772017-05-16 09:38:59 +00001455
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001456bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +00001457 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001458 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +00001459 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001460 elog("Transport error: {0}", std::move(Err));
1461 CleanExit = false;
1462 }
Ilya Biryukovafb55542017-05-16 14:40:30 +00001463
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001464 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001465}
1466
Kadir Cetinkaya35871fd2020-09-28 15:09:55 +02001467void ClangdLSPServer::profile(MemoryTree &MT) const {
1468 if (Server)
1469 Server->profile(MT.child("clangd_server"));
1470}
1471
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001472std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +00001473 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001474 std::lock_guard<std::mutex> Lock(FixItsMutex);
1475 auto DiagToFixItsIter = FixItsMap.find(File);
1476 if (DiagToFixItsIter == FixItsMap.end())
1477 return {};
1478
1479 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1480 auto FixItsIter = DiagToFixItsMap.find(D);
1481 if (FixItsIter == DiagToFixItsMap.end())
1482 return {};
1483
1484 return FixItsIter->second;
1485}
1486
Sam McCall032727f2020-05-06 01:39:59 +02001487// A completion request is sent when the user types '>' or ':', but we only
1488// want to trigger on '->' and '::'. We check the preceeding text to make
1489// sure it matches what we expected.
1490// Running the lexer here would be more robust (e.g. we can detect comments
1491// and avoid triggering completion there), but we choose to err on the side
1492// of simplicity here.
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001493bool ClangdLSPServer::shouldRunCompletion(
1494 const CompletionParams &Params) const {
Sam McCall032727f2020-05-06 01:39:59 +02001495 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter)
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001496 return true;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001497 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1498 if (!Code)
1499 return true; // completion code will log the error for untracked doc.
Sam McCallcaf5a4d2020-03-03 15:57:39 +01001500 auto Offset = positionToOffset(Code->Contents, Params.position,
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001501 /*AllowColumnsBeyondLineLength=*/false);
1502 if (!Offset) {
1503 vlog("could not convert position '{0}' to offset for file '{1}'",
1504 Params.position, Params.textDocument.uri.file());
1505 return true;
1506 }
Sam McCall032727f2020-05-06 01:39:59 +02001507 return allowImplicitCompletion(Code->Contents, *Offset);
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001508}
1509
Johan Vikstroma848dab2019-07-04 07:53:12 +00001510void ClangdLSPServer::onHighlightingsReady(
Sam McCall2cd33e62020-03-04 00:33:29 +01001511 PathRef File, llvm::StringRef Version,
1512 std::vector<HighlightingToken> Highlightings) {
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001513 std::vector<HighlightingToken> Old;
1514 std::vector<HighlightingToken> HighlightingsCopy = Highlightings;
1515 {
1516 std::lock_guard<std::mutex> Lock(HighlightingsMutex);
1517 Old = std::move(FileToHighlightings[File]);
1518 FileToHighlightings[File] = std::move(HighlightingsCopy);
1519 }
1520 // LSP allows us to send incremental edits of highlightings. Also need to diff
1521 // to remove highlightings from tokens that should no longer have them.
Haojian Wu0a6000f2019-08-26 08:38:45 +00001522 std::vector<LineHighlightings> Diffed = diffHighlightings(Highlightings, Old);
Sam McCalledf6a192020-03-24 00:31:14 +01001523 TheiaSemanticHighlightingParams Notification;
Sam McCall2cd33e62020-03-04 00:33:29 +01001524 Notification.TextDocument.uri =
1525 URIForFile::canonicalize(File, /*TUPath=*/File);
1526 Notification.TextDocument.version = decodeVersion(Version);
Sam McCalledf6a192020-03-24 00:31:14 +01001527 Notification.Lines = toTheiaSemanticHighlightingInformation(Diffed);
1528 publishTheiaSemanticHighlighting(Notification);
Johan Vikstroma848dab2019-07-04 07:53:12 +00001529}
1530
Sam McCall2cd33e62020-03-04 00:33:29 +01001531void ClangdLSPServer::onDiagnosticsReady(PathRef File, llvm::StringRef Version,
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001532 std::vector<Diag> Diagnostics) {
Sam McCall6525a6b2020-03-03 12:44:40 +01001533 PublishDiagnosticsParams Notification;
Sam McCall2cd33e62020-03-04 00:33:29 +01001534 Notification.version = decodeVersion(Version);
Sam McCall6525a6b2020-03-03 12:44:40 +01001535 Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File);
Ilya Biryukov38d79772017-05-16 09:38:59 +00001536 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001537 for (auto &Diag : Diagnostics) {
Sam McCall6525a6b2020-03-03 12:44:40 +01001538 toLSPDiags(Diag, Notification.uri, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001539 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001540 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1541 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
Sam McCall6525a6b2020-03-03 12:44:40 +01001542 Notification.diagnostics.push_back(std::move(Diag));
Sam McCall16e70702018-10-24 07:59:38 +00001543 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001544 }
1545
1546 // Cache FixIts
1547 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001548 std::lock_guard<std::mutex> Lock(FixItsMutex);
1549 FixItsMap[File] = LocalFixIts;
1550 }
1551
Ilya Biryukov49c10712019-03-25 10:15:11 +00001552 // Send a notification to the LSP client.
Sam McCall6525a6b2020-03-03 12:44:40 +01001553 publishDiagnostics(Notification);
Ilya Biryukov38d79772017-05-16 09:38:59 +00001554}
Simon Marchi9569fd52018-03-16 14:30:42 +00001555
Sam McCall7d20e802020-01-22 19:41:45 +01001556void ClangdLSPServer::onBackgroundIndexProgress(
1557 const BackgroundQueue::Stats &Stats) {
1558 static const char ProgressToken[] = "backgroundIndexProgress";
1559 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1560
1561 auto NotifyProgress = [this](const BackgroundQueue::Stats &Stats) {
1562 if (BackgroundIndexProgressState != BackgroundIndexProgress::Live) {
1563 WorkDoneProgressBegin Begin;
1564 Begin.percentage = true;
1565 Begin.title = "indexing";
1566 progress(ProgressToken, std::move(Begin));
1567 BackgroundIndexProgressState = BackgroundIndexProgress::Live;
1568 }
1569
1570 if (Stats.Completed < Stats.Enqueued) {
1571 assert(Stats.Enqueued > Stats.LastIdle);
1572 WorkDoneProgressReport Report;
1573 Report.percentage = 100.0 * (Stats.Completed - Stats.LastIdle) /
1574 (Stats.Enqueued - Stats.LastIdle);
1575 Report.message =
1576 llvm::formatv("{0}/{1}", Stats.Completed - Stats.LastIdle,
1577 Stats.Enqueued - Stats.LastIdle);
1578 progress(ProgressToken, std::move(Report));
1579 } else {
1580 assert(Stats.Completed == Stats.Enqueued);
1581 progress(ProgressToken, WorkDoneProgressEnd());
1582 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
1583 }
1584 };
1585
1586 switch (BackgroundIndexProgressState) {
1587 case BackgroundIndexProgress::Unsupported:
1588 return;
1589 case BackgroundIndexProgress::Creating:
1590 // Cache this update for when the progress bar is available.
1591 PendingBackgroundIndexProgress = Stats;
1592 return;
1593 case BackgroundIndexProgress::Empty: {
1594 if (BackgroundIndexSkipCreate) {
1595 NotifyProgress(Stats);
1596 break;
1597 }
1598 // Cache this update for when the progress bar is available.
1599 PendingBackgroundIndexProgress = Stats;
1600 BackgroundIndexProgressState = BackgroundIndexProgress::Creating;
1601 WorkDoneProgressCreateParams CreateRequest;
1602 CreateRequest.token = ProgressToken;
1603 call<std::nullptr_t>(
1604 "window/workDoneProgress/create", CreateRequest,
1605 [this, NotifyProgress](llvm::Expected<std::nullptr_t> E) {
1606 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1607 if (E) {
1608 NotifyProgress(this->PendingBackgroundIndexProgress);
1609 } else {
1610 elog("Failed to create background index progress bar: {0}",
1611 E.takeError());
1612 // give up forever rather than thrashing about
1613 BackgroundIndexProgressState = BackgroundIndexProgress::Unsupported;
1614 }
1615 });
1616 break;
1617 }
1618 case BackgroundIndexProgress::Live:
1619 NotifyProgress(Stats);
1620 break;
1621 }
1622}
1623
Haojian Wub6188492018-12-20 15:39:12 +00001624void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1625 if (!SupportFileStatus)
1626 return;
1627 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1628 // two statuses are running faster in practice, which leads the UI constantly
1629 // changing, and doesn't provide much value. We may want to emit status at a
1630 // reasonable time interval (e.g. 0.5s).
Kadir Cetinkaya6b850322020-03-17 19:08:23 +01001631 if (Status.PreambleActivity == PreambleAction::Idle &&
1632 (Status.ASTActivity.K == ASTAction::Building ||
1633 Status.ASTActivity.K == ASTAction::RunningAction))
Haojian Wub6188492018-12-20 15:39:12 +00001634 return;
1635 notify("textDocument/clangd.fileStatus", Status.render(File));
1636}
1637
Sam McCall596b63a2020-04-10 03:27:37 +02001638void ClangdLSPServer::reparseOpenFilesIfNeeded(
1639 llvm::function_ref<bool(llvm::StringRef File)> Filter) {
David Goldman60249c22020-01-13 17:01:10 -05001640 // Reparse only opened files that were modified.
Simon Marchi9569fd52018-03-16 14:30:42 +00001641 for (const Path &FilePath : DraftMgr.getActiveFiles())
Sam McCall596b63a2020-04-10 03:27:37 +02001642 if (Filter(FilePath))
Sam McCall2cd33e62020-03-04 00:33:29 +01001643 if (auto Draft = DraftMgr.getDraft(FilePath)) // else disappeared in race?
1644 Server->addDocument(FilePath, std::move(Draft->Contents),
1645 encodeVersion(Draft->Version),
1646 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001647}
Alex Lorenzf8087862018-08-01 17:39:29 +00001648
Sam McCallc008af62018-10-20 15:30:37 +00001649} // namespace clangd
1650} // namespace clang