blob: 982e05f68fdd4478bea19adb887b057f142476b0 [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:
51 CA.kind = CodeAction::REFACTOR_KIND;
52 break;
53 case Tweak::Info:
54 CA.kind = CodeAction::INFO_KIND;
55 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;
64 CA.command->command = Command::CLANGD_APPLY_TWEAK;
65 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)
103 LookupTable.push_back({toTextMateScope((HighlightingKind)(KindValue))});
104 return LookupTable;
105}
106
Haojian Wu852bafa2019-10-23 14:40:20 +0200107// Makes sure edits in \p FE are applicable to latest file contents reported by
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000108// editor. If not generates an error message containing information about files
109// that needs to be saved.
Haojian Wu852bafa2019-10-23 14:40:20 +0200110llvm::Error validateEdits(const DraftStore &DraftMgr, const FileEdits &FE) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000111 size_t InvalidFileCount = 0;
112 llvm::StringRef LastInvalidFile;
Haojian Wu852bafa2019-10-23 14:40:20 +0200113 for (const auto &It : FE) {
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000114 if (auto Draft = DraftMgr.getDraft(It.first())) {
115 // If the file is open in user's editor, make sure the version we
116 // saw and current version are compatible as this is the text that
117 // will be replaced by editors.
118 if (!It.second.canApplyTo(*Draft)) {
119 ++InvalidFileCount;
120 LastInvalidFile = It.first();
121 }
122 }
123 }
124 if (!InvalidFileCount)
125 return llvm::Error::success();
126 if (InvalidFileCount == 1)
127 return llvm::createStringError(llvm::inconvertibleErrorCode(),
128 "File must be saved first: " +
129 LastInvalidFile);
130 return llvm::createStringError(
131 llvm::inconvertibleErrorCode(),
132 "Files must be saved first: " + LastInvalidFile + " (and " +
133 llvm::to_string(InvalidFileCount - 1) + " others)");
134}
135
Utkarsh Saxena55925da2019-09-24 13:38:33 +0000136// Converts a list of Ranges to a LinkedList of SelectionRange.
137SelectionRange render(const std::vector<Range> &Ranges) {
138 if (Ranges.empty())
139 return {};
140 SelectionRange Result;
141 Result.range = Ranges[0];
142 auto *Next = &Result.parent;
143 for (const auto &R : llvm::make_range(Ranges.begin() + 1, Ranges.end())) {
144 *Next = std::make_unique<SelectionRange>();
145 Next->get()->range = R;
146 Next = &Next->get()->parent;
147 }
148 return Result;
149}
150
Ilya Biryukovafb55542017-05-16 14:40:30 +0000151} // namespace
152
Sam McCall2c30fbc2018-10-18 12:32:04 +0000153// MessageHandler dispatches incoming LSP messages.
154// It handles cross-cutting concerns:
155// - serializes/deserializes protocol objects to JSON
156// - logging of inbound messages
157// - cancellation handling
158// - basic call tracing
Sam McCall3d0adbe2018-10-18 14:41:50 +0000159// MessageHandler ensures that initialize() is called before any other handler.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000160class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
161public:
162 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
163
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000164 bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000165 WithContext HandlerContext(handlerContext());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000166 log("<-- {0}", Method);
167 if (Method == "exit")
168 return false;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000169 if (!Server.Server)
170 elog("Notification {0} before initialization", Method);
171 else if (Method == "$/cancelRequest")
Sam McCall2c30fbc2018-10-18 12:32:04 +0000172 onCancel(std::move(Params));
173 else if (auto Handler = Notifications.lookup(Method))
174 Handler(std::move(Params));
175 else
176 log("unhandled notification {0}", Method);
177 return true;
178 }
179
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000180 bool onCall(llvm::StringRef Method, llvm::json::Value Params,
181 llvm::json::Value ID) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000182 WithContext HandlerContext(handlerContext());
Sam McCalle2f3a732018-10-24 14:26:26 +0000183 // Calls can be canceled by the client. Add cancellation context.
184 WithContext WithCancel(cancelableRequestContext(ID));
185 trace::Span Tracer(Method);
186 SPAN_ATTACH(Tracer, "Params", Params);
187 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000188 log("<-- {0}({1})", Method, ID);
Sam McCall3d0adbe2018-10-18 14:41:50 +0000189 if (!Server.Server && Method != "initialize") {
190 elog("Call {0} before initialization.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000191 Reply(llvm::make_error<LSPError>("server not initialized",
192 ErrorCode::ServerNotInitialized));
Sam McCall3d0adbe2018-10-18 14:41:50 +0000193 } else if (auto Handler = Calls.lookup(Method))
Sam McCalle2f3a732018-10-24 14:26:26 +0000194 Handler(std::move(Params), std::move(Reply));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000195 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000196 Reply(llvm::make_error<LSPError>("method not found",
197 ErrorCode::MethodNotFound));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000198 return true;
199 }
200
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000201 bool onReply(llvm::json::Value ID,
202 llvm::Expected<llvm::json::Value> Result) override {
Sam McCalla69698f2019-03-27 17:47:49 +0000203 WithContext HandlerContext(handlerContext());
Haojian Wuf2516342019-08-05 12:48:09 +0000204
205 Callback<llvm::json::Value> ReplyHandler = nullptr;
206 if (auto IntID = ID.getAsInteger()) {
207 std::lock_guard<std::mutex> Mutex(CallMutex);
208 // Find a corresponding callback for the request ID;
209 for (size_t Index = 0; Index < ReplyCallbacks.size(); ++Index) {
210 if (ReplyCallbacks[Index].first == *IntID) {
211 ReplyHandler = std::move(ReplyCallbacks[Index].second);
212 ReplyCallbacks.erase(ReplyCallbacks.begin() +
213 Index); // remove the entry
214 break;
215 }
216 }
217 }
218
219 if (!ReplyHandler) {
220 // No callback being found, use a default log callback.
221 ReplyHandler = [&ID](llvm::Expected<llvm::json::Value> Result) {
222 elog("received a reply with ID {0}, but there was no such call", ID);
223 if (!Result)
224 llvm::consumeError(Result.takeError());
225 };
226 }
227
228 // Log and run the reply handler.
229 if (Result) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000230 log("<-- reply({0})", ID);
Haojian Wuf2516342019-08-05 12:48:09 +0000231 ReplyHandler(std::move(Result));
232 } else {
233 auto Err = Result.takeError();
234 log("<-- reply({0}) error: {1}", ID, Err);
235 ReplyHandler(std::move(Err));
236 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000237 return true;
238 }
239
240 // Bind an LSP method name to a call.
Sam McCalle2f3a732018-10-24 14:26:26 +0000241 template <typename Param, typename Result>
Sam McCall2c30fbc2018-10-18 12:32:04 +0000242 void bind(const char *Method,
Sam McCalle2f3a732018-10-24 14:26:26 +0000243 void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000244 Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
Sam McCalle2f3a732018-10-24 14:26:26 +0000245 ReplyOnce Reply) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000246 Param P;
Sam McCalle2f3a732018-10-24 14:26:26 +0000247 if (fromJSON(RawParams, P)) {
248 (Server.*Handler)(P, std::move(Reply));
249 } else {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000250 elog("Failed to decode {0} request.", Method);
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000251 Reply(llvm::make_error<LSPError>("failed to decode request",
252 ErrorCode::InvalidRequest));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000253 }
Sam McCall2c30fbc2018-10-18 12:32:04 +0000254 };
255 }
256
Haojian Wuf2516342019-08-05 12:48:09 +0000257 // Bind a reply callback to a request. The callback will be invoked when
258 // clangd receives the reply from the LSP client.
259 // Return a call id of the request.
260 llvm::json::Value bindReply(Callback<llvm::json::Value> Reply) {
261 llvm::Optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB;
262 int ID;
263 {
264 std::lock_guard<std::mutex> Mutex(CallMutex);
265 ID = NextCallID++;
266 ReplyCallbacks.emplace_back(ID, std::move(Reply));
267
268 // If the queue overflows, we assume that the client didn't reply the
269 // oldest request, and run the corresponding callback which replies an
270 // error to the client.
271 if (ReplyCallbacks.size() > MaxReplayCallbacks) {
272 elog("more than {0} outstanding LSP calls, forgetting about {1}",
273 MaxReplayCallbacks, ReplyCallbacks.front().first);
274 OldestCB = std::move(ReplyCallbacks.front());
275 ReplyCallbacks.pop_front();
276 }
277 }
278 if (OldestCB)
279 OldestCB->second(llvm::createStringError(
280 llvm::inconvertibleErrorCode(),
281 llvm::formatv("failed to receive a client reply for request ({0})",
282 OldestCB->first)));
283 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 McCall2c30fbc2018-10-18 12:32:04 +0000292 Param P;
293 if (!fromJSON(RawParams, P)) {
294 elog("Failed to decode {0} request.", Method);
295 return;
296 }
297 trace::Span Tracer(Method);
298 SPAN_ATTACH(Tracer, "Params", RawParams);
299 (Server.*Handler)(P);
300 };
301 }
302
303private:
Sam McCalle2f3a732018-10-24 14:26:26 +0000304 // Function object to reply to an LSP call.
305 // Each instance must be called exactly once, otherwise:
306 // - the bug is logged, and (in debug mode) an assert will fire
307 // - if there was no reply, an error reply is sent
308 // - if there were multiple replies, only the first is sent
309 class ReplyOnce {
310 std::atomic<bool> Replied = {false};
Sam McCalld7babe42018-10-24 15:18:40 +0000311 std::chrono::steady_clock::time_point Start;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000312 llvm::json::Value ID;
Sam McCalle2f3a732018-10-24 14:26:26 +0000313 std::string Method;
314 ClangdLSPServer *Server; // Null when moved-from.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000315 llvm::json::Object *TraceArgs;
Sam McCalle2f3a732018-10-24 14:26:26 +0000316
317 public:
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000318 ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
319 ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
Sam McCalld7babe42018-10-24 15:18:40 +0000320 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
321 Server(Server), TraceArgs(TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000322 assert(Server);
323 }
324 ReplyOnce(ReplyOnce &&Other)
Sam McCalld7babe42018-10-24 15:18:40 +0000325 : Replied(Other.Replied.load()), Start(Other.Start),
326 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
327 Server(Other.Server), TraceArgs(Other.TraceArgs) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000328 Other.Server = nullptr;
329 }
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000330 ReplyOnce &operator=(ReplyOnce &&) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000331 ReplyOnce(const ReplyOnce &) = delete;
Ilya Biryukov22fa4652019-01-03 13:28:05 +0000332 ReplyOnce &operator=(const ReplyOnce &) = delete;
Sam McCalle2f3a732018-10-24 14:26:26 +0000333
334 ~ReplyOnce() {
Haojian Wuf2516342019-08-05 12:48:09 +0000335 // There's one legitimate reason to never reply to a request: clangd's
336 // request handler send a call to the client (e.g. applyEdit) and the
337 // client never replied. In this case, the ReplyOnce is owned by
338 // ClangdLSPServer's reply callback table and is destroyed along with the
339 // server. We don't attempt to send a reply in this case, there's little
340 // to be gained from doing so.
341 if (Server && !Server->IsBeingDestroyed && !Replied) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000342 elog("No reply to message {0}({1})", Method, ID);
343 assert(false && "must reply to all calls!");
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000344 (*this)(llvm::make_error<LSPError>("server failed to reply",
345 ErrorCode::InternalError));
Sam McCalle2f3a732018-10-24 14:26:26 +0000346 }
347 }
348
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000349 void operator()(llvm::Expected<llvm::json::Value> Reply) {
Sam McCalle2f3a732018-10-24 14:26:26 +0000350 assert(Server && "moved-from!");
351 if (Replied.exchange(true)) {
352 elog("Replied twice to message {0}({1})", Method, ID);
353 assert(false && "must reply to each call only once!");
354 return;
355 }
Sam McCalld7babe42018-10-24 15:18:40 +0000356 auto Duration = std::chrono::steady_clock::now() - Start;
357 if (Reply) {
358 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
359 if (TraceArgs)
Sam McCalle2f3a732018-10-24 14:26:26 +0000360 (*TraceArgs)["Reply"] = *Reply;
Sam McCalld7babe42018-10-24 15:18:40 +0000361 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
362 Server->Transp.reply(std::move(ID), std::move(Reply));
363 } else {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000364 llvm::Error Err = Reply.takeError();
Sam McCalld7babe42018-10-24 15:18:40 +0000365 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
366 if (TraceArgs)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000367 (*TraceArgs)["Error"] = llvm::to_string(Err);
Sam McCalld7babe42018-10-24 15:18:40 +0000368 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
369 Server->Transp.reply(std::move(ID), std::move(Err));
Sam McCalle2f3a732018-10-24 14:26:26 +0000370 }
Sam McCalle2f3a732018-10-24 14:26:26 +0000371 }
372 };
373
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000374 llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
375 llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000376
377 // Method calls may be cancelled by ID, so keep track of their state.
378 // This needs a mutex: handlers may finish on a different thread, and that's
379 // when we clean up entries in the map.
380 mutable std::mutex RequestCancelersMutex;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000381 llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000382 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000383 void onCancel(const llvm::json::Value &Params) {
384 const llvm::json::Value *ID = nullptr;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000385 if (auto *O = Params.getAsObject())
386 ID = O->get("id");
387 if (!ID) {
388 elog("Bad cancellation request: {0}", Params);
389 return;
390 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000391 auto StrID = llvm::to_string(*ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000392 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
393 auto It = RequestCancelers.find(StrID);
394 if (It != RequestCancelers.end())
395 It->second.first(); // Invoke the canceler.
396 }
Sam McCalla69698f2019-03-27 17:47:49 +0000397
398 Context handlerContext() const {
399 return Context::current().derive(
400 kCurrentOffsetEncoding,
401 Server.NegotiatedOffsetEncoding.getValueOr(OffsetEncoding::UTF16));
402 }
403
Sam McCall2c30fbc2018-10-18 12:32:04 +0000404 // We run cancelable requests in a context that does two things:
405 // - allows cancellation using RequestCancelers[ID]
406 // - cleans up the entry in RequestCancelers when it's no longer needed
407 // If a client reuses an ID, the last wins and the first cannot be canceled.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000408 Context cancelableRequestContext(const llvm::json::Value &ID) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000409 auto Task = cancelableTask();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000410 auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
Sam McCall2c30fbc2018-10-18 12:32:04 +0000411 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
412 {
413 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
414 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
415 }
416 // When the request ends, we can clean up the entry we just added.
417 // The cookie lets us check that it hasn't been overwritten due to ID
418 // reuse.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000419 return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000420 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
421 auto It = RequestCancelers.find(StrID);
422 if (It != RequestCancelers.end() && It->second.second == Cookie)
423 RequestCancelers.erase(It);
424 }));
425 }
426
Kadir Cetinkaya9a3a87d2019-10-09 13:59:31 +0000427 // The maximum number of callbacks held in clangd.
428 //
429 // We bound the maximum size to the pending map to prevent memory leakage
430 // for cases where LSP clients don't reply for the request.
431 // This has to go after RequestCancellers and RequestCancellersMutex since it
432 // can contain a callback that has a cancelable context.
433 static constexpr int MaxReplayCallbacks = 100;
434 mutable std::mutex CallMutex;
435 int NextCallID = 0; /* GUARDED_BY(CallMutex) */
436 std::deque<std::pair</*RequestID*/ int,
437 /*ReplyHandler*/ Callback<llvm::json::Value>>>
438 ReplyCallbacks; /* GUARDED_BY(CallMutex) */
439
Sam McCall2c30fbc2018-10-18 12:32:04 +0000440 ClangdLSPServer &Server;
441};
Haojian Wuf2516342019-08-05 12:48:09 +0000442constexpr int ClangdLSPServer::MessageHandler::MaxReplayCallbacks;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000443
444// call(), notify(), and reply() wrap the Transport, adding logging and locking.
Haojian Wuf2516342019-08-05 12:48:09 +0000445void ClangdLSPServer::callRaw(StringRef Method, llvm::json::Value Params,
446 Callback<llvm::json::Value> CB) {
447 auto ID = MsgHandler->bindReply(std::move(CB));
Sam McCall2c30fbc2018-10-18 12:32:04 +0000448 log("--> {0}({1})", Method, ID);
Sam McCall2c30fbc2018-10-18 12:32:04 +0000449 std::lock_guard<std::mutex> Lock(TranspWriter);
450 Transp.call(Method, std::move(Params), ID);
451}
452
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000453void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
Sam McCall2c30fbc2018-10-18 12:32:04 +0000454 log("--> {0}", Method);
455 std::lock_guard<std::mutex> Lock(TranspWriter);
456 Transp.notify(Method, std::move(Params));
457}
458
Sam McCall2c30fbc2018-10-18 12:32:04 +0000459void ClangdLSPServer::onInitialize(const InitializeParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000460 Callback<llvm::json::Value> Reply) {
Sam McCalla69698f2019-03-27 17:47:49 +0000461 // Determine character encoding first as it affects constructed ClangdServer.
462 if (Params.capabilities.offsetEncoding && !NegotiatedOffsetEncoding) {
463 NegotiatedOffsetEncoding = OffsetEncoding::UTF16; // fallback
464 for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
465 if (Supported != OffsetEncoding::UnsupportedEncoding) {
466 NegotiatedOffsetEncoding = Supported;
467 break;
468 }
469 }
Sam McCalla69698f2019-03-27 17:47:49 +0000470
Johan Vikstroma848dab2019-07-04 07:53:12 +0000471 ClangdServerOpts.SemanticHighlighting =
472 Params.capabilities.SemanticHighlighting;
Sam McCall0d9b40f2018-10-19 15:42:23 +0000473 if (Params.rootUri && *Params.rootUri)
474 ClangdServerOpts.WorkspaceRoot = Params.rootUri->file();
475 else if (Params.rootPath && !Params.rootPath->empty())
476 ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
Sam McCall3d0adbe2018-10-18 14:41:50 +0000477 if (Server)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000478 return Reply(llvm::make_error<LSPError>("server already initialized",
479 ErrorCode::InvalidRequest));
Sam McCallbc904612018-10-25 04:22:52 +0000480 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
481 CompileCommandsDir = Dir;
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000482 if (UseDirBasedCDB) {
Jonas Devlieghere1c705d92019-08-14 23:52:23 +0000483 BaseCDB = std::make_unique<DirectoryBasedGlobalCompilationDatabase>(
Sam McCallc55d09a2018-11-02 13:09:36 +0000484 CompileCommandsDir);
Kadir Cetinkaya256247c2019-06-26 07:45:27 +0000485 BaseCDB = getQueryDriverDatabase(
486 llvm::makeArrayRef(ClangdServerOpts.QueryDriverGlobs),
487 std::move(BaseCDB));
488 }
Sam McCall99768b22019-11-29 19:37:48 +0100489 auto Mangler = CommandMangler::detect();
490 if (ClangdServerOpts.ResourceDir)
491 Mangler.ResourceDir = *ClangdServerOpts.ResourceDir;
Kadir Cetinkayabe6b35d2019-01-22 09:10:20 +0000492 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
Sam McCall99768b22019-11-29 19:37:48 +0100493 tooling::ArgumentsAdjuster(Mangler));
Kadir Cetinkaya9d662472019-10-15 14:20:52 +0000494 {
495 // Switch caller's context with LSPServer's background context. Since we
496 // rather want to propagate information from LSPServer's context into the
497 // Server, CDB, etc.
498 WithContext MainContext(BackgroundContext.clone());
499 llvm::Optional<WithContextValue> WithOffsetEncoding;
500 if (NegotiatedOffsetEncoding)
501 WithOffsetEncoding.emplace(kCurrentOffsetEncoding,
502 *NegotiatedOffsetEncoding);
Sam McCall6ef1cce2020-01-24 14:08:56 +0100503 Server.emplace(*CDB, FSProvider, ClangdServerOpts,
504 static_cast<ClangdServer::Callbacks *>(this));
Kadir Cetinkaya9d662472019-10-15 14:20:52 +0000505 }
Sam McCallbc904612018-10-25 04:22:52 +0000506 applyConfiguration(Params.initializationOptions.ConfigSettings);
Simon Marchi88016782018-08-01 11:28:49 +0000507
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000508 CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
Sam McCall8d412942019-06-18 11:57:26 +0000509 CCOpts.IncludeFixIts = Params.capabilities.CompletionFixes;
Sam McCall5f092e32019-07-08 17:27:15 +0000510 if (!CCOpts.BundleOverloads.hasValue())
511 CCOpts.BundleOverloads = Params.capabilities.HasSignatureHelp;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000512 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
513 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
Sam McCallc9e4ee92019-04-18 15:17:07 +0000514 DiagOpts.EmitRelatedLocations =
515 Params.capabilities.DiagnosticRelatedInformation;
Sam McCallbf6a2fc2018-10-17 07:33:42 +0000516 if (Params.capabilities.WorkspaceSymbolKinds)
517 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
518 if (Params.capabilities.CompletionItemKinds)
519 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
520 SupportsCodeAction = Params.capabilities.CodeActionStructure;
Ilya Biryukov19d75602018-11-23 15:21:19 +0000521 SupportsHierarchicalDocumentSymbol =
522 Params.capabilities.HierarchicalDocumentSymbol;
Haojian Wub6188492018-12-20 15:39:12 +0000523 SupportFileStatus = Params.initializationOptions.FileStatus;
Ilya Biryukovf9169d02019-05-29 10:01:00 +0000524 HoverContentFormat = Params.capabilities.HoverContentFormat;
Ilya Biryukov4ef0f822019-06-04 09:36:59 +0000525 SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
Sam McCall7d20e802020-01-22 19:41:45 +0100526 if (Params.capabilities.WorkDoneProgress)
527 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
528 BackgroundIndexSkipCreate = Params.capabilities.ImplicitProgressCreation;
Haojian Wuf429ab62019-07-24 07:49:23 +0000529
530 // Per LSP, renameProvider can be either boolean or RenameOptions.
531 // RenameOptions will be specified if the client states it supports prepare.
532 llvm::json::Value RenameProvider =
533 llvm::json::Object{{"prepareProvider", true}};
534 if (!Params.capabilities.RenamePrepareSupport) // Only boolean allowed per LSP
535 RenameProvider = true;
536
Haojian Wu08d93f12019-08-22 14:53:45 +0000537 // Per LSP, codeActionProvide can be either boolean or CodeActionOptions.
538 // CodeActionOptions is only valid if the client supports action literal
539 // via textDocument.codeAction.codeActionLiteralSupport.
540 llvm::json::Value CodeActionProvider = true;
541 if (Params.capabilities.CodeActionStructure)
542 CodeActionProvider = llvm::json::Object{
543 {"codeActionKinds",
544 {CodeAction::QUICKFIX_KIND, CodeAction::REFACTOR_KIND,
545 CodeAction::INFO_KIND}}};
546
Sam McCalla69698f2019-03-27 17:47:49 +0000547 llvm::json::Object Result{
Sam McCall0930ab02017-11-07 15:49:35 +0000548 {{"capabilities",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000549 llvm::json::Object{
Simon Marchi98082622018-03-26 14:41:40 +0000550 {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
Sam McCall0930ab02017-11-07 15:49:35 +0000551 {"documentFormattingProvider", true},
552 {"documentRangeFormattingProvider", true},
553 {"documentOnTypeFormattingProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000554 llvm::json::Object{
Sam McCall25c62572019-06-10 14:26:21 +0000555 {"firstTriggerCharacter", "\n"},
Sam McCall0930ab02017-11-07 15:49:35 +0000556 {"moreTriggerCharacter", {}},
557 }},
Haojian Wu08d93f12019-08-22 14:53:45 +0000558 {"codeActionProvider", std::move(CodeActionProvider)},
Sam McCall0930ab02017-11-07 15:49:35 +0000559 {"completionProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000560 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000561 {"resolveProvider", false},
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000562 // We do extra checks for '>' and ':' in completion to only
563 // trigger on '->' and '::'.
Sam McCall0930ab02017-11-07 15:49:35 +0000564 {"triggerCharacters", {".", ">", ":"}},
565 }},
566 {"signatureHelpProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000567 llvm::json::Object{
Sam McCall0930ab02017-11-07 15:49:35 +0000568 {"triggerCharacters", {"(", ","}},
569 }},
Sam McCall866ba2c2019-02-01 11:26:13 +0000570 {"declarationProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000571 {"definitionProvider", true},
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +0000572 {"documentHighlightProvider", true},
Sam McCall8d7ecc12019-12-16 19:08:51 +0100573 {"documentLinkProvider",
574 llvm::json::Object{
575 {"resolveProvider", false},
576 }},
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +0000577 {"hoverProvider", true},
Haojian Wuf429ab62019-07-24 07:49:23 +0000578 {"renameProvider", std::move(RenameProvider)},
Utkarsh Saxena55925da2019-09-24 13:38:33 +0000579 {"selectionRangeProvider", true},
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000580 {"documentSymbolProvider", true},
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000581 {"workspaceSymbolProvider", true},
Sam McCall1ad142f2018-09-05 11:53:07 +0000582 {"referencesProvider", true},
Sam McCall0930ab02017-11-07 15:49:35 +0000583 {"executeCommandProvider",
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000584 llvm::json::Object{
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000585 {"commands",
586 {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND,
587 ExecuteCommandParams::CLANGD_APPLY_TWEAK}},
Sam McCall0930ab02017-11-07 15:49:35 +0000588 }},
Kadir Cetinkaya86658022019-03-19 09:27:04 +0000589 {"typeHierarchyProvider", true},
Sam McCalla69698f2019-03-27 17:47:49 +0000590 }}}};
591 if (NegotiatedOffsetEncoding)
592 Result["offsetEncoding"] = *NegotiatedOffsetEncoding;
Johan Vikstroma848dab2019-07-04 07:53:12 +0000593 if (Params.capabilities.SemanticHighlighting)
594 Result.getObject("capabilities")
595 ->insert(
596 {"semanticHighlighting",
Haojian Wu1ca2ee42019-07-04 12:27:21 +0000597 llvm::json::Object{{"scopes", buildHighlightScopeLookupTable()}}});
Sam McCalla69698f2019-03-27 17:47:49 +0000598 Reply(std::move(Result));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000599}
600
Sam McCall2c30fbc2018-10-18 12:32:04 +0000601void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
602 Callback<std::nullptr_t> Reply) {
Ilya Biryukov0d9b8a32017-10-25 08:45:41 +0000603 // Do essentially nothing, just say we're ready to exit.
604 ShutdownRequestReceived = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000605 Reply(nullptr);
Sam McCall8a5dded2017-10-12 13:29:58 +0000606}
Ilya Biryukovafb55542017-05-16 14:40:30 +0000607
Sam McCall422c8282018-11-26 16:00:11 +0000608// sync is a clangd extension: it blocks until all background work completes.
609// It blocks the calling thread, so no messages are processed until it returns!
610void ClangdLSPServer::onSync(const NoParams &Params,
611 Callback<std::nullptr_t> Reply) {
612 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
613 Reply(nullptr);
614 else
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000615 Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
616 "Not idle after a minute"));
Sam McCall422c8282018-11-26 16:00:11 +0000617}
618
Sam McCall2c30fbc2018-10-18 12:32:04 +0000619void ClangdLSPServer::onDocumentDidOpen(
620 const DidOpenTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000621 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovb10ef472018-06-13 09:20:41 +0000622
Sam McCall2c30fbc2018-10-18 12:32:04 +0000623 const std::string &Contents = Params.textDocument.text;
Simon Marchi9569fd52018-03-16 14:30:42 +0000624
Simon Marchi98082622018-03-26 14:41:40 +0000625 DraftMgr.addDraft(File, Contents);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000626 Server->addDocument(File, Contents, WantDiagnostics::Yes);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000627}
628
Sam McCall2c30fbc2018-10-18 12:32:04 +0000629void ClangdLSPServer::onDocumentDidChange(
630 const DidChangeTextDocumentParams &Params) {
Eric Liu51fed182018-02-22 18:40:39 +0000631 auto WantDiags = WantDiagnostics::Auto;
632 if (Params.wantDiagnostics.hasValue())
633 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
634 : WantDiagnostics::No;
Simon Marchi9569fd52018-03-16 14:30:42 +0000635
636 PathRef File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000637 llvm::Expected<std::string> Contents =
Simon Marchi98082622018-03-26 14:41:40 +0000638 DraftMgr.updateDraft(File, Params.contentChanges);
639 if (!Contents) {
640 // If this fails, we are most likely going to be not in sync anymore with
641 // the client. It is better to remove the draft and let further operations
642 // fail rather than giving wrong results.
643 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000644 Server->removeDocument(File);
Sam McCallbed58852018-07-11 10:35:11 +0000645 elog("Failed to update {0}: {1}", File, Contents.takeError());
Simon Marchi98082622018-03-26 14:41:40 +0000646 return;
647 }
Simon Marchi9569fd52018-03-16 14:30:42 +0000648
Ilya Biryukov652364b2018-09-26 05:48:29 +0000649 Server->addDocument(File, *Contents, WantDiags);
Ilya Biryukovafb55542017-05-16 14:40:30 +0000650}
651
Sam McCall2c30fbc2018-10-18 12:32:04 +0000652void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000653 Server->onFileEvent(Params);
Marc-Andre Laperlebf114242017-10-02 18:00:37 +0000654}
655
Sam McCall2c30fbc2018-10-18 12:32:04 +0000656void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000657 Callback<llvm::json::Value> Reply) {
Ilya Biryukov12864002019-08-16 12:46:41 +0000658 auto ApplyEdit = [this](WorkspaceEdit WE, std::string SuccessMessage,
659 decltype(Reply) Reply) {
Eric Liuc5105f92018-02-16 14:15:55 +0000660 ApplyWorkspaceEditParams Edit;
661 Edit.edit = std::move(WE);
Ilya Biryukov12864002019-08-16 12:46:41 +0000662 call<ApplyWorkspaceEditResponse>(
663 "workspace/applyEdit", std::move(Edit),
664 [Reply = std::move(Reply), SuccessMessage = std::move(SuccessMessage)](
665 llvm::Expected<ApplyWorkspaceEditResponse> Response) mutable {
666 if (!Response)
667 return Reply(Response.takeError());
668 if (!Response->applied) {
669 std::string Reason = Response->failureReason
670 ? *Response->failureReason
671 : "unknown reason";
672 return Reply(llvm::createStringError(
673 llvm::inconvertibleErrorCode(),
674 ("edits were not applied: " + Reason).c_str()));
675 }
676 return Reply(SuccessMessage);
677 });
Eric Liuc5105f92018-02-16 14:15:55 +0000678 };
Ilya Biryukov12864002019-08-16 12:46:41 +0000679
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000680 if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND &&
681 Params.workspaceEdit) {
682 // The flow for "apply-fix" :
683 // 1. We publish a diagnostic, including fixits
684 // 2. The user clicks on the diagnostic, the editor asks us for code actions
685 // 3. We send code actions, with the fixit embedded as context
686 // 4. The user selects the fixit, the editor asks us to apply it
687 // 5. We unwrap the changes and send them back to the editor
Haojian Wuf2516342019-08-05 12:48:09 +0000688 // 6. The editor applies the changes (applyEdit), and sends us a reply
689 // 7. We unwrap the reply and send a reply to the editor.
Ilya Biryukov12864002019-08-16 12:46:41 +0000690 ApplyEdit(*Params.workspaceEdit, "Fix applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000691 } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
692 Params.tweakArgs) {
693 auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
694 if (!Code)
695 return Reply(llvm::createStringError(
696 llvm::inconvertibleErrorCode(),
697 "trying to apply a code action for a non-added file"));
698
Ilya Biryukov12864002019-08-16 12:46:41 +0000699 auto Action = [this, ApplyEdit, Reply = std::move(Reply),
700 File = Params.tweakArgs->file, Code = std::move(*Code)](
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000701 llvm::Expected<Tweak::Effect> R) mutable {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000702 if (!R)
703 return Reply(R.takeError());
704
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000705 assert(R->ShowMessage ||
706 (!R->ApplyEdits.empty() && "tweak has no effect"));
Ilya Biryukov12864002019-08-16 12:46:41 +0000707
Sam McCall395fde72019-06-18 13:37:54 +0000708 if (R->ShowMessage) {
709 ShowMessageParams Msg;
710 Msg.message = *R->ShowMessage;
711 Msg.type = MessageType::Info;
712 notify("window/showMessage", Msg);
713 }
Ilya Biryukov12864002019-08-16 12:46:41 +0000714 // When no edit is specified, make sure we Reply().
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000715 if (R->ApplyEdits.empty())
716 return Reply("Tweak applied.");
717
Haojian Wu852bafa2019-10-23 14:40:20 +0200718 if (auto Err = validateEdits(DraftMgr, R->ApplyEdits))
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000719 return Reply(std::move(Err));
720
721 WorkspaceEdit WE;
722 WE.changes.emplace();
723 for (const auto &It : R->ApplyEdits) {
Kadir Cetinkayae95e5162019-10-02 09:12:01 +0000724 (*WE.changes)[URI::createFile(It.first()).toString()] =
Kadir Cetinkaya5b270932019-09-09 12:28:44 +0000725 It.second.asTextEdits();
726 }
727 // ApplyEdit will take care of calling Reply().
728 return ApplyEdit(std::move(WE), "Tweak applied.", std::move(Reply));
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000729 };
730 Server->applyTweak(Params.tweakArgs->file.file(),
731 Params.tweakArgs->selection, Params.tweakArgs->tweakID,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000732 std::move(Action));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000733 } else {
734 // We should not get here because ExecuteCommandParams would not have
735 // parsed in the first place and this handler should not be called. But if
736 // more commands are added, this will be here has a safe guard.
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000737 Reply(llvm::make_error<LSPError>(
738 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
Sam McCall2c30fbc2018-10-18 12:32:04 +0000739 ErrorCode::InvalidParams));
Marc-Andre Laperlee7ec16a2017-11-03 13:39:15 +0000740 }
741}
742
Sam McCall2c30fbc2018-10-18 12:32:04 +0000743void ClangdLSPServer::onWorkspaceSymbol(
744 const WorkspaceSymbolParams &Params,
745 Callback<std::vector<SymbolInformation>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000746 Server->workspaceSymbols(
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000747 Params.query, CCOpts.Limit,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000748 [Reply = std::move(Reply),
749 this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable {
750 if (!Items)
751 return Reply(Items.takeError());
752 for (auto &Sym : *Items)
753 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000754
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000755 Reply(std::move(*Items));
756 });
Marc-Andre Laperleb387b6e2018-04-23 20:00:52 +0000757}
758
Haojian Wuf429ab62019-07-24 07:49:23 +0000759void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params,
760 Callback<llvm::Optional<Range>> Reply) {
761 Server->prepareRename(Params.textDocument.uri.file(), Params.position,
762 std::move(Reply));
763}
764
Sam McCall2c30fbc2018-10-18 12:32:04 +0000765void ClangdLSPServer::onRename(const RenameParams &Params,
766 Callback<WorkspaceEdit> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000767 Path File = Params.textDocument.uri.file();
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000768 llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000769 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000770 return Reply(llvm::make_error<LSPError>(
771 "onRename called for non-added file", ErrorCode::InvalidParams));
Haojian Wu852bafa2019-10-23 14:40:20 +0200772 Server->rename(
773 File, Params.position, Params.newName,
774 /*WantFormat=*/true,
775 [File, Params, Reply = std::move(Reply),
776 this](llvm::Expected<FileEdits> Edits) mutable {
777 if (!Edits)
778 return Reply(Edits.takeError());
779 if (auto Err = validateEdits(DraftMgr, *Edits))
780 return Reply(std::move(Err));
781 WorkspaceEdit Result;
782 Result.changes.emplace();
783 for (const auto &Rep : *Edits) {
784 (*Result.changes)[URI::createFile(Rep.first()).toString()] =
785 Rep.second.asTextEdits();
786 }
787 Reply(Result);
788 });
Haojian Wu345099c2017-11-09 11:30:04 +0000789}
790
Sam McCall2c30fbc2018-10-18 12:32:04 +0000791void ClangdLSPServer::onDocumentDidClose(
792 const DidCloseTextDocumentParams &Params) {
Simon Marchi9569fd52018-03-16 14:30:42 +0000793 PathRef File = Params.textDocument.uri.file();
794 DraftMgr.removeDraft(File);
Ilya Biryukov652364b2018-09-26 05:48:29 +0000795 Server->removeDocument(File);
Ilya Biryukov49c10712019-03-25 10:15:11 +0000796
797 {
798 std::lock_guard<std::mutex> Lock(FixItsMutex);
799 FixItsMap.erase(File);
800 }
Johan Vikstromc2653ef22019-08-01 08:08:44 +0000801 {
802 std::lock_guard<std::mutex> HLock(HighlightingsMutex);
803 FileToHighlightings.erase(File);
804 }
Ilya Biryukov49c10712019-03-25 10:15:11 +0000805 // clangd will not send updates for this file anymore, so we empty out the
806 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
807 // VSCode). Note that this cannot race with actual diagnostics responses
808 // because removeDocument() guarantees no diagnostic callbacks will be
809 // executed after it returns.
810 publishDiagnostics(URIForFile::canonicalize(File, /*TUPath=*/File), {});
Ilya Biryukovafb55542017-05-16 14:40:30 +0000811}
812
Sam McCall4db732a2017-09-30 10:08:52 +0000813void ClangdLSPServer::onDocumentOnTypeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000814 const DocumentOnTypeFormattingParams &Params,
815 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000816 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000817 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000818 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000819 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000820 "onDocumentOnTypeFormatting called for non-added file",
821 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000822
Sam McCall25c62572019-06-10 14:26:21 +0000823 Reply(Server->formatOnType(*Code, File, Params.position, Params.ch));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000824}
825
Sam McCall4db732a2017-09-30 10:08:52 +0000826void ClangdLSPServer::onDocumentRangeFormatting(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000827 const DocumentRangeFormattingParams &Params,
828 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000829 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000830 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000831 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000832 return Reply(llvm::make_error<LSPError>(
Sam McCall2c30fbc2018-10-18 12:32:04 +0000833 "onDocumentRangeFormatting called for non-added file",
834 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000835
Ilya Biryukov652364b2018-09-26 05:48:29 +0000836 auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
Raoul Wols212bcf82017-12-12 20:25:06 +0000837 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000838 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000839 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000840 Reply(ReplacementsOrError.takeError());
Ilya Biryukovafb55542017-05-16 14:40:30 +0000841}
842
Sam McCall2c30fbc2018-10-18 12:32:04 +0000843void ClangdLSPServer::onDocumentFormatting(
844 const DocumentFormattingParams &Params,
845 Callback<std::vector<TextEdit>> Reply) {
Ilya Biryukov7d60d202018-02-16 12:20:47 +0000846 auto File = Params.textDocument.uri.file();
Simon Marchi9569fd52018-03-16 14:30:42 +0000847 auto Code = DraftMgr.getDraft(File);
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000848 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000849 return Reply(llvm::make_error<LSPError>(
850 "onDocumentFormatting called for non-added file",
851 ErrorCode::InvalidParams));
Ilya Biryukov261c72e2018-01-17 12:30:24 +0000852
Ilya Biryukov652364b2018-09-26 05:48:29 +0000853 auto ReplacementsOrError = Server->formatFile(*Code, File);
Raoul Wols212bcf82017-12-12 20:25:06 +0000854 if (ReplacementsOrError)
Sam McCall2c30fbc2018-10-18 12:32:04 +0000855 Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
Raoul Wols212bcf82017-12-12 20:25:06 +0000856 else
Sam McCall2c30fbc2018-10-18 12:32:04 +0000857 Reply(ReplacementsOrError.takeError());
Sam McCall4db732a2017-09-30 10:08:52 +0000858}
859
Ilya Biryukov19d75602018-11-23 15:21:19 +0000860/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
861/// Used by the clients that do not support the hierarchical view.
862static std::vector<SymbolInformation>
863flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
864 const URIForFile &FileURI) {
865
866 std::vector<SymbolInformation> Results;
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000867 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
868 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000869 SymbolInformation SI;
870 SI.containerName = ParentName ? "" : *ParentName;
871 SI.name = S.name;
872 SI.kind = S.kind;
873 SI.location.range = S.range;
874 SI.location.uri = FileURI;
875
876 Results.push_back(std::move(SI));
877 std::string FullName =
878 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
879 for (auto &C : S.children)
880 Process(C, /*ParentName=*/FullName);
881 };
882 for (auto &S : Symbols)
883 Process(S, /*ParentName=*/"");
884 return Results;
885}
886
887void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000888 Callback<llvm::json::Value> Reply) {
Ilya Biryukov19d75602018-11-23 15:21:19 +0000889 URIForFile FileURI = Params.textDocument.uri;
Ilya Biryukov652364b2018-09-26 05:48:29 +0000890 Server->documentSymbols(
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000891 Params.textDocument.uri.file(),
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000892 [this, FileURI, Reply = std::move(Reply)](
893 llvm::Expected<std::vector<DocumentSymbol>> Items) mutable {
894 if (!Items)
895 return Reply(Items.takeError());
896 adjustSymbolKinds(*Items, SupportedSymbolKinds);
897 if (SupportsHierarchicalDocumentSymbol)
898 return Reply(std::move(*Items));
899 else
900 return Reply(flattenSymbolHierarchy(*Items, FileURI));
901 });
Marc-Andre Laperle1be69702018-07-05 19:35:01 +0000902}
903
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000904static llvm::Optional<Command> asCommand(const CodeAction &Action) {
Sam McCall20841d42018-10-16 16:29:41 +0000905 Command Cmd;
906 if (Action.command && Action.edit)
Sam McCallc008af62018-10-20 15:30:37 +0000907 return None; // Not representable. (We never emit these anyway).
Sam McCall20841d42018-10-16 16:29:41 +0000908 if (Action.command) {
909 Cmd = *Action.command;
910 } else if (Action.edit) {
911 Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
912 Cmd.workspaceEdit = *Action.edit;
913 } else {
Sam McCallc008af62018-10-20 15:30:37 +0000914 return None;
Sam McCall20841d42018-10-16 16:29:41 +0000915 }
916 Cmd.title = Action.title;
917 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
918 Cmd.title = "Apply fix: " + Cmd.title;
919 return Cmd;
920}
921
Sam McCall2c30fbc2018-10-18 12:32:04 +0000922void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000923 Callback<llvm::json::Value> Reply) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000924 URIForFile File = Params.textDocument.uri;
925 auto Code = DraftMgr.getDraft(File.file());
Sam McCall2c30fbc2018-10-18 12:32:04 +0000926 if (!Code)
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000927 return Reply(llvm::make_error<LSPError>(
928 "onCodeAction called for non-added file", ErrorCode::InvalidParams));
Sam McCall20841d42018-10-16 16:29:41 +0000929 // We provide a code action for Fixes on the specified diagnostics.
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000930 std::vector<CodeAction> FixIts;
Sam McCall2c30fbc2018-10-18 12:32:04 +0000931 for (const Diagnostic &D : Params.context.diagnostics) {
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000932 for (auto &F : getFixes(File.file(), D)) {
933 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
934 FixIts.back().diagnostics = {D};
Sam McCalldd0566b2017-11-06 15:40:30 +0000935 }
Ilya Biryukovafb55542017-05-16 14:40:30 +0000936 }
Sam McCall20841d42018-10-16 16:29:41 +0000937
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000938 // Now enumerate the semantic code actions.
939 auto ConsumeActions =
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000940 [Reply = std::move(Reply), File, Code = std::move(*Code),
941 Selection = Params.range, FixIts = std::move(FixIts), this](
942 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable {
Ilya Biryukovc6ed7782019-01-30 14:24:17 +0000943 if (!Tweaks)
944 return Reply(Tweaks.takeError());
Ilya Biryukovcce67a32019-01-29 14:17:36 +0000945
946 std::vector<CodeAction> Actions = std::move(FixIts);
947 Actions.reserve(Actions.size() + Tweaks->size());
948 for (const auto &T : *Tweaks)
949 Actions.push_back(toCodeAction(T, File, Selection));
950
951 if (SupportsCodeAction)
952 return Reply(llvm::json::Array(Actions));
953 std::vector<Command> Commands;
954 for (const auto &Action : Actions) {
955 if (auto Command = asCommand(Action))
956 Commands.push_back(std::move(*Command));
957 }
958 return Reply(llvm::json::Array(Commands));
959 };
960
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000961 Server->enumerateTweaks(File.file(), Params.range, std::move(ConsumeActions));
Ilya Biryukovafb55542017-05-16 14:40:30 +0000962}
963
Ilya Biryukovb0826bd2019-01-03 13:37:12 +0000964void ClangdLSPServer::onCompletion(const CompletionParams &Params,
Sam McCall2c30fbc2018-10-18 12:32:04 +0000965 Callback<CompletionList> Reply) {
Ilya Biryukova7a11472019-06-07 16:24:38 +0000966 if (!shouldRunCompletion(Params)) {
967 // Clients sometimes auto-trigger completions in undesired places (e.g.
968 // 'a >^ '), we return empty results in those cases.
969 vlog("ignored auto-triggered completion, preceding char did not match");
970 return Reply(CompletionList());
971 }
Ilya Biryukovf2001aa2019-01-07 15:45:19 +0000972 Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000973 [Reply = std::move(Reply),
974 this](llvm::Expected<CodeCompleteResult> List) mutable {
975 if (!List)
976 return Reply(List.takeError());
977 CompletionList LSPList;
978 LSPList.isIncomplete = List->HasMore;
979 for (const auto &R : List->Completions) {
980 CompletionItem C = R.render(CCOpts);
981 C.kind = adjustKindToCapability(
982 C.kind, SupportedCompletionItemKinds);
983 LSPList.items.push_back(std::move(C));
984 }
985 return Reply(std::move(LSPList));
986 });
Ilya Biryukovd9bdfe02017-10-06 11:54:17 +0000987}
988
Sam McCall2c30fbc2018-10-18 12:32:04 +0000989void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
990 Callback<SignatureHelp> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +0000991 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +0000992 [Reply = std::move(Reply), this](
993 llvm::Expected<SignatureHelp> Signature) mutable {
994 if (!Signature)
995 return Reply(Signature.takeError());
996 if (SupportsOffsetsInSignatureHelp)
997 return Reply(std::move(*Signature));
998 // Strip out the offsets from signature help for
999 // clients that only support string labels.
1000 for (auto &SigInfo : Signature->signatures) {
1001 for (auto &Param : SigInfo.parameters)
1002 Param.labelOffsets.reset();
1003 }
1004 return Reply(std::move(*Signature));
1005 });
Ilya Biryukov652364b2018-09-26 05:48:29 +00001006}
1007
Sam McCall0dbab7f2019-02-02 05:56:00 +00001008// Go to definition has a toggle function: if def and decl are distinct, then
1009// the first press gives you the def, the second gives you the matching def.
1010// getToggle() returns the counterpart location that under the cursor.
1011//
1012// We return the toggled location alone (ignoring other symbols) to encourage
1013// editors to "bounce" quickly between locations, without showing a menu.
1014static Location *getToggle(const TextDocumentPositionParams &Point,
1015 LocatedSymbol &Sym) {
1016 // Toggle only makes sense with two distinct locations.
1017 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
1018 return nullptr;
1019 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
1020 Sym.Definition->range.contains(Point.position))
1021 return &Sym.PreferredDeclaration;
1022 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
1023 Sym.PreferredDeclaration.range.contains(Point.position))
1024 return &*Sym.Definition;
1025 return nullptr;
1026}
1027
Sam McCall2c30fbc2018-10-18 12:32:04 +00001028void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
1029 Callback<std::vector<Location>> Reply) {
Sam McCall866ba2c2019-02-01 11:26:13 +00001030 Server->locateSymbolAt(
1031 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001032 [Params, Reply = std::move(Reply)](
1033 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1034 if (!Symbols)
1035 return Reply(Symbols.takeError());
1036 std::vector<Location> Defs;
1037 for (auto &S : *Symbols) {
1038 if (Location *Toggle = getToggle(Params, S))
1039 return Reply(std::vector<Location>{std::move(*Toggle)});
1040 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
1041 }
1042 Reply(std::move(Defs));
1043 });
Sam McCall866ba2c2019-02-01 11:26:13 +00001044}
1045
1046void ClangdLSPServer::onGoToDeclaration(
1047 const TextDocumentPositionParams &Params,
1048 Callback<std::vector<Location>> Reply) {
1049 Server->locateSymbolAt(
1050 Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001051 [Params, Reply = std::move(Reply)](
1052 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1053 if (!Symbols)
1054 return Reply(Symbols.takeError());
1055 std::vector<Location> Decls;
1056 for (auto &S : *Symbols) {
1057 if (Location *Toggle = getToggle(Params, S))
1058 return Reply(std::vector<Location>{std::move(*Toggle)});
1059 Decls.push_back(std::move(S.PreferredDeclaration));
1060 }
1061 Reply(std::move(Decls));
1062 });
Marc-Andre Laperle2cbf0372017-06-28 16:12:10 +00001063}
1064
Sam McCall111fe842019-05-07 07:55:35 +00001065void ClangdLSPServer::onSwitchSourceHeader(
1066 const TextDocumentIdentifier &Params,
Sam McCallb9ec3e92019-05-07 08:30:32 +00001067 Callback<llvm::Optional<URIForFile>> Reply) {
Haojian Wud6d5edd2019-10-01 10:21:15 +00001068 Server->switchSourceHeader(
1069 Params.uri.file(),
1070 [Reply = std::move(Reply),
1071 Params](llvm::Expected<llvm::Optional<clangd::Path>> Path) mutable {
1072 if (!Path)
1073 return Reply(Path.takeError());
1074 if (*Path)
Haojian Wu77c97002019-10-07 11:37:25 +00001075 return Reply(URIForFile::canonicalize(**Path, Params.uri.file()));
Haojian Wud6d5edd2019-10-01 10:21:15 +00001076 return Reply(llvm::None);
1077 });
Marc-Andre Laperle6571b3e2017-09-28 03:14:40 +00001078}
1079
Sam McCall2c30fbc2018-10-18 12:32:04 +00001080void ClangdLSPServer::onDocumentHighlight(
1081 const TextDocumentPositionParams &Params,
1082 Callback<std::vector<DocumentHighlight>> Reply) {
1083 Server->findDocumentHighlights(Params.textDocument.uri.file(),
1084 Params.position, std::move(Reply));
Ilya Biryukov0e6a51f2017-12-12 12:27:47 +00001085}
1086
Sam McCall2c30fbc2018-10-18 12:32:04 +00001087void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001088 Callback<llvm::Optional<Hover>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001089 Server->findHover(Params.textDocument.uri.file(), Params.position,
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001090 [Reply = std::move(Reply), this](
1091 llvm::Expected<llvm::Optional<HoverInfo>> H) mutable {
1092 if (!H)
1093 return Reply(H.takeError());
1094 if (!*H)
1095 return Reply(llvm::None);
Ilya Biryukovf9169d02019-05-29 10:01:00 +00001096
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001097 Hover R;
1098 R.contents.kind = HoverContentFormat;
1099 R.range = (*H)->SymRange;
1100 switch (HoverContentFormat) {
1101 case MarkupKind::PlainText:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001102 R.contents.value = (*H)->present().asPlainText();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001103 return Reply(std::move(R));
1104 case MarkupKind::Markdown:
Kadir Cetinkaya597c6b62019-12-10 10:28:37 +01001105 R.contents.value = (*H)->present().asMarkdown();
Benjamin Kramer9880b5d2019-08-15 14:16:06 +00001106 return Reply(std::move(R));
1107 };
1108 llvm_unreachable("unhandled MarkupKind");
1109 });
Marc-Andre Laperle3e618ed2018-02-16 21:38:15 +00001110}
1111
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001112void ClangdLSPServer::onTypeHierarchy(
1113 const TypeHierarchyParams &Params,
1114 Callback<Optional<TypeHierarchyItem>> Reply) {
1115 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
1116 Params.resolve, Params.direction, std::move(Reply));
1117}
1118
Nathan Ridge087b0442019-07-13 03:24:48 +00001119void ClangdLSPServer::onResolveTypeHierarchy(
1120 const ResolveTypeHierarchyItemParams &Params,
1121 Callback<Optional<TypeHierarchyItem>> Reply) {
1122 Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
1123 std::move(Reply));
1124}
1125
Simon Marchi88016782018-08-01 11:28:49 +00001126void ClangdLSPServer::applyConfiguration(
Sam McCallbc904612018-10-25 04:22:52 +00001127 const ConfigurationSettings &Settings) {
Simon Marchiabeed662018-10-16 15:55:03 +00001128 // Per-file update to the compilation database.
David Goldman60249c22020-01-13 17:01:10 -05001129 llvm::StringSet<> ModifiedFiles;
Sam McCallbc904612018-10-25 04:22:52 +00001130 for (auto &Entry : Settings.compilationDatabaseChanges) {
Sam McCallbc904612018-10-25 04:22:52 +00001131 PathRef File = Entry.first;
Sam McCallc55d09a2018-11-02 13:09:36 +00001132 auto Old = CDB->getCompileCommand(File);
1133 auto New =
1134 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
1135 std::move(Entry.second.compilationCommand),
1136 /*Output=*/"");
Sam McCall6980edb2018-11-02 14:07:51 +00001137 if (Old != New) {
Sam McCallc55d09a2018-11-02 13:09:36 +00001138 CDB->setCompileCommand(File, std::move(New));
David Goldman60249c22020-01-13 17:01:10 -05001139 ModifiedFiles.insert(File);
Sam McCall6980edb2018-11-02 14:07:51 +00001140 }
Alex Lorenzf8087862018-08-01 17:39:29 +00001141 }
David Goldman60249c22020-01-13 17:01:10 -05001142
1143 reparseOpenedFiles(ModifiedFiles);
Simon Marchi5178f922018-02-22 14:00:39 +00001144}
1145
Johan Vikstroma848dab2019-07-04 07:53:12 +00001146void ClangdLSPServer::publishSemanticHighlighting(
1147 SemanticHighlightingParams Params) {
1148 notify("textDocument/semanticHighlighting", Params);
1149}
1150
Ilya Biryukov49c10712019-03-25 10:15:11 +00001151void ClangdLSPServer::publishDiagnostics(
1152 const URIForFile &File, std::vector<clangd::Diagnostic> Diagnostics) {
1153 // Publish diagnostics.
1154 notify("textDocument/publishDiagnostics",
1155 llvm::json::Object{
1156 {"uri", File},
1157 {"diagnostics", std::move(Diagnostics)},
1158 });
1159}
1160
Simon Marchi88016782018-08-01 11:28:49 +00001161// FIXME: This function needs to be properly tested.
1162void ClangdLSPServer::onChangeConfiguration(
Sam McCall2c30fbc2018-10-18 12:32:04 +00001163 const DidChangeConfigurationParams &Params) {
Simon Marchi88016782018-08-01 11:28:49 +00001164 applyConfiguration(Params.settings);
1165}
1166
Sam McCall2c30fbc2018-10-18 12:32:04 +00001167void ClangdLSPServer::onReference(const ReferenceParams &Params,
1168 Callback<std::vector<Location>> Reply) {
Ilya Biryukov652364b2018-09-26 05:48:29 +00001169 Server->findReferences(Params.textDocument.uri.file(), Params.position,
Haojian Wu5181ada2019-11-18 11:35:00 +01001170 CCOpts.Limit,
1171 [Reply = std::move(Reply)](
1172 llvm::Expected<ReferencesResult> Refs) mutable {
1173 if (!Refs)
1174 return Reply(Refs.takeError());
1175 return Reply(std::move(Refs->References));
1176 });
Sam McCall1ad142f2018-09-05 11:53:07 +00001177}
1178
Jan Korousb4067012018-11-27 16:40:46 +00001179void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
1180 Callback<std::vector<SymbolDetails>> Reply) {
1181 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
1182 std::move(Reply));
1183}
1184
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001185void ClangdLSPServer::onSelectionRange(
1186 const SelectionRangeParams &Params,
1187 Callback<std::vector<SelectionRange>> Reply) {
1188 if (Params.positions.size() != 1) {
1189 elog("{0} positions provided to SelectionRange. Supports exactly one "
1190 "position.",
1191 Params.positions.size());
1192 return Reply(llvm::make_error<LSPError>(
1193 "SelectionRange supports exactly one position",
1194 ErrorCode::InvalidRequest));
1195 }
1196 Server->semanticRanges(
1197 Params.textDocument.uri.file(), Params.positions[0],
1198 [Reply = std::move(Reply)](
1199 llvm::Expected<std::vector<Range>> Ranges) mutable {
1200 if (!Ranges) {
1201 return Reply(Ranges.takeError());
1202 }
1203 std::vector<SelectionRange> Result;
1204 Result.emplace_back(render(std::move(*Ranges)));
1205 return Reply(std::move(Result));
1206 });
1207}
1208
Sam McCall8d7ecc12019-12-16 19:08:51 +01001209void ClangdLSPServer::onDocumentLink(
1210 const DocumentLinkParams &Params,
1211 Callback<std::vector<DocumentLink>> Reply) {
1212
1213 // TODO(forster): This currently resolves all targets eagerly. This is slow,
1214 // because it blocks on the preamble/AST being built. We could respond to the
1215 // request faster by using string matching or the lexer to find the includes
1216 // and resolving the targets lazily.
1217 Server->documentLinks(
1218 Params.textDocument.uri.file(),
1219 [Reply = std::move(Reply)](
1220 llvm::Expected<std::vector<DocumentLink>> Links) mutable {
1221 if (!Links) {
1222 return Reply(Links.takeError());
1223 }
1224 return Reply(std::move(Links));
1225 });
1226}
1227
Sam McCalla69698f2019-03-27 17:47:49 +00001228ClangdLSPServer::ClangdLSPServer(
1229 class Transport &Transp, const FileSystemProvider &FSProvider,
1230 const clangd::CodeCompleteOptions &CCOpts,
1231 llvm::Optional<Path> CompileCommandsDir, bool UseDirBasedCDB,
1232 llvm::Optional<OffsetEncoding> ForcedOffsetEncoding,
1233 const ClangdServer::Options &Opts)
Kadir Cetinkaya9d662472019-10-15 14:20:52 +00001234 : BackgroundContext(Context::current().clone()), Transp(Transp),
1235 MsgHandler(new MessageHandler(*this)), FSProvider(FSProvider),
1236 CCOpts(CCOpts), SupportedSymbolKinds(defaultSymbolKinds()),
Kadir Cetinkaya133d46f2018-09-27 17:13:07 +00001237 SupportedCompletionItemKinds(defaultCompletionItemKinds()),
Sam McCallc55d09a2018-11-02 13:09:36 +00001238 UseDirBasedCDB(UseDirBasedCDB),
Sam McCalla69698f2019-03-27 17:47:49 +00001239 CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts),
1240 NegotiatedOffsetEncoding(ForcedOffsetEncoding) {
Sam McCall2c30fbc2018-10-18 12:32:04 +00001241 // clang-format off
1242 MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
1243 MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
Sam McCall422c8282018-11-26 16:00:11 +00001244 MsgHandler->bind("sync", &ClangdLSPServer::onSync);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001245 MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
1246 MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
1247 MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
1248 MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
1249 MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
1250 MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
1251 MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
Sam McCall866ba2c2019-02-01 11:26:13 +00001252 MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001253 MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
1254 MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
Haojian Wuf429ab62019-07-24 07:49:23 +00001255 MsgHandler->bind("textDocument/prepareRename", &ClangdLSPServer::onPrepareRename);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001256 MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
1257 MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
1258 MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
1259 MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
1260 MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
1261 MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
1262 MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
1263 MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
1264 MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
1265 MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
1266 MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
Jan Korousb4067012018-11-27 16:40:46 +00001267 MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
Kadir Cetinkaya86658022019-03-19 09:27:04 +00001268 MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
Nathan Ridge087b0442019-07-13 03:24:48 +00001269 MsgHandler->bind("typeHierarchy/resolve", &ClangdLSPServer::onResolveTypeHierarchy);
Utkarsh Saxena55925da2019-09-24 13:38:33 +00001270 MsgHandler->bind("textDocument/selectionRange", &ClangdLSPServer::onSelectionRange);
Sam McCall8d7ecc12019-12-16 19:08:51 +01001271 MsgHandler->bind("textDocument/documentLink", &ClangdLSPServer::onDocumentLink);
Sam McCall2c30fbc2018-10-18 12:32:04 +00001272 // clang-format on
1273}
1274
Sam McCall8bda5f22019-10-23 11:11:18 +02001275ClangdLSPServer::~ClangdLSPServer() { IsBeingDestroyed = true;
1276 // Explicitly destroy ClangdServer first, blocking on threads it owns.
1277 // This ensures they don't access any other members.
1278 Server.reset();
1279}
Ilya Biryukov38d79772017-05-16 09:38:59 +00001280
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001281bool ClangdLSPServer::run() {
Ilya Biryukovafb55542017-05-16 14:40:30 +00001282 // Run the Language Server loop.
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001283 bool CleanExit = true;
Sam McCall2c30fbc2018-10-18 12:32:04 +00001284 if (auto Err = Transp.loop(*MsgHandler)) {
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001285 elog("Transport error: {0}", std::move(Err));
1286 CleanExit = false;
1287 }
Ilya Biryukovafb55542017-05-16 14:40:30 +00001288
Sam McCalldc8f3cf2018-10-17 07:32:05 +00001289 return CleanExit && ShutdownRequestReceived;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001290}
1291
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001292std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
Ilya Biryukov71028b82018-03-12 15:28:22 +00001293 const clangd::Diagnostic &D) {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001294 std::lock_guard<std::mutex> Lock(FixItsMutex);
1295 auto DiagToFixItsIter = FixItsMap.find(File);
1296 if (DiagToFixItsIter == FixItsMap.end())
1297 return {};
1298
1299 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1300 auto FixItsIter = DiagToFixItsMap.find(D);
1301 if (FixItsIter == DiagToFixItsMap.end())
1302 return {};
1303
1304 return FixItsIter->second;
1305}
1306
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001307bool ClangdLSPServer::shouldRunCompletion(
1308 const CompletionParams &Params) const {
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001309 llvm::StringRef Trigger = Params.context.triggerCharacter;
Ilya Biryukovb0826bd2019-01-03 13:37:12 +00001310 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter ||
1311 (Trigger != ">" && Trigger != ":"))
1312 return true;
1313
1314 auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1315 if (!Code)
1316 return true; // completion code will log the error for untracked doc.
1317
1318 // A completion request is sent when the user types '>' or ':', but we only
1319 // want to trigger on '->' and '::'. We check the preceeding character to make
1320 // sure it matches what we expected.
1321 // Running the lexer here would be more robust (e.g. we can detect comments
1322 // and avoid triggering completion there), but we choose to err on the side
1323 // of simplicity here.
1324 auto Offset = positionToOffset(*Code, Params.position,
1325 /*AllowColumnsBeyondLineLength=*/false);
1326 if (!Offset) {
1327 vlog("could not convert position '{0}' to offset for file '{1}'",
1328 Params.position, Params.textDocument.uri.file());
1329 return true;
1330 }
1331 if (*Offset < 2)
1332 return false;
1333
1334 if (Trigger == ">")
1335 return (*Code)[*Offset - 2] == '-'; // trigger only on '->'.
1336 if (Trigger == ":")
1337 return (*Code)[*Offset - 2] == ':'; // trigger only on '::'.
1338 assert(false && "unhandled trigger character");
1339 return true;
1340}
1341
Johan Vikstroma848dab2019-07-04 07:53:12 +00001342void ClangdLSPServer::onHighlightingsReady(
Haojian Wu0a6000f2019-08-26 08:38:45 +00001343 PathRef File, std::vector<HighlightingToken> Highlightings) {
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001344 std::vector<HighlightingToken> Old;
1345 std::vector<HighlightingToken> HighlightingsCopy = Highlightings;
1346 {
1347 std::lock_guard<std::mutex> Lock(HighlightingsMutex);
1348 Old = std::move(FileToHighlightings[File]);
1349 FileToHighlightings[File] = std::move(HighlightingsCopy);
1350 }
1351 // LSP allows us to send incremental edits of highlightings. Also need to diff
1352 // to remove highlightings from tokens that should no longer have them.
Haojian Wu0a6000f2019-08-26 08:38:45 +00001353 std::vector<LineHighlightings> Diffed = diffHighlightings(Highlightings, Old);
Johan Vikstroma848dab2019-07-04 07:53:12 +00001354 publishSemanticHighlighting(
1355 {{URIForFile::canonicalize(File, /*TUPath=*/File)},
Johan Vikstromc2653ef22019-08-01 08:08:44 +00001356 toSemanticHighlightingInformation(Diffed)});
Johan Vikstroma848dab2019-07-04 07:53:12 +00001357}
1358
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001359void ClangdLSPServer::onDiagnosticsReady(PathRef File,
1360 std::vector<Diag> Diagnostics) {
Eric Liu4d814a92018-11-28 10:30:42 +00001361 auto URI = URIForFile::canonicalize(File, /*TUPath=*/File);
Sam McCall16e70702018-10-24 07:59:38 +00001362 std::vector<Diagnostic> LSPDiagnostics;
Ilya Biryukov38d79772017-05-16 09:38:59 +00001363 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
Sam McCalla7bb0cc2018-03-12 23:22:35 +00001364 for (auto &Diag : Diagnostics) {
Sam McCall16e70702018-10-24 07:59:38 +00001365 toLSPDiags(Diag, URI, DiagOpts,
Ilya Biryukovf2001aa2019-01-07 15:45:19 +00001366 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
Sam McCall16e70702018-10-24 07:59:38 +00001367 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1368 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
1369 LSPDiagnostics.push_back(std::move(Diag));
1370 });
Ilya Biryukov38d79772017-05-16 09:38:59 +00001371 }
1372
1373 // Cache FixIts
1374 {
Ilya Biryukov38d79772017-05-16 09:38:59 +00001375 std::lock_guard<std::mutex> Lock(FixItsMutex);
1376 FixItsMap[File] = LocalFixIts;
1377 }
1378
Ilya Biryukov49c10712019-03-25 10:15:11 +00001379 // Send a notification to the LSP client.
1380 publishDiagnostics(URI, std::move(LSPDiagnostics));
Ilya Biryukov38d79772017-05-16 09:38:59 +00001381}
Simon Marchi9569fd52018-03-16 14:30:42 +00001382
Sam McCall7d20e802020-01-22 19:41:45 +01001383void ClangdLSPServer::onBackgroundIndexProgress(
1384 const BackgroundQueue::Stats &Stats) {
1385 static const char ProgressToken[] = "backgroundIndexProgress";
1386 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1387
1388 auto NotifyProgress = [this](const BackgroundQueue::Stats &Stats) {
1389 if (BackgroundIndexProgressState != BackgroundIndexProgress::Live) {
1390 WorkDoneProgressBegin Begin;
1391 Begin.percentage = true;
1392 Begin.title = "indexing";
1393 progress(ProgressToken, std::move(Begin));
1394 BackgroundIndexProgressState = BackgroundIndexProgress::Live;
1395 }
1396
1397 if (Stats.Completed < Stats.Enqueued) {
1398 assert(Stats.Enqueued > Stats.LastIdle);
1399 WorkDoneProgressReport Report;
1400 Report.percentage = 100.0 * (Stats.Completed - Stats.LastIdle) /
1401 (Stats.Enqueued - Stats.LastIdle);
1402 Report.message =
1403 llvm::formatv("{0}/{1}", Stats.Completed - Stats.LastIdle,
1404 Stats.Enqueued - Stats.LastIdle);
1405 progress(ProgressToken, std::move(Report));
1406 } else {
1407 assert(Stats.Completed == Stats.Enqueued);
1408 progress(ProgressToken, WorkDoneProgressEnd());
1409 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
1410 }
1411 };
1412
1413 switch (BackgroundIndexProgressState) {
1414 case BackgroundIndexProgress::Unsupported:
1415 return;
1416 case BackgroundIndexProgress::Creating:
1417 // Cache this update for when the progress bar is available.
1418 PendingBackgroundIndexProgress = Stats;
1419 return;
1420 case BackgroundIndexProgress::Empty: {
1421 if (BackgroundIndexSkipCreate) {
1422 NotifyProgress(Stats);
1423 break;
1424 }
1425 // Cache this update for when the progress bar is available.
1426 PendingBackgroundIndexProgress = Stats;
1427 BackgroundIndexProgressState = BackgroundIndexProgress::Creating;
1428 WorkDoneProgressCreateParams CreateRequest;
1429 CreateRequest.token = ProgressToken;
1430 call<std::nullptr_t>(
1431 "window/workDoneProgress/create", CreateRequest,
1432 [this, NotifyProgress](llvm::Expected<std::nullptr_t> E) {
1433 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1434 if (E) {
1435 NotifyProgress(this->PendingBackgroundIndexProgress);
1436 } else {
1437 elog("Failed to create background index progress bar: {0}",
1438 E.takeError());
1439 // give up forever rather than thrashing about
1440 BackgroundIndexProgressState = BackgroundIndexProgress::Unsupported;
1441 }
1442 });
1443 break;
1444 }
1445 case BackgroundIndexProgress::Live:
1446 NotifyProgress(Stats);
1447 break;
1448 }
1449}
1450
Haojian Wub6188492018-12-20 15:39:12 +00001451void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1452 if (!SupportFileStatus)
1453 return;
1454 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1455 // two statuses are running faster in practice, which leads the UI constantly
1456 // changing, and doesn't provide much value. We may want to emit status at a
1457 // reasonable time interval (e.g. 0.5s).
1458 if (Status.Action.S == TUAction::BuildingFile ||
1459 Status.Action.S == TUAction::RunningAction)
1460 return;
1461 notify("textDocument/clangd.fileStatus", Status.render(File));
1462}
1463
David Goldman60249c22020-01-13 17:01:10 -05001464void ClangdLSPServer::reparseOpenedFiles(
1465 const llvm::StringSet<> &ModifiedFiles) {
1466 if (ModifiedFiles.empty())
1467 return;
1468 // Reparse only opened files that were modified.
Simon Marchi9569fd52018-03-16 14:30:42 +00001469 for (const Path &FilePath : DraftMgr.getActiveFiles())
David Goldman60249c22020-01-13 17:01:10 -05001470 if (ModifiedFiles.find(FilePath) != ModifiedFiles.end())
1471 Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
1472 WantDiagnostics::Auto);
Simon Marchi9569fd52018-03-16 14:30:42 +00001473}
Alex Lorenzf8087862018-08-01 17:39:29 +00001474
Sam McCallc008af62018-10-20 15:30:37 +00001475} // namespace clangd
1476} // namespace clang