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

source code of clang-tools-extra/clangd/ClangdLSPServer.cpp