Bug Summary

File:llvm/include/llvm/ADT/FunctionExtras.h
Warning:line 204, column 5
Undefined or garbage value returned to caller

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name ClangdLSPServer.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220125101009+ceec4383681c/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/tools/extra/clangd -I /build/llvm-toolchain-snapshot-14~++20220125101009+ceec4383681c/clang-tools-extra/clangd -I tools/clang/tools/extra/clangd/../clang-tidy -I /build/llvm-toolchain-snapshot-14~++20220125101009+ceec4383681c/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20220125101009+ceec4383681c/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220125101009+ceec4383681c/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220125101009+ceec4383681c/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220125101009+ceec4383681c/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220125101009+ceec4383681c/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220125101009+ceec4383681c/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220125101009+ceec4383681c/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220125101009+ceec4383681c/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-01-25-232935-20746-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220125101009+ceec4383681c/clang-tools-extra/clangd/ClangdLSPServer.cpp

/build/llvm-toolchain-snapshot-14~++20220125101009+ceec4383681c/clang-tools-extra/clangd/ClangdLSPServer.cpp

1//===--- ClangdLSPServer.cpp - LSP server ------------------------*- C++-*-===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8
9#include "ClangdLSPServer.h"
10#include "ClangdServer.h"
11#include "CodeComplete.h"
12#include "Diagnostics.h"
13#include "DraftStore.h"
14#include "DumpAST.h"
15#include "Feature.h"
16#include "GlobalCompilationDatabase.h"
17#include "LSPBinder.h"
18#include "Protocol.h"
19#include "SemanticHighlighting.h"
20#include "SourceCode.h"
21#include "TUScheduler.h"
22#include "URI.h"
23#include "refactor/Tweak.h"
24#include "support/Context.h"
25#include "support/MemoryTree.h"
26#include "support/Trace.h"
27#include "clang/AST/ASTContext.h"
28#include "clang/Tooling/Core/Replacement.h"
29#include "llvm/ADT/ArrayRef.h"
30#include "llvm/ADT/Optional.h"
31#include "llvm/ADT/ScopeExit.h"
32#include "llvm/ADT/StringRef.h"
33#include "llvm/ADT/iterator_range.h"
34#include "llvm/Support/Allocator.h"
35#include "llvm/Support/Errc.h"
36#include "llvm/Support/Error.h"
37#include "llvm/Support/FormatVariadic.h"
38#include "llvm/Support/JSON.h"
39#include "llvm/Support/Path.h"
40#include "llvm/Support/SHA1.h"
41#include "llvm/Support/ScopedPrinter.h"
42#include "llvm/Support/raw_ostream.h"
43#include <chrono>
44#include <cstddef>
45#include <cstdint>
46#include <functional>
47#include <memory>
48#include <mutex>
49#include <string>
50#include <vector>
51
52namespace clang {
53namespace clangd {
54namespace {
55// Tracks end-to-end latency of high level lsp calls. Measurements are in
56// seconds.
57constexpr trace::Metric LSPLatency("lsp_latency", trace::Metric::Distribution,
58 "method_name");
59
60// LSP defines file versions as numbers that increase.
61// ClangdServer treats them as opaque and therefore uses strings instead.
62std::string encodeVersion(llvm::Optional<int64_t> LSPVersion) {
63 return LSPVersion ? llvm::to_string(*LSPVersion) : "";
64}
65llvm::Optional<int64_t> decodeVersion(llvm::StringRef Encoded) {
66 int64_t Result;
67 if (llvm::to_integer(Encoded, Result, 10))
68 return Result;
69 if (!Encoded.empty()) // Empty can be e.g. diagnostics on close.
70 elog("unexpected non-numeric version {0}", Encoded);
71 return llvm::None;
72}
73
74const llvm::StringLiteral APPLY_FIX_COMMAND = "clangd.applyFix";
75const llvm::StringLiteral APPLY_TWEAK_COMMAND = "clangd.applyTweak";
76
77/// Transforms a tweak into a code action that would apply it if executed.
78/// EXPECTS: T.prepare() was called and returned true.
79CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File,
80 Range Selection) {
81 CodeAction CA;
82 CA.title = T.Title;
83 CA.kind = T.Kind.str();
84 // This tweak may have an expensive second stage, we only run it if the user
85 // actually chooses it in the UI. We reply with a command that would run the
86 // corresponding tweak.
87 // FIXME: for some tweaks, computing the edits is cheap and we could send them
88 // directly.
89 CA.command.emplace();
90 CA.command->title = T.Title;
91 CA.command->command = std::string(APPLY_TWEAK_COMMAND);
92 TweakArgs Args;
93 Args.file = File;
94 Args.tweakID = T.ID;
95 Args.selection = Selection;
96 CA.command->argument = std::move(Args);
97 return CA;
98}
99
100void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
101 SymbolKindBitset Kinds) {
102 for (auto &S : Syms) {
103 S.kind = adjustKindToCapability(S.kind, Kinds);
104 adjustSymbolKinds(S.children, Kinds);
105 }
106}
107
108SymbolKindBitset defaultSymbolKinds() {
109 SymbolKindBitset Defaults;
110 for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
111 ++I)
112 Defaults.set(I);
113 return Defaults;
114}
115
116CompletionItemKindBitset defaultCompletionItemKinds() {
117 CompletionItemKindBitset Defaults;
118 for (size_t I = CompletionItemKindMin;
119 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
120 Defaults.set(I);
121 return Defaults;
122}
123
124// Makes sure edits in \p FE are applicable to latest file contents reported by
125// editor. If not generates an error message containing information about files
126// that needs to be saved.
127llvm::Error validateEdits(const ClangdServer &Server, const FileEdits &FE) {
128 size_t InvalidFileCount = 0;
129 llvm::StringRef LastInvalidFile;
130 for (const auto &It : FE) {
131 if (auto Draft = Server.getDraft(It.first())) {
132 // If the file is open in user's editor, make sure the version we
133 // saw and current version are compatible as this is the text that
134 // will be replaced by editors.
135 if (!It.second.canApplyTo(*Draft)) {
136 ++InvalidFileCount;
137 LastInvalidFile = It.first();
138 }
139 }
140 }
141 if (!InvalidFileCount)
142 return llvm::Error::success();
143 if (InvalidFileCount == 1)
144 return error("File must be saved first: {0}", LastInvalidFile);
145 return error("Files must be saved first: {0} (and {1} others)",
146 LastInvalidFile, InvalidFileCount - 1);
147}
148} // namespace
149
150// MessageHandler dispatches incoming LSP messages.
151// It handles cross-cutting concerns:
152// - serializes/deserializes protocol objects to JSON
153// - logging of inbound messages
154// - cancellation handling
155// - basic call tracing
156// MessageHandler ensures that initialize() is called before any other handler.
157class ClangdLSPServer::MessageHandler : public Transport::MessageHandler {
158public:
159 MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
160
161 bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
162 trace::Span Tracer(Method, LSPLatency);
163 SPAN_ATTACH(Tracer, "Params", Params)do { if (auto *Args = (Tracer).Args) (*Args)["Params"] = Params
; } while (0)
;
164 WithContext HandlerContext(handlerContext());
165 log("<-- {0}", Method);
166 if (Method == "exit")
167 return false;
168 auto Handler = Server.Handlers.NotificationHandlers.find(Method);
169 if (Handler != Server.Handlers.NotificationHandlers.end()) {
170 Handler->second(std::move(Params));
171 Server.maybeExportMemoryProfile();
172 Server.maybeCleanupMemory();
173 } else if (!Server.Server) {
174 elog("Notification {0} before initialization", Method);
175 } else if (Method == "$/cancelRequest") {
176 onCancel(std::move(Params));
177 } else {
178 log("unhandled notification {0}", Method);
179 }
180 return true;
181 }
182
183 bool onCall(llvm::StringRef Method, llvm::json::Value Params,
184 llvm::json::Value ID) override {
185 WithContext HandlerContext(handlerContext());
186 // Calls can be canceled by the client. Add cancellation context.
187 WithContext WithCancel(cancelableRequestContext(ID));
188 trace::Span Tracer(Method, LSPLatency);
189 SPAN_ATTACH(Tracer, "Params", Params)do { if (auto *Args = (Tracer).Args) (*Args)["Params"] = Params
; } while (0)
;
190 ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
191 log("<-- {0}({1})", Method, ID);
192 auto Handler = Server.Handlers.MethodHandlers.find(Method);
193 if (Handler != Server.Handlers.MethodHandlers.end()) {
194 Handler->second(std::move(Params), std::move(Reply));
195 } else if (!Server.Server) {
196 elog("Call {0} before initialization.", Method);
197 Reply(llvm::make_error<LSPError>("server not initialized",
198 ErrorCode::ServerNotInitialized));
199 } else {
200 Reply(llvm::make_error<LSPError>("method not found",
201 ErrorCode::MethodNotFound));
202 }
203 return true;
204 }
205
206 bool onReply(llvm::json::Value ID,
207 llvm::Expected<llvm::json::Value> Result) override {
208 WithContext HandlerContext(handlerContext());
209
210 Callback<llvm::json::Value> ReplyHandler = nullptr;
211 if (auto IntID = ID.getAsInteger()) {
212 std::lock_guard<std::mutex> Mutex(CallMutex);
213 // Find a corresponding callback for the request ID;
214 for (size_t Index = 0; Index < ReplyCallbacks.size(); ++Index) {
215 if (ReplyCallbacks[Index].first == *IntID) {
216 ReplyHandler = std::move(ReplyCallbacks[Index].second);
217 ReplyCallbacks.erase(ReplyCallbacks.begin() +
218 Index); // remove the entry
219 break;
220 }
221 }
222 }
223
224 if (!ReplyHandler) {
225 // No callback being found, use a default log callback.
226 ReplyHandler = [&ID](llvm::Expected<llvm::json::Value> Result) {
227 elog("received a reply with ID {0}, but there was no such call", ID);
228 if (!Result)
229 llvm::consumeError(Result.takeError());
230 };
231 }
232
233 // Log and run the reply handler.
234 if (Result) {
235 log("<-- reply({0})", ID);
236 ReplyHandler(std::move(Result));
237 } else {
238 auto Err = Result.takeError();
239 log("<-- reply({0}) error: {1}", ID, Err);
240 ReplyHandler(std::move(Err));
241 }
242 return true;
243 }
244
245 // Bind a reply callback to a request. The callback will be invoked when
246 // clangd receives the reply from the LSP client.
247 // Return a call id of the request.
248 llvm::json::Value bindReply(Callback<llvm::json::Value> Reply) {
249 llvm::Optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB;
250 int ID;
251 {
252 std::lock_guard<std::mutex> Mutex(CallMutex);
253 ID = NextCallID++;
254 ReplyCallbacks.emplace_back(ID, std::move(Reply));
255
256 // If the queue overflows, we assume that the client didn't reply the
257 // oldest request, and run the corresponding callback which replies an
258 // error to the client.
259 if (ReplyCallbacks.size() > MaxReplayCallbacks) {
260 elog("more than {0} outstanding LSP calls, forgetting about {1}",
261 MaxReplayCallbacks, ReplyCallbacks.front().first);
262 OldestCB = std::move(ReplyCallbacks.front());
263 ReplyCallbacks.pop_front();
264 }
265 }
266 if (OldestCB)
267 OldestCB->second(
268 error("failed to receive a client reply for request ({0})",
269 OldestCB->first));
270 return ID;
271 }
272
273private:
274 // Function object to reply to an LSP call.
275 // Each instance must be called exactly once, otherwise:
276 // - the bug is logged, and (in debug mode) an assert will fire
277 // - if there was no reply, an error reply is sent
278 // - if there were multiple replies, only the first is sent
279 class ReplyOnce {
280 std::atomic<bool> Replied = {false};
281 std::chrono::steady_clock::time_point Start;
282 llvm::json::Value ID;
283 std::string Method;
284 ClangdLSPServer *Server; // Null when moved-from.
285 llvm::json::Object *TraceArgs;
286
287 public:
288 ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
289 ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
290 : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
291 Server(Server), TraceArgs(TraceArgs) {
292 assert(Server)(static_cast <bool> (Server) ? void (0) : __assert_fail
("Server", "clang-tools-extra/clangd/ClangdLSPServer.cpp", 292
, __extension__ __PRETTY_FUNCTION__))
;
293 }
294 ReplyOnce(ReplyOnce &&Other)
295 : Replied(Other.Replied.load()), Start(Other.Start),
296 ID(std::move(Other.ID)), Method(std::move(Other.Method)),
297 Server(Other.Server), TraceArgs(Other.TraceArgs) {
298 Other.Server = nullptr;
299 }
300 ReplyOnce &operator=(ReplyOnce &&) = delete;
301 ReplyOnce(const ReplyOnce &) = delete;
302 ReplyOnce &operator=(const ReplyOnce &) = delete;
303
304 ~ReplyOnce() {
305 // There's one legitimate reason to never reply to a request: clangd's
306 // request handler send a call to the client (e.g. applyEdit) and the
307 // client never replied. In this case, the ReplyOnce is owned by
308 // ClangdLSPServer's reply callback table and is destroyed along with the
309 // server. We don't attempt to send a reply in this case, there's little
310 // to be gained from doing so.
311 if (Server && !Server->IsBeingDestroyed && !Replied) {
312 elog("No reply to message {0}({1})", Method, ID);
313 assert(false && "must reply to all calls!")(static_cast <bool> (false && "must reply to all calls!"
) ? void (0) : __assert_fail ("false && \"must reply to all calls!\""
, "clang-tools-extra/clangd/ClangdLSPServer.cpp", 313, __extension__
__PRETTY_FUNCTION__))
;
314 (*this)(llvm::make_error<LSPError>("server failed to reply",
315 ErrorCode::InternalError));
316 }
317 }
318
319 void operator()(llvm::Expected<llvm::json::Value> Reply) {
320 assert(Server && "moved-from!")(static_cast <bool> (Server && "moved-from!") ?
void (0) : __assert_fail ("Server && \"moved-from!\""
, "clang-tools-extra/clangd/ClangdLSPServer.cpp", 320, __extension__
__PRETTY_FUNCTION__))
;
321 if (Replied.exchange(true)) {
322 elog("Replied twice to message {0}({1})", Method, ID);
323 assert(false && "must reply to each call only once!")(static_cast <bool> (false && "must reply to each call only once!"
) ? void (0) : __assert_fail ("false && \"must reply to each call only once!\""
, "clang-tools-extra/clangd/ClangdLSPServer.cpp", 323, __extension__
__PRETTY_FUNCTION__))
;
324 return;
325 }
326 auto Duration = std::chrono::steady_clock::now() - Start;
327 if (Reply) {
328 log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
329 if (TraceArgs)
330 (*TraceArgs)["Reply"] = *Reply;
331 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
332 Server->Transp.reply(std::move(ID), std::move(Reply));
333 } else {
334 llvm::Error Err = Reply.takeError();
335 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
336 if (TraceArgs)
337 (*TraceArgs)["Error"] = llvm::to_string(Err);
338 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
339 Server->Transp.reply(std::move(ID), std::move(Err));
340 }
341 }
342 };
343
344 // Method calls may be cancelled by ID, so keep track of their state.
345 // This needs a mutex: handlers may finish on a different thread, and that's
346 // when we clean up entries in the map.
347 mutable std::mutex RequestCancelersMutex;
348 llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
349 unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
350 void onCancel(const llvm::json::Value &Params) {
351 const llvm::json::Value *ID = nullptr;
352 if (auto *O = Params.getAsObject())
353 ID = O->get("id");
354 if (!ID) {
355 elog("Bad cancellation request: {0}", Params);
356 return;
357 }
358 auto StrID = llvm::to_string(*ID);
359 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
360 auto It = RequestCancelers.find(StrID);
361 if (It != RequestCancelers.end())
362 It->second.first(); // Invoke the canceler.
363 }
364
365 Context handlerContext() const {
366 return Context::current().derive(
367 kCurrentOffsetEncoding,
368 Server.Opts.Encoding.getValueOr(OffsetEncoding::UTF16));
369 }
370
371 // We run cancelable requests in a context that does two things:
372 // - allows cancellation using RequestCancelers[ID]
373 // - cleans up the entry in RequestCancelers when it's no longer needed
374 // If a client reuses an ID, the last wins and the first cannot be canceled.
375 Context cancelableRequestContext(const llvm::json::Value &ID) {
376 auto Task = cancelableTask(
377 /*Reason=*/static_cast<int>(ErrorCode::RequestCancelled));
378 auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
379 auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
380 {
381 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
382 RequestCancelers[StrID] = {std::move(Task.second), Cookie};
383 }
384 // When the request ends, we can clean up the entry we just added.
385 // The cookie lets us check that it hasn't been overwritten due to ID
386 // reuse.
387 return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
388 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
389 auto It = RequestCancelers.find(StrID);
390 if (It != RequestCancelers.end() && It->second.second == Cookie)
391 RequestCancelers.erase(It);
392 }));
393 }
394
395 // The maximum number of callbacks held in clangd.
396 //
397 // We bound the maximum size to the pending map to prevent memory leakage
398 // for cases where LSP clients don't reply for the request.
399 // This has to go after RequestCancellers and RequestCancellersMutex since it
400 // can contain a callback that has a cancelable context.
401 static constexpr int MaxReplayCallbacks = 100;
402 mutable std::mutex CallMutex;
403 int NextCallID = 0; /* GUARDED_BY(CallMutex) */
404 std::deque<std::pair</*RequestID*/ int,
405 /*ReplyHandler*/ Callback<llvm::json::Value>>>
406 ReplyCallbacks; /* GUARDED_BY(CallMutex) */
407
408 ClangdLSPServer &Server;
409};
410constexpr int ClangdLSPServer::MessageHandler::MaxReplayCallbacks;
411
412// call(), notify(), and reply() wrap the Transport, adding logging and locking.
413void ClangdLSPServer::callMethod(StringRef Method, llvm::json::Value Params,
414 Callback<llvm::json::Value> CB) {
415 auto ID = MsgHandler->bindReply(std::move(CB));
416 log("--> {0}({1})", Method, ID);
417 std::lock_guard<std::mutex> Lock(TranspWriter);
418 Transp.call(Method, std::move(Params), ID);
419}
420
421void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
422 log("--> {0}", Method);
423 maybeCleanupMemory();
424 std::lock_guard<std::mutex> Lock(TranspWriter);
425 Transp.notify(Method, std::move(Params));
426}
427
428static std::vector<llvm::StringRef> semanticTokenTypes() {
429 std::vector<llvm::StringRef> Types;
430 for (unsigned I = 0; I <= static_cast<unsigned>(HighlightingKind::LastKind);
431 ++I)
432 Types.push_back(toSemanticTokenType(static_cast<HighlightingKind>(I)));
433 return Types;
434}
435
436static std::vector<llvm::StringRef> semanticTokenModifiers() {
437 std::vector<llvm::StringRef> Modifiers;
438 for (unsigned I = 0;
439 I <= static_cast<unsigned>(HighlightingModifier::LastModifier); ++I)
440 Modifiers.push_back(
441 toSemanticTokenModifier(static_cast<HighlightingModifier>(I)));
442 return Modifiers;
443}
444
445void ClangdLSPServer::onInitialize(const InitializeParams &Params,
446 Callback<llvm::json::Value> Reply) {
447 // Determine character encoding first as it affects constructed ClangdServer.
448 if (Params.capabilities.offsetEncoding && !Opts.Encoding) {
449 Opts.Encoding = OffsetEncoding::UTF16; // fallback
450 for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
451 if (Supported != OffsetEncoding::UnsupportedEncoding) {
452 Opts.Encoding = Supported;
453 break;
454 }
455 }
456
457 if (Params.capabilities.TheiaSemanticHighlighting &&
458 !Params.capabilities.SemanticTokens) {
459 elog("Client requested legacy semanticHighlights notification, which is "
460 "no longer supported. Migrate to standard semanticTokens request");
461 }
462
463 if (Params.rootUri && *Params.rootUri)
464 Opts.WorkspaceRoot = std::string(Params.rootUri->file());
465 else if (Params.rootPath && !Params.rootPath->empty())
466 Opts.WorkspaceRoot = *Params.rootPath;
467 if (Server)
468 return Reply(llvm::make_error<LSPError>("server already initialized",
469 ErrorCode::InvalidRequest));
470 if (Opts.UseDirBasedCDB) {
471 DirectoryBasedGlobalCompilationDatabase::Options CDBOpts(TFS);
472 if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
473 CDBOpts.CompileCommandsDir = Dir;
474 CDBOpts.ContextProvider = Opts.ContextProvider;
475 BaseCDB =
476 std::make_unique<DirectoryBasedGlobalCompilationDatabase>(CDBOpts);
477 BaseCDB = getQueryDriverDatabase(llvm::makeArrayRef(Opts.QueryDriverGlobs),
478 std::move(BaseCDB));
479 }
480 auto Mangler = CommandMangler::detect();
481 if (Opts.ResourceDir)
482 Mangler.ResourceDir = *Opts.ResourceDir;
483 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
484 tooling::ArgumentsAdjuster(std::move(Mangler)));
485 {
486 // Switch caller's context with LSPServer's background context. Since we
487 // rather want to propagate information from LSPServer's context into the
488 // Server, CDB, etc.
489 WithContext MainContext(BackgroundContext.clone());
490 llvm::Optional<WithContextValue> WithOffsetEncoding;
491 if (Opts.Encoding)
492 WithOffsetEncoding.emplace(kCurrentOffsetEncoding, *Opts.Encoding);
493 Server.emplace(*CDB, TFS, Opts,
494 static_cast<ClangdServer::Callbacks *>(this));
495 }
496
497 Opts.CodeComplete.EnableSnippets = Params.capabilities.CompletionSnippets;
498 Opts.CodeComplete.IncludeFixIts = Params.capabilities.CompletionFixes;
499 if (!Opts.CodeComplete.BundleOverloads.hasValue())
500 Opts.CodeComplete.BundleOverloads = Params.capabilities.HasSignatureHelp;
501 Opts.CodeComplete.DocumentationFormat =
502 Params.capabilities.CompletionDocumentationFormat;
503 Opts.SignatureHelpDocumentationFormat =
504 Params.capabilities.SignatureHelpDocumentationFormat;
505 DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
506 DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
507 DiagOpts.EmitRelatedLocations =
508 Params.capabilities.DiagnosticRelatedInformation;
509 if (Params.capabilities.WorkspaceSymbolKinds)
510 SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
511 if (Params.capabilities.CompletionItemKinds)
512 SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
513 SupportsCodeAction = Params.capabilities.CodeActionStructure;
514 SupportsHierarchicalDocumentSymbol =
515 Params.capabilities.HierarchicalDocumentSymbol;
516 SupportFileStatus = Params.initializationOptions.FileStatus;
517 HoverContentFormat = Params.capabilities.HoverContentFormat;
518 SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
519 if (Params.capabilities.WorkDoneProgress)
520 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
521 BackgroundIndexSkipCreate = Params.capabilities.ImplicitProgressCreation;
522 Opts.ImplicitCancellation = !Params.capabilities.CancelsStaleRequests;
523
524 llvm::json::Object ServerCaps{
525 {"textDocumentSync",
526 llvm::json::Object{
527 {"openClose", true},
528 {"change", (int)TextDocumentSyncKind::Incremental},
529 {"save", true},
530 }},
531 {"documentFormattingProvider", true},
532 {"documentRangeFormattingProvider", true},
533 {"documentOnTypeFormattingProvider",
534 llvm::json::Object{
535 {"firstTriggerCharacter", "\n"},
536 {"moreTriggerCharacter", {}},
537 }},
538 {"completionProvider",
539 llvm::json::Object{
540 {"allCommitCharacters",
541 {" ", "\t", "(", ")", "[", "]", "{", "}", "<",
542 ">", ":", ";", ",", "+", "-", "/", "*", "%",
543 "^", "&", "#", "?", ".", "=", "\"", "'", "|"}},
544 {"resolveProvider", false},
545 // We do extra checks, e.g. that > is part of ->.
546 {"triggerCharacters", {".", "<", ">", ":", "\"", "/", "*"}},
547 }},
548 {"semanticTokensProvider",
549 llvm::json::Object{
550 {"full", llvm::json::Object{{"delta", true}}},
551 {"range", false},
552 {"legend",
553 llvm::json::Object{{"tokenTypes", semanticTokenTypes()},
554 {"tokenModifiers", semanticTokenModifiers()}}},
555 }},
556 {"signatureHelpProvider",
557 llvm::json::Object{
558 {"triggerCharacters", {"(", ")", "{", "}", "<", ">", ","}},
559 }},
560 {"declarationProvider", true},
561 {"definitionProvider", true},
562 {"implementationProvider", true},
563 {"typeDefinitionProvider", true},
564 {"documentHighlightProvider", true},
565 {"documentLinkProvider",
566 llvm::json::Object{
567 {"resolveProvider", false},
568 }},
569 {"hoverProvider", true},
570 {"selectionRangeProvider", true},
571 {"documentSymbolProvider", true},
572 {"workspaceSymbolProvider", true},
573 {"referencesProvider", true},
574 {"astProvider", true}, // clangd extension
575 {"typeHierarchyProvider", true},
576 {"memoryUsageProvider", true}, // clangd extension
577 {"compilationDatabase", // clangd extension
578 llvm::json::Object{{"automaticReload", true}}},
579 {"callHierarchyProvider", true},
580 {"clangdInlayHintsProvider", true},
581 };
582
583 {
584 LSPBinder Binder(Handlers, *this);
585 bindMethods(Binder, Params.capabilities);
586 if (Opts.FeatureModules)
587 for (auto &Mod : *Opts.FeatureModules)
588 Mod.initializeLSP(Binder, Params.rawCapabilities, ServerCaps);
589 }
590
591 // Per LSP, renameProvider can be either boolean or RenameOptions.
592 // RenameOptions will be specified if the client states it supports prepare.
593 ServerCaps["renameProvider"] =
594 Params.capabilities.RenamePrepareSupport
595 ? llvm::json::Object{{"prepareProvider", true}}
596 : llvm::json::Value(true);
597
598 // Per LSP, codeActionProvider can be either boolean or CodeActionOptions.
599 // CodeActionOptions is only valid if the client supports action literal
600 // via textDocument.codeAction.codeActionLiteralSupport.
601 llvm::json::Value CodeActionProvider = true;
602 ServerCaps["codeActionProvider"] =
603 Params.capabilities.CodeActionStructure
604 ? llvm::json::Object{{"codeActionKinds",
605 {CodeAction::QUICKFIX_KIND,
606 CodeAction::REFACTOR_KIND,
607 CodeAction::INFO_KIND}}}
608 : llvm::json::Value(true);
609
610 if (Opts.FoldingRanges)
611 ServerCaps["foldingRangeProvider"] = true;
612
613 std::vector<llvm::StringRef> Commands;
614 for (llvm::StringRef Command : Handlers.CommandHandlers.keys())
615 Commands.push_back(Command);
616 llvm::sort(Commands);
617 ServerCaps["executeCommandProvider"] =
618 llvm::json::Object{{"commands", Commands}};
619
620 llvm::json::Object Result{
621 {{"serverInfo",
622 llvm::json::Object{
623 {"name", "clangd"},
624 {"version", llvm::formatv("{0} {1} {2}", versionString(),
625 featureString(), platformString())}}},
626 {"capabilities", std::move(ServerCaps)}}};
627 if (Opts.Encoding)
628 Result["offsetEncoding"] = *Opts.Encoding;
629 Reply(std::move(Result));
630
631 // Apply settings after we're fully initialized.
632 // This can start background indexing and in turn trigger LSP notifications.
633 applyConfiguration(Params.initializationOptions.ConfigSettings);
634}
635
636void ClangdLSPServer::onInitialized(const InitializedParams &Params) {}
637
638void ClangdLSPServer::onShutdown(const NoParams &,
639 Callback<std::nullptr_t> Reply) {
640 // Do essentially nothing, just say we're ready to exit.
641 ShutdownRequestReceived = true;
642 Reply(nullptr);
643}
644
645// sync is a clangd extension: it blocks until all background work completes.
646// It blocks the calling thread, so no messages are processed until it returns!
647void ClangdLSPServer::onSync(const NoParams &, Callback<std::nullptr_t> Reply) {
648 if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
649 Reply(nullptr);
650 else
651 Reply(error("Not idle after a minute"));
652}
653
654void ClangdLSPServer::onDocumentDidOpen(
655 const DidOpenTextDocumentParams &Params) {
656 PathRef File = Params.textDocument.uri.file();
657
658 const std::string &Contents = Params.textDocument.text;
659
660 Server->addDocument(File, Contents,
661 encodeVersion(Params.textDocument.version),
662 WantDiagnostics::Yes);
663}
664
665void ClangdLSPServer::onDocumentDidChange(
666 const DidChangeTextDocumentParams &Params) {
667 auto WantDiags = WantDiagnostics::Auto;
668 if (Params.wantDiagnostics.hasValue())
669 WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
670 : WantDiagnostics::No;
671
672 PathRef File = Params.textDocument.uri.file();
673 auto Code = Server->getDraft(File);
674 if (!Code) {
675 log("Trying to incrementally change non-added document: {0}", File);
676 return;
677 }
678 std::string NewCode(*Code);
679 for (const auto &Change : Params.contentChanges) {
680 if (auto Err = applyChange(NewCode, Change)) {
681 // If this fails, we are most likely going to be not in sync anymore with
682 // the client. It is better to remove the draft and let further
683 // operations fail rather than giving wrong results.
684 Server->removeDocument(File);
685 elog("Failed to update {0}: {1}", File, std::move(Err));
686 return;
687 }
688 }
689 Server->addDocument(File, NewCode, encodeVersion(Params.textDocument.version),
690 WantDiags, Params.forceRebuild);
691}
692
693void ClangdLSPServer::onDocumentDidSave(
694 const DidSaveTextDocumentParams &Params) {
695 Server->reparseOpenFilesIfNeeded([](llvm::StringRef) { return true; });
696}
697
698void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
699 // We could also reparse all open files here. However:
700 // - this could be frequent, and revalidating all the preambles isn't free
701 // - this is useful e.g. when switching git branches, but we're likely to see
702 // fresh headers but still have the old-branch main-file content
703 Server->onFileEvent(Params);
704 // FIXME: observe config files, immediately expire time-based caches, reparse:
705 // - compile_commands.json and compile_flags.txt
706 // - .clang_format and .clang-tidy
707 // - .clangd and clangd/config.yaml
708}
709
710void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
711 Callback<llvm::json::Value> Reply) {
712 auto It = Handlers.CommandHandlers.find(Params.command);
713 if (It == Handlers.CommandHandlers.end()) {
714 return Reply(llvm::make_error<LSPError>(
715 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
716 ErrorCode::InvalidParams));
717 }
718 It->second(Params.argument, std::move(Reply));
719}
720
721void ClangdLSPServer::onCommandApplyEdit(const WorkspaceEdit &WE,
722 Callback<llvm::json::Value> Reply) {
723 // The flow for "apply-fix" :
724 // 1. We publish a diagnostic, including fixits
725 // 2. The user clicks on the diagnostic, the editor asks us for code actions
726 // 3. We send code actions, with the fixit embedded as context
727 // 4. The user selects the fixit, the editor asks us to apply it
728 // 5. We unwrap the changes and send them back to the editor
729 // 6. The editor applies the changes (applyEdit), and sends us a reply
730 // 7. We unwrap the reply and send a reply to the editor.
731 applyEdit(WE, "Fix applied.", std::move(Reply));
732}
733
734void ClangdLSPServer::onCommandApplyTweak(const TweakArgs &Args,
735 Callback<llvm::json::Value> Reply) {
736 auto Action = [this, Reply = std::move(Reply)](
1
Calling implicit move constructor
2
Calling defaulted move constructor for 'unique_function<void (llvm::Expected<llvm::json::Value>)>'
8
Returning from move constructor for 'unique_function<void (llvm::Expected<llvm::json::Value>)>'
9
Returning from move constructor
737 llvm::Expected<Tweak::Effect> R) mutable {
738 if (!R)
739 return Reply(R.takeError());
740
741 assert(R->ShowMessage || (!R->ApplyEdits.empty() && "tweak has no effect"))(static_cast <bool> (R->ShowMessage || (!R->ApplyEdits
.empty() && "tweak has no effect")) ? void (0) : __assert_fail
("R->ShowMessage || (!R->ApplyEdits.empty() && \"tweak has no effect\")"
, "clang-tools-extra/clangd/ClangdLSPServer.cpp", 741, __extension__
__PRETTY_FUNCTION__))
;
742
743 if (R->ShowMessage) {
744 ShowMessageParams Msg;
745 Msg.message = *R->ShowMessage;
746 Msg.type = MessageType::Info;
747 ShowMessage(Msg);
748 }
749 // When no edit is specified, make sure we Reply().
750 if (R->ApplyEdits.empty())
751 return Reply("Tweak applied.");
752
753 if (auto Err = validateEdits(*Server, R->ApplyEdits))
754 return Reply(std::move(Err));
755
756 WorkspaceEdit WE;
757 for (const auto &It : R->ApplyEdits) {
758 WE.changes[URI::createFile(It.first()).toString()] =
759 It.second.asTextEdits();
760 }
761 // ApplyEdit will take care of calling Reply().
762 return applyEdit(std::move(WE), "Tweak applied.", std::move(Reply));
763 };
764 Server->applyTweak(Args.file.file(), Args.selection, Args.tweakID,
765 std::move(Action));
10
Calling 'move<(lambda at /build/llvm-toolchain-snapshot-14~++20220125101009+ceec4383681c/clang-tools-extra/clangd/ClangdLSPServer.cpp:736:17) &>'
11
Returning from 'move<(lambda at /build/llvm-toolchain-snapshot-14~++20220125101009+ceec4383681c/clang-tools-extra/clangd/ClangdLSPServer.cpp:736:17) &>'
12
Calling implicit move constructor
13
Calling defaulted move constructor for 'unique_function<void (llvm::Expected<llvm::json::Value>)>'
17
Returning from move constructor for 'unique_function<void (llvm::Expected<llvm::json::Value>)>'
18
Returning from move constructor
766}
19
Calling implicit destructor
20
Calling implicit destructor for 'unique_function<void (llvm::Expected<llvm::json::Value>)>'
21
Calling '~UniqueFunctionBase'
767
768void ClangdLSPServer::applyEdit(WorkspaceEdit WE, llvm::json::Value Success,
769 Callback<llvm::json::Value> Reply) {
770 ApplyWorkspaceEditParams Edit;
771 Edit.edit = std::move(WE);
772 ApplyWorkspaceEdit(
773 Edit, [Reply = std::move(Reply), SuccessMessage = std::move(Success)](
774 llvm::Expected<ApplyWorkspaceEditResponse> Response) mutable {
775 if (!Response)
776 return Reply(Response.takeError());
777 if (!Response->applied) {
778 std::string Reason = Response->failureReason
779 ? *Response->failureReason
780 : "unknown reason";
781 return Reply(error("edits were not applied: {0}", Reason));
782 }
783 return Reply(SuccessMessage);
784 });
785}
786
787void ClangdLSPServer::onWorkspaceSymbol(
788 const WorkspaceSymbolParams &Params,
789 Callback<std::vector<SymbolInformation>> Reply) {
790 Server->workspaceSymbols(
791 Params.query, Params.limit.getValueOr(Opts.CodeComplete.Limit),
792 [Reply = std::move(Reply),
793 this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable {
794 if (!Items)
795 return Reply(Items.takeError());
796 for (auto &Sym : *Items)
797 Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
798
799 Reply(std::move(*Items));
800 });
801}
802
803void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params,
804 Callback<llvm::Optional<Range>> Reply) {
805 Server->prepareRename(
806 Params.textDocument.uri.file(), Params.position, /*NewName*/ llvm::None,
807 Opts.Rename,
808 [Reply = std::move(Reply)](llvm::Expected<RenameResult> Result) mutable {
809 if (!Result)
810 return Reply(Result.takeError());
811 return Reply(std::move(Result->Target));
812 });
813}
814
815void ClangdLSPServer::onRename(const RenameParams &Params,
816 Callback<WorkspaceEdit> Reply) {
817 Path File = std::string(Params.textDocument.uri.file());
818 if (!Server->getDraft(File))
819 return Reply(llvm::make_error<LSPError>(
820 "onRename called for non-added file", ErrorCode::InvalidParams));
821 Server->rename(File, Params.position, Params.newName, Opts.Rename,
822 [File, Params, Reply = std::move(Reply),
823 this](llvm::Expected<RenameResult> R) mutable {
824 if (!R)
825 return Reply(R.takeError());
826 if (auto Err = validateEdits(*Server, R->GlobalChanges))
827 return Reply(std::move(Err));
828 WorkspaceEdit Result;
829 for (const auto &Rep : R->GlobalChanges) {
830 Result.changes[URI::createFile(Rep.first()).toString()] =
831 Rep.second.asTextEdits();
832 }
833 Reply(Result);
834 });
835}
836
837void ClangdLSPServer::onDocumentDidClose(
838 const DidCloseTextDocumentParams &Params) {
839 PathRef File = Params.textDocument.uri.file();
840 Server->removeDocument(File);
841
842 {
843 std::lock_guard<std::mutex> Lock(FixItsMutex);
844 FixItsMap.erase(File);
845 }
846 {
847 std::lock_guard<std::mutex> HLock(SemanticTokensMutex);
848 LastSemanticTokens.erase(File);
849 }
850 // clangd will not send updates for this file anymore, so we empty out the
851 // list of diagnostics shown on the client (e.g. in the "Problems" pane of
852 // VSCode). Note that this cannot race with actual diagnostics responses
853 // because removeDocument() guarantees no diagnostic callbacks will be
854 // executed after it returns.
855 PublishDiagnosticsParams Notification;
856 Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File);
857 PublishDiagnostics(Notification);
858}
859
860void ClangdLSPServer::onDocumentOnTypeFormatting(
861 const DocumentOnTypeFormattingParams &Params,
862 Callback<std::vector<TextEdit>> Reply) {
863 auto File = Params.textDocument.uri.file();
864 Server->formatOnType(File, Params.position, Params.ch, std::move(Reply));
865}
866
867void ClangdLSPServer::onDocumentRangeFormatting(
868 const DocumentRangeFormattingParams &Params,
869 Callback<std::vector<TextEdit>> Reply) {
870 auto File = Params.textDocument.uri.file();
871 auto Code = Server->getDraft(File);
872 Server->formatFile(File, Params.range,
873 [Code = std::move(Code), Reply = std::move(Reply)](
874 llvm::Expected<tooling::Replacements> Result) mutable {
875 if (Result)
876 Reply(replacementsToEdits(*Code, Result.get()));
877 else
878 Reply(Result.takeError());
879 });
880}
881
882void ClangdLSPServer::onDocumentFormatting(
883 const DocumentFormattingParams &Params,
884 Callback<std::vector<TextEdit>> Reply) {
885 auto File = Params.textDocument.uri.file();
886 auto Code = Server->getDraft(File);
887 Server->formatFile(File,
888 /*Rng=*/llvm::None,
889 [Code = std::move(Code), Reply = std::move(Reply)](
890 llvm::Expected<tooling::Replacements> Result) mutable {
891 if (Result)
892 Reply(replacementsToEdits(*Code, Result.get()));
893 else
894 Reply(Result.takeError());
895 });
896}
897
898/// The functions constructs a flattened view of the DocumentSymbol hierarchy.
899/// Used by the clients that do not support the hierarchical view.
900static std::vector<SymbolInformation>
901flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
902 const URIForFile &FileURI) {
903 std::vector<SymbolInformation> Results;
904 std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
905 [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
906 SymbolInformation SI;
907 SI.containerName = std::string(ParentName ? "" : *ParentName);
908 SI.name = S.name;
909 SI.kind = S.kind;
910 SI.location.range = S.range;
911 SI.location.uri = FileURI;
912
913 Results.push_back(std::move(SI));
914 std::string FullName =
915 !ParentName ? S.name : (ParentName->str() + "::" + S.name);
916 for (auto &C : S.children)
917 Process(C, /*ParentName=*/FullName);
918 };
919 for (auto &S : Symbols)
920 Process(S, /*ParentName=*/"");
921 return Results;
922}
923
924void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
925 Callback<llvm::json::Value> Reply) {
926 URIForFile FileURI = Params.textDocument.uri;
927 Server->documentSymbols(
928 Params.textDocument.uri.file(),
929 [this, FileURI, Reply = std::move(Reply)](
930 llvm::Expected<std::vector<DocumentSymbol>> Items) mutable {
931 if (!Items)
932 return Reply(Items.takeError());
933 adjustSymbolKinds(*Items, SupportedSymbolKinds);
934 if (SupportsHierarchicalDocumentSymbol)
935 return Reply(std::move(*Items));
936 return Reply(flattenSymbolHierarchy(*Items, FileURI));
937 });
938}
939
940void ClangdLSPServer::onFoldingRange(
941 const FoldingRangeParams &Params,
942 Callback<std::vector<FoldingRange>> Reply) {
943 Server->foldingRanges(Params.textDocument.uri.file(), std::move(Reply));
944}
945
946static llvm::Optional<Command> asCommand(const CodeAction &Action) {
947 Command Cmd;
948 if (Action.command && Action.edit)
949 return None; // Not representable. (We never emit these anyway).
950 if (Action.command) {
951 Cmd = *Action.command;
952 } else if (Action.edit) {
953 Cmd.command = std::string(APPLY_FIX_COMMAND);
954 Cmd.argument = *Action.edit;
955 } else {
956 return None;
957 }
958 Cmd.title = Action.title;
959 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
960 Cmd.title = "Apply fix: " + Cmd.title;
961 return Cmd;
962}
963
964void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
965 Callback<llvm::json::Value> Reply) {
966 URIForFile File = Params.textDocument.uri;
967 // Checks whether a particular CodeActionKind is included in the response.
968 auto KindAllowed = [Only(Params.context.only)](llvm::StringRef Kind) {
969 if (Only.empty())
970 return true;
971 return llvm::any_of(Only, [&](llvm::StringRef Base) {
972 return Kind.consume_front(Base) && (Kind.empty() || Kind.startswith("."));
973 });
974 };
975
976 // We provide a code action for Fixes on the specified diagnostics.
977 std::vector<CodeAction> FixIts;
978 if (KindAllowed(CodeAction::QUICKFIX_KIND)) {
979 for (const Diagnostic &D : Params.context.diagnostics) {
980 for (auto &F : getFixes(File.file(), D)) {
981 FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
982 FixIts.back().diagnostics = {D};
983 }
984 }
985 }
986
987 // Now enumerate the semantic code actions.
988 auto ConsumeActions =
989 [Reply = std::move(Reply), File, Selection = Params.range,
990 FixIts = std::move(FixIts), this](
991 llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable {
992 if (!Tweaks)
993 return Reply(Tweaks.takeError());
994
995 std::vector<CodeAction> Actions = std::move(FixIts);
996 Actions.reserve(Actions.size() + Tweaks->size());
997 for (const auto &T : *Tweaks)
998 Actions.push_back(toCodeAction(T, File, Selection));
999
1000 // If there's exactly one quick-fix, call it "preferred".
1001 // We never consider refactorings etc as preferred.
1002 CodeAction *OnlyFix = nullptr;
1003 for (auto &Action : Actions) {
1004 if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND) {
1005 if (OnlyFix) {
1006 OnlyFix->isPreferred = false;
1007 break;
1008 }
1009 Action.isPreferred = true;
1010 OnlyFix = &Action;
1011 }
1012 }
1013
1014 if (SupportsCodeAction)
1015 return Reply(llvm::json::Array(Actions));
1016 std::vector<Command> Commands;
1017 for (const auto &Action : Actions) {
1018 if (auto Command = asCommand(Action))
1019 Commands.push_back(std::move(*Command));
1020 }
1021 return Reply(llvm::json::Array(Commands));
1022 };
1023 Server->enumerateTweaks(
1024 File.file(), Params.range,
1025 [this, KindAllowed(std::move(KindAllowed))](const Tweak &T) {
1026 return Opts.TweakFilter(T) && KindAllowed(T.kind());
1027 },
1028 std::move(ConsumeActions));
1029}
1030
1031void ClangdLSPServer::onCompletion(const CompletionParams &Params,
1032 Callback<CompletionList> Reply) {
1033 if (!shouldRunCompletion(Params)) {
1034 // Clients sometimes auto-trigger completions in undesired places (e.g.
1035 // 'a >^ '), we return empty results in those cases.
1036 vlog("ignored auto-triggered completion, preceding char did not match");
1037 return Reply(CompletionList());
1038 }
1039 auto Opts = this->Opts.CodeComplete;
1040 if (Params.limit && *Params.limit >= 0)
1041 Opts.Limit = *Params.limit;
1042 Server->codeComplete(Params.textDocument.uri.file(), Params.position, Opts,
1043 [Reply = std::move(Reply), Opts,
1044 this](llvm::Expected<CodeCompleteResult> List) mutable {
1045 if (!List)
1046 return Reply(List.takeError());
1047 CompletionList LSPList;
1048 LSPList.isIncomplete = List->HasMore;
1049 for (const auto &R : List->Completions) {
1050 CompletionItem C = R.render(Opts);
1051 C.kind = adjustKindToCapability(
1052 C.kind, SupportedCompletionItemKinds);
1053 LSPList.items.push_back(std::move(C));
1054 }
1055 return Reply(std::move(LSPList));
1056 });
1057}
1058
1059void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
1060 Callback<SignatureHelp> Reply) {
1061 Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
1062 Opts.SignatureHelpDocumentationFormat,
1063 [Reply = std::move(Reply), this](
1064 llvm::Expected<SignatureHelp> Signature) mutable {
1065 if (!Signature)
1066 return Reply(Signature.takeError());
1067 if (SupportsOffsetsInSignatureHelp)
1068 return Reply(std::move(*Signature));
1069 // Strip out the offsets from signature help for
1070 // clients that only support string labels.
1071 for (auto &SigInfo : Signature->signatures) {
1072 for (auto &Param : SigInfo.parameters)
1073 Param.labelOffsets.reset();
1074 }
1075 return Reply(std::move(*Signature));
1076 });
1077}
1078
1079// Go to definition has a toggle function: if def and decl are distinct, then
1080// the first press gives you the def, the second gives you the matching def.
1081// getToggle() returns the counterpart location that under the cursor.
1082//
1083// We return the toggled location alone (ignoring other symbols) to encourage
1084// editors to "bounce" quickly between locations, without showing a menu.
1085static Location *getToggle(const TextDocumentPositionParams &Point,
1086 LocatedSymbol &Sym) {
1087 // Toggle only makes sense with two distinct locations.
1088 if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
1089 return nullptr;
1090 if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
1091 Sym.Definition->range.contains(Point.position))
1092 return &Sym.PreferredDeclaration;
1093 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
1094 Sym.PreferredDeclaration.range.contains(Point.position))
1095 return &*Sym.Definition;
1096 return nullptr;
1097}
1098
1099void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
1100 Callback<std::vector<Location>> Reply) {
1101 Server->locateSymbolAt(
1102 Params.textDocument.uri.file(), Params.position,
1103 [Params, Reply = std::move(Reply)](
1104 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1105 if (!Symbols)
1106 return Reply(Symbols.takeError());
1107 std::vector<Location> Defs;
1108 for (auto &S : *Symbols) {
1109 if (Location *Toggle = getToggle(Params, S))
1110 return Reply(std::vector<Location>{std::move(*Toggle)});
1111 Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
1112 }
1113 Reply(std::move(Defs));
1114 });
1115}
1116
1117void ClangdLSPServer::onGoToDeclaration(
1118 const TextDocumentPositionParams &Params,
1119 Callback<std::vector<Location>> Reply) {
1120 Server->locateSymbolAt(
1121 Params.textDocument.uri.file(), Params.position,
1122 [Params, Reply = std::move(Reply)](
1123 llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1124 if (!Symbols)
1125 return Reply(Symbols.takeError());
1126 std::vector<Location> Decls;
1127 for (auto &S : *Symbols) {
1128 if (Location *Toggle = getToggle(Params, S))
1129 return Reply(std::vector<Location>{std::move(*Toggle)});
1130 Decls.push_back(std::move(S.PreferredDeclaration));
1131 }
1132 Reply(std::move(Decls));
1133 });
1134}
1135
1136void ClangdLSPServer::onSwitchSourceHeader(
1137 const TextDocumentIdentifier &Params,
1138 Callback<llvm::Optional<URIForFile>> Reply) {
1139 Server->switchSourceHeader(
1140 Params.uri.file(),
1141 [Reply = std::move(Reply),
1142 Params](llvm::Expected<llvm::Optional<clangd::Path>> Path) mutable {
1143 if (!Path)
1144 return Reply(Path.takeError());
1145 if (*Path)
1146 return Reply(URIForFile::canonicalize(**Path, Params.uri.file()));
1147 return Reply(llvm::None);
1148 });
1149}
1150
1151void ClangdLSPServer::onDocumentHighlight(
1152 const TextDocumentPositionParams &Params,
1153 Callback<std::vector<DocumentHighlight>> Reply) {
1154 Server->findDocumentHighlights(Params.textDocument.uri.file(),
1155 Params.position, std::move(Reply));
1156}
1157
1158void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
1159 Callback<llvm::Optional<Hover>> Reply) {
1160 Server->findHover(Params.textDocument.uri.file(), Params.position,
1161 [Reply = std::move(Reply), this](
1162 llvm::Expected<llvm::Optional<HoverInfo>> H) mutable {
1163 if (!H)
1164 return Reply(H.takeError());
1165 if (!*H)
1166 return Reply(llvm::None);
1167
1168 Hover R;
1169 R.contents.kind = HoverContentFormat;
1170 R.range = (*H)->SymRange;
1171 switch (HoverContentFormat) {
1172 case MarkupKind::PlainText:
1173 R.contents.value = (*H)->present().asPlainText();
1174 return Reply(std::move(R));
1175 case MarkupKind::Markdown:
1176 R.contents.value = (*H)->present().asMarkdown();
1177 return Reply(std::move(R));
1178 };
1179 llvm_unreachable("unhandled MarkupKind")::llvm::llvm_unreachable_internal("unhandled MarkupKind", "clang-tools-extra/clangd/ClangdLSPServer.cpp"
, 1179)
;
1180 });
1181}
1182
1183void ClangdLSPServer::onTypeHierarchy(
1184 const TypeHierarchyParams &Params,
1185 Callback<Optional<TypeHierarchyItem>> Reply) {
1186 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
1187 Params.resolve, Params.direction, std::move(Reply));
1188}
1189
1190void ClangdLSPServer::onResolveTypeHierarchy(
1191 const ResolveTypeHierarchyItemParams &Params,
1192 Callback<Optional<TypeHierarchyItem>> Reply) {
1193 Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
1194 std::move(Reply));
1195}
1196
1197void ClangdLSPServer::onPrepareCallHierarchy(
1198 const CallHierarchyPrepareParams &Params,
1199 Callback<std::vector<CallHierarchyItem>> Reply) {
1200 Server->prepareCallHierarchy(Params.textDocument.uri.file(), Params.position,
1201 std::move(Reply));
1202}
1203
1204void ClangdLSPServer::onCallHierarchyIncomingCalls(
1205 const CallHierarchyIncomingCallsParams &Params,
1206 Callback<std::vector<CallHierarchyIncomingCall>> Reply) {
1207 Server->incomingCalls(Params.item, std::move(Reply));
1208}
1209
1210void ClangdLSPServer::onInlayHints(const InlayHintsParams &Params,
1211 Callback<std::vector<InlayHint>> Reply) {
1212 Server->inlayHints(Params.textDocument.uri.file(), Params.range,
1213 std::move(Reply));
1214}
1215
1216void ClangdLSPServer::applyConfiguration(
1217 const ConfigurationSettings &Settings) {
1218 // Per-file update to the compilation database.
1219 llvm::StringSet<> ModifiedFiles;
1220 for (auto &Entry : Settings.compilationDatabaseChanges) {
1221 PathRef File = Entry.first;
1222 auto Old = CDB->getCompileCommand(File);
1223 auto New =
1224 tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
1225 std::move(Entry.second.compilationCommand),
1226 /*Output=*/"");
1227 if (Old != New) {
1228 CDB->setCompileCommand(File, std::move(New));
1229 ModifiedFiles.insert(File);
1230 }
1231 }
1232
1233 Server->reparseOpenFilesIfNeeded(
1234 [&](llvm::StringRef File) { return ModifiedFiles.count(File) != 0; });
1235}
1236
1237void ClangdLSPServer::maybeExportMemoryProfile() {
1238 if (!trace::enabled() || !ShouldProfile())
1239 return;
1240
1241 static constexpr trace::Metric MemoryUsage(
1242 "memory_usage", trace::Metric::Value, "component_name");
1243 trace::Span Tracer("ProfileBrief");
1244 MemoryTree MT;
1245 profile(MT);
1246 record(MT, "clangd_lsp_server", MemoryUsage);
1247}
1248
1249void ClangdLSPServer::maybeCleanupMemory() {
1250 if (!Opts.MemoryCleanup || !ShouldCleanupMemory())
1251 return;
1252 Opts.MemoryCleanup();
1253}
1254
1255// FIXME: This function needs to be properly tested.
1256void ClangdLSPServer::onChangeConfiguration(
1257 const DidChangeConfigurationParams &Params) {
1258 applyConfiguration(Params.settings);
1259}
1260
1261void ClangdLSPServer::onReference(const ReferenceParams &Params,
1262 Callback<std::vector<Location>> Reply) {
1263 Server->findReferences(
1264 Params.textDocument.uri.file(), Params.position, Opts.ReferencesLimit,
1265 [Reply = std::move(Reply),
1266 IncludeDecl(Params.context.includeDeclaration)](
1267 llvm::Expected<ReferencesResult> Refs) mutable {
1268 if (!Refs)
1269 return Reply(Refs.takeError());
1270 // Filter out declarations if the client asked.
1271 std::vector<Location> Result;
1272 Result.reserve(Refs->References.size());
1273 for (auto &Ref : Refs->References) {
1274 bool IsDecl = Ref.Attributes & ReferencesResult::Declaration;
1275 if (IncludeDecl || !IsDecl)
1276 Result.push_back(std::move(Ref.Loc));
1277 }
1278 return Reply(std::move(Result));
1279 });
1280}
1281
1282void ClangdLSPServer::onGoToType(const TextDocumentPositionParams &Params,
1283 Callback<std::vector<Location>> Reply) {
1284 Server->findType(
1285 Params.textDocument.uri.file(), Params.position,
1286 [Reply = std::move(Reply)](
1287 llvm::Expected<std::vector<LocatedSymbol>> Types) mutable {
1288 if (!Types)
1289 return Reply(Types.takeError());
1290 std::vector<Location> Response;
1291 for (const LocatedSymbol &Sym : *Types)
1292 Response.push_back(Sym.PreferredDeclaration);
1293 return Reply(std::move(Response));
1294 });
1295}
1296
1297void ClangdLSPServer::onGoToImplementation(
1298 const TextDocumentPositionParams &Params,
1299 Callback<std::vector<Location>> Reply) {
1300 Server->findImplementations(
1301 Params.textDocument.uri.file(), Params.position,
1302 [Reply = std::move(Reply)](
1303 llvm::Expected<std::vector<LocatedSymbol>> Overrides) mutable {
1304 if (!Overrides)
1305 return Reply(Overrides.takeError());
1306 std::vector<Location> Impls;
1307 for (const LocatedSymbol &Sym : *Overrides)
1308 Impls.push_back(Sym.PreferredDeclaration);
1309 return Reply(std::move(Impls));
1310 });
1311}
1312
1313void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
1314 Callback<std::vector<SymbolDetails>> Reply) {
1315 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
1316 std::move(Reply));
1317}
1318
1319void ClangdLSPServer::onSelectionRange(
1320 const SelectionRangeParams &Params,
1321 Callback<std::vector<SelectionRange>> Reply) {
1322 Server->semanticRanges(
1323 Params.textDocument.uri.file(), Params.positions,
1324 [Reply = std::move(Reply)](
1325 llvm::Expected<std::vector<SelectionRange>> Ranges) mutable {
1326 if (!Ranges)
1327 return Reply(Ranges.takeError());
1328 return Reply(std::move(*Ranges));
1329 });
1330}
1331
1332void ClangdLSPServer::onDocumentLink(
1333 const DocumentLinkParams &Params,
1334 Callback<std::vector<DocumentLink>> Reply) {
1335
1336 // TODO(forster): This currently resolves all targets eagerly. This is slow,
1337 // because it blocks on the preamble/AST being built. We could respond to the
1338 // request faster by using string matching or the lexer to find the includes
1339 // and resolving the targets lazily.
1340 Server->documentLinks(
1341 Params.textDocument.uri.file(),
1342 [Reply = std::move(Reply)](
1343 llvm::Expected<std::vector<DocumentLink>> Links) mutable {
1344 if (!Links) {
1345 return Reply(Links.takeError());
1346 }
1347 return Reply(std::move(Links));
1348 });
1349}
1350
1351// Increment a numeric string: "" -> 1 -> 2 -> ... -> 9 -> 10 -> 11 ...
1352static void increment(std::string &S) {
1353 for (char &C : llvm::reverse(S)) {
1354 if (C != '9') {
1355 ++C;
1356 return;
1357 }
1358 C = '0';
1359 }
1360 S.insert(S.begin(), '1');
1361}
1362
1363void ClangdLSPServer::onSemanticTokens(const SemanticTokensParams &Params,
1364 Callback<SemanticTokens> CB) {
1365 Server->semanticHighlights(
1366 Params.textDocument.uri.file(),
1367 [this, File(Params.textDocument.uri.file().str()), CB(std::move(CB))](
1368 llvm::Expected<std::vector<HighlightingToken>> HT) mutable {
1369 if (!HT)
1370 return CB(HT.takeError());
1371 SemanticTokens Result;
1372 Result.tokens = toSemanticTokens(*HT);
1373 {
1374 std::lock_guard<std::mutex> Lock(SemanticTokensMutex);
1375 auto &Last = LastSemanticTokens[File];
1376
1377 Last.tokens = Result.tokens;
1378 increment(Last.resultId);
1379 Result.resultId = Last.resultId;
1380 }
1381 CB(std::move(Result));
1382 });
1383}
1384
1385void ClangdLSPServer::onSemanticTokensDelta(
1386 const SemanticTokensDeltaParams &Params,
1387 Callback<SemanticTokensOrDelta> CB) {
1388 Server->semanticHighlights(
1389 Params.textDocument.uri.file(),
1390 [this, PrevResultID(Params.previousResultId),
1391 File(Params.textDocument.uri.file().str()), CB(std::move(CB))](
1392 llvm::Expected<std::vector<HighlightingToken>> HT) mutable {
1393 if (!HT)
1394 return CB(HT.takeError());
1395 std::vector<SemanticToken> Toks = toSemanticTokens(*HT);
1396
1397 SemanticTokensOrDelta Result;
1398 {
1399 std::lock_guard<std::mutex> Lock(SemanticTokensMutex);
1400 auto &Last = LastSemanticTokens[File];
1401
1402 if (PrevResultID == Last.resultId) {
1403 Result.edits = diffTokens(Last.tokens, Toks);
1404 } else {
1405 vlog("semanticTokens/full/delta: wanted edits vs {0} but last "
1406 "result had ID {1}. Returning full token list.",
1407 PrevResultID, Last.resultId);
1408 Result.tokens = Toks;
1409 }
1410
1411 Last.tokens = std::move(Toks);
1412 increment(Last.resultId);
1413 Result.resultId = Last.resultId;
1414 }
1415
1416 CB(std::move(Result));
1417 });
1418}
1419
1420void ClangdLSPServer::onMemoryUsage(const NoParams &,
1421 Callback<MemoryTree> Reply) {
1422 llvm::BumpPtrAllocator DetailAlloc;
1423 MemoryTree MT(&DetailAlloc);
1424 profile(MT);
1425 Reply(std::move(MT));
1426}
1427
1428void ClangdLSPServer::onAST(const ASTParams &Params,
1429 Callback<llvm::Optional<ASTNode>> CB) {
1430 Server->getAST(Params.textDocument.uri.file(), Params.range, std::move(CB));
1431}
1432
1433ClangdLSPServer::ClangdLSPServer(Transport &Transp, const ThreadsafeFS &TFS,
1434 const ClangdLSPServer::Options &Opts)
1435 : ShouldProfile(/*Period=*/std::chrono::minutes(5),
1436 /*Delay=*/std::chrono::minutes(1)),
1437 ShouldCleanupMemory(/*Period=*/std::chrono::minutes(1),
1438 /*Delay=*/std::chrono::minutes(1)),
1439 BackgroundContext(Context::current().clone()), Transp(Transp),
1440 MsgHandler(new MessageHandler(*this)), TFS(TFS),
1441 SupportedSymbolKinds(defaultSymbolKinds()),
1442 SupportedCompletionItemKinds(defaultCompletionItemKinds()), Opts(Opts) {
1443 if (Opts.ConfigProvider) {
1444 assert(!Opts.ContextProvider &&(static_cast <bool> (!Opts.ContextProvider && "Only one of ConfigProvider and ContextProvider allowed!"
) ? void (0) : __assert_fail ("!Opts.ContextProvider && \"Only one of ConfigProvider and ContextProvider allowed!\""
, "clang-tools-extra/clangd/ClangdLSPServer.cpp", 1445, __extension__
__PRETTY_FUNCTION__))
1445 "Only one of ConfigProvider and ContextProvider allowed!")(static_cast <bool> (!Opts.ContextProvider && "Only one of ConfigProvider and ContextProvider allowed!"
) ? void (0) : __assert_fail ("!Opts.ContextProvider && \"Only one of ConfigProvider and ContextProvider allowed!\""
, "clang-tools-extra/clangd/ClangdLSPServer.cpp", 1445, __extension__
__PRETTY_FUNCTION__))
;
1446 this->Opts.ContextProvider = ClangdServer::createConfiguredContextProvider(
1447 Opts.ConfigProvider, this);
1448 }
1449 LSPBinder Bind(this->Handlers, *this);
1450 Bind.method("initialize", this, &ClangdLSPServer::onInitialize);
1451}
1452
1453void ClangdLSPServer::bindMethods(LSPBinder &Bind,
1454 const ClientCapabilities &Caps) {
1455 // clang-format off
1456 Bind.notification("initialized", this, &ClangdLSPServer::onInitialized);
1457 Bind.method("shutdown", this, &ClangdLSPServer::onShutdown);
1458 Bind.method("sync", this, &ClangdLSPServer::onSync);
1459 Bind.method("textDocument/rangeFormatting", this, &ClangdLSPServer::onDocumentRangeFormatting);
1460 Bind.method("textDocument/onTypeFormatting", this, &ClangdLSPServer::onDocumentOnTypeFormatting);
1461 Bind.method("textDocument/formatting", this, &ClangdLSPServer::onDocumentFormatting);
1462 Bind.method("textDocument/codeAction", this, &ClangdLSPServer::onCodeAction);
1463 Bind.method("textDocument/completion", this, &ClangdLSPServer::onCompletion);
1464 Bind.method("textDocument/signatureHelp", this, &ClangdLSPServer::onSignatureHelp);
1465 Bind.method("textDocument/definition", this, &ClangdLSPServer::onGoToDefinition);
1466 Bind.method("textDocument/declaration", this, &ClangdLSPServer::onGoToDeclaration);
1467 Bind.method("textDocument/typeDefinition", this, &ClangdLSPServer::onGoToType);
1468 Bind.method("textDocument/implementation", this, &ClangdLSPServer::onGoToImplementation);
1469 Bind.method("textDocument/references", this, &ClangdLSPServer::onReference);
1470 Bind.method("textDocument/switchSourceHeader", this, &ClangdLSPServer::onSwitchSourceHeader);
1471 Bind.method("textDocument/prepareRename", this, &ClangdLSPServer::onPrepareRename);
1472 Bind.method("textDocument/rename", this, &ClangdLSPServer::onRename);
1473 Bind.method("textDocument/hover", this, &ClangdLSPServer::onHover);
1474 Bind.method("textDocument/documentSymbol", this, &ClangdLSPServer::onDocumentSymbol);
1475 Bind.method("workspace/executeCommand", this, &ClangdLSPServer::onCommand);
1476 Bind.method("textDocument/documentHighlight", this, &ClangdLSPServer::onDocumentHighlight);
1477 Bind.method("workspace/symbol", this, &ClangdLSPServer::onWorkspaceSymbol);
1478 Bind.method("textDocument/ast", this, &ClangdLSPServer::onAST);
1479 Bind.notification("textDocument/didOpen", this, &ClangdLSPServer::onDocumentDidOpen);
1480 Bind.notification("textDocument/didClose", this, &ClangdLSPServer::onDocumentDidClose);
1481 Bind.notification("textDocument/didChange", this, &ClangdLSPServer::onDocumentDidChange);
1482 Bind.notification("textDocument/didSave", this, &ClangdLSPServer::onDocumentDidSave);
1483 Bind.notification("workspace/didChangeWatchedFiles", this, &ClangdLSPServer::onFileEvent);
1484 Bind.notification("workspace/didChangeConfiguration", this, &ClangdLSPServer::onChangeConfiguration);
1485 Bind.method("textDocument/symbolInfo", this, &ClangdLSPServer::onSymbolInfo);
1486 Bind.method("textDocument/typeHierarchy", this, &ClangdLSPServer::onTypeHierarchy);
1487 Bind.method("typeHierarchy/resolve", this, &ClangdLSPServer::onResolveTypeHierarchy);
1488 Bind.method("textDocument/prepareCallHierarchy", this, &ClangdLSPServer::onPrepareCallHierarchy);
1489 Bind.method("callHierarchy/incomingCalls", this, &ClangdLSPServer::onCallHierarchyIncomingCalls);
1490 Bind.method("textDocument/selectionRange", this, &ClangdLSPServer::onSelectionRange);
1491 Bind.method("textDocument/documentLink", this, &ClangdLSPServer::onDocumentLink);
1492 Bind.method("textDocument/semanticTokens/full", this, &ClangdLSPServer::onSemanticTokens);
1493 Bind.method("textDocument/semanticTokens/full/delta", this, &ClangdLSPServer::onSemanticTokensDelta);
1494 Bind.method("clangd/inlayHints", this, &ClangdLSPServer::onInlayHints);
1495 Bind.method("$/memoryUsage", this, &ClangdLSPServer::onMemoryUsage);
1496 if (Opts.FoldingRanges)
1497 Bind.method("textDocument/foldingRange", this, &ClangdLSPServer::onFoldingRange);
1498 Bind.command(APPLY_FIX_COMMAND, this, &ClangdLSPServer::onCommandApplyEdit);
1499 Bind.command(APPLY_TWEAK_COMMAND, this, &ClangdLSPServer::onCommandApplyTweak);
1500
1501 ApplyWorkspaceEdit = Bind.outgoingMethod("workspace/applyEdit");
1502 PublishDiagnostics = Bind.outgoingNotification("textDocument/publishDiagnostics");
1503 ShowMessage = Bind.outgoingNotification("window/showMessage");
1504 NotifyFileStatus = Bind.outgoingNotification("textDocument/clangd.fileStatus");
1505 CreateWorkDoneProgress = Bind.outgoingMethod("window/workDoneProgress/create");
1506 BeginWorkDoneProgress = Bind.outgoingNotification("$/progress");
1507 ReportWorkDoneProgress = Bind.outgoingNotification("$/progress");
1508 EndWorkDoneProgress = Bind.outgoingNotification("$/progress");
1509 if(Caps.SemanticTokenRefreshSupport)
1510 SemanticTokensRefresh = Bind.outgoingMethod("workspace/semanticTokens/refresh");
1511 // clang-format on
1512}
1513
1514ClangdLSPServer::~ClangdLSPServer() {
1515 IsBeingDestroyed = true;
1516 // Explicitly destroy ClangdServer first, blocking on threads it owns.
1517 // This ensures they don't access any other members.
1518 Server.reset();
1519}
1520
1521bool ClangdLSPServer::run() {
1522 // Run the Language Server loop.
1523 bool CleanExit = true;
1524 if (auto Err = Transp.loop(*MsgHandler)) {
1525 elog("Transport error: {0}", std::move(Err));
1526 CleanExit = false;
1527 }
1528
1529 return CleanExit && ShutdownRequestReceived;
1530}
1531
1532void ClangdLSPServer::profile(MemoryTree &MT) const {
1533 if (Server)
1534 Server->profile(MT.child("clangd_server"));
1535}
1536
1537std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
1538 const clangd::Diagnostic &D) {
1539 std::lock_guard<std::mutex> Lock(FixItsMutex);
1540 auto DiagToFixItsIter = FixItsMap.find(File);
1541 if (DiagToFixItsIter == FixItsMap.end())
1542 return {};
1543
1544 const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1545 auto FixItsIter = DiagToFixItsMap.find(D);
1546 if (FixItsIter == DiagToFixItsMap.end())
1547 return {};
1548
1549 return FixItsIter->second;
1550}
1551
1552// A completion request is sent when the user types '>' or ':', but we only
1553// want to trigger on '->' and '::'. We check the preceeding text to make
1554// sure it matches what we expected.
1555// Running the lexer here would be more robust (e.g. we can detect comments
1556// and avoid triggering completion there), but we choose to err on the side
1557// of simplicity here.
1558bool ClangdLSPServer::shouldRunCompletion(
1559 const CompletionParams &Params) const {
1560 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter)
1561 return true;
1562 auto Code = Server->getDraft(Params.textDocument.uri.file());
1563 if (!Code)
1564 return true; // completion code will log the error for untracked doc.
1565 auto Offset = positionToOffset(*Code, Params.position,
1566 /*AllowColumnsBeyondLineLength=*/false);
1567 if (!Offset) {
1568 vlog("could not convert position '{0}' to offset for file '{1}'",
1569 Params.position, Params.textDocument.uri.file());
1570 return true;
1571 }
1572 return allowImplicitCompletion(*Code, *Offset);
1573}
1574
1575void ClangdLSPServer::onDiagnosticsReady(PathRef File, llvm::StringRef Version,
1576 std::vector<Diag> Diagnostics) {
1577 PublishDiagnosticsParams Notification;
1578 Notification.version = decodeVersion(Version);
1579 Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File);
1580 DiagnosticToReplacementMap LocalFixIts; // Temporary storage
1581 for (auto &Diag : Diagnostics) {
1582 toLSPDiags(Diag, Notification.uri, DiagOpts,
1583 [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
1584 auto &FixItsForDiagnostic = LocalFixIts[Diag];
1585 llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
1586 Notification.diagnostics.push_back(std::move(Diag));
1587 });
1588 }
1589
1590 // Cache FixIts
1591 {
1592 std::lock_guard<std::mutex> Lock(FixItsMutex);
1593 FixItsMap[File] = LocalFixIts;
1594 }
1595
1596 // Send a notification to the LSP client.
1597 PublishDiagnostics(Notification);
1598}
1599
1600void ClangdLSPServer::onBackgroundIndexProgress(
1601 const BackgroundQueue::Stats &Stats) {
1602 static const char ProgressToken[] = "backgroundIndexProgress";
1603
1604 // The background index did some work, maybe we need to cleanup
1605 maybeCleanupMemory();
1606
1607 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1608
1609 auto NotifyProgress = [this](const BackgroundQueue::Stats &Stats) {
1610 if (BackgroundIndexProgressState != BackgroundIndexProgress::Live) {
1611 WorkDoneProgressBegin Begin;
1612 Begin.percentage = true;
1613 Begin.title = "indexing";
1614 BeginWorkDoneProgress({ProgressToken, std::move(Begin)});
1615 BackgroundIndexProgressState = BackgroundIndexProgress::Live;
1616 }
1617
1618 if (Stats.Completed < Stats.Enqueued) {
1619 assert(Stats.Enqueued > Stats.LastIdle)(static_cast <bool> (Stats.Enqueued > Stats.LastIdle
) ? void (0) : __assert_fail ("Stats.Enqueued > Stats.LastIdle"
, "clang-tools-extra/clangd/ClangdLSPServer.cpp", 1619, __extension__
__PRETTY_FUNCTION__))
;
1620 WorkDoneProgressReport Report;
1621 Report.percentage = 100 * (Stats.Completed - Stats.LastIdle) /
1622 (Stats.Enqueued - Stats.LastIdle);
1623 Report.message =
1624 llvm::formatv("{0}/{1}", Stats.Completed - Stats.LastIdle,
1625 Stats.Enqueued - Stats.LastIdle);
1626 ReportWorkDoneProgress({ProgressToken, std::move(Report)});
1627 } else {
1628 assert(Stats.Completed == Stats.Enqueued)(static_cast <bool> (Stats.Completed == Stats.Enqueued)
? void (0) : __assert_fail ("Stats.Completed == Stats.Enqueued"
, "clang-tools-extra/clangd/ClangdLSPServer.cpp", 1628, __extension__
__PRETTY_FUNCTION__))
;
1629 EndWorkDoneProgress({ProgressToken, WorkDoneProgressEnd()});
1630 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
1631 }
1632 };
1633
1634 switch (BackgroundIndexProgressState) {
1635 case BackgroundIndexProgress::Unsupported:
1636 return;
1637 case BackgroundIndexProgress::Creating:
1638 // Cache this update for when the progress bar is available.
1639 PendingBackgroundIndexProgress = Stats;
1640 return;
1641 case BackgroundIndexProgress::Empty: {
1642 if (BackgroundIndexSkipCreate) {
1643 NotifyProgress(Stats);
1644 break;
1645 }
1646 // Cache this update for when the progress bar is available.
1647 PendingBackgroundIndexProgress = Stats;
1648 BackgroundIndexProgressState = BackgroundIndexProgress::Creating;
1649 WorkDoneProgressCreateParams CreateRequest;
1650 CreateRequest.token = ProgressToken;
1651 CreateWorkDoneProgress(
1652 CreateRequest,
1653 [this, NotifyProgress](llvm::Expected<std::nullptr_t> E) {
1654 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1655 if (E) {
1656 NotifyProgress(this->PendingBackgroundIndexProgress);
1657 } else {
1658 elog("Failed to create background index progress bar: {0}",
1659 E.takeError());
1660 // give up forever rather than thrashing about
1661 BackgroundIndexProgressState = BackgroundIndexProgress::Unsupported;
1662 }
1663 });
1664 break;
1665 }
1666 case BackgroundIndexProgress::Live:
1667 NotifyProgress(Stats);
1668 break;
1669 }
1670}
1671
1672void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1673 if (!SupportFileStatus)
1674 return;
1675 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1676 // two statuses are running faster in practice, which leads the UI constantly
1677 // changing, and doesn't provide much value. We may want to emit status at a
1678 // reasonable time interval (e.g. 0.5s).
1679 if (Status.PreambleActivity == PreambleAction::Idle &&
1680 (Status.ASTActivity.K == ASTAction::Building ||
1681 Status.ASTActivity.K == ASTAction::RunningAction))
1682 return;
1683 NotifyFileStatus(Status.render(File));
1684}
1685
1686void ClangdLSPServer::onSemanticsMaybeChanged(PathRef File) {
1687 if (SemanticTokensRefresh) {
1688 SemanticTokensRefresh(NoParams{}, [](llvm::Expected<std::nullptr_t> E) {
1689 if (E)
1690 return;
1691 elog("Failed to refresh semantic tokens: {0}", E.takeError());
1692 });
1693 }
1694}
1695} // namespace clangd
1696} // namespace clang

