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