blob: c31a0a417ebe9211dc53b7791f87f216c8028ba8 [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 Cetinkaya9d662472019-10-15 14:20:52 +000010#include "Context.h"
Ilya Biryukov71028b82018-03-12 15:28:22 +000011#include "Diagnostics.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000012#include "DraftStore.h"
Ilya Biryukovf9169d02019-05-29 10:01:00 +000013#include "FormattedString.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"
Sam McCall2c30fbc2018-10-18 12:32:04 +000018#include "Trace.h"
Eric Liu78ed91a72018-01-29 15:37:46 +000019#include "URI.h"
Sam McCall395fde72019-06-18 13:37:54 +000020#include "refactor/Tweak.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000021#include "clang/Tooling/Core/Replacement.h"
Kadir Cetinkaya256247c2019-06-26 07:45:27 +000022#include "llvm/ADT/ArrayRef.h"
Sam McCalla69698f2019-03-27 17:47:49 +000023#include "llvm/ADT/Optional.h"
Kadir Cetinkaya689bf932018-08-24 13:09:41 +000024#include "llvm/ADT/ScopeExit.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000025#include "llvm/ADT/StringRef.h"
Utkarsh Saxena55925da2019-09-24 13:38:33 +000026#include "llvm/ADT/iterator_range.h"
Simon Marchi9569fd52018-03-16 14:30:42 +000027#include "llvm/Support/Errc.h"
Ilya Biryukovcce67a32019-01-29 14:17:36 +000028#include "llvm/Support/Error.h"
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000029#include "llvm/Support/FormatVariadic.h"
Utkarsh Saxena55925da2019-09-24 13:38:33 +000030#include "llvm/Support/JSON.h"
Eric Liu5740ff52018-01-31 16:26:27 +000031#include "llvm/Support/Path.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000032#include "llvm/Support/SHA1.h"
Sam McCall2c30fbc2018-10-18 12:32:04 +000033#include "llvm/Support/ScopedPrinter.h"
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000034#include <cstddef>
Utkarsh Saxena55925da2019-09-24 13:38:33 +000035#include <memory>
Sam McCall7d20e802020-01-22 19:41:45 +010036#include <mutex>
Kadir Cetinkaya5b270932019-09-09 12:28:44 +000037#include <string>
Utkarsh Saxena55925da2019-09-24 13:38:33 +000038#include <vector>
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +000039
Sam McCallc008af62018-10-20 15:30:37 +000040namespace clang {
41namespace clangd {
Ilya Biryukovafb55542017-05-16 14:40:30 +000042namespace {
Ilya Biryukovcce67a32019-01-29 14:17:36 +000043/// Transforms a tweak into a code action that would apply it if executed.
44/// EXPECTS: T.prepare() was called and returned true.
45CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File,
46 Range Selection) {
47 CodeAction CA;
48 CA.title = T.Title;
Sam McCall395fde72019-06-18 13:37:54 +000049 switch (T.Intent) {
50 case Tweak::Refactor:
Benjamin Krameradcd0262020-01-28 20:23:46 +010051 CA.kind = std::string(CodeAction::REFACTOR_KIND);
Sam McCall395fde72019-06-18 13:37:54 +000052 break;
53 case Tweak::Info:
Benjamin Krameradcd0262020-01-28 20:23:46 +010054 CA.kind = std::string(CodeAction::INFO_KIND);
Sam McCall395fde72019-06-18 13:37:54 +000055 break;
56 }
Ilya Biryukovcce67a32019-01-29 14:17:36 +000057 // This tweak may have an expensive second stage, we only run it if the user
58 // actually chooses it in the UI. We reply with a command that would run the
59 // corresponding tweak.
60 // FIXME: for some tweaks, computing the edits is cheap and we could send them
61 // directly.
62 CA.command.emplace();
63 CA.command->title = T.Title;
Benjamin Krameradcd0262020-01-28 20:23:46 +010064 CA.command->command = std::string(Command::CLANGD_APPLY_TWEAK);
Ilya Biryukovcce67a32019-01-29 14:17:36 +000065 CA.command->tweakArgs.emplace();
66 CA.command->tweakArgs->file = File;
67 CA.command->tweakArgs->tweakID = T.ID;
68 CA.command->tweakArgs->selection = Selection;
69 return CA;
Simon Pilgrime9a136b2019-02-03 14:08:30 +000070}
Ilya Biryukovcce67a32019-01-29 14:17:36 +000071
Ilya Biryukov19d75602018-11-23 15:21:19 +000072void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
73 SymbolKindBitset Kinds) {
74 for (auto &S : Syms) {
75 S.kind = adjustKindToCapability(S.kind, Kinds);
76 adjustSymbolKinds(S.children, Kinds);
77 }
78}
79
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +000080SymbolKindBitset defaultSymbolKinds() {
81 SymbolKindBitset Defaults;
82 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
83 ++I)
84 Defaults.set(I);
85 return Defaults;
86}
87
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +000088CompletionItemKindBitset defaultCompletionItemKinds() {
89 CompletionItemKindBitset Defaults;
90 for (size_t I = CompletionItemKindMin;
91 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
92 Defaults.set(I);
93 return Defaults;
94}
95
Haojian Wu1ca2ee42019-07-04 12:27:21 +000096// Build a lookup table (HighlightingKind => {TextMate Scopes}), which is sent
97// to the LSP client.
98std::vector<std::vector<std::string>> buildHighlightScopeLookupTable() {
99 std::vector<std::vector<std::string>> LookupTable;
100 // HighlightingKind is using as the index.
Ilya Biryukov63d5d162019-09-09 08:57:17 +0000101 for (int KindValue = 0; KindValue <= (int)HighlightingKind::LastKind;
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000102 ++KindValue)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100103 LookupTable.push_back(
104 {std::string(toTextMateScope((HighlightingKind)(KindValue)))});
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000105 return LookupTable;
106}
107
Haojian Wu852bafa2019-10-23 14:40:20 +0200108// Makes sure edits in \p FE are applicable to latest file contents reported by
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000109// editor. If not generates an error message containing information about files
110// that needs to be saved.
Haojian Wu852bafa2019-10-23 14:40:20 +0200111llvm::Error validateEdits(const DraftStore &DraftMgr, const FileEdits &FE) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000112 size_t InvalidFileCount = 0;
113 llvm::StringRef LastInvalidFile;
Haojian Wu852bafa2019-10-23 14:40:20 +0200114 for (const auto &It : FE) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000115 if (auto Draft = DraftMgr.getDraft(It.first())) {
116 // If the file is open in user's editor, make sure the version we
117 // saw and current version are compatible as this is the text that
118 // will be replaced by editors.
119 if (!It.second.canApplyTo(*Draft)) {
120 ++InvalidFileCount;
121 LastInvalidFile = It.first();
122 }
123 }
124 }
125 if (!InvalidFileCount)
126 return llvm::Error::success();
127 if (InvalidFileCount == 1)
128 return llvm::createStringError(llvm::inconvertibleErrorCode(),
129 "File must be saved first: " +
130 LastInvalidFile);
131 return llvm::createStringError(
132 llvm::inconvertibleErrorCode(),
133 "Files must be saved first: " + LastInvalidFile + " (and " +
134 llvm::to_string(InvalidFileCount - 1) + " others)");
135}
136
Utkarsh Saxena55925da2019-09-24 13:38:33 +0000137// Converts a list of Ranges to a LinkedList of SelectionRange.
138SelectionRange render(const std::vector<Range> &Ranges) {
139 if (Ranges.empty())
140 return {};
141 SelectionRange Result;
142 Result.range = Ranges[0];
143 auto *Next = &Result.parent;
144 for (const auto &R : llvm::make_range(Ranges.begin() + 1, Ranges.end())) {
145 *Next = std::make_unique<SelectionRange>();
146 Next->get()->range = R;
147 Next = &Next->get()->parent;
148 }
149 return Result;
150}
151
Ilya Biryukovafb55542017-05-16 14:40:30 +0000152} // namespace
153
Sam McCall2c30fbc2018-10-18 12:32:04 +0000154// MessageHandler dispatches incoming LSP messages.
155// It handles cross-cutting concerns:
156// - serializes/deserializes protocol objects to JSON
157// - logging of inbound messages
158// - cancellation handling
159// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +0000160// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000161class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
162public:
163 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
164
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000165 bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000166 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000167 log("<-- {0}", Method);
168 if (Method == "exit")
169 return false;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000170 if (!Server.Server)
171 elog("Notification {0} before initialization", Method);
172 else if (Method == "$/cancelRequest")
Sam McCall2c30fbc2018-10-18 12:32:04 +0000173 onCancel(std::move(Params));
174 else if (auto Handler = Notifications.lookup(Method))
175 Handler(std::move(Params));
176 else
177 log("unhandled notification {0}", Method);
178 return true;
179 }
180
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000181 bool onCall(llvm::StringRef Method, llvm::json::Value Params,
182 llvm::json::Value ID) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000183 WithContext HandlerContext(handlerContext());
Sam McCalle2f3a732018-10-24 14:26:26 +0000184 // Calls can be canceled by the client. Add cancellation context.
185 WithContext WithCancel(cancelableRequestContext(ID));
186 trace::Span Tracer(Method);
187 SPAN_ATTACH(Tracer, "Params", Params);
188 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000189 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +0000190 if (!Server.Server && Method != "initialize") {
191 elog("Call {0} before initialization.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000192 Reply(llvm::make_error<LSPError>("server not initialized",
193 ErrorCode::ServerNotInitialized));
Sam McCall3d0adbe2018-10-18 14:41:50 +0000194 } else if (auto Handler = Calls.lookup(Method))
Sam McCalle2f3a732018-10-24 14:26:26 +0000195 Handler(std::move(Params), std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000196 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000197 Reply(llvm::make_error<LSPError>("method not found",
198 ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000199 return true;
200 }
201
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000202 bool onReply(llvm::json::Value ID,
203 llvm::Expected<llvm::json::Value> Result) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000204 WithContext HandlerContext(handlerContext());
Haojian Wuf2516342019-08-05 12:48:09 +0000205
206 Callback<llvm::json::Value> ReplyHandler = nullptr;
207 if (auto IntID = ID.getAsInteger()) {
208 std::lock_guard<std::mutex> Mutex(CallMutex);
209 // Find a corresponding callback for the request ID;
210 for (size_t Index = 0; Index < ReplyCallbacks.size(); ++Index) {
211 if (ReplyCallbacks[Index].first == *IntID) {
212 ReplyHandler = std::move(ReplyCallbacks[Index].second);
213 ReplyCallbacks.erase(ReplyCallbacks.begin() +
214 Index); // remove the entry
215 break;
216 }
217 }
218 }
219
220 if (!ReplyHandler) {
221 // No callback being found, use a default log callback.
222 ReplyHandler = [&ID](llvm::Expected<llvm::json::Value> Result) {
223 elog("received a reply with ID {0}, but there was no such call", ID);
224 if (!Result)
225 llvm::consumeError(Result.takeError());
226 };
227 }
228
229 // Log and run the reply handler.
230 if (Result) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000231 log("<-- reply({0})", ID);
Haojian Wuf2516342019-08-05 12:48:09 +0000232 ReplyHandler(std::move(Result));
233 } else {
234 auto Err = Result.takeError();
235 log("<-- reply({0}) error: {1}", ID, Err);
236 ReplyHandler(std::move(Err));
237 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000238 return true;
239 }
240
241 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000242 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000243 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000244 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000245 Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000246 ReplyOnce Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000247 Param P;
Sam McCalle2f3a732018-10-24 14:26:26 +0000248 if (fromJSON(RawParams, P)) {
249 (Server.*Handler)(P, std::move(Reply));
250 } else {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000251 elog("Failed to decode {0} request.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000252 Reply(llvm::make_error<LSPError>("failed to decode request",
253 ErrorCode::InvalidRequest));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000254 }
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)
280 OldestCB->second(llvm::createStringError(
281 llvm::inconvertibleErrorCode(),
282 llvm::formatv("failed to receive a client reply for request ({0})",
283 OldestCB->first)));
284 return ID;
285 }
286
Sam McCall2c30fbc2018-10-18 12:32:04 +0000287 // Bind an LSP method name to a notification.
288 template <typename Param>
289 void bind(const char *Method,
290 void (ClangdLSPServer::*Handler)(const Param &)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000291 Notifications[Method] = [Method, Handler,
292 this](llvm::json::Value RawParams) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000293 Param P;
294 if (!fromJSON(RawParams, P)) {
295 elog("Failed to decode {0} request.", Method);
296 return;
297 }
298 trace::Span Tracer(Method);
299 SPAN_ATTACH(Tracer, "Params", RawParams);
300 (Server.*Handler)(P);
301 };
302 }
303
304private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000305 // Function object to reply to an LSP call.
306 // Each instance must be called exactly once, otherwise:
307 // - the bug is logged, and (in debug mode) an assert will fire
308 // - if there was no reply, an error reply is sent
309 // - if there were multiple replies, only the first is sent
310 class ReplyOnce {
311 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000312 std::chrono::steady_clock::time_point Start;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000313 llvm::json::Value ID;
Sam McCalle2f3a732018-10-24 14:26:26 +0000314 std::string Method;
315 ClangdLSPServer *Server; // Null when moved-from.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000316 llvm::json::Object *TraceArgs;
Sam McCalle2f3a732018-10-24 14:26:26 +0000317
318 public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000319 ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
320 ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000321 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
322 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000323 assert(Server);
324 }
325 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000326 : Replied(Other.Replied.load()), Start(Other.Start),
327 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
328 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000329 Other.Server = nullptr;
330 }
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000331 ReplyOnce &operator=(ReplyOnce &&) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000332 ReplyOnce(const ReplyOnce &) = delete;
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000333 ReplyOnce &operator=(const ReplyOnce &) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000334
335 ~ReplyOnce() {
Haojian Wuf2516342019-08-05 12:48:09 +0000336 // There's one legitimate reason to never reply to a request: clangd's
337 // request handler send a call to the client (e.g. applyEdit) and the
338 // client never replied. In this case, the ReplyOnce is owned by
339 // ClangdLSPServer's reply callback table and is destroyed along with the
340 // server. We don't attempt to send a reply in this case, there's little
341 // to be gained from doing so.
342 if (Server && !Server->IsBeingDestroyed && !Replied) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000343 elog("No reply to message {0}({1})", Method, ID);
344 assert(false && "must reply to all calls!");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000345 (*this)(llvm::make_error<LSPError>("server failed to reply",
346 ErrorCode::InternalError));
Sam McCalle2f3a732018-10-24 14:26:26 +0000347 }
348 }
349
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000350 void operator()(llvm::Expected<llvm::json::Value> Reply) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000351 assert(Server && "moved-from!");
352 if (Replied.exchange(true)) {
353 elog("Replied twice to message {0}({1})", Method, ID);
354 assert(false && "must reply to each call only once!");
355 return;
356 }
Sam McCalld7babe42018-10-24 15:18:40 +0000357 auto Duration = std::chrono::steady_clock::now() - Start;
358 if (Reply) {
359 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
360 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000361 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000362 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
363 Server->Transp.reply(std::move(ID), std::move(Reply));
364 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000365 llvm::Error Err = Reply.takeError();
Sam McCalld7babe42018-10-24 15:18:40 +0000366 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
367 if (TraceArgs)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000368 (*TraceArgs)["Error"] = llvm::to_string(Err);
Sam McCalld7babe42018-10-24 15:18:40 +0000369 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
370 Server->Transp.reply(std::move(ID), std::move(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000371 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000372 }
373 };
374
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000375 llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
376 llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000377
378 // Method calls may be cancelled by ID, so keep track of their state.
379 // This needs a mutex: handlers may finish on a different thread, and that's
380 // when we clean up entries in the map.
381 mutable std::mutex RequestCancelersMutex;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000382 llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000383 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000384 void onCancel(const llvm::json::Value &Params) {
385 const llvm::json::Value *ID = nullptr;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000386 if (auto *O = Params.getAsObject())
387 ID = O->get("id");
388 if (!ID) {
389 elog("Bad cancellation request: {0}", Params);
390 return;
391 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000392 auto StrID = llvm::to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000393 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
394 auto It = RequestCancelers.find(StrID);
395 if (It != RequestCancelers.end())
396 It->second.first(); // Invoke the canceler.
397 }
Sam McCalla69698f2019-03-27 17:47:49 +0000398
399 Context handlerContext() const {
400 return Context::current().derive(
401 kCurrentOffsetEncoding,
402 Server.NegotiatedOffsetEncoding.getValueOr(OffsetEncoding::UTF16));
403 }
404
Sam McCall2c30fbc2018-10-18 12:32:04 +0000405 // We run cancelable requests in a context that does two things:
406 // - allows cancellation using RequestCancelers[ID]
407 // - cleans up the entry in RequestCancelers when it's no longer needed
408 // If a client reuses an ID, the last wins and the first cannot be canceled.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000409 Context cancelableRequestContext(const llvm::json::Value &ID) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000410 auto Task = cancelableTask();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000411 auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000412 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
413 {
414 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
415 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
416 }
417 // When the request ends, we can clean up the entry we just added.
418 // The cookie lets us check that it hasn't been overwritten due to ID
419 // reuse.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000420 return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000421 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
422 auto It = RequestCancelers.find(StrID);
423 if (It != RequestCancelers.end() && It->second.second == Cookie)
424 RequestCancelers.erase(It);
425 }));
426 }
427
Kadir Cetinkaya9a3a87d2019-10-09 13:59:31 +0000428 // The maximum number of callbacks held in clangd.
429 //
430 // We bound the maximum size to the pending map to prevent memory leakage
431 // for cases where LSP clients don't reply for the request.
432 // This has to go after RequestCancellers and RequestCancellersMutex since it
433 // can contain a callback that has a cancelable context.
434 static constexpr int MaxReplayCallbacks = 100;
435 mutable std::mutex CallMutex;
436 int NextCallID = 0; /* GUARDED_BY(CallMutex) */
437 std::deque<std::pair</*RequestID*/ int,
438 /*ReplyHandler*/ Callback<llvm::json::Value>>>
439 ReplyCallbacks; /* GUARDED_BY(CallMutex) */
440
Sam McCall2c30fbc2018-10-18 12:32:04 +0000441 ClangdLSPServer &Server;
442};
Haojian Wuf2516342019-08-05 12:48:09 +0000443constexpr int ClangdLSPServer::MessageHandler::MaxReplayCallbacks;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000444
445// call(), notify(), and reply() wrap the Transport, adding logging and locking.
Haojian Wuf2516342019-08-05 12:48:09 +0000446void ClangdLSPServer::callRaw(StringRef Method, llvm::json::Value Params,
447 Callback<llvm::json::Value> CB) {
448 auto ID = MsgHandler->bindReply(std::move(CB));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000449 log("--> {0}({1})", Method, ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000450 std::lock_guard<std::mutex> Lock(TranspWriter);
451 Transp.call(Method, std::move(Params), ID);
452}
453
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000454void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000455 log("--> {0}", Method);
456 std::lock_guard<std::mutex> Lock(TranspWriter);
457 Transp.notify(Method, std::move(Params));
458}
459
Sam McCall2c30fbc2018-10-18 12:32:04 +0000460void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000461 Callback<llvm::json::Value> Reply) {
Sam McCalla69698f2019-03-27 17:47:49 +0000462 // Determine character encoding first as it affects constructed ClangdServer.
463 if (Params.capabilities.offsetEncoding && !NegotiatedOffsetEncoding) {
464 NegotiatedOffsetEncoding = OffsetEncoding::UTF16; // fallback
465 for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
466 if (Supported != OffsetEncoding::UnsupportedEncoding) {
467 NegotiatedOffsetEncoding = Supported;
468 break;
469 }
470 }
Sam McCalla69698f2019-03-27 17:47:49 +0000471
Johan Vikstroma848dab2019-07-04 07:53:12 +0000472 ClangdServerOpts.SemanticHighlighting =
473 Params.capabilities.SemanticHighlighting;
Sam McCall0d9b40f2018-10-19 15:42:23 +0000474 if (Params.rootUri && *Params.rootUri)
Benjamin Krameradcd0262020-01-28 20:23:46 +0100475 ClangdServerOpts.WorkspaceRoot = std::string(Params.rootUri->file());
Sam McCall0d9b40f2018-10-19 15:42:23 +0000476 else if (Params.rootPath && !Params.rootPath->empty())
477 ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000478 if (Server)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000479 return Reply(llvm::make_error<LSPError>("server already initialized",
480 ErrorCode::InvalidRequest));
Sam McCallbc904612018-10-25 04:22:52 +0000481 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
482 CompileCommandsDir = Dir;
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000483 if (UseDirBasedCDB) {
Jonas Devlieghere1c705d92019-08-14 23:52:23 +0000484 BaseCDB = std::make_unique<DirectoryBasedGlobalCompilationDatabase>(
Sam McCallc55d09a2018-11-02 13:09:36 +0000485 CompileCommandsDir);
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000486 BaseCDB = getQueryDriverDatabase(
487 llvm::makeArrayRef(ClangdServerOpts.QueryDriverGlobs),
488 std::move(BaseCDB));
489 }
Sam McCall99768b22019-11-29 19:37:48 +0100490 auto Mangler = CommandMangler::detect();
491 if (ClangdServerOpts.ResourceDir)
492 Mangler.ResourceDir = *ClangdServerOpts.ResourceDir;
Kadir Cetinkayabe6b35d2019-01-22 09:10:20 +0000493 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
Sam McCall99768b22019-11-29 19:37:48 +0100494 tooling::ArgumentsAdjuster(Mangler));
Kadir Cetinkaya9d662472019-10-15 14:20:52 +0000495 {
496 // Switch caller's context with LSPServer's background context. Since we
497 // rather want to propagate information from LSPServer's context into the
498 // Server, CDB, etc.
499 WithContext MainContext(BackgroundContext.clone());
500 llvm::Optional<WithContextValue> WithOffsetEncoding;
501 if (NegotiatedOffsetEncoding)
502 WithOffsetEncoding.emplace(kCurrentOffsetEncoding,
503 *NegotiatedOffsetEncoding);
Sam McCall6ef1cce2020-01-24 14:08:56 +0100504 Server.emplace(*CDB, FSProvider, ClangdServerOpts,
505 static_cast<ClangdServer::Callbacks *>(this));
Kadir Cetinkaya9d662472019-10-15 14:20:52 +0000506 }
Sam McCallbc904612018-10-25 04:22:52 +0000507 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000508
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000509 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
Sam McCall8d412942019-06-18 11:57:26 +0000510 CCOpts.IncludeFixIts = Params.capabilities.CompletionFixes;
Sam McCall5f092e32019-07-08 17:27:15 +0000511 if (!CCOpts.BundleOverloads.hasValue())
512 CCOpts.BundleOverloads = Params.capabilities.HasSignatureHelp;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000513 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
514 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
Sam McCallc9e4ee92019-04-18 15:17:07 +0000515 DiagOpts.EmitRelatedLocations =
516 Params.capabilities.DiagnosticRelatedInformation;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000517 if (Params.capabilities.WorkspaceSymbolKinds)
518 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
519 if (Params.capabilities.CompletionItemKinds)
520 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
521 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000522 SupportsHierarchicalDocumentSymbol =
523 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000524 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000525 HoverContentFormat = Params.capabilities.HoverContentFormat;
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000526 SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
Sam McCall7d20e802020-01-22 19:41:45 +0100527 if (Params.capabilities.WorkDoneProgress)
528 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
529 BackgroundIndexSkipCreate = Params.capabilities.ImplicitProgressCreation;
Haojian Wuf429ab62019-07-24 07:49:23 +0000530
531 // Per LSP, renameProvider can be either boolean or RenameOptions.
532 // RenameOptions will be specified if the client states it supports prepare.
533 llvm::json::Value RenameProvider =
534 llvm::json::Object{{"prepareProvider", true}};
535 if (!Params.capabilities.RenamePrepareSupport) // Only boolean allowed per LSP
536 RenameProvider = true;
537
Haojian Wu08d93f12019-08-22 14:53:45 +0000538 // Per LSP, codeActionProvide can be either boolean or CodeActionOptions.
539 // CodeActionOptions is only valid if the client supports action literal
540 // via textDocument.codeAction.codeActionLiteralSupport.
541 llvm::json::Value CodeActionProvider = true;
542 if (Params.capabilities.CodeActionStructure)
543 CodeActionProvider = llvm::json::Object{
544 {"codeActionKinds",
545 {CodeAction::QUICKFIX_KIND, CodeAction::REFACTOR_KIND,
546 CodeAction::INFO_KIND}}};
547
Sam McCalla69698f2019-03-27 17:47:49 +0000548 llvm::json::Object Result{
Sam McCall0930ab02017-11-07 15:49:35 +0000549 {{"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000550 llvm::json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000551 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000552 {"documentFormattingProvider", true},
553 {"documentRangeFormattingProvider", true},
554 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000555 llvm::json::Object{
Sam McCall25c62572019-06-10 14:26:21 +0000556 {"firstTriggerCharacter", "\n"},
Sam McCall0930ab02017-11-07 15:49:35 +0000557 {"moreTriggerCharacter", {}},
558 }},
Haojian Wu08d93f12019-08-22 14:53:45 +0000559 {"codeActionProvider", std::move(CodeActionProvider)},
Sam McCall0930ab02017-11-07 15:49:35 +0000560 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000561 llvm::json::Object{
Kirill Bobyrev2a095ff2020-02-18 17:55:12 +0100562 {"allCommitCharacters", " \t()[]{}<>:;,+-/*%^&#?.=\"'|"},
Sam McCall0930ab02017-11-07 15:49:35 +0000563 {"resolveProvider", false},
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000564 // We do extra checks for '>' and ':' in completion to only
565 // trigger on '->' and '::'.
Sam McCall0930ab02017-11-07 15:49:35 +0000566 {"triggerCharacters", {".", ">", ":"}},
567 }},
568 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000569 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000570 {"triggerCharacters", {"(", ","}},
571 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000572 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000573 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000574 {"documentHighlightProvider", true},
Sam McCall8d7ecc12019-12-16 19:08:51 +0100575 {"documentLinkProvider",
576 llvm::json::Object{
577 {"resolveProvider", false},
578 }},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000579 {"hoverProvider", true},
Haojian Wuf429ab62019-07-24 07:49:23 +0000580 {"renameProvider", std::move(RenameProvider)},
Utkarsh Saxena55925da2019-09-24 13:38:33 +0000581 {"selectionRangeProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000582 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000583 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000584 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000585 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000586 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000587 {"commands",
588 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
589 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000590 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000591 {"typeHierarchyProvider", true},
Sam McCalla69698f2019-03-27 17:47:49 +0000592 }}}};
593 if (NegotiatedOffsetEncoding)
594 Result["offsetEncoding"] = *NegotiatedOffsetEncoding;
Johan Vikstroma848dab2019-07-04 07:53:12 +0000595 if (Params.capabilities.SemanticHighlighting)
596 Result.getObject("capabilities")
597 ->insert(
598 {"semanticHighlighting",
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000599 llvm::json::Object{{"scopes", buildHighlightScopeLookupTable()}}});
Sam McCalla69698f2019-03-27 17:47:49 +0000600 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000601}
602
Sam McCall2c30fbc2018-10-18 12:32:04 +0000603void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
604 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000605 // Do essentially nothing, just say we're ready to exit.
606 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000607 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000608}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000609
Sam McCall422c8282018-11-26 16:00:11 +0000610// sync is a clangd extension: it blocks until all background work completes.
611// It blocks the calling thread, so no messages are processed until it returns!
612void ClangdLSPServer::onSync(const NoParams &Params,
613 Callback<std::nullptr_t> Reply) {
614 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
615 Reply(nullptr);
616 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000617 Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
618 "Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000619}
620
Sam McCall2c30fbc2018-10-18 12:32:04 +0000621void ClangdLSPServer::onDocumentDidOpen(
622 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000623 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000624
Sam McCall2c30fbc2018-10-18 12:32:04 +0000625 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000626
Simon Marchi98082622018-03-26 14:41:40 +0000627 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000628 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000629}
630
Sam McCall2c30fbc2018-10-18 12:32:04 +0000631void ClangdLSPServer::onDocumentDidChange(
632 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000633 auto WantDiags = WantDiagnostics::Auto;
634 if (Params.wantDiagnostics.hasValue())
635 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
636 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000637
638 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000639 llvm::Expected<std::string> Contents =
Simon Marchi98082622018-03-26 14:41:40 +0000640 DraftMgr.updateDraft(File, Params.contentChanges);
641 if (!Contents) {
642 // If this fails, we are most likely going to be not in sync anymore with
643 // the client. It is better to remove the draft and let further operations
644 // fail rather than giving wrong results.
645 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000646 Server->removeDocument(File);
Sam McCallbed58852018-07-11 10:35:11 +0000647 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000648 return;
649 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000650
David Goldman6ff02282020-02-03 15:14:49 -0500651 Server->addDocument(File, *Contents, WantDiags, Params.forceRebuild);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000652}
653
Sam McCall2c30fbc2018-10-18 12:32:04 +0000654void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000655 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000656}
657
Sam McCall2c30fbc2018-10-18 12:32:04 +0000658void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000659 Callback<llvm::json::Value> Reply) {
Ilya Biryukov12864002019-08-16 12:46:41 +0000660 auto ApplyEdit = [this](WorkspaceEdit WE, std::string SuccessMessage,
661 decltype(Reply) Reply) {
Eric Liuc5105f92018-02-16 14:15:55 +0000662 ApplyWorkspaceEditParams Edit;
663 Edit.edit = std::move(WE);
Ilya Biryukov12864002019-08-16 12:46:41 +0000664 call<ApplyWorkspaceEditResponse>(
665 "workspace/applyEdit", std::move(Edit),
666 [Reply = std::move(Reply), SuccessMessage = std::move(SuccessMessage)](
667 llvm::Expected<ApplyWorkspaceEditResponse> Response) mutable {
668 if (!Response)
669 return Reply(Response.takeError());
670 if (!Response->applied) {
671 std::string Reason = Response->failureReason
672 ? *Response->failureReason
673 : "unknown reason";
674 return Reply(llvm::createStringError(
675 llvm::inconvertibleErrorCode(),
676 ("edits were not applied: " + Reason).c_str()));
677 }
678 return Reply(SuccessMessage);
679 });
Eric Liuc5105f92018-02-16 14:15:55 +0000680 };
Ilya Biryukov12864002019-08-16 12:46:41 +0000681
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000682 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
683 Params.workspaceEdit) {
684 // The flow for "apply-fix" :
685 // 1. We publish a diagnostic, including fixits
686 // 2. The user clicks on the diagnostic, the editor asks us for code actions
687 // 3. We send code actions, with the fixit embedded as context
688 // 4. The user selects the fixit, the editor asks us to apply it
689 // 5. We unwrap the changes and send them back to the editor
Haojian Wuf2516342019-08-05 12:48:09 +0000690 // 6. The editor applies the changes (applyEdit), and sends us a reply
691 // 7. We unwrap the reply and send a reply to the editor.
Ilya Biryukov12864002019-08-16 12:46:41 +0000692 ApplyEdit(*Params.workspaceEdit, "Fix applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000693 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
694 Params.tweakArgs) {
695 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
696 if (!Code)
697 return Reply(llvm::createStringError(
698 llvm::inconvertibleErrorCode(),
699 "trying to apply a code action for a non-added file"));
700
Ilya Biryukov12864002019-08-16 12:46:41 +0000701 auto Action = [this, ApplyEdit, Reply = std::move(Reply),
702 File = Params.tweakArgs->file, Code = std::move(*Code)](
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000703 llvm::Expected<Tweak::Effect> R) mutable {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000704 if (!R)
705 return Reply(R.takeError());
706
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000707 assert(R->ShowMessage ||
708 (!R->ApplyEdits.empty() && "tweak has no effect"));
Ilya Biryukov12864002019-08-16 12:46:41 +0000709
Sam McCall395fde72019-06-18 13:37:54 +0000710 if (R->ShowMessage) {
711 ShowMessageParams Msg;
712 Msg.message = *R->ShowMessage;
713 Msg.type = MessageType::Info;
714 notify("window/showMessage", Msg);
715 }
Ilya Biryukov12864002019-08-16 12:46:41 +0000716 // When no edit is specified, make sure we Reply().
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000717 if (R->ApplyEdits.empty())
718 return Reply("Tweak applied.");
719
Haojian Wu852bafa2019-10-23 14:40:20 +0200720 if (auto Err = validateEdits(DraftMgr, R->ApplyEdits))
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000721 return Reply(std::move(Err));
722
723 WorkspaceEdit WE;
724 WE.changes.emplace();
725 for (const auto &It : R->ApplyEdits) {
Kadir Cetinkayae95e5162019-10-02 09:12:01 +0000726 (*WE.changes)[URI::createFile(It.first()).toString()] =
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000727 It.second.asTextEdits();
728 }
729 // ApplyEdit will take care of calling Reply().
730 return ApplyEdit(std::move(WE), "Tweak applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000731 };
732 Server->applyTweak(Params.tweakArgs->file.file(),
733 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000734 std::move(Action));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000735 } else {
736 // We should not get here because ExecuteCommandParams would not have
737 // parsed in the first place and this handler should not be called. But if
738 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000739 Reply(llvm::make_error<LSPError>(
740 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000741 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000742 }
743}
744
Sam McCall2c30fbc2018-10-18 12:32:04 +0000745void ClangdLSPServer::onWorkspaceSymbol(
746 const WorkspaceSymbolParams &Params,
747 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000748 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000749 Params.query, CCOpts.Limit,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000750 [Reply = std::move(Reply),
751 this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable {
752 if (!Items)
753 return Reply(Items.takeError());
754 for (auto &Sym : *Items)
755 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000756
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000757 Reply(std::move(*Items));
758 });
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000759}
760
Haojian Wuf429ab62019-07-24 07:49:23 +0000761void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params,
762 Callback<llvm::Optional<Range>> Reply) {
763 Server->prepareRename(Params.textDocument.uri.file(), Params.position,
764 std::move(Reply));
765}
766
Sam McCall2c30fbc2018-10-18 12:32:04 +0000767void ClangdLSPServer::onRename(const RenameParams &Params,
768 Callback<WorkspaceEdit> Reply) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100769 Path File = std::string(Params.textDocument.uri.file());
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000770 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000771 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000772 return Reply(llvm::make_error<LSPError>(
773 "onRename called for non-added file", ErrorCode::InvalidParams));
Haojian Wu852bafa2019-10-23 14:40:20 +0200774 Server->rename(
775 File, Params.position, Params.newName,
776 /*WantFormat=*/true,
777 [File, Params, Reply = std::move(Reply),
778 this](llvm::Expected<FileEdits> Edits) mutable {
779 if (!Edits)
780 return Reply(Edits.takeError());
781 if (auto Err = validateEdits(DraftMgr, *Edits))
782 return Reply(std::move(Err));
783 WorkspaceEdit Result;
784 Result.changes.emplace();
785 for (const auto &Rep : *Edits) {
786 (*Result.changes)[URI::createFile(Rep.first()).toString()] =
787 Rep.second.asTextEdits();
788 }
789 Reply(Result);
790 });
Haojian Wu345099c2017-11-09 11:30:04 +0000791}
792
Sam McCall2c30fbc2018-10-18 12:32:04 +0000793void ClangdLSPServer::onDocumentDidClose(
794 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000795 PathRef File = Params.textDocument.uri.file();
796 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000797 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000798
799 {
800 std::lock_guard<std::mutex> Lock(FixItsMutex);
801 FixItsMap.erase(File);
802 }
Johan Vikstromc2653ef22019-08-01 08:08:44 +0000803 {
804 std::lock_guard<std::mutex> HLock(HighlightingsMutex);
805 FileToHighlightings.erase(File);
806 }
Ilya Biryukov49c10712019-03-25 10:15:11 +0000807 // clangd will not send updates for this file anymore, so we empty out the
808 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
809 // VSCode). Note that this cannot race with actual diagnostics responses
810 // because removeDocument() guarantees no diagnostic callbacks will be
811 // executed after it returns.
812 publishDiagnostics(URIForFile::canonicalize(File, /*TUPath=*/File), {});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000813}
814
Sam McCall4db732a2017-09-30 10:08:52 +0000815void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000816 const DocumentOnTypeFormattingParams &Params,
817 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000818 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000819 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000820 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000821 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000822 "onDocumentOnTypeFormatting called for non-added file",
823 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000824
Sam McCall25c62572019-06-10 14:26:21 +0000825 Reply(Server->formatOnType(*Code, File, Params.position, Params.ch));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000826}
827
Sam McCall4db732a2017-09-30 10:08:52 +0000828void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000829 const DocumentRangeFormattingParams &Params,
830 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000831 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000832 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000833 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000834 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000835 "onDocumentRangeFormatting called for non-added file",
836 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000837
Ilya Biryukov652364b2018-09-26 05:48:29 +0000838 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000839 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000840 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000841 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000842 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000843}
844
Sam McCall2c30fbc2018-10-18 12:32:04 +0000845void ClangdLSPServer::onDocumentFormatting(
846 const DocumentFormattingParams &Params,
847 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000848 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000849 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000850 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000851 return Reply(llvm::make_error<LSPError>(
852 "onDocumentFormatting called for non-added file",
853 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000854
Ilya Biryukov652364b2018-09-26 05:48:29 +0000855 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000856 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000857 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000858 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000859 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000860}
861
Ilya Biryukov19d75602018-11-23 15:21:19 +0000862/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
863/// Used by the clients that do not support the hierarchical view.
864static std::vector<SymbolInformation>
865flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
866 const URIForFile &FileURI) {
867
868 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000869 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
870 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000871 SymbolInformation SI;
Benjamin Krameradcd0262020-01-28 20:23:46 +0100872 SI.containerName = std::string(ParentName ? "" : *ParentName);
Ilya Biryukov19d75602018-11-23 15:21:19 +0000873 SI.name = S.name;
874 SI.kind = S.kind;
875 SI.location.range = S.range;
876 SI.location.uri = FileURI;
877
878 Results.push_back(std::move(SI));
879 std::string FullName =
880 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
881 for (auto &C : S.children)
882 Process(C, /*ParentName=*/FullName);
883 };
884 for (auto &S : Symbols)
885 Process(S, /*ParentName=*/"");
886 return Results;
887}
888
889void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000890 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000891 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000892 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000893 Params.textDocument.uri.file(),
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000894 [this, FileURI, Reply = std::move(Reply)](
895 llvm::Expected<std::vector<DocumentSymbol>> Items) mutable {
896 if (!Items)
897 return Reply(Items.takeError());
898 adjustSymbolKinds(*Items, SupportedSymbolKinds);
899 if (SupportsHierarchicalDocumentSymbol)
900 return Reply(std::move(*Items));
901 else
902 return Reply(flattenSymbolHierarchy(*Items, FileURI));
903 });
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000904}
905
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000906static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000907 Command Cmd;
908 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000909 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000910 if (Action.command) {
911 Cmd = *Action.command;
912 } else if (Action.edit) {
Benjamin Krameradcd0262020-01-28 20:23:46 +0100913 Cmd.command = std::string(Command::CLANGD_APPLY_FIX_COMMAND);
Sam McCall20841d42018-10-16 16:29:41 +0000914 Cmd.workspaceEdit = *Action.edit;
915 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000916 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000917 }
918 Cmd.title = Action.title;
919 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
920 Cmd.title = "Apply fix: " + Cmd.title;
921 return Cmd;
922}
923
Sam McCall2c30fbc2018-10-18 12:32:04 +0000924void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000925 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000926 URIForFile File = Params.textDocument.uri;
927 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000928 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000929 return Reply(llvm::make_error<LSPError>(
930 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000931 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000932 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000933 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000934 for (auto &F : getFixes(File.file(), D)) {
935 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
936 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000937 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000938 }
Sam McCall20841d42018-10-16 16:29:41 +0000939
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000940 // Now enumerate the semantic code actions.
941 auto ConsumeActions =
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000942 [Reply = std::move(Reply), File, Code = std::move(*Code),
943 Selection = Params.range, FixIts = std::move(FixIts), this](
944 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +0000945 if (!Tweaks)
946 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000947
948 std::vector<CodeAction> Actions = std::move(FixIts);
949 Actions.reserve(Actions.size() + Tweaks->size());
950 for (const auto &T : *Tweaks)
951 Actions.push_back(toCodeAction(T, File, Selection));
952
953 if (SupportsCodeAction)
954 return Reply(llvm::json::Array(Actions));
955 std::vector<Command> Commands;
956 for (const auto &Action : Actions) {
957 if (auto Command = asCommand(Action))
958 Commands.push_back(std::move(*Command));
959 }
960 return Reply(llvm::json::Array(Commands));
961 };
962
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000963 Server->enumerateTweaks(File.file(), Params.range, std::move(ConsumeActions));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000964}
965
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000966void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000967 Callback<CompletionList> Reply) {
Ilya Biryukova7a11472019-06-07 16:24:38 +0000968 if (!shouldRunCompletion(Params)) {
969 // Clients sometimes auto-trigger completions in undesired places (e.g.
970 // 'a >^ '), we return empty results in those cases.
971 vlog("ignored auto-triggered completion, preceding char did not match");
972 return Reply(CompletionList());
973 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000974 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000975 [Reply = std::move(Reply),
976 this](llvm::Expected<CodeCompleteResult> List) mutable {
977 if (!List)
978 return Reply(List.takeError());
979 CompletionList LSPList;
980 LSPList.isIncomplete = List->HasMore;
981 for (const auto &R : List->Completions) {
982 CompletionItem C = R.render(CCOpts);
983 C.kind = adjustKindToCapability(
984 C.kind, SupportedCompletionItemKinds);
985 LSPList.items.push_back(std::move(C));
986 }
987 return Reply(std::move(LSPList));
988 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000989}
990
Sam McCall2c30fbc2018-10-18 12:32:04 +0000991void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
992 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000993 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000994 [Reply = std::move(Reply), this](
995 llvm::Expected<SignatureHelp> Signature) mutable {
996 if (!Signature)
997 return Reply(Signature.takeError());
998 if (SupportsOffsetsInSignatureHelp)
999 return Reply(std::move(*Signature));
1000 // Strip out the offsets from signature help for
1001 // clients that only support string labels.
1002 for (auto &SigInfo : Signature->signatures) {
1003 for (auto &Param : SigInfo.parameters)
1004 Param.labelOffsets.reset();
1005 }
1006 return Reply(std::move(*Signature));
1007 });
Ilya Biryukov652364b2018-09-26 05:48:29 +00001008}
1009
Sam McCall0dbab7f2019-02-02 05:56:00 +00001010// Go to definition has a toggle function: if def and decl are distinct, then
1011// the first press gives you the def, the second gives you the matching def.
1012// getToggle() returns the counterpart location that under the cursor.
1013//
1014// We return the toggled location alone (ignoring other symbols) to encourage
1015// editors to "bounce" quickly between locations, without showing a menu.
1016static Location *getToggle(const TextDocumentPositionParams &Point,
1017 LocatedSymbol &Sym) {
1018 // Toggle only makes sense with two distinct locations.
1019 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
1020 return nullptr;
1021 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
1022 Sym.Definition->range.contains(Point.position))
1023 return &Sym.PreferredDeclaration;
1024 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
1025 Sym.PreferredDeclaration.range.contains(Point.position))
1026 return &*Sym.Definition;
1027 return nullptr;
1028}
1029
Sam McCall2c30fbc2018-10-18 12:32:04 +00001030void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
1031 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +00001032 Server->locateSymbolAt(
1033 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001034 [Params, Reply = std::move(Reply)](
1035 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1036 if (!Symbols)
1037 return Reply(Symbols.takeError());
1038 std::vector<Location> Defs;
1039 for (auto &S : *Symbols) {
1040 if (Location *Toggle = getToggle(Params, S))
1041 return Reply(std::vector<Location>{std::move(*Toggle)});
1042 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
1043 }
1044 Reply(std::move(Defs));
1045 });
Sam McCall866ba2c2019-02-01 11:26:13 +00001046}
1047
1048void ClangdLSPServer::onGoToDeclaration(
1049 const TextDocumentPositionParams &Params,
1050 Callback<std::vector<Location>> Reply) {
1051 Server->locateSymbolAt(
1052 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001053 [Params, Reply = std::move(Reply)](
1054 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1055 if (!Symbols)
1056 return Reply(Symbols.takeError());
1057 std::vector<Location> Decls;
1058 for (auto &S : *Symbols) {
1059 if (Location *Toggle = getToggle(Params, S))
1060 return Reply(std::vector<Location>{std::move(*Toggle)});
1061 Decls.push_back(std::move(S.PreferredDeclaration));
1062 }
1063 Reply(std::move(Decls));
1064 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001065}
1066
Sam McCall111fe842019-05-07 07:55:35 +00001067void ClangdLSPServer::onSwitchSourceHeader(
1068 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +00001069 Callback<llvm::Optional<URIForFile>> Reply) {
Haojian Wud6d5edd2019-10-01 10:21:15 +00001070 Server->switchSourceHeader(
1071 Params.uri.file(),
1072 [Reply = std::move(Reply),
1073 Params](llvm::Expected<llvm::Optional<clangd::Path>> Path) mutable {
1074 if (!Path)
1075 return Reply(Path.takeError());
1076 if (*Path)
Haojian Wu77c97002019-10-07 11:37:25 +00001077 return Reply(URIForFile::canonicalize(**Path, Params.uri.file()));
Haojian Wud6d5edd2019-10-01 10:21:15 +00001078 return Reply(llvm::None);
1079 });
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +00001080}
1081
Sam McCall2c30fbc2018-10-18 12:32:04 +00001082void ClangdLSPServer::onDocumentHighlight(
1083 const TextDocumentPositionParams &Params,
1084 Callback<std::vector<DocumentHighlight>> Reply) {
1085 Server->findDocumentHighlights(Params.textDocument.uri.file(),
1086 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +00001087}
1088
Sam McCall2c30fbc2018-10-18 12:32:04 +00001089void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001090 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001091 Server->findHover(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001092 [Reply = std::move(Reply), this](
1093 llvm::Expected<llvm::Optional<HoverInfo>> H) mutable {
1094 if (!H)
1095 return Reply(H.takeError());
1096 if (!*H)
1097 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +00001098
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001099 Hover R;
1100 R.contents.kind = HoverContentFormat;
1101 R.range = (*H)->SymRange;
1102 switch (HoverContentFormat) {
1103 case MarkupKind::PlainText:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001104 R.contents.value = (*H)->present().asPlainText();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001105 return Reply(std::move(R));
1106 case MarkupKind::Markdown:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001107 R.contents.value = (*H)->present().asMarkdown();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001108 return Reply(std::move(R));
1109 };
1110 llvm_unreachable("unhandled MarkupKind");
1111 });
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +00001112}
1113
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001114void ClangdLSPServer::onTypeHierarchy(
1115 const TypeHierarchyParams &Params,
1116 Callback<Optional<TypeHierarchyItem>> Reply) {
1117 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
1118 Params.resolve, Params.direction, std::move(Reply));
1119}
1120
Nathan Ridge087b0442019-07-13 03:24:48 +00001121void ClangdLSPServer::onResolveTypeHierarchy(
1122 const ResolveTypeHierarchyItemParams &Params,
1123 Callback<Optional<TypeHierarchyItem>> Reply) {
1124 Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
1125 std::move(Reply));
1126}
1127
Simon Marchi88016782018-08-01 11:28:49 +00001128void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +00001129 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +00001130 // Per-file update to the compilation database.
David Goldman60249c22020-01-13 17:01:10 -05001131 llvm::StringSet<> ModifiedFiles;
Sam McCallbc904612018-10-25 04:22:52 +00001132 for (auto &Entry : Settings.compilationDatabaseChanges) {
Sam McCallbc904612018-10-25 04:22:52 +00001133 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +00001134 auto Old = CDB->getCompileCommand(File);
1135 auto New =
1136 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
1137 std::move(Entry.second.compilationCommand),
1138 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +00001139 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +00001140 CDB->setCompileCommand(File, std::move(New));
David Goldman60249c22020-01-13 17:01:10 -05001141 ModifiedFiles.insert(File);
Sam McCall6980edb2018-11-02 14:07:51 +00001142 }
Alex Lorenzf8087862018-08-01 17:39:29 +00001143 }
David Goldman60249c22020-01-13 17:01:10 -05001144
1145 reparseOpenedFiles(ModifiedFiles);
Simon Marchi5178f922018-02-22 14:00:39 +00001146}
1147
Johan Vikstroma848dab2019-07-04 07:53:12 +00001148void ClangdLSPServer::publishSemanticHighlighting(
1149 SemanticHighlightingParams Params) {
1150 notify("textDocument/semanticHighlighting", Params);
1151}
1152
Ilya Biryukov49c10712019-03-25 10:15:11 +00001153void ClangdLSPServer::publishDiagnostics(
1154 const URIForFile &File, std::vector<clangd::Diagnostic> Diagnostics) {
1155 // Publish diagnostics.
1156 notify("textDocument/publishDiagnostics",
1157 llvm::json::Object{
1158 {"uri", File},
1159 {"diagnostics", std::move(Diagnostics)},
1160 });
1161}
1162
Simon Marchi88016782018-08-01 11:28:49 +00001163// FIXME: This function needs to be properly tested.
1164void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +00001165 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +00001166 applyConfiguration(Params.settings);
1167}
1168
Sam McCall2c30fbc2018-10-18 12:32:04 +00001169void ClangdLSPServer::onReference(const ReferenceParams &Params,
1170 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001171 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wu5181ada2019-11-18 11:35:00 +01001172 CCOpts.Limit,
1173 [Reply = std::move(Reply)](
1174 llvm::Expected<ReferencesResult> Refs) mutable {
1175 if (!Refs)
1176 return Reply(Refs.takeError());
1177 return Reply(std::move(Refs->References));
1178 });
Sam McCall1ad142f2018-09-05 11:53:07 +00001179}
1180
Jan Korousb4067012018-11-27 16:40:46 +00001181void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
1182 Callback<std::vector<SymbolDetails>> Reply) {
1183 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
1184 std::move(Reply));
1185}
1186
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001187void ClangdLSPServer::onSelectionRange(
1188 const SelectionRangeParams &Params,
1189 Callback<std::vector<SelectionRange>> Reply) {
1190 if (Params.positions.size() != 1) {
1191 elog("{0} positions provided to SelectionRange. Supports exactly one "
1192 "position.",
1193 Params.positions.size());
1194 return Reply(llvm::make_error<LSPError>(
1195 "SelectionRange supports exactly one position",
1196 ErrorCode::InvalidRequest));
1197 }
1198 Server->semanticRanges(
1199 Params.textDocument.uri.file(), Params.positions[0],
1200 [Reply = std::move(Reply)](
1201 llvm::Expected<std::vector<Range>> Ranges) mutable {
1202 if (!Ranges) {
1203 return Reply(Ranges.takeError());
1204 }
1205 std::vector<SelectionRange> Result;
1206 Result.emplace_back(render(std::move(*Ranges)));
1207 return Reply(std::move(Result));
1208 });
1209}
1210
Sam McCall8d7ecc12019-12-16 19:08:51 +01001211void ClangdLSPServer::onDocumentLink(
1212 const DocumentLinkParams &Params,
1213 Callback<std::vector<DocumentLink>> Reply) {
1214
1215 // TODO(forster): This currently resolves all targets eagerly. This is slow,
1216 // because it blocks on the preamble/AST being built. We could respond to the
1217 // request faster by using string matching or the lexer to find the includes
1218 // and resolving the targets lazily.
1219 Server->documentLinks(
1220 Params.textDocument.uri.file(),
1221 [Reply = std::move(Reply)](
1222 llvm::Expected<std::vector<DocumentLink>> Links) mutable {
1223 if (!Links) {
1224 return Reply(Links.takeError());
1225 }
1226 return Reply(std::move(Links));
1227 });
1228}
1229
Sam McCalla69698f2019-03-27 17:47:49 +00001230ClangdLSPServer::ClangdLSPServer(
1231 class Transport &Transp, const FileSystemProvider &FSProvider,
1232 const clangd::CodeCompleteOptions &CCOpts,
1233 llvm::Optional<Path> CompileCommandsDir, bool UseDirBasedCDB,
1234 llvm::Optional<OffsetEncoding> ForcedOffsetEncoding,
1235 const ClangdServer::Options &Opts)
Kadir Cetinkaya9d662472019-10-15 14:20:52 +00001236 : BackgroundContext(Context::current().clone()), Transp(Transp),
1237 MsgHandler(new MessageHandler(*this)), FSProvider(FSProvider),
1238 CCOpts(CCOpts), SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +00001239 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +00001240 UseDirBasedCDB(UseDirBasedCDB),
Sam McCalla69698f2019-03-27 17:47:49 +00001241 CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts),
1242 NegotiatedOffsetEncoding(ForcedOffsetEncoding) {
Sam McCall2c30fbc2018-10-18 12:32:04 +00001243 // clang-format off
1244 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
1245 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +00001246 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001247 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
1248 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
1249 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
1250 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
1251 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
1252 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
1253 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +00001254 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001255 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
1256 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
Haojian Wuf429ab62019-07-24 07:49:23 +00001257 MsgHandler->bind("textDocument/prepareRename", &ClangdLSPServer::onPrepareRename);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001258 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
1259 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
1260 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
1261 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
1262 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
1263 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
1264 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
1265 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
1266 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
1267 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
1268 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +00001269 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001270 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Nathan Ridge087b0442019-07-13 03:24:48 +00001271 MsgHandler->bind("typeHierarchy/resolve", &ClangdLSPServer::onResolveTypeHierarchy);
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001272 MsgHandler->bind("textDocument/selectionRange", &ClangdLSPServer::onSelectionRange);
Sam McCall8d7ecc12019-12-16 19:08:51 +01001273 MsgHandler->bind("textDocument/documentLink", &ClangdLSPServer::onDocumentLink);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001274 // clang-format on
1275}
1276
Sam McCall8bda5f22019-10-23 11:11:18 +02001277ClangdLSPServer::~ClangdLSPServer() { IsBeingDestroyed = true;
1278 // Explicitly destroy ClangdServer first, blocking on threads it owns.
1279 // This ensures they don't access any other members.
1280 Server.reset();
1281}
Ilya Biryukov38d79772017-05-16 09:38:59 +00001282
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001283bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +00001284 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001285 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +00001286 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001287 elog("Transport error: {0}", std::move(Err));
1288 CleanExit = false;
1289 }
Ilya Biryukovafb55542017-05-16 14:40:30 +00001290
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001291 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001292}
1293
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001294std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +00001295 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001296 std::lock_guard<std::mutex> Lock(FixItsMutex);
1297 auto DiagToFixItsIter = FixItsMap.find(File);
1298 if (DiagToFixItsIter == FixItsMap.end())
1299 return {};
1300
1301 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1302 auto FixItsIter = DiagToFixItsMap.find(D);
1303 if (FixItsIter == DiagToFixItsMap.end())
1304 return {};
1305
1306 return FixItsIter->second;
1307}
1308
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001309bool ClangdLSPServer::shouldRunCompletion(
1310 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001311 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001312 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
1313 (Trigger != ">" && Trigger != ":"))
1314 return true;
1315
1316 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1317 if (!Code)
1318 return true; // completion code will log the error for untracked doc.
1319
1320 // A completion request is sent when the user types '>' or ':', but we only
1321 // want to trigger on '->' and '::'. We check the preceeding character to make
1322 // sure it matches what we expected.
1323 // Running the lexer here would be more robust (e.g. we can detect comments
1324 // and avoid triggering completion there), but we choose to err on the side
1325 // of simplicity here.
1326 auto Offset = positionToOffset(*Code, Params.position,
1327 /*AllowColumnsBeyondLineLength=*/false);
1328 if (!Offset) {
1329 vlog("could not convert position '{0}' to offset for file '{1}'",
1330 Params.position, Params.textDocument.uri.file());
1331 return true;
1332 }
1333 if (*Offset < 2)
1334 return false;
1335
1336 if (Trigger == ">")
1337 return (*Code)[*Offset - 2] == '-'; // trigger only on '->'.
1338 if (Trigger == ":")
1339 return (*Code)[*Offset - 2] == ':'; // trigger only on '::'.
1340 assert(false && "unhandled trigger character");
1341 return true;
1342}
1343
Johan Vikstroma848dab2019-07-04 07:53:12 +00001344void ClangdLSPServer::onHighlightingsReady(
Haojian Wu0a6000f2019-08-26 08:38:45 +00001345 PathRef File, std::vector<HighlightingToken> Highlightings) {
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001346 std::vector<HighlightingToken> Old;
1347 std::vector<HighlightingToken> HighlightingsCopy = Highlightings;
1348 {
1349 std::lock_guard<std::mutex> Lock(HighlightingsMutex);
1350 Old = std::move(FileToHighlightings[File]);
1351 FileToHighlightings[File] = std::move(HighlightingsCopy);
1352 }
1353 // LSP allows us to send incremental edits of highlightings. Also need to diff
1354 // to remove highlightings from tokens that should no longer have them.
Haojian Wu0a6000f2019-08-26 08:38:45 +00001355 std::vector<LineHighlightings> Diffed = diffHighlightings(Highlightings, Old);
Johan Vikstroma848dab2019-07-04 07:53:12 +00001356 publishSemanticHighlighting(
1357 {{URIForFile::canonicalize(File, /*TUPath=*/File)},
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001358 toSemanticHighlightingInformation(Diffed)});
Johan Vikstroma848dab2019-07-04 07:53:12 +00001359}
1360
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001361void ClangdLSPServer::onDiagnosticsReady(PathRef File,
1362 std::vector<Diag> Diagnostics) {
Eric Liu4d814a92018-11-28 10:30:42 +00001363 auto URI = URIForFile::canonicalize(File, /*TUPath=*/File);
Sam McCall16e70702018-10-24 07:59:38 +00001364 std::vector<Diagnostic> LSPDiagnostics;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001365 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001366 for (auto &Diag : Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +00001367 toLSPDiags(Diag, URI, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001368 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001369 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1370 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
1371 LSPDiagnostics.push_back(std::move(Diag));
1372 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001373 }
1374
1375 // Cache FixIts
1376 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001377 std::lock_guard<std::mutex> Lock(FixItsMutex);
1378 FixItsMap[File] = LocalFixIts;
1379 }
1380
Ilya Biryukov49c10712019-03-25 10:15:11 +00001381 // Send a notification to the LSP client.
1382 publishDiagnostics(URI, std::move(LSPDiagnostics));
Ilya Biryukov38d79772017-05-16 09:38:59 +00001383}
Simon Marchi9569fd52018-03-16 14:30:42 +00001384
Sam McCall7d20e802020-01-22 19:41:45 +01001385void ClangdLSPServer::onBackgroundIndexProgress(
1386 const BackgroundQueue::Stats &Stats) {
1387 static const char ProgressToken[] = "backgroundIndexProgress";
1388 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1389
1390 auto NotifyProgress = [this](const BackgroundQueue::Stats &Stats) {
1391 if (BackgroundIndexProgressState != BackgroundIndexProgress::Live) {
1392 WorkDoneProgressBegin Begin;
1393 Begin.percentage = true;
1394 Begin.title = "indexing";
1395 progress(ProgressToken, std::move(Begin));
1396 BackgroundIndexProgressState = BackgroundIndexProgress::Live;
1397 }
1398
1399 if (Stats.Completed < Stats.Enqueued) {
1400 assert(Stats.Enqueued > Stats.LastIdle);
1401 WorkDoneProgressReport Report;
1402 Report.percentage = 100.0 * (Stats.Completed - Stats.LastIdle) /
1403 (Stats.Enqueued - Stats.LastIdle);
1404 Report.message =
1405 llvm::formatv("{0}/{1}", Stats.Completed - Stats.LastIdle,
1406 Stats.Enqueued - Stats.LastIdle);
1407 progress(ProgressToken, std::move(Report));
1408 } else {
1409 assert(Stats.Completed == Stats.Enqueued);
1410 progress(ProgressToken, WorkDoneProgressEnd());
1411 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
1412 }
1413 };
1414
1415 switch (BackgroundIndexProgressState) {
1416 case BackgroundIndexProgress::Unsupported:
1417 return;
1418 case BackgroundIndexProgress::Creating:
1419 // Cache this update for when the progress bar is available.
1420 PendingBackgroundIndexProgress = Stats;
1421 return;
1422 case BackgroundIndexProgress::Empty: {
1423 if (BackgroundIndexSkipCreate) {
1424 NotifyProgress(Stats);
1425 break;
1426 }
1427 // Cache this update for when the progress bar is available.
1428 PendingBackgroundIndexProgress = Stats;
1429 BackgroundIndexProgressState = BackgroundIndexProgress::Creating;
1430 WorkDoneProgressCreateParams CreateRequest;
1431 CreateRequest.token = ProgressToken;
1432 call<std::nullptr_t>(
1433 "window/workDoneProgress/create", CreateRequest,
1434 [this, NotifyProgress](llvm::Expected<std::nullptr_t> E) {
1435 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1436 if (E) {
1437 NotifyProgress(this->PendingBackgroundIndexProgress);
1438 } else {
1439 elog("Failed to create background index progress bar: {0}",
1440 E.takeError());
1441 // give up forever rather than thrashing about
1442 BackgroundIndexProgressState = BackgroundIndexProgress::Unsupported;
1443 }
1444 });
1445 break;
1446 }
1447 case BackgroundIndexProgress::Live:
1448 NotifyProgress(Stats);
1449 break;
1450 }
1451}
1452
Haojian Wub6188492018-12-20 15:39:12 +00001453void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1454 if (!SupportFileStatus)
1455 return;
1456 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1457 // two statuses are running faster in practice, which leads the UI constantly
1458 // changing, and doesn't provide much value. We may want to emit status at a
1459 // reasonable time interval (e.g. 0.5s).
1460 if (Status.Action.S == TUAction::BuildingFile ||
1461 Status.Action.S == TUAction::RunningAction)
1462 return;
1463 notify("textDocument/clangd.fileStatus", Status.render(File));
1464}
1465
David Goldman60249c22020-01-13 17:01:10 -05001466void ClangdLSPServer::reparseOpenedFiles(
1467 const llvm::StringSet<> &ModifiedFiles) {
1468 if (ModifiedFiles.empty())
1469 return;
1470 // Reparse only opened files that were modified.
Simon Marchi9569fd52018-03-16 14:30:42 +00001471 for (const Path &FilePath : DraftMgr.getActiveFiles())
David Goldman60249c22020-01-13 17:01:10 -05001472 if (ModifiedFiles.find(FilePath) != ModifiedFiles.end())
1473 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
1474 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001475}
Alex Lorenzf8087862018-08-01 17:39:29 +00001476
Sam McCallc008af62018-10-20 15:30:37 +00001477} // namespace clangd
1478} // namespace clang