clang-tools  9.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 "Diagnostics.h"
11 #include "FormattedString.h"
13 #include "Protocol.h"
14 #include "SemanticHighlighting.h"
15 #include "SourceCode.h"
16 #include "Trace.h"
17 #include "URI.h"
18 #include "refactor/Tweak.h"
19 #include "clang/Tooling/Core/Replacement.h"
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/ScopeExit.h"
23 #include "llvm/Support/Errc.h"
24 #include "llvm/Support/Error.h"
25 #include "llvm/Support/FormatVariadic.h"
26 #include "llvm/Support/Path.h"
27 #include "llvm/Support/ScopedPrinter.h"
28 
29 namespace clang {
30 namespace clangd {
31 namespace {
32 /// Transforms a tweak into a code action that would apply it if executed.
33 /// EXPECTS: T.prepare() was called and returned true.
34 CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File,
35  Range Selection) {
36  CodeAction CA;
37  CA.title = T.Title;
38  switch (T.Intent) {
39  case Tweak::Refactor:
40  CA.kind = CodeAction::REFACTOR_KIND;
41  break;
42  case Tweak::Info:
43  CA.kind = CodeAction::INFO_KIND;
44  break;
45  }
46  // This tweak may have an expensive second stage, we only run it if the user
47  // actually chooses it in the UI. We reply with a command that would run the
48  // corresponding tweak.
49  // FIXME: for some tweaks, computing the edits is cheap and we could send them
50  // directly.
51  CA.command.emplace();
52  CA.command->title = T.Title;
53  CA.command->command = Command::CLANGD_APPLY_TWEAK;
54  CA.command->tweakArgs.emplace();
55  CA.command->tweakArgs->file = File;
56  CA.command->tweakArgs->tweakID = T.ID;
57  CA.command->tweakArgs->selection = Selection;
58  return CA;
59 }
60 
61 void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms,
62  SymbolKindBitset Kinds) {
63  for (auto &S : Syms) {
64  S.kind = adjustKindToCapability(S.kind, Kinds);
65  adjustSymbolKinds(S.children, Kinds);
66  }
67 }
68 
69 SymbolKindBitset defaultSymbolKinds() {
70  SymbolKindBitset Defaults;
71  for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array);
72  ++I)
73  Defaults.set(I);
74  return Defaults;
75 }
76 
77 CompletionItemKindBitset defaultCompletionItemKinds() {
78  CompletionItemKindBitset Defaults;
79  for (size_t I = CompletionItemKindMin;
80  I <= static_cast<size_t>(CompletionItemKind::Reference); ++I)
81  Defaults.set(I);
82  return Defaults;
83 }
84 
85 // Build a lookup table (HighlightingKind => {TextMate Scopes}), which is sent
86 // to the LSP client.
87 std::vector<std::vector<std::string>> buildHighlightScopeLookupTable() {
88  std::vector<std::vector<std::string>> LookupTable;
89  // HighlightingKind is using as the index.
90  for (int KindValue = 0; KindValue < (int)HighlightingKind::NumKinds;
91  ++KindValue)
92  LookupTable.push_back({toTextMateScope((HighlightingKind)(KindValue))});
93  return LookupTable;
94 }
95 
96 } // namespace
97 
98 // MessageHandler dispatches incoming LSP messages.
99 // It handles cross-cutting concerns:
100 // - serializes/deserializes protocol objects to JSON
101 // - logging of inbound messages
102 // - cancellation handling
103 // - basic call tracing
104 // MessageHandler ensures that initialize() is called before any other handler.
106 public:
107  MessageHandler(ClangdLSPServer &Server) : Server(Server) {}
108 
109  bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override {
110  WithContext HandlerContext(handlerContext());
111  log("<-- {0}", Method);
112  if (Method == "exit")
113  return false;
114  if (!Server.Server)
115  elog("Notification {0} before initialization", Method);
116  else if (Method == "$/cancelRequest")
117  onCancel(std::move(Params));
118  else if (auto Handler = Notifications.lookup(Method))
119  Handler(std::move(Params));
120  else
121  log("unhandled notification {0}", Method);
122  return true;
123  }
124 
125  bool onCall(llvm::StringRef Method, llvm::json::Value Params,
126  llvm::json::Value ID) override {
127  WithContext HandlerContext(handlerContext());
128  // Calls can be canceled by the client. Add cancellation context.
129  WithContext WithCancel(cancelableRequestContext(ID));
130  trace::Span Tracer(Method);
131  SPAN_ATTACH(Tracer, "Params", Params);
132  ReplyOnce Reply(ID, Method, &Server, Tracer.Args);
133  log("<-- {0}({1})", Method, ID);
134  if (!Server.Server && Method != "initialize") {
135  elog("Call {0} before initialization.", Method);
136  Reply(llvm::make_error<LSPError>("server not initialized",
138  } else if (auto Handler = Calls.lookup(Method))
139  Handler(std::move(Params), std::move(Reply));
140  else
141  Reply(llvm::make_error<LSPError>("method not found",
143  return true;
144  }
145 
146  bool onReply(llvm::json::Value ID,
147  llvm::Expected<llvm::json::Value> Result) override {
148  WithContext HandlerContext(handlerContext());
149  // We ignore replies, just log them.
150  if (Result)
151  log("<-- reply({0})", ID);
152  else
153  log("<-- reply({0}) error: {1}", ID, llvm::toString(Result.takeError()));
154  return true;
155  }
156 
157  // Bind an LSP method name to a call.
158  template <typename Param, typename Result>
159  void bind(const char *Method,
160  void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) {
161  Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams,
162  ReplyOnce Reply) {
163  Param P;
164  if (fromJSON(RawParams, P)) {
165  (Server.*Handler)(P, std::move(Reply));
166  } else {
167  elog("Failed to decode {0} request.", Method);
168  Reply(llvm::make_error<LSPError>("failed to decode request",
170  }
171  };
172  }
173 
174  // Bind an LSP method name to a notification.
175  template <typename Param>
176  void bind(const char *Method,
177  void (ClangdLSPServer::*Handler)(const Param &)) {
178  Notifications[Method] = [Method, Handler,
179  this](llvm::json::Value RawParams) {
180  Param P;
181  if (!fromJSON(RawParams, P)) {
182  elog("Failed to decode {0} request.", Method);
183  return;
184  }
185  trace::Span Tracer(Method);
186  SPAN_ATTACH(Tracer, "Params", RawParams);
187  (Server.*Handler)(P);
188  };
189  }
190 
191 private:
192  // Function object to reply to an LSP call.
193  // Each instance must be called exactly once, otherwise:
194  // - the bug is logged, and (in debug mode) an assert will fire
195  // - if there was no reply, an error reply is sent
196  // - if there were multiple replies, only the first is sent
197  class ReplyOnce {
198  std::atomic<bool> Replied = {false};
199  std::chrono::steady_clock::time_point Start;
200  llvm::json::Value ID;
201  std::string Method;
202  ClangdLSPServer *Server; // Null when moved-from.
203  llvm::json::Object *TraceArgs;
204 
205  public:
206  ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method,
207  ClangdLSPServer *Server, llvm::json::Object *TraceArgs)
208  : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method),
209  Server(Server), TraceArgs(TraceArgs) {
210  assert(Server);
211  }
212  ReplyOnce(ReplyOnce &&Other)
213  : Replied(Other.Replied.load()), Start(Other.Start),
214  ID(std::move(Other.ID)), Method(std::move(Other.Method)),
215  Server(Other.Server), TraceArgs(Other.TraceArgs) {
216  Other.Server = nullptr;
217  }
218  ReplyOnce &operator=(ReplyOnce &&) = delete;
219  ReplyOnce(const ReplyOnce &) = delete;
220  ReplyOnce &operator=(const ReplyOnce &) = delete;
221 
222  ~ReplyOnce() {
223  if (Server && !Replied) {
224  elog("No reply to message {0}({1})", Method, ID);
225  assert(false && "must reply to all calls!");
226  (*this)(llvm::make_error<LSPError>("server failed to reply",
228  }
229  }
230 
231  void operator()(llvm::Expected<llvm::json::Value> Reply) {
232  assert(Server && "moved-from!");
233  if (Replied.exchange(true)) {
234  elog("Replied twice to message {0}({1})", Method, ID);
235  assert(false && "must reply to each call only once!");
236  return;
237  }
238  auto Duration = std::chrono::steady_clock::now() - Start;
239  if (Reply) {
240  log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration);
241  if (TraceArgs)
242  (*TraceArgs)["Reply"] = *Reply;
243  std::lock_guard<std::mutex> Lock(Server->TranspWriter);
244  Server->Transp.reply(std::move(ID), std::move(Reply));
245  } else {
246  llvm::Error Err = Reply.takeError();
247  log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err);
248  if (TraceArgs)
249  (*TraceArgs)["Error"] = llvm::to_string(Err);
250  std::lock_guard<std::mutex> Lock(Server->TranspWriter);
251  Server->Transp.reply(std::move(ID), std::move(Err));
252  }
253  }
254  };
255 
256  llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications;
257  llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls;
258 
259  // Method calls may be cancelled by ID, so keep track of their state.
260  // This needs a mutex: handlers may finish on a different thread, and that's
261  // when we clean up entries in the map.
262  mutable std::mutex RequestCancelersMutex;
263  llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers;
264  unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below.
265  void onCancel(const llvm::json::Value &Params) {
266  const llvm::json::Value *ID = nullptr;
267  if (auto *O = Params.getAsObject())
268  ID = O->get("id");
269  if (!ID) {
270  elog("Bad cancellation request: {0}", Params);
271  return;
272  }
273  auto StrID = llvm::to_string(*ID);
274  std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
275  auto It = RequestCancelers.find(StrID);
276  if (It != RequestCancelers.end())
277  It->second.first(); // Invoke the canceler.
278  }
279 
280  Context handlerContext() const {
281  return Context::current().derive(
283  Server.NegotiatedOffsetEncoding.getValueOr(OffsetEncoding::UTF16));
284  }
285 
286  // We run cancelable requests in a context that does two things:
287  // - allows cancellation using RequestCancelers[ID]
288  // - cleans up the entry in RequestCancelers when it's no longer needed
289  // If a client reuses an ID, the last wins and the first cannot be canceled.
290  Context cancelableRequestContext(const llvm::json::Value &ID) {
291  auto Task = cancelableTask();
292  auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key.
293  auto Cookie = NextRequestCookie++; // No lock, only called on main thread.
294  {
295  std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
296  RequestCancelers[StrID] = {std::move(Task.second), Cookie};
297  }
298  // When the request ends, we can clean up the entry we just added.
299  // The cookie lets us check that it hasn't been overwritten due to ID
300  // reuse.
301  return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] {
302  std::lock_guard<std::mutex> Lock(RequestCancelersMutex);
303  auto It = RequestCancelers.find(StrID);
304  if (It != RequestCancelers.end() && It->second.second == Cookie)
305  RequestCancelers.erase(It);
306  }));
307  }
308 
310 };
311 
312 // call(), notify(), and reply() wrap the Transport, adding logging and locking.
313 void ClangdLSPServer::call(llvm::StringRef Method, llvm::json::Value Params) {
314  auto ID = NextCallID++;
315  log("--> {0}({1})", Method, ID);
316  // We currently don't handle responses, so no need to store ID anywhere.
317  std::lock_guard<std::mutex> Lock(TranspWriter);
318  Transp.call(Method, std::move(Params), ID);
319 }
320 
321 void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) {
322  log("--> {0}", Method);
323  std::lock_guard<std::mutex> Lock(TranspWriter);
324  Transp.notify(Method, std::move(Params));
325 }
326 
327 void ClangdLSPServer::onInitialize(const InitializeParams &Params,
329  // Determine character encoding first as it affects constructed ClangdServer.
330  if (Params.capabilities.offsetEncoding && !NegotiatedOffsetEncoding) {
331  NegotiatedOffsetEncoding = OffsetEncoding::UTF16; // fallback
332  for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding)
333  if (Supported != OffsetEncoding::UnsupportedEncoding) {
334  NegotiatedOffsetEncoding = Supported;
335  break;
336  }
337  }
338  llvm::Optional<WithContextValue> WithOffsetEncoding;
339  if (NegotiatedOffsetEncoding)
340  WithOffsetEncoding.emplace(kCurrentOffsetEncoding,
341  *NegotiatedOffsetEncoding);
342 
343  ClangdServerOpts.SemanticHighlighting =
345  if (Params.rootUri && *Params.rootUri)
346  ClangdServerOpts.WorkspaceRoot = Params.rootUri->file();
347  else if (Params.rootPath && !Params.rootPath->empty())
348  ClangdServerOpts.WorkspaceRoot = *Params.rootPath;
349  if (Server)
350  return Reply(llvm::make_error<LSPError>("server already initialized",
352  if (const auto &Dir = Params.initializationOptions.compilationDatabasePath)
353  CompileCommandsDir = Dir;
354  if (UseDirBasedCDB) {
355  BaseCDB = llvm::make_unique<DirectoryBasedGlobalCompilationDatabase>(
356  CompileCommandsDir);
357  BaseCDB = getQueryDriverDatabase(
358  llvm::makeArrayRef(ClangdServerOpts.QueryDriverGlobs),
359  std::move(BaseCDB));
360  }
361  CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags,
362  ClangdServerOpts.ResourceDir);
363  Server.emplace(*CDB, FSProvider, static_cast<DiagnosticsConsumer &>(*this),
364  ClangdServerOpts);
365  applyConfiguration(Params.initializationOptions.ConfigSettings);
366 
367  CCOpts.EnableSnippets = Params.capabilities.CompletionSnippets;
368  CCOpts.IncludeFixIts = Params.capabilities.CompletionFixes;
369  if (!CCOpts.BundleOverloads.hasValue())
370  CCOpts.BundleOverloads = Params.capabilities.HasSignatureHelp;
371  DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes;
372  DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory;
373  DiagOpts.EmitRelatedLocations =
376  SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds;
378  SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds;
379  SupportsCodeAction = Params.capabilities.CodeActionStructure;
380  SupportsHierarchicalDocumentSymbol =
382  SupportFileStatus = Params.initializationOptions.FileStatus;
383  HoverContentFormat = Params.capabilities.HoverContentFormat;
384  SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp;
385  llvm::json::Object Result{
386  {{"capabilities",
387  llvm::json::Object{
388  {"textDocumentSync", (int)TextDocumentSyncKind::Incremental},
389  {"documentFormattingProvider", true},
390  {"documentRangeFormattingProvider", true},
391  {"documentOnTypeFormattingProvider",
392  llvm::json::Object{
393  {"firstTriggerCharacter", "\n"},
394  {"moreTriggerCharacter", {}},
395  }},
396  {"codeActionProvider", true},
397  {"completionProvider",
398  llvm::json::Object{
399  {"resolveProvider", false},
400  // We do extra checks for '>' and ':' in completion to only
401  // trigger on '->' and '::'.
402  {"triggerCharacters", {".", ">", ":"}},
403  }},
404  {"signatureHelpProvider",
405  llvm::json::Object{
406  {"triggerCharacters", {"(", ","}},
407  }},
408  {"declarationProvider", true},
409  {"definitionProvider", true},
410  {"documentHighlightProvider", true},
411  {"hoverProvider", true},
412  {"renameProvider", true},
413  {"documentSymbolProvider", true},
414  {"workspaceSymbolProvider", true},
415  {"referencesProvider", true},
416  {"executeCommandProvider",
417  llvm::json::Object{
418  {"commands",
421  }},
422  {"typeHierarchyProvider", true},
423  }}}};
424  if (NegotiatedOffsetEncoding)
425  Result["offsetEncoding"] = *NegotiatedOffsetEncoding;
427  Result.getObject("capabilities")
428  ->insert(
429  {"semanticHighlighting",
430  llvm::json::Object{{"scopes", buildHighlightScopeLookupTable()}}});
431  Reply(std::move(Result));
432 }
433 
434 void ClangdLSPServer::onShutdown(const ShutdownParams &Params,
435  Callback<std::nullptr_t> Reply) {
436  // Do essentially nothing, just say we're ready to exit.
437  ShutdownRequestReceived = true;
438  Reply(nullptr);
439 }
440 
441 // sync is a clangd extension: it blocks until all background work completes.
442 // It blocks the calling thread, so no messages are processed until it returns!
443 void ClangdLSPServer::onSync(const NoParams &Params,
444  Callback<std::nullptr_t> Reply) {
445  if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60))
446  Reply(nullptr);
447  else
448  Reply(llvm::createStringError(llvm::inconvertibleErrorCode(),
449  "Not idle after a minute"));
450 }
451 
452 void ClangdLSPServer::onDocumentDidOpen(
453  const DidOpenTextDocumentParams &Params) {
454  PathRef File = Params.textDocument.uri.file();
455 
456  const std::string &Contents = Params.textDocument.text;
457 
458  DraftMgr.addDraft(File, Contents);
459  Server->addDocument(File, Contents, WantDiagnostics::Yes);
460 }
461 
462 void ClangdLSPServer::onDocumentDidChange(
463  const DidChangeTextDocumentParams &Params) {
464  auto WantDiags = WantDiagnostics::Auto;
465  if (Params.wantDiagnostics.hasValue())
466  WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes
468 
469  PathRef File = Params.textDocument.uri.file();
470  llvm::Expected<std::string> Contents =
471  DraftMgr.updateDraft(File, Params.contentChanges);
472  if (!Contents) {
473  // If this fails, we are most likely going to be not in sync anymore with
474  // the client. It is better to remove the draft and let further operations
475  // fail rather than giving wrong results.
476  DraftMgr.removeDraft(File);
477  Server->removeDocument(File);
478  elog("Failed to update {0}: {1}", File, Contents.takeError());
479  return;
480  }
481 
482  Server->addDocument(File, *Contents, WantDiags);
483 }
484 
485 void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) {
486  Server->onFileEvent(Params);
487 }
488 
489 void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params,
491  auto ApplyEdit = [this](WorkspaceEdit WE) {
493  Edit.edit = std::move(WE);
494  // Ideally, we would wait for the response and if there is no error, we
495  // would reply success/failure to the original RPC.
496  call("workspace/applyEdit", Edit);
497  };
499  Params.workspaceEdit) {
500  // The flow for "apply-fix" :
501  // 1. We publish a diagnostic, including fixits
502  // 2. The user clicks on the diagnostic, the editor asks us for code actions
503  // 3. We send code actions, with the fixit embedded as context
504  // 4. The user selects the fixit, the editor asks us to apply it
505  // 5. We unwrap the changes and send them back to the editor
506  // 6. The editor applies the changes (applyEdit), and sends us a reply (but
507  // we ignore it)
508 
509  Reply("Fix applied.");
510  ApplyEdit(*Params.workspaceEdit);
511  } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK &&
512  Params.tweakArgs) {
513  auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file());
514  if (!Code)
515  return Reply(llvm::createStringError(
516  llvm::inconvertibleErrorCode(),
517  "trying to apply a code action for a non-added file"));
518 
519  auto Action = [this, ApplyEdit](decltype(Reply) Reply, URIForFile File,
520  std::string Code,
521  llvm::Expected<Tweak::Effect> R) {
522  if (!R)
523  return Reply(R.takeError());
524 
525  if (R->ApplyEdit) {
526  WorkspaceEdit WE;
527  WE.changes.emplace();
528  (*WE.changes)[File.uri()] = replacementsToEdits(Code, *R->ApplyEdit);
529  ApplyEdit(std::move(WE));
530  }
531  if (R->ShowMessage) {
532  ShowMessageParams Msg;
533  Msg.message = *R->ShowMessage;
534  Msg.type = MessageType::Info;
535  notify("window/showMessage", Msg);
536  }
537  Reply("Tweak applied.");
538  };
539  Server->applyTweak(Params.tweakArgs->file.file(),
540  Params.tweakArgs->selection, Params.tweakArgs->tweakID,
541  Bind(Action, std::move(Reply), Params.tweakArgs->file,
542  std::move(*Code)));
543  } else {
544  // We should not get here because ExecuteCommandParams would not have
545  // parsed in the first place and this handler should not be called. But if
546  // more commands are added, this will be here has a safe guard.
547  Reply(llvm::make_error<LSPError>(
548  llvm::formatv("Unsupported command \"{0}\".", Params.command).str(),
550  }
551 }
552 
553 void ClangdLSPServer::onWorkspaceSymbol(
554  const WorkspaceSymbolParams &Params,
555  Callback<std::vector<SymbolInformation>> Reply) {
556  Server->workspaceSymbols(
557  Params.query, CCOpts.Limit,
558  Bind(
559  [this](decltype(Reply) Reply,
560  llvm::Expected<std::vector<SymbolInformation>> Items) {
561  if (!Items)
562  return Reply(Items.takeError());
563  for (auto &Sym : *Items)
564  Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds);
565 
566  Reply(std::move(*Items));
567  },
568  std::move(Reply)));
569 }
570 
571 void ClangdLSPServer::onRename(const RenameParams &Params,
572  Callback<WorkspaceEdit> Reply) {
573  Path File = Params.textDocument.uri.file();
574  llvm::Optional<std::string> Code = DraftMgr.getDraft(File);
575  if (!Code)
576  return Reply(llvm::make_error<LSPError>(
577  "onRename called for non-added file", ErrorCode::InvalidParams));
578 
579  Server->rename(
580  File, Params.position, Params.newName, /*WantFormat=*/true,
581  Bind(
582  [File, Code, Params](decltype(Reply) Reply,
583  llvm::Expected<std::vector<TextEdit>> Edits) {
584  if (!Edits)
585  return Reply(Edits.takeError());
586 
587  WorkspaceEdit WE;
588  WE.changes = {{Params.textDocument.uri.uri(), *Edits}};
589  Reply(WE);
590  },
591  std::move(Reply)));
592 }
593 
594 void ClangdLSPServer::onDocumentDidClose(
595  const DidCloseTextDocumentParams &Params) {
596  PathRef File = Params.textDocument.uri.file();
597  DraftMgr.removeDraft(File);
598  Server->removeDocument(File);
599 
600  {
601  std::lock_guard<std::mutex> Lock(FixItsMutex);
602  FixItsMap.erase(File);
603  }
604  // clangd will not send updates for this file anymore, so we empty out the
605  // list of diagnostics shown on the client (e.g. in the "Problems" pane of
606  // VSCode). Note that this cannot race with actual diagnostics responses
607  // because removeDocument() guarantees no diagnostic callbacks will be
608  // executed after it returns.
609  publishDiagnostics(URIForFile::canonicalize(File, /*TUPath=*/File), {});
610 }
611 
612 void ClangdLSPServer::onDocumentOnTypeFormatting(
613  const DocumentOnTypeFormattingParams &Params,
614  Callback<std::vector<TextEdit>> Reply) {
615  auto File = Params.textDocument.uri.file();
616  auto Code = DraftMgr.getDraft(File);
617  if (!Code)
618  return Reply(llvm::make_error<LSPError>(
619  "onDocumentOnTypeFormatting called for non-added file",
621 
622  Reply(Server->formatOnType(*Code, File, Params.position, Params.ch));
623 }
624 
625 void ClangdLSPServer::onDocumentRangeFormatting(
626  const DocumentRangeFormattingParams &Params,
627  Callback<std::vector<TextEdit>> Reply) {
628  auto File = Params.textDocument.uri.file();
629  auto Code = DraftMgr.getDraft(File);
630  if (!Code)
631  return Reply(llvm::make_error<LSPError>(
632  "onDocumentRangeFormatting called for non-added file",
634 
635  auto ReplacementsOrError = Server->formatRange(*Code, File, Params.range);
636  if (ReplacementsOrError)
637  Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
638  else
639  Reply(ReplacementsOrError.takeError());
640 }
641 
642 void ClangdLSPServer::onDocumentFormatting(
643  const DocumentFormattingParams &Params,
644  Callback<std::vector<TextEdit>> Reply) {
645  auto File = Params.textDocument.uri.file();
646  auto Code = DraftMgr.getDraft(File);
647  if (!Code)
648  return Reply(llvm::make_error<LSPError>(
649  "onDocumentFormatting called for non-added file",
651 
652  auto ReplacementsOrError = Server->formatFile(*Code, File);
653  if (ReplacementsOrError)
654  Reply(replacementsToEdits(*Code, ReplacementsOrError.get()));
655  else
656  Reply(ReplacementsOrError.takeError());
657 }
658 
659 /// The functions constructs a flattened view of the DocumentSymbol hierarchy.
660 /// Used by the clients that do not support the hierarchical view.
661 static std::vector<SymbolInformation>
662 flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols,
663  const URIForFile &FileURI) {
664 
665  std::vector<SymbolInformation> Results;
666  std::function<void(const DocumentSymbol &, llvm::StringRef)> Process =
667  [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) {
669  SI.containerName = ParentName ? "" : *ParentName;
670  SI.name = S.name;
671  SI.kind = S.kind;
672  SI.location.range = S.range;
673  SI.location.uri = FileURI;
674 
675  Results.push_back(std::move(SI));
676  std::string FullName =
677  !ParentName ? S.name : (ParentName->str() + "::" + S.name);
678  for (auto &C : S.children)
679  Process(C, /*ParentName=*/FullName);
680  };
681  for (auto &S : Symbols)
682  Process(S, /*ParentName=*/"");
683  return Results;
684 }
685 
686 void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params,
688  URIForFile FileURI = Params.textDocument.uri;
689  Server->documentSymbols(
690  Params.textDocument.uri.file(),
691  Bind(
692  [this, FileURI](decltype(Reply) Reply,
693  llvm::Expected<std::vector<DocumentSymbol>> Items) {
694  if (!Items)
695  return Reply(Items.takeError());
696  adjustSymbolKinds(*Items, SupportedSymbolKinds);
697  if (SupportsHierarchicalDocumentSymbol)
698  return Reply(std::move(*Items));
699  else
700  return Reply(flattenSymbolHierarchy(*Items, FileURI));
701  },
702  std::move(Reply)));
703 }
704 
705 static llvm::Optional<Command> asCommand(const CodeAction &Action) {
706  Command Cmd;
707  if (Action.command && Action.edit)
708  return None; // Not representable. (We never emit these anyway).
709  if (Action.command) {
710  Cmd = *Action.command;
711  } else if (Action.edit) {
712  Cmd.command = Command::CLANGD_APPLY_FIX_COMMAND;
713  Cmd.workspaceEdit = *Action.edit;
714  } else {
715  return None;
716  }
717  Cmd.title = Action.title;
718  if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND)
719  Cmd.title = "Apply fix: " + Cmd.title;
720  return Cmd;
721 }
722 
723 void ClangdLSPServer::onCodeAction(const CodeActionParams &Params,
725  URIForFile File = Params.textDocument.uri;
726  auto Code = DraftMgr.getDraft(File.file());
727  if (!Code)
728  return Reply(llvm::make_error<LSPError>(
729  "onCodeAction called for non-added file", ErrorCode::InvalidParams));
730  // We provide a code action for Fixes on the specified diagnostics.
731  std::vector<CodeAction> FixIts;
732  for (const Diagnostic &D : Params.context.diagnostics) {
733  for (auto &F : getFixes(File.file(), D)) {
734  FixIts.push_back(toCodeAction(F, Params.textDocument.uri));
735  FixIts.back().diagnostics = {D};
736  }
737  }
738 
739  // Now enumerate the semantic code actions.
740  auto ConsumeActions =
741  [this](decltype(Reply) Reply, URIForFile File, std::string Code,
742  Range Selection, std::vector<CodeAction> FixIts,
743  llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) {
744  if (!Tweaks)
745  return Reply(Tweaks.takeError());
746 
747  std::vector<CodeAction> Actions = std::move(FixIts);
748  Actions.reserve(Actions.size() + Tweaks->size());
749  for (const auto &T : *Tweaks)
750  Actions.push_back(toCodeAction(T, File, Selection));
751 
752  if (SupportsCodeAction)
753  return Reply(llvm::json::Array(Actions));
754  std::vector<Command> Commands;
755  for (const auto &Action : Actions) {
756  if (auto Command = asCommand(Action))
757  Commands.push_back(std::move(*Command));
758  }
759  return Reply(llvm::json::Array(Commands));
760  };
761 
762  Server->enumerateTweaks(File.file(), Params.range,
763  Bind(ConsumeActions, std::move(Reply), File,
764  std::move(*Code), Params.range,
765  std::move(FixIts)));
766 }
767 
768 void ClangdLSPServer::onCompletion(const CompletionParams &Params,
769  Callback<CompletionList> Reply) {
770  if (!shouldRunCompletion(Params)) {
771  // Clients sometimes auto-trigger completions in undesired places (e.g.
772  // 'a >^ '), we return empty results in those cases.
773  vlog("ignored auto-triggered completion, preceding char did not match");
774  return Reply(CompletionList());
775  }
776  Server->codeComplete(Params.textDocument.uri.file(), Params.position, CCOpts,
777  Bind(
778  [this](decltype(Reply) Reply,
779  llvm::Expected<CodeCompleteResult> List) {
780  if (!List)
781  return Reply(List.takeError());
782  CompletionList LSPList;
783  LSPList.isIncomplete = List->HasMore;
784  for (const auto &R : List->Completions) {
785  CompletionItem C = R.render(CCOpts);
787  C.kind, SupportedCompletionItemKinds);
788  LSPList.items.push_back(std::move(C));
789  }
790  return Reply(std::move(LSPList));
791  },
792  std::move(Reply)));
793 }
794 
795 void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params,
796  Callback<SignatureHelp> Reply) {
797  Server->signatureHelp(Params.textDocument.uri.file(), Params.position,
798  Bind(
799  [this](decltype(Reply) Reply,
800  llvm::Expected<SignatureHelp> Signature) {
801  if (!Signature)
802  return Reply(Signature.takeError());
803  if (SupportsOffsetsInSignatureHelp)
804  return Reply(std::move(*Signature));
805  // Strip out the offsets from signature help for
806  // clients that only support string labels.
807  for (auto &SigInfo : Signature->signatures) {
808  for (auto &Param : SigInfo.parameters)
809  Param.labelOffsets.reset();
810  }
811  return Reply(std::move(*Signature));
812  },
813  std::move(Reply)));
814 }
815 
816 // Go to definition has a toggle function: if def and decl are distinct, then
817 // the first press gives you the def, the second gives you the matching def.
818 // getToggle() returns the counterpart location that under the cursor.
819 //
820 // We return the toggled location alone (ignoring other symbols) to encourage
821 // editors to "bounce" quickly between locations, without showing a menu.
823  LocatedSymbol &Sym) {
824  // Toggle only makes sense with two distinct locations.
825  if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration)
826  return nullptr;
827  if (Sym.Definition->uri.file() == Point.textDocument.uri.file() &&
828  Sym.Definition->range.contains(Point.position))
829  return &Sym.PreferredDeclaration;
830  if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() &&
832  return &*Sym.Definition;
833  return nullptr;
834 }
835 
836 void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params,
837  Callback<std::vector<Location>> Reply) {
838  Server->locateSymbolAt(
839  Params.textDocument.uri.file(), Params.position,
840  Bind(
841  [&, Params](decltype(Reply) Reply,
842  llvm::Expected<std::vector<LocatedSymbol>> Symbols) {
843  if (!Symbols)
844  return Reply(Symbols.takeError());
845  std::vector<Location> Defs;
846  for (auto &S : *Symbols) {
847  if (Location *Toggle = getToggle(Params, S))
848  return Reply(std::vector<Location>{std::move(*Toggle)});
849  Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration));
850  }
851  Reply(std::move(Defs));
852  },
853  std::move(Reply)));
854 }
855 
856 void ClangdLSPServer::onGoToDeclaration(
857  const TextDocumentPositionParams &Params,
858  Callback<std::vector<Location>> Reply) {
859  Server->locateSymbolAt(
860  Params.textDocument.uri.file(), Params.position,
861  Bind(
862  [&, Params](decltype(Reply) Reply,
863  llvm::Expected<std::vector<LocatedSymbol>> Symbols) {
864  if (!Symbols)
865  return Reply(Symbols.takeError());
866  std::vector<Location> Decls;
867  for (auto &S : *Symbols) {
868  if (Location *Toggle = getToggle(Params, S))
869  return Reply(std::vector<Location>{std::move(*Toggle)});
870  Decls.push_back(std::move(S.PreferredDeclaration));
871  }
872  Reply(std::move(Decls));
873  },
874  std::move(Reply)));
875 }
876 
877 void ClangdLSPServer::onSwitchSourceHeader(
878  const TextDocumentIdentifier &Params,
879  Callback<llvm::Optional<URIForFile>> Reply) {
880  if (auto Result = Server->switchSourceHeader(Params.uri.file()))
881  Reply(URIForFile::canonicalize(*Result, Params.uri.file()));
882  else
883  Reply(llvm::None);
884 }
885 
886 void ClangdLSPServer::onDocumentHighlight(
887  const TextDocumentPositionParams &Params,
888  Callback<std::vector<DocumentHighlight>> Reply) {
889  Server->findDocumentHighlights(Params.textDocument.uri.file(),
890  Params.position, std::move(Reply));
891 }
892 
893 void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params,
894  Callback<llvm::Optional<Hover>> Reply) {
895  Server->findHover(Params.textDocument.uri.file(), Params.position,
896  Bind(
897  [this](decltype(Reply) Reply,
898  llvm::Expected<llvm::Optional<HoverInfo>> H) {
899  if (!H)
900  return Reply(H.takeError());
901  if (!*H)
902  return Reply(llvm::None);
903 
904  Hover R;
905  R.contents.kind = HoverContentFormat;
906  R.range = (*H)->SymRange;
907  switch (HoverContentFormat) {
909  R.contents.value =
910  (*H)->present().renderAsPlainText();
911  return Reply(std::move(R));
913  R.contents.value =
914  (*H)->present().renderAsMarkdown();
915  return Reply(std::move(R));
916  };
917  llvm_unreachable("unhandled MarkupKind");
918  },
919  std::move(Reply)));
920 }
921 
922 void ClangdLSPServer::onTypeHierarchy(
923  const TypeHierarchyParams &Params,
924  Callback<Optional<TypeHierarchyItem>> Reply) {
925  Server->typeHierarchy(Params.textDocument.uri.file(), Params.position,
926  Params.resolve, Params.direction, std::move(Reply));
927 }
928 
929 void ClangdLSPServer::onResolveTypeHierarchy(
930  const ResolveTypeHierarchyItemParams &Params,
931  Callback<Optional<TypeHierarchyItem>> Reply) {
932  Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction,
933  std::move(Reply));
934 }
935 
936 void ClangdLSPServer::applyConfiguration(
937  const ConfigurationSettings &Settings) {
938  // Per-file update to the compilation database.
939  bool ShouldReparseOpenFiles = false;
940  for (auto &Entry : Settings.compilationDatabaseChanges) {
941  /// The opened files need to be reparsed only when some existing
942  /// entries are changed.
943  PathRef File = Entry.first;
944  auto Old = CDB->getCompileCommand(File);
945  auto New =
946  tooling::CompileCommand(std::move(Entry.second.workingDirectory), File,
947  std::move(Entry.second.compilationCommand),
948  /*Output=*/"");
949  if (Old != New) {
950  CDB->setCompileCommand(File, std::move(New));
951  ShouldReparseOpenFiles = true;
952  }
953  }
954  if (ShouldReparseOpenFiles)
955  reparseOpenedFiles();
956 }
957 
958 void ClangdLSPServer::publishSemanticHighlighting(
959  SemanticHighlightingParams Params) {
960  notify("textDocument/semanticHighlighting", Params);
961 }
962 
963 void ClangdLSPServer::publishDiagnostics(
964  const URIForFile &File, std::vector<clangd::Diagnostic> Diagnostics) {
965  // Publish diagnostics.
966  notify("textDocument/publishDiagnostics",
967  llvm::json::Object{
968  {"uri", File},
969  {"diagnostics", std::move(Diagnostics)},
970  });
971 }
972 
973 // FIXME: This function needs to be properly tested.
974 void ClangdLSPServer::onChangeConfiguration(
975  const DidChangeConfigurationParams &Params) {
976  applyConfiguration(Params.settings);
977 }
978 
979 void ClangdLSPServer::onReference(const ReferenceParams &Params,
980  Callback<std::vector<Location>> Reply) {
981  Server->findReferences(Params.textDocument.uri.file(), Params.position,
982  CCOpts.Limit, std::move(Reply));
983 }
984 
985 void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params,
986  Callback<std::vector<SymbolDetails>> Reply) {
987  Server->symbolInfo(Params.textDocument.uri.file(), Params.position,
988  std::move(Reply));
989 }
990 
992  class Transport &Transp, const FileSystemProvider &FSProvider,
993  const clangd::CodeCompleteOptions &CCOpts,
994  llvm::Optional<Path> CompileCommandsDir, bool UseDirBasedCDB,
995  llvm::Optional<OffsetEncoding> ForcedOffsetEncoding,
996  const ClangdServer::Options &Opts)
997  : Transp(Transp), MsgHandler(new MessageHandler(*this)),
998  FSProvider(FSProvider), CCOpts(CCOpts),
999  SupportedSymbolKinds(defaultSymbolKinds()),
1000  SupportedCompletionItemKinds(defaultCompletionItemKinds()),
1001  UseDirBasedCDB(UseDirBasedCDB),
1002  CompileCommandsDir(std::move(CompileCommandsDir)), ClangdServerOpts(Opts),
1003  NegotiatedOffsetEncoding(ForcedOffsetEncoding) {
1004  // clang-format off
1005  MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize);
1006  MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown);
1007  MsgHandler->bind("sync", &ClangdLSPServer::onSync);
1008  MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting);
1009  MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting);
1010  MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting);
1011  MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction);
1012  MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion);
1013  MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp);
1014  MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition);
1015  MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration);
1016  MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference);
1017  MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader);
1018  MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename);
1019  MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover);
1020  MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol);
1021  MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand);
1022  MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight);
1023  MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol);
1024  MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen);
1025  MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose);
1026  MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange);
1027  MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent);
1028  MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration);
1029  MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo);
1030  MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy);
1031  MsgHandler->bind("typeHierarchy/resolve", &ClangdLSPServer::onResolveTypeHierarchy);
1032  // clang-format on
1033 }
1034 
1036 
1038  // Run the Language Server loop.
1039  bool CleanExit = true;
1040  if (auto Err = Transp.loop(*MsgHandler)) {
1041  elog("Transport error: {0}", std::move(Err));
1042  CleanExit = false;
1043  }
1044 
1045  // Destroy ClangdServer to ensure all worker threads finish.
1046  Server.reset();
1047  return CleanExit && ShutdownRequestReceived;
1048 }
1049 
1050 std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File,
1051  const clangd::Diagnostic &D) {
1052  std::lock_guard<std::mutex> Lock(FixItsMutex);
1053  auto DiagToFixItsIter = FixItsMap.find(File);
1054  if (DiagToFixItsIter == FixItsMap.end())
1055  return {};
1056 
1057  const auto &DiagToFixItsMap = DiagToFixItsIter->second;
1058  auto FixItsIter = DiagToFixItsMap.find(D);
1059  if (FixItsIter == DiagToFixItsMap.end())
1060  return {};
1061 
1062  return FixItsIter->second;
1063 }
1064 
1065 bool ClangdLSPServer::shouldRunCompletion(
1066  const CompletionParams &Params) const {
1067  llvm::StringRef Trigger = Params.context.triggerCharacter;
1069  (Trigger != ">" && Trigger != ":"))
1070  return true;
1071 
1072  auto Code = DraftMgr.getDraft(Params.textDocument.uri.file());
1073  if (!Code)
1074  return true; // completion code will log the error for untracked doc.
1075 
1076  // A completion request is sent when the user types '>' or ':', but we only
1077  // want to trigger on '->' and '::'. We check the preceeding character to make
1078  // sure it matches what we expected.
1079  // Running the lexer here would be more robust (e.g. we can detect comments
1080  // and avoid triggering completion there), but we choose to err on the side
1081  // of simplicity here.
1082  auto Offset = positionToOffset(*Code, Params.position,
1083  /*AllowColumnsBeyondLineLength=*/false);
1084  if (!Offset) {
1085  vlog("could not convert position '{0}' to offset for file '{1}'",
1086  Params.position, Params.textDocument.uri.file());
1087  return true;
1088  }
1089  if (*Offset < 2)
1090  return false;
1091 
1092  if (Trigger == ">")
1093  return (*Code)[*Offset - 2] == '-'; // trigger only on '->'.
1094  if (Trigger == ":")
1095  return (*Code)[*Offset - 2] == ':'; // trigger only on '::'.
1096  assert(false && "unhandled trigger character");
1097  return true;
1098 }
1099 
1100 void ClangdLSPServer::onHighlightingsReady(
1101  PathRef File, std::vector<HighlightingToken> Highlightings) {
1102  publishSemanticHighlighting(
1103  {{URIForFile::canonicalize(File, /*TUPath=*/File)},
1104  toSemanticHighlightingInformation(Highlightings)});
1105 }
1106 
1107 void ClangdLSPServer::onDiagnosticsReady(PathRef File,
1108  std::vector<Diag> Diagnostics) {
1109  auto URI = URIForFile::canonicalize(File, /*TUPath=*/File);
1110  std::vector<Diagnostic> LSPDiagnostics;
1111  DiagnosticToReplacementMap LocalFixIts; // Temporary storage
1112  for (auto &Diag : Diagnostics) {
1113  toLSPDiags(Diag, URI, DiagOpts,
1114  [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) {
1115  auto &FixItsForDiagnostic = LocalFixIts[Diag];
1116  llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic));
1117  LSPDiagnostics.push_back(std::move(Diag));
1118  });
1119  }
1120 
1121  // Cache FixIts
1122  {
1123  std::lock_guard<std::mutex> Lock(FixItsMutex);
1124  FixItsMap[File] = LocalFixIts;
1125  }
1126 
1127  // Send a notification to the LSP client.
1128  publishDiagnostics(URI, std::move(LSPDiagnostics));
1129 }
1130 
1131 void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) {
1132  if (!SupportFileStatus)
1133  return;
1134  // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these
1135  // two statuses are running faster in practice, which leads the UI constantly
1136  // changing, and doesn't provide much value. We may want to emit status at a
1137  // reasonable time interval (e.g. 0.5s).
1138  if (Status.Action.S == TUAction::BuildingFile ||
1139  Status.Action.S == TUAction::RunningAction)
1140  return;
1141  notify("textDocument/clangd.fileStatus", Status.render(File));
1142 }
1143 
1144 void ClangdLSPServer::reparseOpenedFiles() {
1145  for (const Path &FilePath : DraftMgr.getActiveFiles())
1146  Server->addDocument(FilePath, *DraftMgr.getDraft(FilePath),
1148 }
1149 
1150 } // namespace clangd
1151 } // namespace clang
Range range
The range to format.
Definition: Protocol.h:602
const tooling::CompileCommand & Command
TextDocumentIdentifier textDocument
The document to format.
Definition: Protocol.h:620
Location location
The location of this symbol.
Definition: Protocol.h:832
llvm::StringRef Contents
Exact commands are not specified in the protocol so we define the ones supported by Clangd here...
Definition: Protocol.h:741
TextDocumentIdentifier textDocument
The document to format.
Definition: Protocol.h:608
llvm::Optional< SymbolKindBitset > WorkspaceSymbolKinds
The supported set of SymbolKinds for workspace/symbol.
Definition: Protocol.h:371
llvm::Optional< URIForFile > rootUri
The rootUri of the workspace.
Definition: Protocol.h:481
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:999
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:556
Range range
The range for which the command was invoked.
Definition: Protocol.h:701
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:704
bool onReply(llvm::json::Value ID, llvm::Expected< llvm::json::Value > Result) override
static const llvm::StringLiteral CLANGD_APPLY_FIX_COMMAND
Definition: Protocol.h:743
CompletionItemKind kind
The kind of this completion item.
Definition: Protocol.h:947
bool CompletionSnippets
Client supports snippets as insert text.
Definition: Protocol.h:388
std::string ch
The character that has been typed.
Definition: Protocol.h:614
Apply changes that preserve the behavior of the code.
Definition: Tweak.h:63
std::vector< CompletionItem > items
The completion items.
Definition: Protocol.h:1005
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:710
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:772
std::string title
A short, human-readable, title for this code action.
Definition: Protocol.h:768
Provide information to the user.
Definition: Tweak.h:65
TextDocumentIdentifier textDocument
The document that was closed.
Definition: Protocol.h:527
bool run()
Run LSP server loop, communicating with the Transport provided in the constructor.
llvm::Optional< Location > Definition
Definition: XRefs.h:41
A code action represents a change that can be performed in code, e.g.
Definition: Protocol.h:766
URIForFile uri
The text document&#39;s URI.
Definition: Protocol.h:183
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:781
static llvm::StringRef toString(SpecialMemberFunctionsCheck::SpecialMemberFunctionKind K)
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:328
The show message notification is sent from a server to a client to ask the client to display a partic...
Definition: Protocol.h:511
llvm::Optional< std::string > compilationDatabasePath
Definition: Protocol.h:454
constexpr auto CompletionItemKindMin
Definition: Protocol.h:288
std::bitset< CompletionItemKindMax+1 > CompletionItemKindBitset
Definition: Protocol.h:292
Documents should not be synced at all.
bool isIncomplete
The list is not complete.
Definition: Protocol.h:1002
Range range
The range enclosing this symbol not including leading/trailing whitespace but everything else like co...
Definition: Protocol.h:810
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:793
static const llvm::StringLiteral CLANGD_APPLY_TWEAK
Definition: Protocol.h:745
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:424
MockFSProvider FSProvider
ConfigurationSettings ConfigSettings
Definition: Protocol.h:452
A top-level diagnostic that may have Notes and Fixes.
Definition: Diagnostics.h:84
std::string uri() const
Definition: Protocol.h:95
bool OffsetsInSignatureHelp
Client supports processing label offsets instead of a simple label string.
Definition: Protocol.h:405
URIForFile uri
The text document&#39;s URI.
Definition: Protocol.h:219
bool CompletionFixes
Client supports completions with additionalTextEdit near the cursor.
Definition: Protocol.h:393
llvm::Optional< TweakArgs > tweakArgs
Definition: Protocol.h:752
TextDocumentIdentifier textDocument
The document that was opened.
Definition: Protocol.h:1065
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:384
std::string newName
The new name of the symbol.
Definition: Protocol.h:1071
std::string command
The command identifier, e.g. CLANGD_APPLY_FIX_COMMAND.
Definition: Protocol.h:748
InitializationOptions initializationOptions
User-provided initialization options.
Definition: Protocol.h:493
TextDocumentIdentifier textDocument
Definition: Protocol.h:626
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:141
ForwardBinder< Func, Args... > Bind(Func F, Args &&... As)
Creates an object that stores a callable (F) and first arguments to the callable (As) and allows to c...
Definition: Function.h:81
TextDocumentIdentifier textDocument
The document in which the command was invoked.
Definition: Protocol.h:698
static Location * getToggle(const TextDocumentPositionParams &Point, LocatedSymbol &Sym)
llvm::unique_function< void()> Action
std::vector< std::string > fallbackFlags
Definition: Protocol.h:458
std::string Signature
void log(const char *Fmt, Ts &&... Vals)
Definition: Logger.h:62
MessageType type
The message type.
Definition: Protocol.h:513
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:894
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:877
Key< OffsetEncoding > kCurrentOffsetEncoding
Definition: SourceCode.cpp:110
bool SemanticHighlighting
Client supports semantic highlighting.
Definition: Protocol.h:417
Location PreferredDeclaration
Definition: XRefs.h:39
std::vector< DocumentSymbol > children
Children of this symbol, e.g. properties of a class.
Definition: Protocol.h:817
const Decl * D
Definition: XRefs.cpp:868
SymbolKind kind
The kind of this symbol.
Definition: Protocol.h:829
static const llvm::StringLiteral REFACTOR_KIND
Definition: Protocol.h:774
bool FileStatus
Clients supports show file status for textDocument/clangd.fileStatus.
Definition: Protocol.h:461
SymbolSlab Symbols
std::string name
The name of this symbol.
Definition: Protocol.h:795
std::pair< Context, Canceler > cancelableTask()
Defines a new task whose cancellation may be requested.
static llvm::Optional< Command > asCommand(const CodeAction &Action)
std::vector< SemanticHighlightingInformation > toSemanticHighlightingInformation(llvm::ArrayRef< HighlightingToken > Tokens)
bool DiagnosticFixes
Whether the client accepts diagnostics with codeActions attached inline.
Definition: Protocol.h:375
ClientCapabilities capabilities
The capabilities provided by the client (editor or tool)
Definition: Protocol.h:487
TextDocumentItem textDocument
The document that was opened.
Definition: Protocol.h:521
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:547
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:409
llvm::Optional< std::string > rootPath
The rootPath of the workspace.
Definition: Protocol.h:476
virtual llvm::Error loop(MessageHandler &)=0
Position position
The position at which this request was sent.
Definition: Protocol.h:611
bool CodeActionStructure
Client supports CodeAction return value for textDocument/codeAction.
Definition: Protocol.h:413
WithContext replaces Context::current() with a provided scope.
Definition: Context.h:189
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:550
CompletionContext context
Definition: Protocol.h:902
bool contains(Position Pos) const
Definition: Protocol.h:172
std::string query
A non-empty query string.
Definition: Protocol.h:863
SymbolKind kind
The kind of this symbol.
Definition: Protocol.h:801
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
std::bitset< SymbolKindMax+1 > SymbolKindBitset
Definition: Protocol.h:330
std::string triggerCharacter
The trigger character (a single character) that has trigger code complete.
Definition: Protocol.h:897
TextDocumentIdentifier textDocument
The text document.
Definition: Protocol.h:874
ClangdServer Server
static const llvm::StringLiteral INFO_KIND
Definition: Protocol.h:775
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:773
A URI describes the location of a source file.
Definition: URI.h:28
std::vector< Diagnostic > diagnostics
An array of diagnostics.
Definition: Protocol.h:692
llvm::Optional< Command > command
A command this code action executes.
Definition: Protocol.h:785
llvm::Optional< llvm::Expected< tooling::AtomicChanges > > Result
Definition: Rename.cpp:36
std::vector< TextEdit > replacementsToEdits(llvm::StringRef Code, const tooling::Replacements &Repls)
Definition: SourceCode.cpp:451
The parameters of a Workspace Symbol Request.
Definition: Protocol.h:861
std::vector< const char * > Expected
std::string text
The content of the opened text document.
Definition: Protocol.h:228
std::string containerName
The name of the symbol containing this symbol.
Definition: Protocol.h:835
Position position
The position at which this request was sent.
Definition: Protocol.h:1068
URIForFile uri
The text document&#39;s URI.
Definition: Protocol.h:121
std::string message
The actual message.
Definition: Protocol.h:515
bool HasSignatureHelp
Client supports signature help.
Definition: Protocol.h:401
bool DiagnosticRelatedInformation
Whether the client accepts diagnostics with related locations.
Definition: Protocol.h:379
std::vector< Path > getActiveFiles() const
Definition: DraftStore.cpp:26
TextDocumentIdentifier textDocument
The document to format.
Definition: Protocol.h:599
llvm::Optional< WorkspaceEdit > workspaceEdit
Definition: Protocol.h:751
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:90
std::string name
The name of this symbol.
Definition: Protocol.h:826
Records an event whose duration is the lifetime of the Span object.
Definition: Trace.h:82
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:98
Diagnostics must not be generated for this snapshot.
llvm::Optional< std::vector< OffsetEncoding > > offsetEncoding
Supported encodings for LSP character offsets. (clangd extension).
Definition: Protocol.h:420
llvm::Optional< std::string > getDraft(PathRef File) const
Definition: DraftStore.cpp:16
bool HierarchicalDocumentSymbol
Client supports hierarchical document symbols.
Definition: Protocol.h:397
llvm::StringRef file() const
Retrieves absolute path to the file.
Definition: Protocol.h:92
Represents information about programming constructs like variables, classes, interfaces etc...
Definition: Protocol.h:824