/build/llvm-toolchain-snapshot-14~++20220125101009+ceec4383681c/llvm/include/llvm/ADT/FunctionExtras.h

1//===- FunctionExtras.h - Function type erasure utilities -------*- C++ -*-===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8/// \file
9/// This file provides a collection of function (or more generally, callable)
10/// type erasure utilities supplementing those provided by the standard library
11/// in `<function>`.
12///
13/// It provides `unique_function`, which works like `std::function` but supports
14/// move-only callable objects and const-qualification.
15///
16/// Future plans:
17/// - Add a `function` that provides ref-qualified support, which doesn't work
18/// with `std::function`.
19/// - Provide support for specifying multiple signatures to type erase callable
20/// objects with an overload set, such as those produced by generic lambdas.
21/// - Expand to include a copyable utility that directly replaces std::function
22/// but brings the above improvements.
23///
24/// Note that LLVM's utilities are greatly simplified by not supporting
25/// allocators.
26///
27/// If the standard library ever begins to provide comparable facilities we can
28/// consider switching to those.
29///
30//===----------------------------------------------------------------------===//
31
32#ifndef LLVM_ADT_FUNCTIONEXTRAS_H
33#define LLVM_ADT_FUNCTIONEXTRAS_H
34
35#include "llvm/ADT/PointerIntPair.h"
36#include "llvm/ADT/PointerUnion.h"
37#include "llvm/ADT/STLForwardCompat.h"
38#include "llvm/Support/MemAlloc.h"
39#include "llvm/Support/type_traits.h"
40#include <cstring>
41#include <memory>
42#include <type_traits>
43
44namespace llvm {
45
46/// unique_function is a type-erasing functor similar to std::function.
47///
48/// It can hold move-only function objects, like lambdas capturing unique_ptrs.
49/// Accordingly, it is movable but not copyable.
50///
51/// It supports const-qualification:
52/// - unique_function<int() const> has a const operator().
53/// It can only hold functions which themselves have a const operator().
54/// - unique_function<int()> has a non-const operator().
55/// It can hold functions with a non-const operator(), like mutable lambdas.
56template <typename FunctionT> class unique_function;
57
58namespace detail {
59
60template <typename T>
61using EnableIfTrivial =
62 std::enable_if_t<llvm::is_trivially_move_constructible<T>::value &&
63 std::is_trivially_destructible<T>::value>;
64template <typename CallableT, typename ThisT>
65using EnableUnlessSameType =
66 std::enable_if_t<!std::is_same<remove_cvref_t<CallableT>, ThisT>::value>;
67template <typename CallableT, typename Ret, typename... Params>
68using EnableIfCallable = std::enable_if_t<llvm::disjunction<
69 std::is_void<Ret>,
70 std::is_same<decltype(std::declval<CallableT>()(std::declval<Params>()...)),
71 Ret>,
72 std::is_same<const decltype(std::declval<CallableT>()(
73 std::declval<Params>()...)),
74 Ret>,
75 std::is_convertible<decltype(std::declval<CallableT>()(
76 std::declval<Params>()...)),
77 Ret>>::value>;
78
79template <typename ReturnT, typename... ParamTs> class UniqueFunctionBase {
80protected:
81 static constexpr size_t InlineStorageSize = sizeof(void *) * 3;
82
83 template <typename T, class = void>
84 struct IsSizeLessThanThresholdT : std::false_type {};
85
86 template <typename T>
87 struct IsSizeLessThanThresholdT<
88 T, std::enable_if_t<sizeof(T) <= 2 * sizeof(void *)>> : std::true_type {};
89
90 // Provide a type function to map parameters that won't observe extra copies
91 // or moves and which are small enough to likely pass in register to values
92 // and all other types to l-value reference types. We use this to compute the
93 // types used in our erased call utility to minimize copies and moves unless
94 // doing so would force things unnecessarily into memory.
95 //
96 // The heuristic used is related to common ABI register passing conventions.
97 // It doesn't have to be exact though, and in one way it is more strict
98 // because we want to still be able to observe either moves *or* copies.
99 template <typename T> struct AdjustedParamTBase {
100 static_assert(!std::is_reference<T>::value,
101 "references should be handled by template specialization");
102 using type = typename std::conditional<
103 llvm::is_trivially_copy_constructible<T>::value &&
104 llvm::is_trivially_move_constructible<T>::value &&
105 IsSizeLessThanThresholdT<T>::value,
106 T, T &>::type;
107 };
108
109 // This specialization ensures that 'AdjustedParam<V<T>&>' or
110 // 'AdjustedParam<V<T>&&>' does not trigger a compile-time error when 'T' is
111 // an incomplete type and V a templated type.
112 template <typename T> struct AdjustedParamTBase<T &> { using type = T &; };
113 template <typename T> struct AdjustedParamTBase<T &&> { using type = T &; };
114
115 template <typename T>
116 using AdjustedParamT = typename AdjustedParamTBase<T>::type;
117
118 // The type of the erased function pointer we use as a callback to dispatch to
119 // the stored callable when it is trivial to move and destroy.
120 using CallPtrT = ReturnT (*)(void *CallableAddr,
121 AdjustedParamT<ParamTs>... Params);
122 using MovePtrT = void (*)(void *LHSCallableAddr, void *RHSCallableAddr);
123 using DestroyPtrT = void (*)(void *CallableAddr);
124
125 /// A struct to hold a single trivial callback with sufficient alignment for
126 /// our bitpacking.
127 struct alignas(8) TrivialCallback {
128 CallPtrT CallPtr;
129 };
130
131 /// A struct we use to aggregate three callbacks when we need full set of
132 /// operations.
133 struct alignas(8) NonTrivialCallbacks {
134 CallPtrT CallPtr;
135 MovePtrT MovePtr;
136 DestroyPtrT DestroyPtr;
137 };
138
139 // Create a pointer union between either a pointer to a static trivial call
140 // pointer in a struct or a pointer to a static struct of the call, move, and
141 // destroy pointers.
142 using CallbackPointerUnionT =
143 PointerUnion<TrivialCallback *, NonTrivialCallbacks *>;
144
145 // The main storage buffer. This will either have a pointer to out-of-line
146 // storage or an inline buffer storing the callable.
147 union StorageUnionT {
148 // For out-of-line storage we keep a pointer to the underlying storage and
149 // the size. This is enough to deallocate the memory.
150 struct OutOfLineStorageT {
151 void *StoragePtr;
152 size_t Size;
153 size_t Alignment;
154 } OutOfLineStorage;
155 static_assert(
156 sizeof(OutOfLineStorageT) <= InlineStorageSize,
157 "Should always use all of the out-of-line storage for inline storage!");
158
159 // For in-line storage, we just provide an aligned character buffer. We
160 // provide three pointers worth of storage here.
161 // This is mutable as an inlined `const unique_function<void() const>` may
162 // still modify its own mutable members.
163 mutable
164 typename std::aligned_storage<InlineStorageSize, alignof(void *)>::type
165 InlineStorage;
166 } StorageUnion;
167
168 // A compressed pointer to either our dispatching callback or our table of
169 // dispatching callbacks and the flag for whether the callable itself is
170 // stored inline or not.
171 PointerIntPair<CallbackPointerUnionT, 1, bool> CallbackAndInlineFlag;
172
173 bool isInlineStorage() const { return CallbackAndInlineFlag.getInt(); }
174
175 bool isTrivialCallback() const {
176 return CallbackAndInlineFlag.getPointer().template is<TrivialCallback *>();
177 }
178
179 CallPtrT getTrivialCallback() const {
180 return CallbackAndInlineFlag.getPointer().template get<TrivialCallback *>()->CallPtr;
181 }
182
183 NonTrivialCallbacks *getNonTrivialCallbacks() const {
184 return CallbackAndInlineFlag.getPointer()
185 .template get<NonTrivialCallbacks *>();
186 }
187
188 CallPtrT getCallPtr() const {
189 return isTrivialCallback() ? getTrivialCallback()
190 : getNonTrivialCallbacks()->CallPtr;
191 }
192
193 // These three functions are only const in the narrow sense. They return
194 // mutable pointers to function state.
195 // This allows unique_function<T const>::operator() to be const, even if the
196 // underlying functor may be internally mutable.
197 //
198 // const callers must ensure they're only used in const-correct ways.
199 void *getCalleePtr() const {
200 return isInlineStorage() ? getInlineStorage() : getOutOfLineStorage();
201 }
202 void *getInlineStorage() const { return &StorageUnion.InlineStorage; }
203 void *getOutOfLineStorage() const {
204 return StorageUnion.OutOfLineStorage.StoragePtr;
28
Undefined or garbage value returned to caller
205 }
206
207 size_t getOutOfLineStorageSize() const {
208 return StorageUnion.OutOfLineStorage.Size;
209 }
210 size_t getOutOfLineStorageAlignment() const {
211 return StorageUnion.OutOfLineStorage.Alignment;
212 }
213
214 void setOutOfLineStorage(void *Ptr, size_t Size, size_t Alignment) {
215 StorageUnion.OutOfLineStorage = {Ptr, Size, Alignment};
216 }
217
218 template <typename CalledAsT>
219 static ReturnT CallImpl(void *CallableAddr,
220 AdjustedParamT<ParamTs>... Params) {
221 auto &Func = *reinterpret_cast<CalledAsT *>(CallableAddr);
222 return Func(std::forward<ParamTs>(Params)...);
223 }
224
225 template <typename CallableT>
226 static void MoveImpl(void *LHSCallableAddr, void *RHSCallableAddr) noexcept {
227 new (LHSCallableAddr)
228 CallableT(std::move(*reinterpret_cast<CallableT *>(RHSCallableAddr)));
229 }
230
231 template <typename CallableT>
232 static void DestroyImpl(void *CallableAddr) noexcept {
233 reinterpret_cast<CallableT *>(CallableAddr)->~CallableT();
234 }
235
236 // The pointers to call/move/destroy functions are determined for each
237 // callable type (and called-as type, which determines the overload chosen).
238 // (definitions are out-of-line).
239
240 // By default, we need an object that contains all the different
241 // type erased behaviors needed. Create a static instance of the struct type
242 // here and each instance will contain a pointer to it.
243 // Wrap in a struct to avoid https://gcc.gnu.org/PR71954
244 template <typename CallableT, typename CalledAs, typename Enable = void>
245 struct CallbacksHolder {
246 static NonTrivialCallbacks Callbacks;
247 };
248 // See if we can create a trivial callback. We need the callable to be
249 // trivially moved and trivially destroyed so that we don't have to store
250 // type erased callbacks for those operations.
251 template <typename CallableT, typename CalledAs>
252 struct CallbacksHolder<CallableT, CalledAs, EnableIfTrivial<CallableT>> {
253 static TrivialCallback Callbacks;
254 };
255
256 // A simple tag type so the call-as type to be passed to the constructor.
257 template <typename T> struct CalledAs {};
258
259 // Essentially the "main" unique_function constructor, but subclasses
260 // provide the qualified type to be used for the call.
261 // (We always store a T, even if the call will use a pointer to const T).
262 template <typename CallableT, typename CalledAsT>
263 UniqueFunctionBase(CallableT Callable, CalledAs<CalledAsT>) {
264 bool IsInlineStorage = true;
265 void *CallableAddr = getInlineStorage();
266 if (sizeof(CallableT) > InlineStorageSize ||
267 alignof(CallableT) > alignof(decltype(StorageUnion.InlineStorage))) {
268 IsInlineStorage = false;
269 // Allocate out-of-line storage. FIXME: Use an explicit alignment
270 // parameter in C++17 mode.
271 auto Size = sizeof(CallableT);
272 auto Alignment = alignof(CallableT);
273 CallableAddr = allocate_buffer(Size, Alignment);
274 setOutOfLineStorage(CallableAddr, Size, Alignment);
275 }
276
277 // Now move into the storage.
278 new (CallableAddr) CallableT(std::move(Callable));
279 CallbackAndInlineFlag.setPointerAndInt(
280 &CallbacksHolder<CallableT, CalledAsT>::Callbacks, IsInlineStorage);
281 }
282
283 ~UniqueFunctionBase() {
284 if (!CallbackAndInlineFlag.getPointer())
22
Taking false branch
285 return;
286
287 // Cache this value so we don't re-check it after type-erased operations.
288 bool IsInlineStorage = isInlineStorage();
289
290 if (!isTrivialCallback())
23
Assuming the condition is false
24
Taking false branch
291 getNonTrivialCallbacks()->DestroyPtr(
292 IsInlineStorage ? getInlineStorage() : getOutOfLineStorage());
293
294 if (!IsInlineStorage)
25
Assuming 'IsInlineStorage' is false
26
Taking true branch
295 deallocate_buffer(getOutOfLineStorage(), getOutOfLineStorageSize(),
27
Calling 'UniqueFunctionBase::getOutOfLineStorage'
296 getOutOfLineStorageAlignment());
297 }
298
299 UniqueFunctionBase(UniqueFunctionBase &&RHS) noexcept {
300 // Copy the callback and inline flag.
301 CallbackAndInlineFlag = RHS.CallbackAndInlineFlag;
302
303 // If the RHS is empty, just copying the above is sufficient.
304 if (!RHS)
4
Taking true branch
15
Taking true branch
305 return;
5
Returning without writing to 'this->StorageUnion.OutOfLineStorage.StoragePtr'
306
307 if (!isInlineStorage()) {
308 // The out-of-line case is easiest to move.
309 StorageUnion.OutOfLineStorage = RHS.StorageUnion.OutOfLineStorage;
310 } else if (isTrivialCallback()) {
311 // Move is trivial, just memcpy the bytes across.
312 memcpy(getInlineStorage(), RHS.getInlineStorage(), InlineStorageSize);
313 } else {
314 // Non-trivial move, so dispatch to a type-erased implementation.
315 getNonTrivialCallbacks()->MovePtr(getInlineStorage(),
316 RHS.getInlineStorage());
317 }
318
319 // Clear the old callback and inline flag to get back to as-if-null.
320 RHS.CallbackAndInlineFlag = {};
321
322#ifndef NDEBUG
323 // In debug builds, we also scribble across the rest of the storage.
324 memset(RHS.getInlineStorage(), 0xAD, InlineStorageSize);
325#endif
326 }
327
328 UniqueFunctionBase &operator=(UniqueFunctionBase &&RHS) noexcept {
329 if (this == &RHS)
330 return *this;
331
332 // Because we don't try to provide any exception safety guarantees we can
333 // implement move assignment very simply by first destroying the current
334 // object and then move-constructing over top of it.
335 this->~UniqueFunctionBase();
336 new (this) UniqueFunctionBase(std::move(RHS));
337 return *this;
338 }
339
340 UniqueFunctionBase() = default;
341
342public:
343 explicit operator bool() const {
344 return (bool)CallbackAndInlineFlag.getPointer();
345 }
346};
347
348template <typename R, typename... P>
349template <typename CallableT, typename CalledAsT, typename Enable>
350typename UniqueFunctionBase<R, P...>::NonTrivialCallbacks UniqueFunctionBase<
351 R, P...>::CallbacksHolder<CallableT, CalledAsT, Enable>::Callbacks = {
352 &CallImpl<CalledAsT>, &MoveImpl<CallableT>, &DestroyImpl<CallableT>};
353
354template <typename R, typename... P>
355template <typename CallableT, typename CalledAsT>
356typename UniqueFunctionBase<R, P...>::TrivialCallback
357 UniqueFunctionBase<R, P...>::CallbacksHolder<
358 CallableT, CalledAsT, EnableIfTrivial<CallableT>>::Callbacks{
359 &CallImpl<CalledAsT>};
360
361} // namespace detail
362
363template <typename R, typename... P>
364class unique_function<R(P...)> : public detail::UniqueFunctionBase<R, P...> {
365 using Base = detail::UniqueFunctionBase<R, P...>;
366
367public:
368 unique_function() = default;
369 unique_function(std::nullptr_t) {}
370 unique_function(unique_function &&) = default;
3
Calling move constructor for 'UniqueFunctionBase<void, llvm::Expected<llvm::json::Value>>'
6
Returning from move constructor for 'UniqueFunctionBase<void, llvm::Expected<llvm::json::Value>>'
7
Returning without writing to 'this->StorageUnion.OutOfLineStorage.StoragePtr'
14
Calling move constructor for 'UniqueFunctionBase<void, llvm::Expected<llvm::json::Value>>'
16
Returning from move constructor for 'UniqueFunctionBase<void, llvm::Expected<llvm::json::Value>>'
371 unique_function(const unique_function &) = delete;
372 unique_function &operator=(unique_function &&) = default;
373 unique_function &operator=(const unique_function &) = delete;
374
375 template <typename CallableT>
376 unique_function(
377 CallableT Callable,
378 detail::EnableUnlessSameType<CallableT, unique_function> * = nullptr,
379 detail::EnableIfCallable<CallableT, R, P...> * = nullptr)
380 : Base(std::forward<CallableT>(Callable),
381 typename Base::template CalledAs<CallableT>{}) {}
382
383 R operator()(P... Params) {
384 return this->getCallPtr()(this->getCalleePtr(), Params...);
385 }
386};
387
388template <typename R, typename... P>
389class unique_function<R(P...) const>
390 : public detail::UniqueFunctionBase<R, P...> {
391 using Base = detail::UniqueFunctionBase<R, P...>;
392
393public:
394 unique_function() = default;
395 unique_function(std::nullptr_t) {}
396 unique_function(unique_function &&) = default;
397 unique_function(const unique_function &) = delete;
398 unique_function &operator=(unique_function &&) = default;
399 unique_function &operator=(const unique_function &) = delete;
400
401 template <typename CallableT>
402 unique_function(
403 CallableT Callable,
404 detail::EnableUnlessSameType<CallableT, unique_function> * = nullptr,
405 detail::EnableIfCallable<const CallableT, R, P...> * = nullptr)
406 : Base(std::forward<CallableT>(Callable),
407 typename Base::template CalledAs<const CallableT>{}) {}
408
409 R operator()(P... Params) const {
410 return this->getCallPtr()(this->getCalleePtr(), Params...);
411 }
412};
413
414} // end namespace llvm
415
416#endif // LLVM_ADT_FUNCTIONEXTRAS_H

/usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/bits/move.h

1// Move, forward and identity for C++11 + swap -*- C++ -*-
2
3// Copyright (C) 2007-2020 Free Software Foundation, Inc.
4//
5// This file is part of the GNU ISO C++ Library. This library is free
6// software; you can redistribute it and/or modify it under the
7// terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 3, or (at your option)
9// any later version.
10
11// This library is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// Under Section 7 of GPL version 3, you are granted additional
17// permissions described in the GCC Runtime Library Exception, version
18// 3.1, as published by the Free Software Foundation.
19
20// You should have received a copy of the GNU General Public License and
21// a copy of the GCC Runtime Library Exception along with this program;
22// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23// <http://www.gnu.org/licenses/>.
24
25/** @file bits/move.h
26 * This is an internal header file, included by other library headers.
27 * Do not attempt to use it directly. @headername{utility}
28 */
29
30#ifndef _MOVE_H1
31#define _MOVE_H1 1
32
33#include <bits/c++config.h>
34#if __cplusplus201402L < 201103L
35# include <bits/concept_check.h>
36#endif
37
38namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default")))
39{
40_GLIBCXX_BEGIN_NAMESPACE_VERSION
41
42 // Used, in C++03 mode too, by allocators, etc.
43 /**
44 * @brief Same as C++11 std::addressof
45 * @ingroup utilities
46 */
47 template<typename _Tp>
48 inline _GLIBCXX_CONSTEXPRconstexpr _Tp*
49 __addressof(_Tp& __r) _GLIBCXX_NOEXCEPTnoexcept
50 { return __builtin_addressof(__r); }
51
52#if __cplusplus201402L >= 201103L
53
54_GLIBCXX_END_NAMESPACE_VERSION
55} // namespace
56
57#include <type_traits> // Brings in std::declval too.
58
59namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default")))
60{
61_GLIBCXX_BEGIN_NAMESPACE_VERSION
62
63 /**
64 * @addtogroup utilities
65 * @{
66 */
67
68 /**
69 * @brief Forward an lvalue.
70 * @return The parameter cast to the specified type.
71 *
72 * This function is used to implement "perfect forwarding".
73 */
74 template<typename _Tp>
75 constexpr _Tp&&
76 forward(typename std::remove_reference<_Tp>::type& __t) noexcept
77 { return static_cast<_Tp&&>(__t); }
78
79 /**
80 * @brief Forward an rvalue.
81 * @return The parameter cast to the specified type.
82 *
83 * This function is used to implement "perfect forwarding".
84 */
85 template<typename _Tp>
86 constexpr _Tp&&
87 forward(typename std::remove_reference<_Tp>::type&& __t) noexcept
88 {
89 static_assert(!std::is_lvalue_reference<_Tp>::value, "template argument"
90 " substituting _Tp is an lvalue reference type");
91 return static_cast<_Tp&&>(__t);
92 }
93
94 /**
95 * @brief Convert a value to an rvalue.
96 * @param __t A thing of arbitrary type.
97 * @return The parameter cast to an rvalue-reference to allow moving it.
98 */
99 template<typename _Tp>
100 constexpr typename std::remove_reference<_Tp>::type&&
101 move(_Tp&& __t) noexcept
102 { return static_cast<typename std::remove_reference<_Tp>::type&&>(__t); }
103
104
105 template<typename _Tp>
106 struct __move_if_noexcept_cond
107 : public __and_<__not_<is_nothrow_move_constructible<_Tp>>,
108 is_copy_constructible<_Tp>>::type { };
109
110 /**
111 * @brief Conditionally convert a value to an rvalue.
112 * @param __x A thing of arbitrary type.
113 * @return The parameter, possibly cast to an rvalue-reference.
114 *
115 * Same as std::move unless the type's move constructor could throw and the
116 * type is copyable, in which case an lvalue-reference is returned instead.
117 */
118 template<typename _Tp>
119 constexpr typename
120 conditional<__move_if_noexcept_cond<_Tp>::value, const _Tp&, _Tp&&>::type
121 move_if_noexcept(_Tp& __x) noexcept
122 { return std::move(__x); }
123
124 // declval, from type_traits.
125
126#if __cplusplus201402L > 201402L
127 // _GLIBCXX_RESOLVE_LIB_DEFECTS
128 // 2296. std::addressof should be constexpr
129# define __cpp_lib_addressof_constexpr 201603
130#endif
131 /**
132 * @brief Returns the actual address of the object or function
133 * referenced by r, even in the presence of an overloaded
134 * operator&.
135 * @param __r Reference to an object or function.
136 * @return The actual address.
137 */
138 template<typename _Tp>
139 inline _GLIBCXX17_CONSTEXPR _Tp*
140 addressof(_Tp& __r) noexcept
141 { return std::__addressof(__r); }
142
143 // _GLIBCXX_RESOLVE_LIB_DEFECTS
144 // 2598. addressof works on temporaries
145 template<typename _Tp>
146 const _Tp* addressof(const _Tp&&) = delete;
147
148 // C++11 version of std::exchange for internal use.
149 template <typename _Tp, typename _Up = _Tp>
150 _GLIBCXX20_CONSTEXPR
151 inline _Tp
152 __exchange(_Tp& __obj, _Up&& __new_val)
153 {
154 _Tp __old_val = std::move(__obj);
155 __obj = std::forward<_Up>(__new_val);
156 return __old_val;
157 }
158
159 /// @} group utilities
160
161#define _GLIBCXX_MOVE(__val)std::move(__val) std::move(__val)
162#define _GLIBCXX_FORWARD(_Tp, __val)std::forward<_Tp>(__val) std::forward<_Tp>(__val)
163#else
164#define _GLIBCXX_MOVE(__val)std::move(__val) (__val)
165#define _GLIBCXX_FORWARD(_Tp, __val)std::forward<_Tp>(__val) (__val)
166#endif
167
168 /**
169 * @addtogroup utilities
170 * @{
171 */
172
173 /**
174 * @brief Swaps two values.
175 * @param __a A thing of arbitrary type.
176 * @param __b Another thing of arbitrary type.
177 * @return Nothing.
178 */
179 template<typename _Tp>
180 _GLIBCXX20_CONSTEXPR
181 inline
182#if __cplusplus201402L >= 201103L
183 typename enable_if<__and_<__not_<__is_tuple_like<_Tp>>,
184 is_move_constructible<_Tp>,
185 is_move_assignable<_Tp>>::value>::type
186#else
187 void
188#endif
189 swap(_Tp& __a, _Tp& __b)
190 _GLIBCXX_NOEXCEPT_IF(__and_<is_nothrow_move_constructible<_Tp>,noexcept(__and_<is_nothrow_move_constructible<_Tp>, is_nothrow_move_assignable
<_Tp>>::value)
191 is_nothrow_move_assignable<_Tp>>::value)noexcept(__and_<is_nothrow_move_constructible<_Tp>, is_nothrow_move_assignable
<_Tp>>::value)
192 {
193#if __cplusplus201402L < 201103L
194 // concept requirements
195 __glibcxx_function_requires(_SGIAssignableConcept<_Tp>)
196#endif
197 _Tp __tmp = _GLIBCXX_MOVE(__a)std::move(__a);
198 __a = _GLIBCXX_MOVE(__b)std::move(__b);
199 __b = _GLIBCXX_MOVE(__tmp)std::move(__tmp);
200 }
201
202 // _GLIBCXX_RESOLVE_LIB_DEFECTS
203 // DR 809. std::swap should be overloaded for array types.
204 /// Swap the contents of two arrays.
205 template<typename _Tp, size_t _Nm>
206 _GLIBCXX20_CONSTEXPR
207 inline
208#if __cplusplus201402L >= 201103L
209 typename enable_if<__is_swappable<_Tp>::value>::type
210#else
211 void
212#endif
213 swap(_Tp (&__a)[_Nm], _Tp (&__b)[_Nm])
214 _GLIBCXX_NOEXCEPT_IF(__is_nothrow_swappable<_Tp>::value)noexcept(__is_nothrow_swappable<_Tp>::value)
215 {
216 for (size_t __n = 0; __n < _Nm; ++__n)
217 swap(__a[__n], __b[__n]);
218 }
219
220 /// @} group utilities
221_GLIBCXX_END_NAMESPACE_VERSION
222} // namespace
223
224#endif /* _MOVE_H */