clang-tools  10.0.0
ClangdLSPServer.cpp
Go to the documentation of this file.
1 //===--- ClangdLSPServer.cpp - LSP server ------------------------*- C++-*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "ClangdLSPServer.h"
10 #include "Context.h"
11 #include "Diagnostics.h"
12 #include "DraftStore.h"
13 #include "FormattedString.h"
15 #include "Protocol.h"
16 #include "SemanticHighlighting.h"
17 #include "SourceCode.h"
18 #include "Trace.h"
19 #include "URI.h"
20 #include "refactor/Tweak.h"
21 #include "clang/Tooling/Core/Replacement.h"
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/ADT/Optional.h"
24 #include "llvm/ADT/ScopeExit.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/ADT/iterator_range.h"
27 #include "llvm/Support/Errc.h"
28 #include "llvm/Support/Error.h"
29 #include "llvm/Support/FormatVariadic.h"
30 #include "llvm/Support/JSON.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/SHA1.h"
33 #include "llvm/Support/ScopedPrinter.h"
34 #include <cstddef>
35 #include <memory>
36 #include <string>
37 #include <vector>
38 
39 namespace clang {
40 namespace clangd {
41 namespace {
42 /// Transforms a tweak into a code action that would apply it if executed.
43 /// EXPECTS: T.prepare() was called and returned true.
44 CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File,
45  Range Selection) {
46  CodeAction CA;
47  CA.title = T.Title;
48  switch (T.Intent) {
49  case Tweak::Refactor:
50  CA.kind = CodeAction::REFACTOR_KIND;
51  break;
52  case Tweak::Info:
53  CA.kind = CodeAction::INFO_KIND;
54  break;
55  }
56  // This tweak may have an expensive second stage, we only run it if the user
57  // actually chooses it in the UI. We reply with a command that would run the
58  // corresponding tweak.
59  // FIXME: for some tweaks, computing the edits is cheap and we could send them
60  // directly.
61  CA.command.emplace();
62  CA.command->title = T.Title;
63  CA.command->command = Command::CLANGD_APPLY_TWEAK;
64  CA.command->tweakArgs.emplace();
65  CA.command->tweakArgs->file = File;
66  CA.command->tweakArgs->tweakID = T.ID;
67  CA.command->tweakArgs->selection = Selection;
68  return CA;
69 }
70 
71 void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
72  SymbolKindBitset Kinds) {
73  for (auto &S : Syms) {
74  S.kind = adjustKindToCapability(S.kind, Kinds);
75  adjustSymbolKinds(S.children, Kinds);
76  }
77 }
78 
79 SymbolKindBitset defaultSymbolKinds() {
80  SymbolKindBitset Defaults;
81  for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
82  ++I)
83  Defaults.set(I);
84  return Defaults;
85 }
86 
87 CompletionItemKindBitset defaultCompletionItemKinds() {
88  CompletionItemKindBitset Defaults;
89  for (size_t I = CompletionItemKindMin;
90  I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
91  Defaults.set(I);
92  return Defaults;
93 }
94 
95 // Build a lookup table (HighlightingKind => {TextMate Scopes}), which is sent
96 // to the LSP client.
97 std::vector<std::vector<std::string>> buildHighlightScopeLookupTable() {
98  std::vector<std::vector<std::string>> LookupTable;
99  // HighlightingKind is using as the index.
100  for (int KindValue = 0; KindValue <= (int)HighlightingKind::LastKind;
101  ++KindValue)
102  LookupTable.push_back({toTextMateScope((HighlightingKind)(KindValue))});
103  return LookupTable;
104 }
105 
106 // Makes sure edits in \p FE are applicable to latest file contents reported by
107 // editor. If not generates an error message containing information about files
108 // that needs to be saved.
109 llvm::Error validateEdits(const DraftStore &DraftMgr, const FileEdits &FE) {
110  size_t InvalidFileCount = 0;
111  llvm::StringRef LastInvalidFile;
112  for (const auto &It : FE) {
113  if (auto Draft = DraftMgr.getDraft(It.first())) {
114  // If the file is open in user's editor, make sure the version we
115  // saw and current version are compatible as this is the text that
116  // will be replaced by editors.
117  if (!It.second.canApplyTo(*Draft)) {
118  ++InvalidFileCount;
119  LastInvalidFile = It.first();
120  }
121  }
122  }
123  if (!InvalidFileCount)
124  return llvm::Error::success();
125  if (InvalidFileCount == 1)
126  return llvm::createStringError(llvm::inconvertibleErrorCode(),
127  "File must be saved first: " +
128  LastInvalidFile);
129  return llvm::createStringError(
130  llvm::inconvertibleErrorCode(),
131  "Files must be saved first: " + LastInvalidFile + " (and " +
132  llvm::to_string(InvalidFileCount - 1) + " others)");
133 }
134 
135 // Converts a list of Ranges to a LinkedList of SelectionRange.
136 SelectionRange render(const std::vector<Range> &Ranges) {
137  if (Ranges.empty())
138  return {};
139  SelectionRange Result;
140  Result.range = Ranges[0];
141  auto *Next = &Result.parent;
142  for (const auto &R : llvm::make_range(Ranges.begin() + 1, Ranges.end())) {
143  *Next = std::make_unique<SelectionRange>();
144  Next->get()->range = R;
145  Next = &Next->get()->parent;
146  }
147  return Result;
148 }
149 
150 } // namespace
151 
152 // MessageHandler dispatches incoming LSP messages.
153 // It handles cross-cutting concerns:
154 // - serializes/deserializes protocol objects to JSON
155 // - logging of inbound messages
156 // - cancellation handling
157 // - basic call tracing
158 // MessageHandler ensures that initialize() is called before any other handler.
160 public:
161  MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
162 
163  bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
164  WithContext HandlerContext(handlerContext());
165  log("<-- {0}", Method);
166  if (Method == "exit")
167  return false;
168  if (!Server.Server)
169  elog("Notification {0} before initialization", Method);
170  else if (Method == "$/cancelRequest")
171  onCancel(std::move(Params));
172  else if (auto Handler = Notifications.lookup(Method))
173  Handler(std::move(Params));
174  else
175  log("unhandled notification {0}", Method);
176  return true;
177  }
178 
179  bool onCall(llvm::StringRef Method, llvm::json::Value Params,
180  llvm::json::Value ID) override {
181  WithContext HandlerContext(handlerContext());
182  // Calls can be canceled by the client. Add cancellation context.
183  WithContext WithCancel(cancelableRequestContext(ID));
184  trace::Span Tracer(Method);
185  SPAN_ATTACH(Tracer, "Params", Params);
186  ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
187  log("<-- {0}({1})", Method, ID);
188  if (!Server.Server && Method != "initialize") {
189  elog("Call {0} before initialization.", Method);
190  Reply(llvm::make_error<LSPError>("server not initialized",
192  } else if (auto Handler = Calls.lookup(Method))
193  Handler(std::move(Params), std::move(Reply));
194  else
195  Reply(llvm::make_error<LSPError>("method not found",
197  return true;
198  }
199 
200  bool onReply(llvm::json::Value ID,
201  llvm::Expected<llvm::json::Value> Result) override {
202  WithContext HandlerContext(handlerContext());
203 
204  Callback<llvm::json::Value> ReplyHandler = nullptr;
205  if (auto IntID = ID.getAsInteger()) {
206  std::lock_guard<std::mutex> Mutex(CallMutex);
207  // Find a corresponding callback for the request ID;
208  for (size_t Index = 0; Index < ReplyCallbacks.size(); ++Index) {
209  if (ReplyCallbacks[Index].first == *IntID) {
210  ReplyHandler = std::move(ReplyCallbacks[Index].second);
211  ReplyCallbacks.erase(ReplyCallbacks.begin() +
212  Index); // remove the entry
213  break;
214  }
215  }
216  }
217 
218  if (!ReplyHandler) {
219  // No callback being found, use a default log callback.
220  ReplyHandler = [&ID](llvm::Expected<llvm::json::Value> Result) {
221  elog("received a reply with ID {0}, but there was no such call", ID);
222  if (!Result)
223  llvm::consumeError(Result.takeError());
224  };
225  }
226 
227  // Log and run the reply handler.
228  if (Result) {
229  log("<-- reply({0})", ID);
230  ReplyHandler(std::move(Result));
231  } else {
232  auto Err = Result.takeError();
233  log("<-- reply({0}) error: {1}", ID, Err);
234  ReplyHandler(std::move(Err));
235  }
236  return true;
237  }
238 
239  // Bind an LSP method name to a call.
240  template <typename Param, typename Result>
241  void bind(const char *Method,
242  void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
243  Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
244  ReplyOnce Reply) {
245  Param P;
246  if (fromJSON(RawParams, P)) {
247  (Server.*Handler)(P, std::move(Reply));
248  } else {
249  elog("Failed to decode {0} request.", Method);
250  Reply(llvm::make_error<LSPError>("failed to decode request",
252  }
253  };
254  }
255 
256  // Bind a reply callback to a request. The callback will be invoked when
257  // clangd receives the reply from the LSP client.
258  // Return a call id of the request.
259  llvm::json::Value bindReply(Callback<llvm::json::Value> Reply) {
260  llvm::Optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB;
261  int ID;
262  {
263  std::lock_guard<std::mutex> Mutex(CallMutex);
264  ID = NextCallID++;
265  ReplyCallbacks.emplace_back(ID, std::move(Reply));
266 
267  // If the queue overflows, we assume that the client didn't reply the
268  // oldest request, and run the corresponding callback which replies an
269  // error to the client.
270  if (ReplyCallbacks.size() > MaxReplayCallbacks) {
271  elog("more than {0} outstanding LSP calls, forgetting about {1}",
272  MaxReplayCallbacks, ReplyCallbacks.front().first);
273  OldestCB = std::move(ReplyCallbacks.front());
274  ReplyCallbacks.pop_front();
275  }
276  }
277  if (OldestCB)
278  OldestCB->second(llvm::createStringError(
279  llvm::inconvertibleErrorCode(),
280  llvm::formatv("failed to receive a client reply for request ({0})",
281  OldestCB->first)));
282  return ID;
283  }
284 
285  // Bind an LSP method name to a notification.
286  template <typename Param>
287  void bind(const char *Method,
288  void (ClangdLSPServer::*Handler)(const Param &)) {
289  Notifications[Method] = [Method, Handler,
290  this](llvm::json::Value RawParams) {
291  Param P;
292  if (!fromJSON(RawParams, P)) {
293  elog("Failed to decode {0} request.", Method);
294  return;
295  }
296  trace::Span Tracer(Method);
297  SPAN_ATTACH(Tracer, "Params", RawParams);
298  (Server.*Handler)(P);
299  };
300  }
301 
302 private:
303  // Function object to reply to an LSP call.
304  // Each instance must be called exactly once, otherwise:
305  // - the bug is logged, and (in debug mode) an assert will fire
306  // - if there was no reply, an error reply is sent
307  // - if there were multiple replies, only the first is sent
308  class ReplyOnce {
309  std::atomic<bool> Replied = {false};
310  std::chrono::steady_clock::time_point Start;
311  llvm::json::Value ID;
312  std::string Method;
313  ClangdLSPServer *Server; // Null when moved-from.
314  llvm::json::Object *TraceArgs;
315 
316  public:
317  ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
318  ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
319  : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
320  Server(Server), TraceArgs(TraceArgs) {
321  assert(Server);
322  }
323  ReplyOnce(ReplyOnce &&Other)
324  : Replied(Other.Replied.load()), Start(Other.Start),
325  ID(std::move(Other.ID)), Method(std::move(Other.Method)),
326  Server(Other.Server), TraceArgs(Other.TraceArgs) {
327  Other.Server = nullptr;
328  }
329  ReplyOnce &operator=(ReplyOnce &&) = delete;
330  ReplyOnce(const ReplyOnce &) = delete;
331  ReplyOnce &operator=(const ReplyOnce &) = delete;
332 
333  ~ReplyOnce() {
334  // There's one legitimate reason to never reply to a request: clangd's
335  // request handler send a call to the client (e.g. applyEdit) and the
336  // client never replied. In this case, the ReplyOnce is owned by
337  // ClangdLSPServer's reply callback table and is destroyed along with the
338  // server. We don't attempt to send a reply in this case, there's little
339  // to be gained from doing so.
340  if (Server && !Server->IsBeingDestroyed && !Replied) {
341  elog("No reply to message {0}({1})", Method, ID);
342  assert(false && "must reply to all calls!");
343  (*this)(llvm::make_error<LSPError>("server failed to reply",
345  }
346  }
347 
348  void operator()(llvm::Expected<llvm::json::Value> Reply) {
349  assert(Server && "moved-from!");
350  if (Replied.exchange(true)) {
351  elog("Replied twice to message {0}({1})", Method, ID);
352  assert(false && "must reply to each call only once!");
353  return;
354  }
355  auto Duration = std::chrono::steady_clock::now() - Start;
356  if (Reply) {
357  log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
358  if (TraceArgs)
359  (*TraceArgs)["Reply"] = *Reply;
360  std::lock_guard<std::mutex> Lock(Server->TranspWriter);
361  Server->Transp.reply(std::move(ID), std::move(Reply));
362  } else {
363  llvm::Error Err = Reply.takeError();
364  log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
365  if (TraceArgs)
366  (*TraceArgs)["Error"] = llvm::to_string(Err);
367  std::lock_guard<std::mutex> Lock(Server->TranspWriter);
368  Server->Transp.reply(std::move(ID), std::move(Err));
369  }
370  }
371  };
372 
373  llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
374  llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
375 
376  // Method calls may be cancelled by ID, so keep track of their state.
377  // This needs a mutex: handlers may finish on a different thread, and that's
378  // when we clean up entries in the map.
379  mutable std::mutex RequestCancelersMutex;
380  llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
381  unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
382  void onCancel(const llvm::json::Value &Params) {
383  const llvm::json::Value *ID = nullptr;
384  if (auto *O = Params.getAsObject())
385  ID = O->get("id");
386  if (!ID) {
387  elog("Bad cancellation request: {0}", Params);
388  return;
389  }
390  auto StrID = llvm::to_string(*ID);
391  std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
392  auto It = RequestCancelers.find(StrID);
393  if (It != RequestCancelers.end())
394  It->second.first(); // Invoke the canceler.
395  }
396 
397  Context handlerContext() const {
398  return Context::current().derive(
400  Server.NegotiatedOffsetEncoding.getValueOr(OffsetEncoding::UTF16));
401  }
402 
403  // We run cancelable requests in a context that does two things:
404  // - allows cancellation using RequestCancelers[ID]
405  // - cleans up the entry in RequestCancelers when it's no longer needed
406  // If a client reuses an ID, the last wins and the first cannot be canceled.
407  Context cancelableRequestContext(const llvm::json::Value &ID) {
408  auto Task = cancelableTask();
409  auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
410  auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
411  {
412  std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
413  RequestCancelers[StrID] = {std::move(Task.second), Cookie};
414  }
415  // When the request ends, we can clean up the entry we just added.
416  // The cookie lets us check that it hasn't been overwritten due to ID
417  // reuse.
418  return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
419  std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
420  auto It = RequestCancelers.find(StrID);
421  if (It != RequestCancelers.end() && It->second.second == Cookie)
422  RequestCancelers.erase(It);
423  }));
424  }
425 
426  // The maximum number of callbacks held in clangd.
427  //
428  // We bound the maximum size to the pending map to prevent memory leakage
429  // for cases where LSP clients don't reply for the request.
430  // This has to go after RequestCancellers and RequestCancellersMutex since it
431  // can contain a callback that has a cancelable context.
432  static constexpr int MaxReplayCallbacks = 100;
433  mutable std::mutex CallMutex;
434  int NextCallID = 0; /* GUARDED_BY(CallMutex) */
435  std::deque<std::pair</*RequestID*/ int,
436  /*ReplyHandler*/ Callback<llvm::json::Value>>>
437  ReplyCallbacks; /* GUARDED_BY(CallMutex) */
438 
440 };
441 constexpr int ClangdLSPServer::MessageHandler::MaxReplayCallbacks;
442 
443 // call(), notify(), and reply() wrap the Transport, adding logging and locking.
444 void ClangdLSPServer::callRaw(StringRef Method, llvm::json::Value Params,
446  auto ID = MsgHandler->bindReply(std::move(CB));
447  log("--> {0}({1})", Method, ID);
448  std::lock_guard<std::mutex> Lock(TranspWriter);
449  Transp.call(Method, std::move(Params), ID);
450 }
451 
452 void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
453  log("--> {0}", Method);
454  std::lock_guard<std::mutex> Lock(TranspWriter);
455  Transp.notify(Method, std::move(Params));
456 }
457 
458 void ClangdLSPServer::onInitialize(const InitializeParams &Params,
460  // Determine character encoding first as it affects constructed ClangdServer.
461  if (Params.capabilities.offsetEncoding && !NegotiatedOffsetEncoding) {
462  NegotiatedOffsetEncoding = OffsetEncoding::UTF16; // fallback
463  for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
464  if (Supported != OffsetEncoding::UnsupportedEncoding) {
465  NegotiatedOffsetEncoding = Supported;
466  break;
467  }
468  }
469 
470  ClangdServerOpts.SemanticHighlighting =
472  if (Params.rootUri && *Params.rootUri)
473  ClangdServerOpts.WorkspaceRoot = Params.rootUri->file();
474  else if (Params.rootPath && !Params.rootPath->empty())
475  ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
476  if (Server)
477  return Reply(llvm::make_error<LSPError>("server already initialized",
479  if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
480  CompileCommandsDir = Dir;
481  if (UseDirBasedCDB) {
482  BaseCDB = std::make_unique<DirectoryBasedGlobalCompilationDatabase>(
483  CompileCommandsDir);
484  BaseCDB = getQueryDriverDatabase(
485  llvm::makeArrayRef(ClangdServerOpts.QueryDriverGlobs),
486  std::move(BaseCDB));
487  }
488  auto Mangler = CommandMangler::detect();
489  if (ClangdServerOpts.ResourceDir)
490  Mangler.ResourceDir = *ClangdServerOpts.ResourceDir;
491  CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
492  tooling::ArgumentsAdjuster(Mangler));
493  {
494  // Switch caller's context with LSPServer's background context. Since we
495  // rather want to propagate information from LSPServer's context into the
496  // Server, CDB, etc.
497  WithContext MainContext(BackgroundContext.clone());
498  llvm::Optional<WithContextValue> WithOffsetEncoding;
499  if (NegotiatedOffsetEncoding)
500  WithOffsetEncoding.emplace(kCurrentOffsetEncoding,
501  *NegotiatedOffsetEncoding);
502  Server.emplace(*CDB, FSProvider, static_cast<DiagnosticsConsumer &>(*this),
503  ClangdServerOpts);
504  }
505  applyConfiguration(Params.initializationOptions.ConfigSettings);
506 
507  CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
508  CCOpts.IncludeFixIts = Params.capabilities.CompletionFixes;
509  if (!CCOpts.BundleOverloads.hasValue())
510  CCOpts.BundleOverloads = Params.capabilities.HasSignatureHelp;
511  DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
512  DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
513  DiagOpts.EmitRelatedLocations =
516  SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
518  SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
519  SupportsCodeAction = Params.capabilities.CodeActionStructure;
520  SupportsHierarchicalDocumentSymbol =
522  SupportFileStatus = Params.initializationOptions.FileStatus;
523  HoverContentFormat = Params.capabilities.HoverContentFormat;
524  SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
525 
526  // Per LSP, renameProvider can be either boolean or RenameOptions.
527  // RenameOptions will be specified if the client states it supports prepare.
528  llvm::json::Value RenameProvider =
529  llvm::json::Object{{"prepareProvider", true}};
530  if (!Params.capabilities.RenamePrepareSupport) // Only boolean allowed per LSP
531  RenameProvider = true;
532 
533  // Per LSP, codeActionProvide can be either boolean or CodeActionOptions.
534  // CodeActionOptions is only valid if the client supports action literal
535  // via textDocument.codeAction.codeActionLiteralSupport.
536  llvm::json::Value CodeActionProvider = true;
538  CodeActionProvider = llvm::json::Object{
539  {"codeActionKinds",
542 
543  llvm::json::Object Result{
544  {{"capabilities",
545  llvm::json::Object{
546  {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
547  {"documentFormattingProvider", true},
548  {"documentRangeFormattingProvider", true},
549  {"documentOnTypeFormattingProvider",
550  llvm::json::Object{
551  {"firstTriggerCharacter", "\n"},
552  {"moreTriggerCharacter", {}},
553  }},
554  {"codeActionProvider", std::move(CodeActionProvider)},
555  {"completionProvider",
556  llvm::json::Object{
557  {"resolveProvider", false},
558  // We do extra checks for '>' and ':' in completion to only
559  // trigger on '->' and '::'.
560  {"triggerCharacters", {".", ">", ":"}},
561  }},
562  {"signatureHelpProvider",
563  llvm::json::Object{
564  {"triggerCharacters", {"(", ","}},
565  }},
566  {"declarationProvider", true},
567  {"definitionProvider", true},
568  {"documentHighlightProvider", true},
569  {"documentLinkProvider",
570  llvm::json::Object{
571  {"resolveProvider", false},
572  }},
573  {"hoverProvider", true},
574  {"renameProvider", std::move(RenameProvider)},
575  {"selectionRangeProvider", true},
576  {"documentSymbolProvider", true},
577  {"workspaceSymbolProvider", true},
578  {"referencesProvider", true},
579  {"executeCommandProvider",
580  llvm::json::Object{
581  {"commands",
584  }},
585  {"typeHierarchyProvider", true},
586  }}}};
587  if (NegotiatedOffsetEncoding)
588  Result["offsetEncoding"] = *NegotiatedOffsetEncoding;
590  Result.getObject("capabilities")
591  ->insert(
592  {"semanticHighlighting",
593  llvm::json::Object{{"scopes", buildHighlightScopeLookupTable()}}});
594  Reply(std::move(Result));
595 }
596 
597 void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
598  Callback<std::nullptr_t> Reply) {
599  // Do essentially nothing, just say we're ready to exit.
600  ShutdownRequestReceived = true;
601  Reply(nullptr);
602 }
603 
604 // sync is a clangd extension: it blocks until all background work completes.
605 // It blocks the calling thread, so no messages are processed until it returns!
606 void ClangdLSPServer::onSync(const NoParams &Params,
607  Callback<std::nullptr_t> Reply) {
608  if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
609  Reply(nullptr);
610  else
611  Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
612  "Not idle after a minute"));
613 }
614 
615 void ClangdLSPServer::onDocumentDidOpen(
616  const DidOpenTextDocumentParams &Params) {
617  PathRef File = Params.textDocument.uri.file();
618 
619  const std::string &Contents = Params.textDocument.text;
620 
621  DraftMgr.addDraft(File, Contents);
622  Server->addDocument(File, Contents, WantDiagnostics::Yes);
623 }
624 
625 void ClangdLSPServer::onDocumentDidChange(
626  const DidChangeTextDocumentParams &Params) {
627  auto WantDiags = WantDiagnostics::Auto;
628  if (Params.wantDiagnostics.hasValue())
629  WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
631 
632  PathRef File = Params.textDocument.uri.file();
633  llvm::Expected<std::string> Contents =
634  DraftMgr.updateDraft(File, Params.contentChanges);
635  if (!Contents) {
636  // If this fails, we are most likely going to be not in sync anymore with
637  // the client. It is better to remove the draft and let further operations
638  // fail rather than giving wrong results.
639  DraftMgr.removeDraft(File);
640  Server->removeDocument(File);
641  elog("Failed to update {0}: {1}", File, Contents.takeError());
642  return;
643  }
644 
645  Server->addDocument(File, *Contents, WantDiags);
646 }
647 
648 void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
649  Server->onFileEvent(Params);
650 }
651 
652 void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
654  auto ApplyEdit = [this](WorkspaceEdit WE, std::string SuccessMessage,
655  decltype(Reply) Reply) {
657  Edit.edit = std::move(WE);
658  call<ApplyWorkspaceEditResponse>(
659  "workspace/applyEdit", std::move(Edit),
660  [Reply = std::move(Reply), SuccessMessage = std::move(SuccessMessage)](
661  llvm::Expected<ApplyWorkspaceEditResponse> Response) mutable {
662  if (!Response)
663  return Reply(Response.takeError());
664  if (!Response->applied) {
665  std::string Reason = Response->failureReason
666  ? *Response->failureReason
667  : "unknown reason";
668  return Reply(llvm::createStringError(
669  llvm::inconvertibleErrorCode(),
670  ("edits were not applied: " + Reason).c_str()));
671  }
672  return Reply(SuccessMessage);
673  });
674  };
675 
677  Params.workspaceEdit) {
678  // The flow for "apply-fix" :
679  // 1. We publish a diagnostic, including fixits
680  // 2. The user clicks on the diagnostic, the editor asks us for code actions
681  // 3. We send code actions, with the fixit embedded as context
682  // 4. The user selects the fixit, the editor asks us to apply it
683  // 5. We unwrap the changes and send them back to the editor
684  // 6. The editor applies the changes (applyEdit), and sends us a reply
685  // 7. We unwrap the reply and send a reply to the editor.
686  ApplyEdit(*Params.workspaceEdit, "Fix applied.", std::move(Reply));
687  } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
688  Params.tweakArgs) {
689  auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
690  if (!Code)
691  return Reply(llvm::createStringError(
692  llvm::inconvertibleErrorCode(),
693  "trying to apply a code action for a non-added file"));
694 
695  auto Action = [this, ApplyEdit, Reply = std::move(Reply),
696  File = Params.tweakArgs->file, Code = std::move(*Code)](
697  llvm::Expected<Tweak::Effect> R) mutable {
698  if (!R)
699  return Reply(R.takeError());
700 
701  assert(R->ShowMessage ||
702  (!R->ApplyEdits.empty() && "tweak has no effect"));
703 
704  if (R->ShowMessage) {
705  ShowMessageParams Msg;
706  Msg.message = *R->ShowMessage;
707  Msg.type = MessageType::Info;
708  notify("window/showMessage", Msg);
709  }
710  // When no edit is specified, make sure we Reply().
711  if (R->ApplyEdits.empty())
712  return Reply("Tweak applied.");
713 
714  if (auto Err = validateEdits(DraftMgr, R->ApplyEdits))
715  return Reply(std::move(Err));
716 
717  WorkspaceEdit WE;
718  WE.changes.emplace();
719  for (const auto &It : R->ApplyEdits) {
720  (*WE.changes)[URI::createFile(It.first()).toString()] =
721  It.second.asTextEdits();
722  }
723  // ApplyEdit will take care of calling Reply().
724  return ApplyEdit(std::move(WE), "Tweak applied.", std::move(Reply));
725  };
726  Server->applyTweak(Params.tweakArgs->file.file(),
727  Params.tweakArgs->selection, Params.tweakArgs->tweakID,
728  std::move(Action));
729  } else {
730  // We should not get here because ExecuteCommandParams would not have
731  // parsed in the first place and this handler should not be called. But if
732  // more commands are added, this will be here has a safe guard.
733  Reply(llvm::make_error<LSPError>(
734  llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
736  }
737 }
738 
739 void ClangdLSPServer::onWorkspaceSymbol(
740  const WorkspaceSymbolParams &Params,
741  Callback<std::vector<SymbolInformation>> Reply) {
742  Server->workspaceSymbols(
743  Params.query, CCOpts.Limit,
744  [Reply = std::move(Reply),
745  this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable {
746  if (!Items)
747  return Reply(Items.takeError());
748  for (auto &Sym : *Items)
749  Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
750 
751  Reply(std::move(*Items));
752  });
753 }
754 
755 void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params,
756  Callback<llvm::Optional<Range>> Reply) {
757  Server->prepareRename(Params.textDocument.uri.file(), Params.position,
758  std::move(Reply));
759 }
760 
761 void ClangdLSPServer::onRename(const RenameParams &Params,
762  Callback<WorkspaceEdit> Reply) {
763  Path File = Params.textDocument.uri.file();
764  llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
765  if (!Code)
766  return Reply(llvm::make_error<LSPError>(
767  "onRename called for non-added file", ErrorCode::InvalidParams));
768  Server->rename(
769  File, Params.position, Params.newName,
770  /*WantFormat=*/true,
771  [File, Params, Reply = std::move(Reply),
772  this](llvm::Expected<FileEdits> Edits) mutable {
773  if (!Edits)
774  return Reply(Edits.takeError());
775  if (auto Err = validateEdits(DraftMgr, *Edits))
776  return Reply(std::move(Err));
777  WorkspaceEdit Result;
778  Result.changes.emplace();
779  for (const auto &Rep : *Edits) {
780  (*Result.changes)[URI::createFile(Rep.first()).toString()] =
781  Rep.second.asTextEdits();
782  }
783  Reply(Result);
784  });
785 }
786 
787 void ClangdLSPServer::onDocumentDidClose(
788  const DidCloseTextDocumentParams &Params) {
789  PathRef File = Params.textDocument.uri.file();
790  DraftMgr.removeDraft(File);
791  Server->removeDocument(File);
792 
793  {
794  std::lock_guard<std::mutex> Lock(FixItsMutex);
795  FixItsMap.erase(File);
796  }
797  {
798  std::lock_guard<std::mutex> HLock(HighlightingsMutex);
799  FileToHighlightings.erase(File);
800  }
801  // clangd will not send updates for this file anymore, so we empty out the
802  // list of diagnostics shown on the client (e.g. in the "Problems" pane of
803  // VSCode). Note that this cannot race with actual diagnostics responses
804  // because removeDocument() guarantees no diagnostic callbacks will be
805  // executed after it returns.
806  publishDiagnostics(URIForFile::canonicalize(File, /*TUPath=*/File), {});
807 }
808 
809 void ClangdLSPServer::onDocumentOnTypeFormatting(
810  const DocumentOnTypeFormattingParams &Params,
811  Callback<std::vector<TextEdit>> Reply) {
812  auto File = Params.textDocument.uri.file();
813  auto Code = DraftMgr.getDraft(File);
814  if (!Code)
815  return Reply(llvm::make_error<LSPError>(
816  "onDocumentOnTypeFormatting called for non-added file",
818 
819  Reply(Server->formatOnType(*Code, File, Params.position, Params.ch));
820 }
821 
822 void ClangdLSPServer::onDocumentRangeFormatting(
823  const DocumentRangeFormattingParams &Params,
824  Callback<std::vector<TextEdit>> Reply) {
825  auto File = Params.textDocument.uri.file();
826  auto Code = DraftMgr.getDraft(File);
827  if (!Code)
828  return Reply(llvm::make_error<LSPError>(
829  "onDocumentRangeFormatting called for non-added file",
831 
832  auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
833  if (ReplacementsOrError)
834  Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
835  else
836  Reply(ReplacementsOrError.takeError());
837 }
838 
839 void ClangdLSPServer::onDocumentFormatting(
840  const DocumentFormattingParams &Params,
841  Callback<std::vector<TextEdit>> Reply) {
842  auto File = Params.textDocument.uri.file();
843  auto Code = DraftMgr.getDraft(File);
844  if (!Code)
845  return Reply(llvm::make_error<LSPError>(
846  "onDocumentFormatting called for non-added file",
848 
849  auto ReplacementsOrError = Server->formatFile(*Code, File);
850  if (ReplacementsOrError)
851  Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
852  else
853  Reply(ReplacementsOrError.takeError());
854 }
855 
856 /// The functions constructs a flattened view of the DocumentSymbol hierarchy.
857 /// Used by the clients that do not support the hierarchical view.
858 static std::vector<SymbolInformation>
859 flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
860  const URIForFile &FileURI) {
861 
862  std::vector<SymbolInformation> Results;
863  std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
864  [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
866  SI.containerName = ParentName ? "" : *ParentName;
867  SI.name = S.name;
868  SI.kind = S.kind;
869  SI.location.range = S.range;
870  SI.location.uri = FileURI;
871 
872  Results.push_back(std::move(SI));
873  std::string FullName =
874  !ParentName ? S.name : (ParentName->str() + "::" + S.name);
875  for (auto &C : S.children)
876  Process(C, /*ParentName=*/FullName);
877  };
878  for (auto &S : Symbols)
879  Process(S, /*ParentName=*/"");
880  return Results;
881 }
882 
883 void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
885  URIForFile FileURI = Params.textDocument.uri;
886  Server->documentSymbols(
887  Params.textDocument.uri.file(),
888  [this, FileURI, Reply = std::move(Reply)](
889  llvm::Expected<std::vector<DocumentSymbol>> Items) mutable {
890  if (!Items)
891  return Reply(Items.takeError());
892  adjustSymbolKinds(*Items, SupportedSymbolKinds);
893  if (SupportsHierarchicalDocumentSymbol)
894  return Reply(std::move(*Items));
895  else
896  return Reply(flattenSymbolHierarchy(*Items, FileURI));
897  });
898 }
899 
900 static llvm::Optional<Command> asCommand(const CodeAction &Action) {
901  Command Cmd;
902  if (Action.command && Action.edit)
903  return None; // Not representable. (We never emit these anyway).
904  if (Action.command) {
905  Cmd = *Action.command;
906  } else if (Action.edit) {
907  Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
908  Cmd.workspaceEdit = *Action.edit;
909  } else {
910  return None;
911  }
912  Cmd.title = Action.title;
913  if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
914  Cmd.title = "Apply fix: " + Cmd.title;
915  return Cmd;
916 }
917 
918 void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
920  URIForFile File = Params.textDocument.uri;
921  auto Code = DraftMgr.getDraft(File.file());
922  if (!Code)
923  return Reply(llvm::make_error<LSPError>(
924  "onCodeAction called for non-added file", ErrorCode::InvalidParams));
925  // We provide a code action for Fixes on the specified diagnostics.
926  std::vector<CodeAction> FixIts;
927  for (const Diagnostic &D : Params.context.diagnostics) {
928  for (auto &F : getFixes(File.file(), D)) {
929  FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
930  FixIts.back().diagnostics = {D};
931  }
932  }
933 
934  // Now enumerate the semantic code actions.
935  auto ConsumeActions =
936  [Reply = std::move(Reply), File, Code = std::move(*Code),
937  Selection = Params.range, FixIts = std::move(FixIts), this](
938  llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable {
939  if (!Tweaks)
940  return Reply(Tweaks.takeError());
941 
942  std::vector<CodeAction> Actions = std::move(FixIts);
943  Actions.reserve(Actions.size() + Tweaks->size());
944  for (const auto &T : *Tweaks)
945  Actions.push_back(toCodeAction(T, File, Selection));
946 
947  if (SupportsCodeAction)
948  return Reply(llvm::json::Array(Actions));
949  std::vector<Command> Commands;
950  for (const auto &Action : Actions) {
951  if (auto Command = asCommand(Action))
952  Commands.push_back(std::move(*Command));
953  }
954  return Reply(llvm::json::Array(Commands));
955  };
956 
957  Server->enumerateTweaks(File.file(), Params.range, std::move(ConsumeActions));
958 }
959 
960 void ClangdLSPServer::onCompletion(const CompletionParams &Params,
961  Callback<CompletionList> Reply) {
962  if (!shouldRunCompletion(Params)) {
963  // Clients sometimes auto-trigger completions in undesired places (e.g.
964  // 'a >^ '), we return empty results in those cases.
965  vlog("ignored auto-triggered completion, preceding char did not match");
966  return Reply(CompletionList());
967  }
968  Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
969  [Reply = std::move(Reply),
970  this](llvm::Expected<CodeCompleteResult> List) mutable {
971  if (!List)
972  return Reply(List.takeError());
973  CompletionList LSPList;
974  LSPList.isIncomplete = List->HasMore;
975  for (const auto &R : List->Completions) {
976  CompletionItem C = R.render(CCOpts);
978  C.kind, SupportedCompletionItemKinds);
979  LSPList.items.push_back(std::move(C));
980  }
981  return Reply(std::move(LSPList));
982  });
983 }
984 
985 void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
986  Callback<SignatureHelp> Reply) {
987  Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
988  [Reply = std::move(Reply), this](
989  llvm::Expected<SignatureHelp> Signature) mutable {
990  if (!Signature)
991  return Reply(Signature.takeError());
992  if (SupportsOffsetsInSignatureHelp)
993  return Reply(std::move(*Signature));
994  // Strip out the offsets from signature help for
995  // clients that only support string labels.
996  for (auto &SigInfo : Signature->signatures) {
997  for (auto &Param : SigInfo.parameters)
998  Param.labelOffsets.reset();
999  }
1000  return Reply(std::move(*Signature));
1001  });
1002 }
1003 
1004 // Go to definition has a toggle function: if def and decl are distinct, then
1005 // the first press gives you the def, the second gives you the matching def.
1006 // getToggle() returns the counterpart location that under the cursor.
1007 //
1008 // We return the toggled location alone (ignoring other symbols) to encourage
1009 // editors to "bounce" quickly between locations, without showing a menu.
1011  LocatedSymbol &Sym) {
1012  // Toggle only makes sense with two distinct locations.
1013  if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
1014  return nullptr;
1015  if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
1016  Sym.Definition->range.contains(Point.position))
1017  return &Sym.PreferredDeclaration;
1018  if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
1020  return &*Sym.Definition;
1021  return nullptr;
1022 }
1023 
1024 void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
1025  Callback<std::vector<Location>> Reply) {
1026  Server->locateSymbolAt(
1027  Params.textDocument.uri.file(), Params.position,
1028  [Params, Reply = std::move(Reply)](
1029  llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1030  if (!Symbols)
1031  return Reply(Symbols.takeError());
1032  std::vector<Location> Defs;
1033  for (auto &S : *Symbols) {
1034  if (Location *Toggle = getToggle(Params, S))
1035  return Reply(std::vector<Location>{std::move(*Toggle)});
1036  Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
1037  }
1038  Reply(std::move(Defs));
1039  });
1040 }
1041 
1042 void ClangdLSPServer::onGoToDeclaration(
1043  const TextDocumentPositionParams &Params,
1044  Callback<std::vector<Location>> Reply) {
1045  Server->locateSymbolAt(
1046  Params.textDocument.uri.file(), Params.position,
1047  [Params, Reply = std::move(Reply)](
1048  llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable {
1049  if (!Symbols)
1050  return Reply(Symbols.takeError());
1051  std::vector<Location> Decls;
1052  for (auto &S : *Symbols) {
1053  if (Location *Toggle = getToggle(Params, S))
1054  return Reply(std::vector<Location>{std::move(*Toggle)});
1055  Decls.push_back(std::move(S.PreferredDeclaration));
1056  }
1057  Reply(std::move(Decls));
1058  });
1059 }
1060 
1061 void ClangdLSPServer::onSwitchSourceHeader(
1062  const TextDocumentIdentifier &Params,
1063  Callback<llvm::Optional<URIForFile>> Reply) {
1064  Server->switchSourceHeader(
1065  Params.uri.file(),
1066  [Reply = std::move(Reply),
1067  Params](llvm::Expected<llvm::Optional<clangd::Path>> Path) mutable {
1068  if (!Path)
1069  return Reply(Path.takeError());
1070  if (*Path)
1071  return Reply(URIForFile::canonicalize(**Path, Params.uri.file()));
1072  return Reply(llvm::None);
1073  });
1074 }
1075 
1076 void ClangdLSPServer::onDocumentHighlight(
1077  const TextDocumentPositionParams &Params,
1078  Callback<std::vector<DocumentHighlight>> Reply) {
1079  Server->findDocumentHighlights(Params.textDocument.uri.file(),
1080  Params.position, std::move(Reply));
1081 }
1082 
1083 void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
1084  Callback<llvm::Optional<Hover>> Reply) {
1085  Server->findHover(Params.textDocument.uri.file(), Params.position,
1086  [Reply = std::move(Reply), this](
1087  llvm::Expected<llvm::Optional<HoverInfo>> H) mutable {
1088  if (!H)
1089  return Reply(H.takeError());
1090  if (!*H)
1091  return Reply(llvm::None);
1092 
1093  Hover R;
1094  R.contents.kind = HoverContentFormat;
1095  R.range = (*H)->SymRange;
1096  switch (HoverContentFormat) {
1097  case MarkupKind::PlainText:
1098  R.contents.value = (*H)->present().asPlainText();
1099  return Reply(std::move(R));
1100  case MarkupKind::Markdown:
1101  R.contents.value = (*H)->present().asMarkdown();
1102  return Reply(std::move(R));
1103  };
1104  llvm_unreachable("unhandled MarkupKind");
1105  });
1106 }
1107 
1108 void ClangdLSPServer::onTypeHierarchy(
1109  const TypeHierarchyParams &Params,
1110  Callback<Optional<TypeHierarchyItem>> Reply) {
1111  Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
1112  Params.resolve, Params.direction, std::move(Reply));
1113 }
1114 
1115 void ClangdLSPServer::onResolveTypeHierarchy(
1116  const ResolveTypeHierarchyItemParams &Params,
1117  Callback<Optional<TypeHierarchyItem>> Reply) {
1118  Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
1119  std::move(Reply));
1120 }
1121 
1122 void ClangdLSPServer::applyConfiguration(
1123  const ConfigurationSettings &Settings) {
1124  // Per-file update to the compilation database.
1125  bool ShouldReparseOpenFiles = false;
1126  for (auto &Entry : Settings.compilationDatabaseChanges) {
1127  /// The opened files need to be reparsed only when some existing
1128  /// entries are changed.
1129  PathRef File = Entry.first;
1130  auto Old = CDB->getCompileCommand(File);
1131  auto New =
1132  tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
1133  std::move(Entry.second.compilationCommand),
1134  /*Output=*/"");
1135  if (Old != New) {
1136  CDB->setCompileCommand(File, std::move(New));
1137  ShouldReparseOpenFiles = true;
1138  }
1139  }
1140  if (ShouldReparseOpenFiles)
1141  reparseOpenedFiles();
1142 }
1143 
1144 void ClangdLSPServer::publishSemanticHighlighting(
1145  SemanticHighlightingParams Params) {
1146  notify("textDocument/semanticHighlighting", Params);
1147 }
1148 
1149 void ClangdLSPServer::publishDiagnostics(
1150  const URIForFile &File, std::vector<clangd::Diagnostic> Diagnostics) {
1151  // Publish diagnostics.
1152  notify("textDocument/publishDiagnostics",
1153  llvm::json::Object{
1154  {"uri", File},
1155  {"diagnostics", std::move(Diagnostics)},
1156  });
1157 }
1158 
1159 // FIXME: This function needs to be properly tested.
1160 void ClangdLSPServer::onChangeConfiguration(
1161  const DidChangeConfigurationParams &Params) {
1162  applyConfiguration(Params.settings);
1163 }
1164 
1165 void ClangdLSPServer::onReference(const ReferenceParams &Params,
1166  Callback<std::vector<Location>> Reply) {
1167  Server->findReferences(Params.textDocument.uri.file(), Params.position,
1168  CCOpts.Limit,
1169  [Reply = std::move(Reply)](
1170  llvm::Expected<ReferencesResult> Refs) mutable {
1171  if (!Refs)
1172  return Reply(Refs.takeError());
1173  return Reply(std::move(Refs->References));
1174  });
1175 }
1176 
1177 void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
1178  Callback<std::vector<SymbolDetails>> Reply) {
1179  Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
1180  std::move(Reply));
1181 }
1182 
1183 void ClangdLSPServer::onSelectionRange(
1184  const SelectionRangeParams &Params,
1185  Callback<std::vector<SelectionRange>> Reply) {
1186  if (Params.positions.size() != 1) {
1187  elog("{0} positions provided to SelectionRange. Supports exactly one "
1188  "position.",
1189  Params.positions.size());
1190  return Reply(llvm::make_error<LSPError>(
1191  "SelectionRange supports exactly one position",
1193  }
1194  Server->semanticRanges(
1195  Params.textDocument.uri.file(), Params.positions[0],
1196  [Reply = std::move(Reply)](
1197  llvm::Expected<std::vector<Range>> Ranges) mutable {
1198  if (!Ranges) {
1199  return Reply(Ranges.takeError());
1200  }
1201  std::vector<SelectionRange> Result;
1202  Result.emplace_back(render(std::move(*Ranges)));
1203  return Reply(std::move(Result));
1204  });
1205 }
1206 
1207 void ClangdLSPServer::onDocumentLink(
1208  const DocumentLinkParams &Params,
1209  Callback<std::vector<DocumentLink>> Reply) {
1210 
1211  // TODO(forster): This currently resolves all targets eagerly. This is slow,
1212  // because it blocks on the preamble/AST being built. We could respond to the
1213  // request faster by using string matching or the lexer to find the includes
1214  // and resolving the targets lazily.
1215  Server->documentLinks(
1216  Params.textDocument.uri.file(),
1217  [Reply = std::move(Reply)](
1218  llvm::Expected<std::vector<DocumentLink>> Links) mutable {
1219  if (!Links) {
1220  return Reply(Links.takeError());
1221  }
1222  return Reply(std::move(Links));
1223  });
1224 }
1225 
1227  class Transport &Transp, const FileSystemProvider &FSProvider,
1228  const clangd::CodeCompleteOptions &CCOpts,
1229  llvm::Optional<Path> CompileCommandsDir, bool UseDirBasedCDB,
1230  llvm::Optional<OffsetEncoding> ForcedOffsetEncoding,
1231  const ClangdServer::Options &Opts)
1232  : BackgroundContext(Context::current().clone()), Transp(Transp),
1233  MsgHandler(new MessageHandler(*this)), FSProvider(FSProvider),
1234  CCOpts(CCOpts), SupportedSymbolKinds(defaultSymbolKinds()),
1235  SupportedCompletionItemKinds(defaultCompletionItemKinds()),
1236  UseDirBasedCDB(UseDirBasedCDB),
1237  CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts),
1238  NegotiatedOffsetEncoding(ForcedOffsetEncoding) {
1239  // clang-format off
1240  MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
1241  MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
1242  MsgHandler->bind("sync", &ClangdLSPServer::onSync);
1243  MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
1244  MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
1245  MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
1246  MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
1247  MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
1248  MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
1249  MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
1250  MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
1251  MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
1252  MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
1253  MsgHandler->bind("textDocument/prepareRename", &ClangdLSPServer::onPrepareRename);
1254  MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
1255  MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
1256  MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
1257  MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
1258  MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
1259  MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
1260  MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
1261  MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
1262  MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
1263  MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
1264  MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
1265  MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
1266  MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
1267  MsgHandler->bind("typeHierarchy/resolve", &ClangdLSPServer::onResolveTypeHierarchy);
1268  MsgHandler->bind("textDocument/selectionRange", &ClangdLSPServer::onSelectionRange);
1269  MsgHandler->bind("textDocument/documentLink", &ClangdLSPServer::onDocumentLink);
1270  // clang-format on
1271 }
1272 
1273 ClangdLSPServer::~ClangdLSPServer() { IsBeingDestroyed = true;
1274  // Explicitly destroy ClangdServer first, blocking on threads it owns.
1275  // This ensures they don't access any other members.
1276  Server.reset();
1277 }
1278 
1280  // Run the Language Server loop.
1281  bool CleanExit = true;
1282  if (auto Err = Transp.loop(*MsgHandler)) {
1283  elog("Transport error: {0}", std::move(Err));
1284  CleanExit = false;
1285  }
1286 
1287  return CleanExit && ShutdownRequestReceived;
1288 }
1289 
1290 std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
1291  const clangd::Diagnostic &D) {
1292  std::lock_guard<std::mutex> Lock(FixItsMutex);
1293  auto DiagToFixItsIter = FixItsMap.find(File);
1294  if (DiagToFixItsIter == FixItsMap.end())
1295  return {};
1296 
1297  const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1298  auto FixItsIter = DiagToFixItsMap.find(D);
1299  if (FixItsIter == DiagToFixItsMap.end())
1300  return {};
1301 
1302  return FixItsIter->second;
1303 }
1304 
1305 bool ClangdLSPServer::shouldRunCompletion(
1306  const CompletionParams &Params) const {
1307  llvm::StringRef Trigger = Params.context.triggerCharacter;
1309  (Trigger != ">" && Trigger != ":"))
1310  return true;
1311 
1312  auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1313  if (!Code)
1314  return true; // completion code will log the error for untracked doc.
1315 
1316  // A completion request is sent when the user types '>' or ':', but we only
1317  // want to trigger on '->' and '::'. We check the preceeding character to make
1318  // sure it matches what we expected.
1319  // Running the lexer here would be more robust (e.g. we can detect comments
1320  // and avoid triggering completion there), but we choose to err on the side
1321  // of simplicity here.
1322  auto Offset = positionToOffset(*Code, Params.position,
1323  /*AllowColumnsBeyondLineLength=*/false);
1324  if (!Offset) {
1325  vlog("could not convert position '{0}' to offset for file '{1}'",
1326  Params.position, Params.textDocument.uri.file());
1327  return true;
1328  }
1329  if (*Offset < 2)
1330  return false;
1331 
1332  if (Trigger == ">")
1333  return (*Code)[*Offset - 2] == '-'; // trigger only on '->'.
1334  if (Trigger == ":")
1335  return (*Code)[*Offset - 2] == ':'; // trigger only on '::'.
1336  assert(false && "unhandled trigger character");
1337  return true;
1338 }
1339 
1340 void ClangdLSPServer::onHighlightingsReady(
1341  PathRef File, std::vector<HighlightingToken> Highlightings) {
1342  std::vector<HighlightingToken> Old;
1343  std::vector<HighlightingToken> HighlightingsCopy = Highlightings;
1344  {
1345  std::lock_guard<std::mutex> Lock(HighlightingsMutex);
1346  Old = std::move(FileToHighlightings[File]);
1347  FileToHighlightings[File] = std::move(HighlightingsCopy);
1348  }
1349  // LSP allows us to send incremental edits of highlightings. Also need to diff
1350  // to remove highlightings from tokens that should no longer have them.
1351  std::vector<LineHighlightings> Diffed = diffHighlightings(Highlightings, Old);
1352  publishSemanticHighlighting(
1353  {{URIForFile::canonicalize(File, /*TUPath=*/File)},
1355 }
1356 
1357 void ClangdLSPServer::onDiagnosticsReady(PathRef File,
1358  std::vector<Diag> Diagnostics) {
1359  auto URI = URIForFile::canonicalize(File, /*TUPath=*/File);
1360  std::vector<Diagnostic> LSPDiagnostics;
1361  DiagnosticToReplacementMap LocalFixIts; // Temporary storage
1362  for (auto &Diag : Diagnostics) {
1363  toLSPDiags(Diag, URI, DiagOpts,
1364  [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
1365  auto &FixItsForDiagnostic = LocalFixIts[Diag];
1366  llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
1367  LSPDiagnostics.push_back(std::move(Diag));
1368  });
1369  }
1370 
1371  // Cache FixIts
1372  {
1373  std::lock_guard<std::mutex> Lock(FixItsMutex);
1374  FixItsMap[File] = LocalFixIts;
1375  }
1376 
1377  // Send a notification to the LSP client.
1378  publishDiagnostics(URI, std::move(LSPDiagnostics));
1379 }
1380 
1381 void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1382  if (!SupportFileStatus)
1383  return;
1384  // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1385  // two statuses are running faster in practice, which leads the UI constantly
1386  // changing, and doesn't provide much value. We may want to emit status at a
1387  // reasonable time interval (e.g. 0.5s).
1388  if (Status.Action.S == TUAction::BuildingFile ||
1389  Status.Action.S == TUAction::RunningAction)
1390  return;
1391  notify("textDocument/clangd.fileStatus", Status.render(File));
1392 }
1393 
1394 void ClangdLSPServer::reparseOpenedFiles() {
1395  for (const Path &FilePath : DraftMgr.getActiveFiles())
1396  Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
1398 }
1399 
1400 } // namespace clangd
1401 } // namespace clang
Range range
The range to format.
Definition: Protocol.h:607
const tooling::CompileCommand & Command
TextDocumentIdentifier textDocument
The document to format.
Definition: Protocol.h:625
std::string Code
Location location
The location of this symbol.
Definition: Protocol.h:837
llvm::StringRef Contents
Exact commands are not specified in the protocol so we define the ones supported by Clangd here...
Definition: Protocol.h:746
TextDocumentIdentifier textDocument
The document to format.
Definition: Protocol.h:613
llvm::Optional< SymbolKindBitset > WorkspaceSymbolKinds
The supported set of SymbolKinds for workspace/symbol.
Definition: Protocol.h:372
llvm::Optional< URIForFile > rootUri
The rootUri of the workspace.
Definition: Protocol.h:486
std::unique_ptr< GlobalCompilationDatabase > getQueryDriverDatabase(llvm::ArrayRef< std::string > QueryDriverGlobs, std::unique_ptr< GlobalCompilationDatabase > Base)
Extracts system include search path from drivers matching QueryDriverGlobs and adds them to the compi...
static std::vector< SymbolInformation > flattenSymbolHierarchy(llvm::ArrayRef< DocumentSymbol > Symbols, const URIForFile &FileURI)
The functions constructs a flattened view of the DocumentSymbol hierarchy.
Represents a collection of completion items to be presented in the editor.
Definition: Protocol.h:1017
Diagnostics must be generated for this snapshot.
llvm::Optional< bool > wantDiagnostics
Forces diagnostics to be generated, or to not be generated, for this version of the file...
Definition: Protocol.h:561
Range range
The range for which the command was invoked.
Definition: Protocol.h:706
std::function< void()> Canceler
A canceller requests cancellation of a task, when called.
Definition: Cancellation.h:70
FileStatus render(PathRef File) const
Serialize this to an LSP file status item.
CodeActionContext context
Context carrying additional information.
Definition: Protocol.h:709
bool onReply(llvm::json::Value ID, llvm::Expected< llvm::json::Value > Result) override
static const llvm::StringLiteral CLANGD_APPLY_FIX_COMMAND
Definition: Protocol.h:748
CompletionItemKind kind
The kind of this completion item.
Definition: Protocol.h:958
bool CompletionSnippets
Client supports snippets as insert text.
Definition: Protocol.h:389
std::string ch
The character that has been typed.
Definition: Protocol.h:619
Apply changes that preserve the behavior of the code.
Definition: Tweak.h:73
void bind(const char *Method, void(ClangdLSPServer::*Handler)(const Param &))
CodeAction toCodeAction(const Fix &F, const URIForFile &File)
Convert from Fix to LSP CodeAction.
Documents are synced by sending the full content on open.
llvm::Optional< std::map< std::string, std::vector< TextEdit > > > changes
Holds changes to existing resources.
Definition: Protocol.h:715
static cl::list< std::string > Commands("c", cl::desc("Specify command to run"), cl::value_desc("command"), cl::cat(ClangQueryCategory))
llvm::Optional< std::string > kind
The kind of the code action.
Definition: Protocol.h:777
std::string title
A short, human-readable, title for this code action.
Definition: Protocol.h:773
Provide information to the user.
Definition: Tweak.h:75
TextDocumentIdentifier textDocument
The document that was closed.
Definition: Protocol.h:532
bool run()
Run LSP server loop, communicating with the Transport provided in the constructor.
llvm::Optional< Location > Definition
Definition: XRefs.h:44
A code action represents a change that can be performed in code, e.g.
Definition: Protocol.h:771
URIForFile uri
The text document&#39;s URI.
Definition: Protocol.h:184
llvm::StringRef PathRef
A typedef to represent a ref to file path.
Definition: Path.h:23
llvm::Optional< WorkspaceEdit > edit
The workspace edit this code action performs.
Definition: Protocol.h:786
std::vector< CodeCompletionResult > Results
llvm::unique_function< void(llvm::Expected< T >)> Callback
A Callback<T> is a void function that accepts Expected<T>.
Definition: Function.h:28
constexpr auto SymbolKindMin
Definition: Protocol.h:329
The show message notification is sent from a server to a client to ask the client to display a partic...
Definition: Protocol.h:516
llvm::Optional< std::string > compilationDatabasePath
Definition: Protocol.h:459
constexpr auto CompletionItemKindMin
Definition: Protocol.h:289
std::bitset< CompletionItemKindMax+1 > CompletionItemKindBitset
Definition: Protocol.h:293
Documents should not be synced at all.
bool isIncomplete
The list is not complete.
Definition: Protocol.h:1020
Range range
The range enclosing this symbol not including leading/trailing whitespace but everything else like co...
Definition: Protocol.h:815
void vlog(const char *Fmt, Ts &&... Vals)
Definition: Logger.h:67
void elog(const char *Fmt, Ts &&... Vals)
Definition: Logger.h:56
Represents programming constructs like variables, classes, interfaces etc.
Definition: Protocol.h:798
static const llvm::StringLiteral CLANGD_APPLY_TWEAK
Definition: Protocol.h:750
bool onCall(llvm::StringRef Method, llvm::json::Value Params, llvm::json::Value ID) override
MarkupKind HoverContentFormat
The content format that should be used for Hover requests.
Definition: Protocol.h:425
MockFSProvider FSProvider
ConfigurationSettings ConfigSettings
Definition: Protocol.h:457
A top-level diagnostic that may have Notes and Fixes.
Definition: Diagnostics.h:84
bool OffsetsInSignatureHelp
Client supports processing label offsets instead of a simple label string.
Definition: Protocol.h:406
URIForFile uri
The text document&#39;s URI.
Definition: Protocol.h:220
bool CompletionFixes
Client supports completions with additionalTextEdit near the cursor.
Definition: Protocol.h:394
llvm::Optional< TweakArgs > tweakArgs
Definition: Protocol.h:757
static URI createFile(llvm::StringRef AbsolutePath)
This creates a file:// URI for AbsolutePath. The path must be absolute.
Definition: URI.cpp:226
TextDocumentIdentifier textDocument
The document that was opened.
Definition: Protocol.h:1083
void toLSPDiags(const Diag &D, const URIForFile &File, const ClangdDiagnosticOptions &Opts, llvm::function_ref< void(clangd::Diagnostic, llvm::ArrayRef< Fix >)> OutFn)
Conversion to LSP diagnostics.
bool DiagnosticCategory
Whether the client accepts diagnostics with category attached to it using the "category" extension...
Definition: Protocol.h:385
std::string newName
The new name of the symbol.
Definition: Protocol.h:1089
std::vector< SemanticHighlightingInformation > toSemanticHighlightingInformation(llvm::ArrayRef< LineHighlightings > Tokens)
Convert to LSP&#39;s semantic highlighting information.
std::string command
The command identifier, e.g. CLANGD_APPLY_FIX_COMMAND.
Definition: Protocol.h:753
InitializationOptions initializationOptions
User-provided initialization options.
Definition: Protocol.h:498
TextDocumentIdentifier textDocument
Definition: Protocol.h:631
llvm::Expected< size_t > positionToOffset(llvm::StringRef Code, Position P, bool AllowColumnsBeyondLineLength)
Turn a [line, column] pair into an offset in Code.
Definition: SourceCode.cpp:155
TextDocumentIdentifier textDocument
The document in which the command was invoked.
Definition: Protocol.h:703
static Location * getToggle(const TextDocumentPositionParams &Point, LocatedSymbol &Sym)
llvm::unique_function< void()> Action
std::vector< std::string > fallbackFlags
Definition: Protocol.h:463
std::string Signature
void log(const char *Fmt, Ts &&... Vals)
Definition: Logger.h:62
MessageType type
The message type.
Definition: Protocol.h:518
static const char * toString(OffsetEncoding OE)
Definition: Protocol.cpp:1031
std::string Path
A typedef to represent a file path.
Definition: Path.h:20
static const Context & current()
Returns the context for the current thread, creating it if needed.
Definition: Context.cpp:27
CompletionTriggerKind triggerKind
How the completion was triggered.
Definition: Protocol.h:905
static URIForFile canonicalize(llvm::StringRef AbsPath, llvm::StringRef TUPath)
Canonicalizes AbsPath via URI.
Definition: Protocol.cpp:32
Position position
The position inside the text document.
Definition: Protocol.h:888
enum clang::clangd::@771::NamespaceEvent::@3 Trigger
Key< OffsetEncoding > kCurrentOffsetEncoding
Definition: SourceCode.cpp:124
bool SemanticHighlighting
Client supports semantic highlighting.
Definition: Protocol.h:418
Location PreferredDeclaration
Definition: XRefs.h:42
std::vector< LineHighlightings > diffHighlightings(ArrayRef< HighlightingToken > New, ArrayRef< HighlightingToken > Old)
Return a line-by-line diff between two highlightings.
std::vector< DocumentSymbol > children
Children of this symbol, e.g. properties of a class.
Definition: Protocol.h:822
SymbolKind kind
The kind of this symbol.
Definition: Protocol.h:834
static const llvm::StringLiteral REFACTOR_KIND
Definition: Protocol.h:779
llvm::json::Value bindReply(Callback< llvm::json::Value > Reply)
bool FileStatus
Clients supports show file status for textDocument/clangd.fileStatus.
Definition: Protocol.h:466
SymbolSlab Symbols
std::string name
The name of this symbol.
Definition: Protocol.h:800
std::pair< Context, Canceler > cancelableTask()
Defines a new task whose cancellation may be requested.
static llvm::Optional< Command > asCommand(const CodeAction &Action)
bool DiagnosticFixes
Whether the client accepts diagnostics with codeActions attached inline.
Definition: Protocol.h:376
ClientCapabilities capabilities
The capabilities provided by the client (editor or tool)
Definition: Protocol.h:492
TextDocumentItem textDocument
The document that was opened.
Definition: Protocol.h:526
A context is an immutable container for per-request data that must be propagated through layers that ...
Definition: Context.h:69
TextDocumentIdentifier textDocument
The document that did change.
Definition: Protocol.h:552
Completion was triggered by a trigger character specified by the triggerCharacters properties of the ...
bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override
An information message.
llvm::Optional< CompletionItemKindBitset > CompletionItemKinds
The supported set of CompletionItemKinds for textDocument/completion.
Definition: Protocol.h:410
~ClangdLSPServer()
The destructor blocks on any outstanding background tasks.
llvm::Optional< std::string > rootPath
The rootPath of the workspace.
Definition: Protocol.h:481
virtual llvm::Error loop(MessageHandler &)=0
Position position
The position at which this request was sent.
Definition: Protocol.h:616
bool CodeActionStructure
Client supports CodeAction return value for textDocument/codeAction.
Definition: Protocol.h:414
WithContext replaces Context::current() with a provided scope.
Definition: Context.h:189
llvm::StringMap< Edit > FileEdits
A mapping from absolute file path (the one used for accessing the underlying VFS) to edits...
Definition: SourceCode.h:222
bool fromJSON(const llvm::json::Value &Parameters, FuzzyFindRequest &Request)
Definition: Index.cpp:34
void bind(const char *Method, void(ClangdLSPServer::*Handler)(const Param &, Callback< Result >))
size_t Offset
std::vector< TextDocumentContentChangeEvent > contentChanges
The actual content changes.
Definition: Protocol.h:555
CompletionContext context
Definition: Protocol.h:913
bool contains(Position Pos) const
Definition: Protocol.h:173
std::string query
A non-empty query string.
Definition: Protocol.h:868
SymbolKind kind
The kind of this symbol.
Definition: Protocol.h:806
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
std::bitset< SymbolKindMax+1 > SymbolKindBitset
Definition: Protocol.h:331
std::string triggerCharacter
The trigger character (a single character) that has trigger code complete.
Definition: Protocol.h:908
TextDocumentIdentifier textDocument
The text document.
Definition: Protocol.h:885
ClangdServer Server
static const llvm::StringLiteral INFO_KIND
Definition: Protocol.h:780
Context derive(const Key< Type > &Key, typename std::decay< Type >::type Value) const &
Derives a child context It is safe to move or destroy a parent context after calling derive()...
Definition: Context.h:121
virtual void reply(llvm::json::Value ID, llvm::Expected< llvm::json::Value > Result)=0
CharSourceRange Range
SourceRange for the file name.
SymbolKind adjustKindToCapability(SymbolKind Kind, SymbolKindBitset &SupportedSymbolKinds)
Definition: Protocol.cpp:198
static const llvm::StringLiteral QUICKFIX_KIND
Definition: Protocol.h:778
A URI describes the location of a source file.
Definition: URI.h:28
std::vector< Diagnostic > diagnostics
An array of diagnostics.
Definition: Protocol.h:697
llvm::Optional< Command > command
A command this code action executes.
Definition: Protocol.h:790
std::vector< TextEdit > replacementsToEdits(llvm::StringRef Code, const tooling::Replacements &Repls)
Definition: SourceCode.cpp:614
The parameters of a Workspace Symbol Request.
Definition: Protocol.h:866
std::vector< const char * > Expected
std::string text
The content of the opened text document.
Definition: Protocol.h:229
std::string containerName
The name of the symbol containing this symbol.
Definition: Protocol.h:840
Position position
The position at which this request was sent.
Definition: Protocol.h:1086
URIForFile uri
The text document&#39;s URI.
Definition: Protocol.h:122
std::string message
The actual message.
Definition: Protocol.h:520
bool HasSignatureHelp
Client supports signature help.
Definition: Protocol.h:402
bool DiagnosticRelatedInformation
Whether the client accepts diagnostics with related locations.
Definition: Protocol.h:380
TextDocumentIdentifier textDocument
The document to format.
Definition: Protocol.h:604
RefSlab Refs
llvm::Optional< WorkspaceEdit > workspaceEdit
Definition: Protocol.h:756
This class exposes ClangdServer&#39;s capabilities via Language Server Protocol.
llvm::json::Object *const Args
Mutable metadata, if this span is interested.
Definition: Trace.h:89
static CommandMangler detect()
std::string name
The name of this symbol.
Definition: Protocol.h:831
Records an event whose duration is the lifetime of the Span object.
Definition: Trace.h:81
bool RenamePrepareSupport
The client supports testing for validity of rename operations before execution.
Definition: Protocol.h:429
ClangdLSPServer(Transport &Transp, const FileSystemProvider &FSProvider, const clangd::CodeCompleteOptions &CCOpts, llvm::Optional< Path > CompileCommandsDir, bool UseDirBasedCDB, llvm::Optional< OffsetEncoding > ForcedOffsetEncoding, const ClangdServer::Options &Opts)
If CompileCommandsDir has a value, compile_commands.json will be loaded only from CompileCommandsDir...
#define SPAN_ATTACH(S, Name, Expr)
Attach a key-value pair to a Span event.
Definition: Trace.h:97
Diagnostics must not be generated for this snapshot.
A set of edits generated for a single file.
Definition: SourceCode.h:204
llvm::Optional< std::vector< OffsetEncoding > > offsetEncoding
Supported encodings for LSP character offsets. (clangd extension).
Definition: Protocol.h:421
bool HierarchicalDocumentSymbol
Client supports hierarchical document symbols.
Definition: Protocol.h:398
llvm::StringRef file() const
Retrieves absolute path to the file.
Definition: Protocol.h:93
const SymbolIndex * Index
Definition: Dexp.cpp:84
Represents information about programming constructs like variables, classes, interfaces etc...
Definition: Protocol.h:829