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