clang-tools 22.0.0git
ClangdLSPServer.cpp
Go to the documentation of this file.
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"
16#include "LSPBinder.h"
17#include "ModulesBuilder.h"
18#include "Protocol.h"
20#include "SourceCode.h"
21#include "TUScheduler.h"
22#include "URI.h"
23#include "refactor/Tweak.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(*LSPVersion) : "";
66}
67std::optional<int64_t> decodeVersion(llvm::StringRef Encoded) {
68 int64_t Result;
69 if (llvm::to_integer(Encoded, Result, 10))
70 return Result;
71 if (!Encoded.empty()) // Empty can be e.g. diagnostics on close.
72 elog("unexpected non-numeric version {0}", 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
81 const URIForFile &File) {
82 CodeAction CA;
83 CA.title = R.FixMessage;
84 CA.kind = std::string(CodeAction::REFACTOR_KIND);
85 CA.command.emplace();
86 CA.command->title = R.FixMessage;
87 CA.command->command = std::string(ApplyRenameCommand);
88 RenameParams Params;
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({E.range, E.newText, /*annotationId=*/""});
133 } else {
134 Action.edit->documentChanges.emplace();
135 TextDocumentEdit &Edit = Action.edit->documentChanges->emplace_back();
136 Edit.textDocument = VersionedTextDocumentIdentifier{{File}, Version};
137 for (const auto &E : F.Edits)
138 Edit.edits.push_back(
139 {E.range, E.newText,
140 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(S.kind, Kinds);
153 adjustSymbolKinds(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(I);
162 return Defaults;
163}
164
165CompletionItemKindBitset defaultCompletionItemKinds() {
167 for (size_t I = CompletionItemKindMin;
168 I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
169 Defaults.set(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(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(*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("File must be saved first: {0}", LastInvalidFile);
194 return error("Files must be saved first: {0} (and {1} others)",
195 LastInvalidFile, 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.
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("<-- {0}", Method);
215 if (Method == "exit")
216 return false;
217 auto Handler = Server.Handlers.NotificationHandlers.find(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("Notification {0} before initialization", Method);
224 } else if (Method == "$/cancelRequest") {
225 onCancel(std::move(Params));
226 } else {
227 log("unhandled notification {0}", 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("<-- {0}({1})", Method, ID);
241 auto Handler = Server.Handlers.MethodHandlers.find(Method);
242 if (Handler != Server.Handlers.MethodHandlers.end()) {
243 Handler->second(std::move(Params), std::move(Reply));
244 } else if (!Server.Server) {
245 elog("Call {0} before initialization.", Method);
246 Reply(llvm::make_error<LSPError>("server not initialized",
248 } else {
249 Reply(llvm::make_error<LSPError>("method not found",
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(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("received a reply with ID {0}, but there was no such call", ID);
277 if (!Result)
278 llvm::consumeError(Result.takeError());
279 };
280 }
281
282 // Log and run the reply handler.
283 if (Result) {
284 log("<-- reply({0})", ID);
285 ReplyHandler(std::move(Result));
286 } else {
287 auto Err = Result.takeError();
288 log("<-- reply({0}) error: {1}", ID, 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(ID, 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("more than {0} outstanding LSP calls, forgetting about {1}",
310 MaxReplayCallbacks, ReplyCallbacks.front().first);
311 OldestCB = std::move(ReplyCallbacks.front());
312 ReplyCallbacks.pop_front();
313 }
314 }
315 if (OldestCB)
316 OldestCB->second(
317 error("failed to receive a client reply for request ({0})",
318 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("No reply to message {0}({1})", Method, ID);
362 assert(false && "must reply to all calls!");
363 (*this)(llvm::make_error<LSPError>("server failed to reply",
365 }
366 }
367
368 void operator()(llvm::Expected<llvm::json::Value> Reply) {
369 assert(Server && "moved-from!");
370 if (Replied.exchange(true)) {
371 elog("Replied twice to message {0}({1})", Method, 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("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
378 if (TraceArgs)
379 (*TraceArgs)["Reply"] = *Reply;
380 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
381 Server->Transp.reply(std::move(ID), std::move(Reply));
382 } else {
383 llvm::Error Err = Reply.takeError();
384 log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
385 if (TraceArgs)
386 (*TraceArgs)["Error"] = llvm::to_string(Err);
387 std::lock_guard<std::mutex> Lock(Server->TranspWriter);
388 Server->Transp.reply(std::move(ID), 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("id");
403 if (!ID) {
404 elog("Bad cancellation request: {0}", Params);
405 return;
406 }
407 auto StrID = llvm::to_string(*ID);
408 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
409 auto It = RequestCancelers.find(StrID);
410 if (It != RequestCancelers.end())
411 It->second.first(); // Invoke the canceler.
412 }
413
414 Context handlerContext() const {
415 return Context::current().derive(
417 Server.Opts.Encoding.value_or(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(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(llvm::make_scope_exit([this, StrID, Cookie] {
437 std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
438 auto It = RequestCancelers.find(StrID);
439 if (It != RequestCancelers.end() && It->second.second == Cookie)
440 RequestCancelers.erase(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,
464 auto ID = MsgHandler->bindReply(std::move(CB));
465 log("--> {0}({1})", Method, ID);
466 std::lock_guard<std::mutex> Lock(TranspWriter);
467 Transp.call(Method, std::move(Params), ID);
468}
469
470void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
471 log("--> {0}", Method);
472 maybeCleanupMemory();
473 std::lock_guard<std::mutex> Lock(TranspWriter);
474 Transp.notify(Method, 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(toSemanticTokenType(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(
491 return Modifiers;
492}
493
494void ClangdLSPServer::onInitialize(const InitializeParams &Params,
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("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>("server already initialized",
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>(CDBOpts);
560 }
561 auto Mangler = CommandMangler::detect();
562 Mangler.SystemIncludeExtractor =
563 getSystemIncludeExtractor(llvm::ArrayRef(Opts.QueryDriverGlobs));
564 if (Opts.ResourceDir)
565 Mangler.ResourceDir = *Opts.ResourceDir;
566 CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
567 std::move(Mangler));
568
569 if (Opts.EnableExperimentalModulesSupport) {
570 ModulesManager.emplace(*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(kCurrentOffsetEncoding, *Opts.Encoding);
582 Server.emplace(*CDB, TFS, Opts,
583 static_cast<ClangdServer::Callbacks *>(this));
584 }
585
586 llvm::json::Object ServerCaps{
587 {"textDocumentSync",
588 llvm::json::Object{
589 {"openClose", true},
590 {"change", (int)TextDocumentSyncKind::Incremental},
591 {"save", true},
592 }},
593 {"documentFormattingProvider", true},
594 {"documentRangeFormattingProvider",
595 llvm::json::Object{
596 {"rangesSupport", true},
597 }},
598 {"documentOnTypeFormattingProvider",
599 llvm::json::Object{
600 {"firstTriggerCharacter", "\n"},
601 {"moreTriggerCharacter", {}},
602 }},
603 {"completionProvider",
604 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 {"resolveProvider", false},
611 // We do extra checks, e.g. that > is part of ->.
612 {"triggerCharacters", {".", "<", ">", ":", "\"", "/", "*"}},
613 }},
614 {"semanticTokensProvider",
615 llvm::json::Object{
616 {"full", llvm::json::Object{{"delta", true}}},
617 {"range", false},
618 {"legend",
619 llvm::json::Object{{"tokenTypes", semanticTokenTypes()},
620 {"tokenModifiers", semanticTokenModifiers()}}},
621 }},
622 {"signatureHelpProvider",
623 llvm::json::Object{
624 {"triggerCharacters", {"(", ")", "{", "}", "<", ">", ","}},
625 }},
626 {"declarationProvider", true},
627 {"definitionProvider", true},
628 {"implementationProvider", true},
629 {"typeDefinitionProvider", true},
630 {"documentHighlightProvider", true},
631 {"documentLinkProvider",
632 llvm::json::Object{
633 {"resolveProvider", false},
634 }},
635 {"hoverProvider", true},
636 {"selectionRangeProvider", true},
637 {"documentSymbolProvider", true},
638 {"workspaceSymbolProvider", true},
639 {"referencesProvider", true},
640 {"astProvider", true}, // clangd extension
641 {"typeHierarchyProvider", 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 {"standardTypeHierarchyProvider", true}, // clangd extension
646 {"memoryUsageProvider", true}, // clangd extension
647 {"compilationDatabase", // clangd extension
648 llvm::json::Object{{"automaticReload", true}}},
649 {"inactiveRegionsProvider", true}, // clangd extension
650 {"callHierarchyProvider", true},
651 {"clangdInlayHintsProvider", true},
652 {"inlayHintProvider", true},
653 {"foldingRangeProvider", true},
654 };
655
656 {
657 LSPBinder Binder(Handlers, *this);
658 bindMethods(Binder, Params.capabilities);
659 if (Opts.FeatureModules)
660 for (auto &Mod : *Opts.FeatureModules)
661 Mod.initializeLSP(Binder, 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{{"prepareProvider", 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{{"codeActionKinds",
680 : llvm::json::Value(true);
681
682 std::vector<llvm::StringRef> Commands;
683 for (llvm::StringRef Command : Handlers.CommandHandlers.keys())
684 Commands.push_back(Command);
685 llvm::sort(Commands);
686 ServerCaps["executeCommandProvider"] =
687 llvm::json::Object{{"commands", Commands}};
688
689 if (Opts.Encoding)
690 ServerCaps["positionEncoding"] = *Opts.Encoding;
691
692 llvm::json::Object Result{
693 {{"serverInfo",
694 llvm::json::Object{
695 {"name", "clangd"},
696 {"version", llvm::formatv("{0} {1} {2}", versionString(),
698 {"capabilities", 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(Params.initializationOptions.ConfigSettings);
709}
710
711void ClangdLSPServer::onInitialized(const InitializedParams &Params) {}
712
713void ClangdLSPServer::onShutdown(const NoParams &,
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("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 encodeVersion(Params.textDocument.version),
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("Trying to incrementally change non-added document: {0}", File);
751 return;
752 }
753 std::string NewCode(*Code);
754 for (const auto &Change : Params.contentChanges) {
755 if (auto Err = applyChange(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("Failed to update {0}: {1}", File, std::move(Err));
761 return;
762 }
763 }
764 Server->addDocument(File, NewCode, encodeVersion(Params.textDocument.version),
765 WantDiags, Params.forceRebuild);
766}
767
768void ClangdLSPServer::onDocumentDidSave(
769 const DidSaveTextDocumentParams &Params) {
770 Server->reparseOpenFilesIfNeeded([](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,
787 auto It = Handlers.CommandHandlers.find(Params.command);
788 if (It == Handlers.CommandHandlers.end()) {
789 return Reply(llvm::make_error<LSPError>(
790 llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
792 }
793 It->second(Params.argument, std::move(Reply));
794}
795
796void ClangdLSPServer::onCommandApplyEdit(const WorkspaceEdit &WE,
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, "Fix applied.", std::move(Reply));
807}
808
809void ClangdLSPServer::onCommandApplyTweak(const TweakArgs &Args,
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, 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(It.first()).toString()] =
836 It.second.asTextEdits();
837 }
838 // ApplyEdit will take care of calling Reply().
839 return applyEdit(std::move(WE), "Tweak applied.", std::move(Reply));
840 };
841 Server->applyTweak(Args.file.file(), Args.selection, Args.tweakID,
842 std::move(Action));
843}
844
845void ClangdLSPServer::onCommandApplyRename(const RenameParams &R,
847 onRename(R, [this, Reply = std::move(Reply)](
848 llvm::Expected<WorkspaceEdit> Edit) mutable {
849 if (!Edit)
850 Reply(Edit.takeError());
851 applyEdit(std::move(*Edit), "Rename applied.", std::move(Reply));
852 });
853}
854
855void ClangdLSPServer::applyEdit(WorkspaceEdit WE, llvm::json::Value Success,
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("edits were not applied: {0}", 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 Params.query, Params.limit.value_or(Opts.CodeComplete.Limit),
879 [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(Sym.kind, SupportedSymbolKinds);
885
886 Reply(std::move(*Items));
887 });
888}
889
890void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params,
892 Server->prepareRename(
893 Params.textDocument.uri.file(), Params.position, /*NewName*/ std::nullopt,
894 Opts.Rename,
895 [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,
907 Path File = std::string(Params.textDocument.uri.file());
908 if (!Server->getDraft(File))
909 return Reply(llvm::make_error<LSPError>(
910 "onRename called for non-added file", ErrorCode::InvalidParams));
911 Server->rename(File, Params.position, Params.newName, Opts.Rename,
912 [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, 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(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(File);
939 }
940 {
941 std::lock_guard<std::mutex> HLock(SemanticTokensMutex);
942 LastSemanticTokens.erase(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(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, Params.position, Params.ch, std::move(Reply));
959}
960
961void ClangdLSPServer::onDocumentRangeFormatting(
962 const DocumentRangeFormattingParams &Params,
963 Callback<std::vector<TextEdit>> Reply) {
964 onDocumentRangesFormatting(
965 DocumentRangesFormattingParams{Params.textDocument, {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, Params.ranges,
975 [Code = std::move(Code), Reply = std::move(Reply)](
976 llvm::Expected<tooling::Replacements> Result) mutable {
977 if (Result)
978 Reply(replacementsToEdits(*Code, 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 [Code = std::move(Code), Reply = std::move(Reply)](
992 llvm::Expected<tooling::Replacements> Result) mutable {
993 if (Result)
994 Reply(replacementsToEdits(*Code, 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) {
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(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 Params.textDocument.uri.file(),
1031 [this, FileURI, Reply = std::move(Reply)](
1032 llvm::Expected<std::vector<DocumentSymbol>> Items) mutable {
1033 if (!Items)
1034 return Reply(Items.takeError());
1035 adjustSymbolKinds(*Items, SupportedSymbolKinds);
1036 if (SupportsHierarchicalDocumentSymbol)
1037 return Reply(std::move(*Items));
1038 return Reply(flattenSymbolHierarchy(*Items, FileURI));
1039 });
1040}
1041
1042void ClangdLSPServer::onFoldingRange(
1043 const FoldingRangeParams &Params,
1044 Callback<std::vector<FoldingRange>> Reply) {
1045 Server->foldingRanges(Params.textDocument.uri.file(), 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(), LSPDiag)) {
1074 ToLSPDiags[*DiagRef] = LSPDiag;
1075 Inputs.Diagnostics.push_back(*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(Fixits->Version);
1093 for (const auto &QF : Fixits->QuickFixes) {
1094 CAs.push_back(toCodeAction(QF.F, File, Version, SupportsDocumentChanges,
1095 SupportsChangeAnnotation));
1096 if (auto It = ToLSPDiags.find(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(toCodeAction(R, File));
1104
1105 for (const auto &TR : Fixits->TweakRefs)
1106 CAs.push_back(toCodeAction(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(std::move(*Command));
1133 }
1134 return Reply(llvm::json::Array(Commands));
1135 };
1136 Server->codeAction(Inputs, 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("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(Params.textDocument.uri.file(), Params.position, Opts,
1151 [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 C.kind, SupportedCompletionItemKinds);
1161 if (!SupportsCompletionLabelDetails)
1162 removeCompletionLabelDetails(C);
1163 LSPList.items.push_back(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(Params.textDocument.uri.file(), Params.position,
1172 Opts.SignatureHelpDocumentationFormat,
1173 [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.
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(Point.position))
1202 return &Sym.PreferredDeclaration;
1203 if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
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 Params.textDocument.uri.file(), Params.position,
1213 [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(Params, S))
1220 return Reply(std::vector<Location>{std::move(*Toggle)});
1221 Defs.push_back(S.Definition.value_or(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 Params.textDocument.uri.file(), Params.position,
1232 [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(Params, S))
1239 return Reply(std::vector<Location>{std::move(*Toggle)});
1240 Decls.push_back(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 Params.uri.file(),
1251 [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(**Path, 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(Params.textDocument.uri.file(),
1265 Params.position, std::move(Reply));
1266}
1267
1268void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
1269 Callback<std::optional<Hover>> Reply) {
1270 Server->findHover(Params.textDocument.uri.file(), Params.position,
1271 [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::Markdown:
1283 case MarkupKind::PlainText:
1284 R.contents.value = (*H)->present(HoverContentFormat);
1285 return Reply(std::move(R));
1286 };
1287 llvm_unreachable("unhandled MarkupKind");
1288 });
1289}
1290
1291// Our extension has a different representation on the wire than the standard.
1292// https://clangd.llvm.org/extensions#type-hierarchy
1294 llvm::json::Object Result{{
1295 {"name", std::move(THI.name)},
1296 {"kind", static_cast<int>(THI.kind)},
1297 {"uri", std::move(THI.uri)},
1298 {"range", THI.range},
1299 {"selectionRange", THI.selectionRange},
1300 {"data", std::move(THI.data)},
1301 }};
1302 if (THI.deprecated)
1303 Result["deprecated"] = THI.deprecated;
1304 if (THI.detail)
1305 Result["detail"] = std::move(*THI.detail);
1306
1307 if (THI.parents) {
1308 llvm::json::Array Parents;
1309 for (auto &Parent : *THI.parents)
1310 Parents.emplace_back(serializeTHIForExtension(std::move(Parent)));
1311 Result["parents"] = std::move(Parents);
1312 }
1313
1314 if (THI.children) {
1315 llvm::json::Array Children;
1316 for (auto &child : *THI.children)
1317 Children.emplace_back(serializeTHIForExtension(std::move(child)));
1318 Result["children"] = std::move(Children);
1319 }
1320 return Result;
1321}
1322
1323void ClangdLSPServer::onTypeHierarchy(const TypeHierarchyPrepareParams &Params,
1324 Callback<llvm::json::Value> Reply) {
1325 auto Serialize =
1326 [Reply = std::move(Reply)](
1327 llvm::Expected<std::vector<TypeHierarchyItem>> Resp) mutable {
1328 if (!Resp) {
1329 Reply(Resp.takeError());
1330 return;
1331 }
1332 if (Resp->empty()) {
1333 Reply(nullptr);
1334 return;
1335 }
1336 Reply(serializeTHIForExtension(std::move(Resp->front())));
1337 };
1338 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
1339 Params.resolve, Params.direction, std::move(Serialize));
1340}
1341
1342void ClangdLSPServer::onResolveTypeHierarchy(
1343 const ResolveTypeHierarchyItemParams &Params,
1344 Callback<llvm::json::Value> Reply) {
1345 auto Serialize =
1346 [Reply = std::move(Reply)](
1347 llvm::Expected<std::optional<TypeHierarchyItem>> Resp) mutable {
1348 if (!Resp) {
1349 Reply(Resp.takeError());
1350 return;
1351 }
1352 if (!*Resp) {
1353 Reply(std::move(*Resp));
1354 return;
1355 }
1356 Reply(serializeTHIForExtension(std::move(**Resp)));
1357 };
1358 Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
1359 std::move(Serialize));
1360}
1361
1362void ClangdLSPServer::onPrepareTypeHierarchy(
1363 const TypeHierarchyPrepareParams &Params,
1364 Callback<std::vector<TypeHierarchyItem>> Reply) {
1365 Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
1366 Params.resolve, Params.direction, std::move(Reply));
1367}
1368
1369void ClangdLSPServer::onSuperTypes(
1370 const ResolveTypeHierarchyItemParams &Params,
1371 Callback<std::optional<std::vector<TypeHierarchyItem>>> Reply) {
1372 Server->superTypes(Params.item, std::move(Reply));
1373}
1374
1375void ClangdLSPServer::onSubTypes(
1376 const ResolveTypeHierarchyItemParams &Params,
1377 Callback<std::vector<TypeHierarchyItem>> Reply) {
1378 Server->subTypes(Params.item, std::move(Reply));
1379}
1380
1381void ClangdLSPServer::onPrepareCallHierarchy(
1382 const CallHierarchyPrepareParams &Params,
1383 Callback<std::vector<CallHierarchyItem>> Reply) {
1384 Server->prepareCallHierarchy(Params.textDocument.uri.file(), Params.position,
1385 std::move(Reply));
1386}
1387
1388void ClangdLSPServer::onCallHierarchyIncomingCalls(
1389 const CallHierarchyIncomingCallsParams &Params,
1390 Callback<std::vector<CallHierarchyIncomingCall>> Reply) {
1391 Server->incomingCalls(Params.item, std::move(Reply));
1392}
1393
1394void ClangdLSPServer::onClangdInlayHints(const InlayHintsParams &Params,
1395 Callback<llvm::json::Value> Reply) {
1396 // Our extension has a different representation on the wire than the standard.
1397 // We have a "range" property and "kind" is represented as a string, not as an
1398 // enum value.
1399 // https://clangd.llvm.org/extensions#inlay-hints
1400 auto Serialize = [Reply = std::move(Reply)](
1401 llvm::Expected<std::vector<InlayHint>> Hints) mutable {
1402 if (!Hints) {
1403 Reply(Hints.takeError());
1404 return;
1405 }
1406 llvm::json::Array Result;
1407 Result.reserve(Hints->size());
1408 for (auto &Hint : *Hints) {
1409 Result.emplace_back(llvm::json::Object{
1410 {"kind", llvm::to_string(Hint.kind)},
1411 {"range", Hint.range},
1412 {"position", Hint.position},
1413 // Extension doesn't have paddingLeft/Right so adjust the label
1414 // accordingly.
1415 {"label",
1416 ((Hint.paddingLeft ? " " : "") + llvm::StringRef(Hint.joinLabels()) +
1417 (Hint.paddingRight ? " " : ""))
1418 .str()},
1419 });
1420 }
1421 Reply(std::move(Result));
1422 };
1423 Server->inlayHints(Params.textDocument.uri.file(), Params.range,
1424 std::move(Serialize));
1425}
1426
1427void ClangdLSPServer::onInlayHint(const InlayHintsParams &Params,
1428 Callback<std::vector<InlayHint>> Reply) {
1429 Server->inlayHints(Params.textDocument.uri.file(), Params.range,
1430 std::move(Reply));
1431}
1432
1433void ClangdLSPServer::onCallHierarchyOutgoingCalls(
1434 const CallHierarchyOutgoingCallsParams &Params,
1435 Callback<std::vector<CallHierarchyOutgoingCall>> Reply) {
1436 Server->outgoingCalls(Params.item, std::move(Reply));
1437}
1438
1439void ClangdLSPServer::applyConfiguration(
1440 const ConfigurationSettings &Settings) {
1441 // Per-file update to the compilation database.
1442 llvm::StringSet<> ModifiedFiles;
1443 for (auto &[File, Command] : Settings.compilationDatabaseChanges) {
1444 auto Cmd =
1445 tooling::CompileCommand(std::move(Command.workingDirectory), File,
1446 std::move(Command.compilationCommand),
1447 /*Output=*/"");
1448 if (CDB->setCompileCommand(File, std::move(Cmd))) {
1449 ModifiedFiles.insert(File);
1450 }
1451 }
1452
1453 Server->reparseOpenFilesIfNeeded(
1454 [&](llvm::StringRef File) { return ModifiedFiles.count(File) != 0; });
1455}
1456
1457void ClangdLSPServer::maybeExportMemoryProfile() {
1458 if (!trace::enabled() || !ShouldProfile())
1459 return;
1460
1461 static constexpr trace::Metric MemoryUsage(
1462 "memory_usage", trace::Metric::Value, "component_name");
1463 trace::Span Tracer("ProfileBrief");
1464 MemoryTree MT;
1465 profile(MT);
1466 record(MT, "clangd_lsp_server", MemoryUsage);
1467}
1468
1469void ClangdLSPServer::maybeCleanupMemory() {
1470 if (!Opts.MemoryCleanup || !ShouldCleanupMemory())
1471 return;
1472 Opts.MemoryCleanup();
1473}
1474
1475// FIXME: This function needs to be properly tested.
1476void ClangdLSPServer::onChangeConfiguration(
1477 const DidChangeConfigurationParams &Params) {
1478 applyConfiguration(Params.settings);
1479}
1480
1481void ClangdLSPServer::onReference(
1482 const ReferenceParams &Params,
1483 Callback<std::vector<ReferenceLocation>> Reply) {
1484 Server->findReferences(Params.textDocument.uri.file(), Params.position,
1485 Opts.ReferencesLimit, SupportsReferenceContainer,
1486 [Reply = std::move(Reply),
1487 IncludeDecl(Params.context.includeDeclaration)](
1488 llvm::Expected<ReferencesResult> Refs) mutable {
1489 if (!Refs)
1490 return Reply(Refs.takeError());
1491 // Filter out declarations if the client asked.
1492 std::vector<ReferenceLocation> Result;
1493 Result.reserve(Refs->References.size());
1494 for (auto &Ref : Refs->References) {
1495 bool IsDecl =
1496 Ref.Attributes & ReferencesResult::Declaration;
1497 if (IncludeDecl || !IsDecl)
1498 Result.push_back(std::move(Ref.Loc));
1499 }
1500 return Reply(std::move(Result));
1501 });
1502}
1503
1504void ClangdLSPServer::onGoToType(const TextDocumentPositionParams &Params,
1505 Callback<std::vector<Location>> Reply) {
1506 Server->findType(
1507 Params.textDocument.uri.file(), Params.position,
1508 [Reply = std::move(Reply)](
1509 llvm::Expected<std::vector<LocatedSymbol>> Types) mutable {
1510 if (!Types)
1511 return Reply(Types.takeError());
1512 std::vector<Location> Response;
1513 for (const LocatedSymbol &Sym : *Types)
1514 Response.push_back(Sym.Definition.value_or(Sym.PreferredDeclaration));
1515 return Reply(std::move(Response));
1516 });
1517}
1518
1519void ClangdLSPServer::onGoToImplementation(
1520 const TextDocumentPositionParams &Params,
1521 Callback<std::vector<Location>> Reply) {
1522 Server->findImplementations(
1523 Params.textDocument.uri.file(), Params.position,
1524 [Reply = std::move(Reply)](
1525 llvm::Expected<std::vector<LocatedSymbol>> Overrides) mutable {
1526 if (!Overrides)
1527 return Reply(Overrides.takeError());
1528 std::vector<Location> Impls;
1529 for (const LocatedSymbol &Sym : *Overrides)
1530 Impls.push_back(Sym.Definition.value_or(Sym.PreferredDeclaration));
1531 return Reply(std::move(Impls));
1532 });
1533}
1534
1535void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
1536 Callback<std::vector<SymbolDetails>> Reply) {
1537 Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
1538 std::move(Reply));
1539}
1540
1541void ClangdLSPServer::onSelectionRange(
1542 const SelectionRangeParams &Params,
1543 Callback<std::vector<SelectionRange>> Reply) {
1544 Server->semanticRanges(
1545 Params.textDocument.uri.file(), Params.positions,
1546 [Reply = std::move(Reply)](
1547 llvm::Expected<std::vector<SelectionRange>> Ranges) mutable {
1548 if (!Ranges)
1549 return Reply(Ranges.takeError());
1550 return Reply(std::move(*Ranges));
1551 });
1552}
1553
1554void ClangdLSPServer::onDocumentLink(
1555 const DocumentLinkParams &Params,
1556 Callback<std::vector<DocumentLink>> Reply) {
1557
1558 // TODO(forster): This currently resolves all targets eagerly. This is slow,
1559 // because it blocks on the preamble/AST being built. We could respond to the
1560 // request faster by using string matching or the lexer to find the includes
1561 // and resolving the targets lazily.
1562 Server->documentLinks(
1563 Params.textDocument.uri.file(),
1564 [Reply = std::move(Reply)](
1565 llvm::Expected<std::vector<DocumentLink>> Links) mutable {
1566 if (!Links) {
1567 return Reply(Links.takeError());
1568 }
1569 return Reply(std::move(Links));
1570 });
1571}
1572
1573// Increment a numeric string: "" -> 1 -> 2 -> ... -> 9 -> 10 -> 11 ...
1574static void increment(std::string &S) {
1575 for (char &C : llvm::reverse(S)) {
1576 if (C != '9') {
1577 ++C;
1578 return;
1579 }
1580 C = '0';
1581 }
1582 S.insert(S.begin(), '1');
1583}
1584
1585void ClangdLSPServer::onSemanticTokens(const SemanticTokensParams &Params,
1586 Callback<SemanticTokens> CB) {
1587 auto File = Params.textDocument.uri.file();
1588 Server->semanticHighlights(
1589 Params.textDocument.uri.file(),
1590 [this, File(File.str()), CB(std::move(CB)), Code(Server->getDraft(File))](
1591 llvm::Expected<std::vector<HighlightingToken>> HT) mutable {
1592 if (!HT)
1593 return CB(HT.takeError());
1594 SemanticTokens Result;
1595 Result.tokens = toSemanticTokens(*HT, *Code);
1596 {
1597 std::lock_guard<std::mutex> Lock(SemanticTokensMutex);
1598 auto &Last = LastSemanticTokens[File];
1599
1600 Last.tokens = Result.tokens;
1601 increment(Last.resultId);
1602 Result.resultId = Last.resultId;
1603 }
1604 CB(std::move(Result));
1605 });
1606}
1607
1608void ClangdLSPServer::onSemanticTokensDelta(
1609 const SemanticTokensDeltaParams &Params,
1610 Callback<SemanticTokensOrDelta> CB) {
1611 auto File = Params.textDocument.uri.file();
1612 Server->semanticHighlights(
1613 Params.textDocument.uri.file(),
1614 [this, PrevResultID(Params.previousResultId), File(File.str()),
1615 CB(std::move(CB)), Code(Server->getDraft(File))](
1616 llvm::Expected<std::vector<HighlightingToken>> HT) mutable {
1617 if (!HT)
1618 return CB(HT.takeError());
1619 std::vector<SemanticToken> Toks = toSemanticTokens(*HT, *Code);
1620
1621 SemanticTokensOrDelta Result;
1622 {
1623 std::lock_guard<std::mutex> Lock(SemanticTokensMutex);
1624 auto &Last = LastSemanticTokens[File];
1625
1626 if (PrevResultID == Last.resultId) {
1627 Result.edits = diffTokens(Last.tokens, Toks);
1628 } else {
1629 vlog("semanticTokens/full/delta: wanted edits vs {0} but last "
1630 "result had ID {1}. Returning full token list.",
1631 PrevResultID, Last.resultId);
1632 Result.tokens = Toks;
1633 }
1634
1635 Last.tokens = std::move(Toks);
1636 increment(Last.resultId);
1637 Result.resultId = Last.resultId;
1638 }
1639
1640 CB(std::move(Result));
1641 });
1642}
1643
1644void ClangdLSPServer::onMemoryUsage(const NoParams &,
1645 Callback<MemoryTree> Reply) {
1646 llvm::BumpPtrAllocator DetailAlloc;
1647 MemoryTree MT(&DetailAlloc);
1648 profile(MT);
1649 Reply(std::move(MT));
1650}
1651
1652void ClangdLSPServer::onAST(const ASTParams &Params,
1653 Callback<std::optional<ASTNode>> CB) {
1654 Server->getAST(Params.textDocument.uri.file(), Params.range, std::move(CB));
1655}
1656
1658 const ClangdLSPServer::Options &Opts)
1659 : ShouldProfile(/*Period=*/std::chrono::minutes(5),
1660 /*Delay=*/std::chrono::minutes(1)),
1661 ShouldCleanupMemory(/*Period=*/std::chrono::minutes(1),
1662 /*Delay=*/std::chrono::minutes(1)),
1663 BackgroundContext(Context::current().clone()), Transp(Transp),
1664 MsgHandler(new MessageHandler(*this)), TFS(TFS),
1665 SupportedSymbolKinds(defaultSymbolKinds()),
1666 SupportedCompletionItemKinds(defaultCompletionItemKinds()), Opts(Opts) {
1667 if (Opts.ConfigProvider) {
1668 assert(!Opts.ContextProvider &&
1669 "Only one of ConfigProvider and ContextProvider allowed!");
1670 this->Opts.ContextProvider = ClangdServer::createConfiguredContextProvider(
1671 Opts.ConfigProvider, this);
1672 }
1673 LSPBinder Bind(this->Handlers, *this);
1674 Bind.method("initialize", this, &ClangdLSPServer::onInitialize);
1675}
1676
1677void ClangdLSPServer::bindMethods(LSPBinder &Bind,
1678 const ClientCapabilities &Caps) {
1679 // clang-format off
1680 Bind.notification("initialized", this, &ClangdLSPServer::onInitialized);
1681 Bind.method("shutdown", this, &ClangdLSPServer::onShutdown);
1682 Bind.method("sync", this, &ClangdLSPServer::onSync);
1683 Bind.method("textDocument/rangeFormatting", this, &ClangdLSPServer::onDocumentRangeFormatting);
1684 Bind.method("textDocument/rangesFormatting", this, &ClangdLSPServer::onDocumentRangesFormatting);
1685 Bind.method("textDocument/onTypeFormatting", this, &ClangdLSPServer::onDocumentOnTypeFormatting);
1686 Bind.method("textDocument/formatting", this, &ClangdLSPServer::onDocumentFormatting);
1687 Bind.method("textDocument/codeAction", this, &ClangdLSPServer::onCodeAction);
1688 Bind.method("textDocument/completion", this, &ClangdLSPServer::onCompletion);
1689 Bind.method("textDocument/signatureHelp", this, &ClangdLSPServer::onSignatureHelp);
1690 Bind.method("textDocument/definition", this, &ClangdLSPServer::onGoToDefinition);
1691 Bind.method("textDocument/declaration", this, &ClangdLSPServer::onGoToDeclaration);
1692 Bind.method("textDocument/typeDefinition", this, &ClangdLSPServer::onGoToType);
1693 Bind.method("textDocument/implementation", this, &ClangdLSPServer::onGoToImplementation);
1694 Bind.method("textDocument/references", this, &ClangdLSPServer::onReference);
1695 Bind.method("textDocument/switchSourceHeader", this, &ClangdLSPServer::onSwitchSourceHeader);
1696 Bind.method("textDocument/prepareRename", this, &ClangdLSPServer::onPrepareRename);
1697 Bind.method("textDocument/rename", this, &ClangdLSPServer::onRename);
1698 Bind.method("textDocument/hover", this, &ClangdLSPServer::onHover);
1699 Bind.method("textDocument/documentSymbol", this, &ClangdLSPServer::onDocumentSymbol);
1700 Bind.method("workspace/executeCommand", this, &ClangdLSPServer::onCommand);
1701 Bind.method("textDocument/documentHighlight", this, &ClangdLSPServer::onDocumentHighlight);
1702 Bind.method("workspace/symbol", this, &ClangdLSPServer::onWorkspaceSymbol);
1703 Bind.method("textDocument/ast", this, &ClangdLSPServer::onAST);
1704 Bind.notification("textDocument/didOpen", this, &ClangdLSPServer::onDocumentDidOpen);
1705 Bind.notification("textDocument/didClose", this, &ClangdLSPServer::onDocumentDidClose);
1706 Bind.notification("textDocument/didChange", this, &ClangdLSPServer::onDocumentDidChange);
1707 Bind.notification("textDocument/didSave", this, &ClangdLSPServer::onDocumentDidSave);
1708 Bind.notification("workspace/didChangeWatchedFiles", this, &ClangdLSPServer::onFileEvent);
1709 Bind.notification("workspace/didChangeConfiguration", this, &ClangdLSPServer::onChangeConfiguration);
1710 Bind.method("textDocument/symbolInfo", this, &ClangdLSPServer::onSymbolInfo);
1711 Bind.method("textDocument/typeHierarchy", this, &ClangdLSPServer::onTypeHierarchy);
1712 Bind.method("typeHierarchy/resolve", this, &ClangdLSPServer::onResolveTypeHierarchy);
1713 Bind.method("textDocument/prepareTypeHierarchy", this, &ClangdLSPServer::onPrepareTypeHierarchy);
1714 Bind.method("typeHierarchy/supertypes", this, &ClangdLSPServer::onSuperTypes);
1715 Bind.method("typeHierarchy/subtypes", this, &ClangdLSPServer::onSubTypes);
1716 Bind.method("textDocument/prepareCallHierarchy", this, &ClangdLSPServer::onPrepareCallHierarchy);
1717 Bind.method("callHierarchy/incomingCalls", this, &ClangdLSPServer::onCallHierarchyIncomingCalls);
1718 if (Opts.EnableOutgoingCalls)
1719 Bind.method("callHierarchy/outgoingCalls", this, &ClangdLSPServer::onCallHierarchyOutgoingCalls);
1720 Bind.method("textDocument/selectionRange", this, &ClangdLSPServer::onSelectionRange);
1721 Bind.method("textDocument/documentLink", this, &ClangdLSPServer::onDocumentLink);
1722 Bind.method("textDocument/semanticTokens/full", this, &ClangdLSPServer::onSemanticTokens);
1723 Bind.method("textDocument/semanticTokens/full/delta", this, &ClangdLSPServer::onSemanticTokensDelta);
1724 Bind.method("clangd/inlayHints", this, &ClangdLSPServer::onClangdInlayHints);
1725 Bind.method("textDocument/inlayHint", this, &ClangdLSPServer::onInlayHint);
1726 Bind.method("$/memoryUsage", this, &ClangdLSPServer::onMemoryUsage);
1727 Bind.method("textDocument/foldingRange", this, &ClangdLSPServer::onFoldingRange);
1728 Bind.command(ApplyFixCommand, this, &ClangdLSPServer::onCommandApplyEdit);
1729 Bind.command(ApplyTweakCommand, this, &ClangdLSPServer::onCommandApplyTweak);
1730 Bind.command(ApplyRenameCommand, this, &ClangdLSPServer::onCommandApplyRename);
1731
1732 ApplyWorkspaceEdit = Bind.outgoingMethod("workspace/applyEdit");
1733 PublishDiagnostics = Bind.outgoingNotification("textDocument/publishDiagnostics");
1734 if (Caps.InactiveRegions)
1735 PublishInactiveRegions = Bind.outgoingNotification("textDocument/inactiveRegions");
1736 ShowMessage = Bind.outgoingNotification("window/showMessage");
1737 NotifyFileStatus = Bind.outgoingNotification("textDocument/clangd.fileStatus");
1738 CreateWorkDoneProgress = Bind.outgoingMethod("window/workDoneProgress/create");
1739 BeginWorkDoneProgress = Bind.outgoingNotification("$/progress");
1740 ReportWorkDoneProgress = Bind.outgoingNotification("$/progress");
1741 EndWorkDoneProgress = Bind.outgoingNotification("$/progress");
1743 SemanticTokensRefresh = Bind.outgoingMethod("workspace/semanticTokens/refresh");
1744 // clang-format on
1745}
1746
1748 IsBeingDestroyed = true;
1749 // Explicitly destroy ClangdServer first, blocking on threads it owns.
1750 // This ensures they don't access any other members.
1751 Server.reset();
1752}
1753
1755 // Run the Language Server loop.
1756 bool CleanExit = true;
1757 if (auto Err = Transp.loop(*MsgHandler)) {
1758 elog("Transport error: {0}", std::move(Err));
1759 CleanExit = false;
1760 }
1761
1762 return CleanExit && ShutdownRequestReceived;
1763}
1764
1766 if (Server)
1767 Server->profile(MT.child("clangd_server"));
1768}
1769
1770std::optional<ClangdServer::DiagRef>
1771ClangdLSPServer::getDiagRef(StringRef File, const clangd::Diagnostic &D) {
1772 std::lock_guard<std::mutex> Lock(DiagRefMutex);
1773 auto DiagToDiagRefIter = DiagRefMap.find(File);
1774 if (DiagToDiagRefIter == DiagRefMap.end())
1775 return std::nullopt;
1776
1777 const auto &DiagToDiagRefMap = DiagToDiagRefIter->second;
1778 auto FixItsIter = DiagToDiagRefMap.find(toDiagKey(D));
1779 if (FixItsIter == DiagToDiagRefMap.end())
1780 return std::nullopt;
1781
1782 return FixItsIter->second;
1783}
1784
1785// A completion request is sent when the user types '>' or ':', but we only
1786// want to trigger on '->' and '::'. We check the preceding text to make
1787// sure it matches what we expected.
1788// Running the lexer here would be more robust (e.g. we can detect comments
1789// and avoid triggering completion there), but we choose to err on the side
1790// of simplicity here.
1791bool ClangdLSPServer::shouldRunCompletion(
1792 const CompletionParams &Params) const {
1793 if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter)
1794 return true;
1795 auto Code = Server->getDraft(Params.textDocument.uri.file());
1796 if (!Code)
1797 return true; // completion code will log the error for untracked doc.
1798 auto Offset = positionToOffset(*Code, Params.position,
1799 /*AllowColumnsBeyondLineLength=*/false);
1800 if (!Offset) {
1801 vlog("could not convert position '{0}' to offset for file '{1}'",
1802 Params.position, Params.textDocument.uri.file());
1803 return true;
1804 }
1805 return allowImplicitCompletion(*Code, *Offset);
1806}
1807
1808void ClangdLSPServer::onDiagnosticsReady(PathRef File, llvm::StringRef Version,
1809 llvm::ArrayRef<Diag> Diagnostics) {
1810 PublishDiagnosticsParams Notification;
1811 Notification.version = decodeVersion(Version);
1812 Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File);
1813 DiagnosticToDiagRefMap LocalDiagMap; // Temporary storage
1814 for (auto &Diag : Diagnostics) {
1815 toLSPDiags(Diag, Notification.uri, DiagOpts,
1816 [&](clangd::Diagnostic LSPDiag, llvm::ArrayRef<Fix> Fixes) {
1817 if (DiagOpts.EmbedFixesInDiagnostics) {
1818 std::vector<CodeAction> CodeActions;
1819 for (const auto &Fix : Fixes)
1820 CodeActions.push_back(toCodeAction(
1821 Fix, Notification.uri, Notification.version,
1822 SupportsDocumentChanges, SupportsChangeAnnotation));
1823 LSPDiag.codeActions.emplace(std::move(CodeActions));
1824 if (LSPDiag.codeActions->size() == 1)
1825 LSPDiag.codeActions->front().isPreferred = true;
1826 }
1827 LocalDiagMap[toDiagKey(LSPDiag)] = {Diag.Range, Diag.Message};
1828 Notification.diagnostics.push_back(std::move(LSPDiag));
1829 });
1830 }
1831
1832 // Cache DiagRefMap
1833 {
1834 std::lock_guard<std::mutex> Lock(DiagRefMutex);
1835 DiagRefMap[File] = LocalDiagMap;
1836 }
1837
1838 // Send a notification to the LSP client.
1839 PublishDiagnostics(Notification);
1840}
1841
1842void ClangdLSPServer::onInactiveRegionsReady(
1843 PathRef File, std::vector<Range> InactiveRegions) {
1844 InactiveRegionsParams Notification;
1845 Notification.TextDocument = {URIForFile::canonicalize(File, /*TUPath=*/File)};
1846 Notification.InactiveRegions = std::move(InactiveRegions);
1847
1848 PublishInactiveRegions(Notification);
1849}
1850
1851void ClangdLSPServer::onBackgroundIndexProgress(
1852 const BackgroundQueue::Stats &Stats) {
1853 static const char ProgressToken[] = "backgroundIndexProgress";
1854
1855 // The background index did some work, maybe we need to cleanup
1856 maybeCleanupMemory();
1857
1858 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1859
1860 auto NotifyProgress = [this](const BackgroundQueue::Stats &Stats) {
1861 if (BackgroundIndexProgressState != BackgroundIndexProgress::Live) {
1862 WorkDoneProgressBegin Begin;
1863 Begin.percentage = true;
1864 Begin.title = "indexing";
1865 BeginWorkDoneProgress({ProgressToken, std::move(Begin)});
1866 BackgroundIndexProgressState = BackgroundIndexProgress::Live;
1867 }
1868
1869 if (Stats.Completed < Stats.Enqueued) {
1870 assert(Stats.Enqueued > Stats.LastIdle);
1871 WorkDoneProgressReport Report;
1872 Report.percentage = 100 * (Stats.Completed - Stats.LastIdle) /
1873 (Stats.Enqueued - Stats.LastIdle);
1874 Report.message =
1875 llvm::formatv("{0}/{1}", Stats.Completed - Stats.LastIdle,
1876 Stats.Enqueued - Stats.LastIdle);
1877 ReportWorkDoneProgress({ProgressToken, std::move(Report)});
1878 } else {
1879 assert(Stats.Completed == Stats.Enqueued);
1880 EndWorkDoneProgress({ProgressToken, WorkDoneProgressEnd()});
1881 BackgroundIndexProgressState = BackgroundIndexProgress::Empty;
1882 }
1883 };
1884
1885 switch (BackgroundIndexProgressState) {
1886 case BackgroundIndexProgress::Unsupported:
1887 return;
1888 case BackgroundIndexProgress::Creating:
1889 // Cache this update for when the progress bar is available.
1890 PendingBackgroundIndexProgress = Stats;
1891 return;
1892 case BackgroundIndexProgress::Empty: {
1893 if (BackgroundIndexSkipCreate) {
1894 NotifyProgress(Stats);
1895 break;
1896 }
1897 // Cache this update for when the progress bar is available.
1898 PendingBackgroundIndexProgress = Stats;
1899 BackgroundIndexProgressState = BackgroundIndexProgress::Creating;
1900 WorkDoneProgressCreateParams CreateRequest;
1901 CreateRequest.token = ProgressToken;
1902 CreateWorkDoneProgress(
1903 CreateRequest,
1904 [this, NotifyProgress](llvm::Expected<std::nullptr_t> E) {
1905 std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex);
1906 if (E) {
1907 NotifyProgress(this->PendingBackgroundIndexProgress);
1908 } else {
1909 elog("Failed to create background index progress bar: {0}",
1910 E.takeError());
1911 // give up forever rather than thrashing about
1912 BackgroundIndexProgressState = BackgroundIndexProgress::Unsupported;
1913 }
1914 });
1915 break;
1916 }
1917 case BackgroundIndexProgress::Live:
1918 NotifyProgress(Stats);
1919 break;
1920 }
1921}
1922
1923void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1924 if (!SupportFileStatus)
1925 return;
1926 // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1927 // two statuses are running faster in practice, which leads the UI constantly
1928 // changing, and doesn't provide much value. We may want to emit status at a
1929 // reasonable time interval (e.g. 0.5s).
1930 if (Status.PreambleActivity == PreambleAction::Idle &&
1931 (Status.ASTActivity.K == ASTAction::Building ||
1932 Status.ASTActivity.K == ASTAction::RunningAction))
1933 return;
1934 NotifyFileStatus(Status.render(File));
1935}
1936
1937void ClangdLSPServer::onSemanticsMaybeChanged(PathRef File) {
1938 if (SemanticTokensRefresh) {
1939 SemanticTokensRefresh(NoParams{}, [](llvm::Expected<std::nullptr_t> E) {
1940 if (E)
1941 return;
1942 elog("Failed to refresh semantic tokens: {0}", E.takeError());
1943 });
1944 }
1945}
1946
1947} // namespace clangd
1948} // namespace clang
static cl::list< std::string > Commands("c", cl::desc("Specify command to run"), cl::value_desc("command"), cl::cat(ClangQueryCategory))
#define SPAN_ATTACH(S, Name, Expr)
Attach a key-value pair to a Span event.
Definition Trace.h:164
bool onReply(llvm::json::Value ID, llvm::Expected< llvm::json::Value > Result) override
bool onCall(llvm::StringRef Method, llvm::json::Value Params, llvm::json::Value ID) override
bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override
llvm::json::Value bindReply(Callback< llvm::json::Value > Reply)
This class exposes ClangdServer's capabilities via Language Server Protocol.
~ClangdLSPServer()
The destructor blocks on any outstanding background tasks.
ClangdLSPServer(Transport &Transp, const ThreadsafeFS &TFS, const ClangdLSPServer::Options &Opts)
void profile(MemoryTree &MT) const
Profiles resource-usage.
bool run()
Run LSP server loop, communicating with the Transport provided in the constructor.
Manages a collection of source files and derived data (ASTs, indexes), and provides language-aware fe...
A context is an immutable container for per-request data that must be propagated through layers that ...
Definition Context.h:69
Context derive(const Key< Type > &Key, std::decay_t< Type > Value) const &
Derives a child context It is safe to move or destroy a parent context after calling derive().
Definition Context.h:119
static const Context & current()
Returns the context for the current thread, creating it if needed.
Definition Context.cpp:27
LSPBinder collects a table of functions that handle LSP calls.
Definition LSPBinder.h:34
UntypedOutgoingMethod outgoingMethod(llvm::StringLiteral Method)
Bind a function object to be used for outgoing method calls.
Definition LSPBinder.h:216
void method(llvm::StringLiteral Method, ThisT *This, void(ThisT::*Handler)(const Param &, Callback< Result >))
Bind a handler for an LSP method.
Definition LSPBinder.h:133
void notification(llvm::StringLiteral Method, ThisT *This, void(ThisT::*Handler)(const Param &))
Bind a handler for an LSP notification.
Definition LSPBinder.h:146
UntypedOutgoingNotification outgoingNotification(llvm::StringLiteral Method)
Bind a function object to be used for outgoing notifications.
Definition LSPBinder.h:186
void command(llvm::StringLiteral Command, ThisT *This, void(ThisT::*Handler)(const Param &, Callback< Result >))
Bind a handler for an LSP command.
Definition LSPBinder.h:158
A threadsafe flag that is initially clear.
Definition Threading.h:91
Wrapper for vfs::FileSystem for use in multithreaded programs like clangd.
static URI createFile(llvm::StringRef AbsolutePath)
This creates a file:// URI for AbsolutePath. The path must be absolute.
Definition URI.cpp:237
std::string toString() const
Returns a string URI with all components percent-encoded.
Definition URI.cpp:160
WithContext replaces Context::current() with a provided scope.
Definition Context.h:185
Records an event whose duration is the lifetime of the Span object.
Definition Trace.h:143
llvm::json::Object *const Args
Mutable metadata, if this span is interested.
Definition Trace.h:154
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
Definition AST.cpp:45
@ Info
An information message.
Definition Protocol.h:738
llvm::StringRef toSemanticTokenModifier(HighlightingModifier Modifier)
constexpr auto CompletionItemKindMin
Definition Protocol.h:368
llvm::Error applyChange(std::string &Contents, const TextDocumentContentChangeEvent &Change)
Apply an incremental update to a text document.
llvm::StringRef toSemanticTokenType(HighlightingKind Kind)
SystemIncludeExtractorFn getSystemIncludeExtractor(llvm::ArrayRef< std::string > QueryDriverGlobs)
static std::vector< llvm::StringRef > semanticTokenModifiers()
constexpr auto SymbolKindMin
Definition Protocol.h:409
Key< OffsetEncoding > kCurrentOffsetEncoding
void toLSPDiags(const Diag &D, const URIForFile &File, const ClangdDiagnosticOptions &Opts, llvm::function_ref< void(clangd::Diagnostic, llvm::ArrayRef< Fix >)> OutFn)
Conversion to LSP diagnostics.
@ TriggerCharacter
Completion was triggered by a trigger character specified by the triggerCharacters properties of the ...
Definition Protocol.h:1231
bool allowImplicitCompletion(llvm::StringRef Content, unsigned Offset)
void record(const MemoryTree &MT, std::string RootName, const trace::Metric &Out)
Records total memory usage of each node under Out.
void vlog(const char *Fmt, Ts &&... Vals)
Definition Logger.h:72
llvm::unique_function< void(llvm::Expected< T >)> Callback
A Callback<T> is a void function that accepts Expected<T>.
Definition Function.h:28
std::string platformString()
Definition Feature.cpp:20
llvm::Error error(std::error_code EC, const char *Fmt, Ts &&... Vals)
Definition Logger.h:79
llvm::json::Value serializeTHIForExtension(TypeHierarchyItem THI)
static std::vector< SymbolInformation > flattenSymbolHierarchy(llvm::ArrayRef< DocumentSymbol > Symbols, const URIForFile &FileURI)
The functions constructs a flattened view of the DocumentSymbol hierarchy.
std::bitset< SymbolKindMax+1 > SymbolKindBitset
Definition Protocol.h:411
static void increment(std::string &S)
std::string featureString()
Definition Feature.cpp:33
llvm::StringMap< Edit > FileEdits
A mapping from absolute file path (the one used for accessing the underlying VFS) to edits.
Definition SourceCode.h:209
SymbolKind adjustKindToCapability(SymbolKind Kind, SymbolKindBitset &SupportedSymbolKinds)
Definition Protocol.cpp:280
static std::optional< Command > asCommand(const CodeAction &Action)
std::pair< Context, Canceler > cancelableTask(int Reason)
Defines a new task whose cancellation may be requested.
NoParams InitializedParams
Definition Protocol.h:321
void log(const char *Fmt, Ts &&... Vals)
Definition Logger.h:67
llvm::Expected< size_t > positionToOffset(llvm::StringRef Code, Position P, bool AllowColumnsBeyondLineLength)
Turn a [line, column] pair into an offset in Code.
std::bitset< CompletionItemKindMax+1 > CompletionItemKindBitset
Definition Protocol.h:372
static std::vector< llvm::StringRef > semanticTokenTypes()
llvm::StringRef PathRef
A typedef to represent a ref to file path.
Definition Path.h:29
@ Auto
Diagnostics must not be generated for this snapshot.
Definition TUScheduler.h:56
@ No
Diagnostics must be generated for this snapshot.
Definition TUScheduler.h:55
static Location * getToggle(const TextDocumentPositionParams &Point, LocatedSymbol &Sym)
std::string Path
A typedef to represent a file path.
Definition Path.h:26
std::function< void()> Canceler
A canceller requests cancellation of a task, when called.
@ Incremental
Documents are synced by sending the full content on open.
Definition Protocol.h:334
void elog(const char *Fmt, Ts &&... Vals)
Definition Logger.h:61
std::string versionString()
Definition Feature.cpp:18
std::vector< TextEdit > replacementsToEdits(llvm::StringRef Code, const tooling::Replacements &Repls)
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
std::optional< OffsetEncoding > Encoding
The offset-encoding to use, or std::nullopt to negotiate it over LSP.
bool EnableOutgoingCalls
Call hierarchy's outgoing calls feature requires additional index serving structures which increase m...
bool SemanticTokenRefreshSupport
Whether the client implementation supports a refresh request sent from the server to the client.
Definition Protocol.h:559
bool InactiveRegions
Whether the client supports the textDocument/inactiveRegions notification.
Definition Protocol.h:570
A code action represents a change that can be performed in code, e.g.
Definition Protocol.h:1077
static const llvm::StringLiteral INFO_KIND
Definition Protocol.h:1086
static const llvm::StringLiteral REFACTOR_KIND
Definition Protocol.h:1085
static const llvm::StringLiteral QUICKFIX_KIND
Definition Protocol.h:1084
std::optional< WorkspaceEdit > edit
The workspace edit this code action performs.
Definition Protocol.h:1099
std::optional< Command > command
A command this code action executes.
Definition Protocol.h:1103
std::optional< std::string > kind
The kind of the code action.
Definition Protocol.h:1083
std::string title
A short, human-readable, title for this code action.
Definition Protocol.h:1079
static CommandMangler detect()
Represents programming constructs like variables, classes, interfaces etc.
Definition Protocol.h:1111
std::vector< DocumentSymbol > children
Children of this symbol, e.g. properties of a class.
Definition Protocol.h:1135
std::string name
The name of this symbol.
Definition Protocol.h:1113
Range range
The range enclosing this symbol not including leading/trailing whitespace but everything else like co...
Definition Protocol.h:1128
SymbolKind kind
The kind of this symbol.
Definition Protocol.h:1119
A set of edits generated for a single file.
Definition SourceCode.h:189
Represents a single fix-it that editor can apply to fix the error.
Definition Diagnostics.h:81
Location PreferredDeclaration
Definition XRefs.h:45
std::optional< Location > Definition
Definition XRefs.h:47
URIForFile uri
The text document's URI.
Definition Protocol.h:213
A tree that can be used to represent memory usage of nested components while preserving the hierarchy...
Definition MemoryTree.h:30
MemoryTree & child(llvm::StringLiteral Name)
No copy of the Name.
Definition MemoryTree.h:39
bool contains(Position Pos) const
Definition Protocol.h:202
TextDocumentIdentifier textDocument
The document that was opened.
Definition Protocol.h:1443
Represents information about programming constructs like variables, classes, interfaces etc.
Definition Protocol.h:1142
std::string containerName
The name of the symbol containing this symbol.
Definition Protocol.h:1153
Location location
The location of this symbol.
Definition Protocol.h:1150
SymbolKind kind
The kind of this symbol.
Definition Protocol.h:1147
std::string name
The name of this symbol.
Definition Protocol.h:1144
URIForFile uri
The text document's URI.
Definition Protocol.h:133
TextDocumentIdentifier textDocument
The text document.
Definition Protocol.h:1217
Position position
The position inside the text document.
Definition Protocol.h:1220
Arguments for the 'applyTweak' command.
Definition Protocol.h:1045
URIForFile file
A file provided by the client on a textDocument/codeAction request.
Definition Protocol.h:1047
Range range
The range enclosing this symbol not including leading/trailing whitespace but everything else,...
Definition Protocol.h:1524
URIForFile uri
The resource identifier of this item.
Definition Protocol.h:1520
Range selectionRange
The range that should be selected and revealed when this symbol is being picked, e....
Definition Protocol.h:1528
SymbolKind kind
The kind of this item.
Definition Protocol.h:1514
std::optional< std::vector< TypeHierarchyItem > > children
If this type hierarchy item is resolved, it contains the direct children of the current item.
Definition Protocol.h:1553
std::optional< std::vector< TypeHierarchyItem > > parents
This is a clangd exntesion.
Definition Protocol.h:1547
bool deprecated
true if the hierarchy item is deprecated.
Definition Protocol.h:1544
std::optional< std::string > detail
More detail for this item, e.g. the signature of a function.
Definition Protocol.h:1517
ResolveParams data
A data entry field that is preserved between a type hierarchy prepare and supertypes or subtypes requ...
Definition Protocol.h:1540
std::string name
The name of this item.
Definition Protocol.h:1511
static URIForFile canonicalize(llvm::StringRef AbsPath, llvm::StringRef TUPath)
Canonicalizes AbsPath via URI.
Definition Protocol.cpp:46
llvm::StringRef file() const
Retrieves absolute path to the file.
Definition Protocol.h:104
The edit should either provide changes or documentChanges.
Definition Protocol.h:1024
The parameters of a Workspace Symbol Request.
Definition Protocol.h:1191
Represents measurements of clangd events, e.g.
Definition Trace.h:38
@ Distribution
A distribution of values with a meaningful mean and count.
Definition Trace.h:52