clang-tools  15.0.0git
Hover.cpp
Go to the documentation of this file.
1 //===--- Hover.cpp - Information about code at the cursor location --------===//
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 "Hover.h"
10 
11 #include "AST.h"
12 #include "CodeCompletionStrings.h"
13 #include "Config.h"
14 #include "FindTarget.h"
15 #include "ParsedAST.h"
16 #include "Selection.h"
17 #include "SourceCode.h"
18 #include "index/SymbolCollector.h"
19 #include "support/Markup.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/ASTDiagnostic.h"
22 #include "clang/AST/ASTTypeTraits.h"
23 #include "clang/AST/Attr.h"
24 #include "clang/AST/Decl.h"
25 #include "clang/AST/DeclBase.h"
26 #include "clang/AST/DeclCXX.h"
27 #include "clang/AST/DeclObjC.h"
28 #include "clang/AST/DeclTemplate.h"
29 #include "clang/AST/Expr.h"
30 #include "clang/AST/ExprCXX.h"
31 #include "clang/AST/OperationKinds.h"
32 #include "clang/AST/PrettyPrinter.h"
33 #include "clang/AST/RecordLayout.h"
34 #include "clang/AST/Type.h"
35 #include "clang/Basic/SourceLocation.h"
36 #include "clang/Basic/Specifiers.h"
37 #include "clang/Basic/TokenKinds.h"
38 #include "clang/Index/IndexSymbol.h"
39 #include "clang/Tooling/Syntax/Tokens.h"
40 #include "llvm/ADT/None.h"
41 #include "llvm/ADT/Optional.h"
42 #include "llvm/ADT/STLExtras.h"
43 #include "llvm/ADT/SmallVector.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/StringRef.h"
46 #include "llvm/Support/Casting.h"
47 #include "llvm/Support/Format.h"
48 #include "llvm/Support/ScopedPrinter.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include <string>
51 
52 namespace clang {
53 namespace clangd {
54 namespace {
55 
56 PrintingPolicy getPrintingPolicy(PrintingPolicy Base) {
57  Base.AnonymousTagLocations = false;
58  Base.TerseOutput = true;
59  Base.PolishForDeclaration = true;
60  Base.ConstantsAsWritten = true;
61  Base.SuppressTemplateArgsInCXXConstructors = true;
62  return Base;
63 }
64 
65 /// Given a declaration \p D, return a human-readable string representing the
66 /// local scope in which it is declared, i.e. class(es) and method name. Returns
67 /// an empty string if it is not local.
68 std::string getLocalScope(const Decl *D) {
69  std::vector<std::string> Scopes;
70  const DeclContext *DC = D->getDeclContext();
71 
72  // ObjC scopes won't have multiple components for us to join, instead:
73  // - Methods: "-[Class methodParam1:methodParam2]"
74  // - Classes, categories, and protocols: "MyClass(Category)"
75  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
76  return printObjCMethod(*MD);
77  if (const ObjCContainerDecl *CD = dyn_cast<ObjCContainerDecl>(DC))
78  return printObjCContainer(*CD);
79 
80  auto GetName = [](const TypeDecl *D) {
81  if (!D->getDeclName().isEmpty()) {
82  PrintingPolicy Policy = D->getASTContext().getPrintingPolicy();
83  Policy.SuppressScope = true;
84  return declaredType(D).getAsString(Policy);
85  }
86  if (auto *RD = dyn_cast<RecordDecl>(D))
87  return ("(anonymous " + RD->getKindName() + ")").str();
88  return std::string("");
89  };
90  while (DC) {
91  if (const TypeDecl *TD = dyn_cast<TypeDecl>(DC))
92  Scopes.push_back(GetName(TD));
93  else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
94  Scopes.push_back(FD->getNameAsString());
95  DC = DC->getParent();
96  }
97 
98  return llvm::join(llvm::reverse(Scopes), "::");
99 }
100 
101 /// Returns the human-readable representation for namespace containing the
102 /// declaration \p D. Returns empty if it is contained global namespace.
103 std::string getNamespaceScope(const Decl *D) {
104  const DeclContext *DC = D->getDeclContext();
105 
106  // ObjC does not have the concept of namespaces, so instead we support
107  // local scopes.
108  if (isa<ObjCMethodDecl, ObjCContainerDecl>(DC))
109  return "";
110 
111  if (const TagDecl *TD = dyn_cast<TagDecl>(DC))
112  return getNamespaceScope(TD);
113  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
114  return getNamespaceScope(FD);
115  if (const NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(DC)) {
116  // Skip inline/anon namespaces.
117  if (NSD->isInline() || NSD->isAnonymousNamespace())
118  return getNamespaceScope(NSD);
119  }
120  if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
121  return printQualifiedName(*ND);
122 
123  return "";
124 }
125 
126 std::string printDefinition(const Decl *D, PrintingPolicy PP,
127  const syntax::TokenBuffer &TB) {
128  if (auto *VD = llvm::dyn_cast<VarDecl>(D)) {
129  if (auto *IE = VD->getInit()) {
130  // Initializers might be huge and result in lots of memory allocations in
131  // some catostrophic cases. Such long lists are not useful in hover cards
132  // anyway.
133  if (200 < TB.expandedTokens(IE->getSourceRange()).size())
134  PP.SuppressInitializers = true;
135  }
136  }
137  std::string Definition;
138  llvm::raw_string_ostream OS(Definition);
139  D->print(OS, PP);
140  OS.flush();
141  return Definition;
142 }
143 
144 const char *getMarkdownLanguage(const ASTContext &Ctx) {
145  const auto &LangOpts = Ctx.getLangOpts();
146  if (LangOpts.ObjC && LangOpts.CPlusPlus)
147  return "objective-cpp";
148  return LangOpts.ObjC ? "objective-c" : "cpp";
149 }
150 
151 HoverInfo::PrintedType printType(QualType QT, ASTContext &ASTCtx,
152  const PrintingPolicy &PP) {
153  // TypePrinter doesn't resolve decltypes, so resolve them here.
154  // FIXME: This doesn't handle composite types that contain a decltype in them.
155  // We should rather have a printing policy for that.
156  while (!QT.isNull() && QT->isDecltypeType())
157  QT = QT->castAs<DecltypeType>()->getUnderlyingType();
158  HoverInfo::PrintedType Result;
159  llvm::raw_string_ostream OS(Result.Type);
160  // Special case: if the outer type is a tag type without qualifiers, then
161  // include the tag for extra clarity.
162  // This isn't very idiomatic, so don't attempt it for complex cases, including
163  // pointers/references, template specializations, etc.
164  if (!QT.isNull() && !QT.hasQualifiers() && PP.SuppressTagKeyword) {
165  if (auto *TT = llvm::dyn_cast<TagType>(QT.getTypePtr()))
166  OS << TT->getDecl()->getKindName() << " ";
167  }
168  QT.print(OS, PP);
169  OS.flush();
170 
171  const Config &Cfg = Config::current();
172  if (!QT.isNull() && Cfg.Hover.ShowAKA) {
173  bool ShouldAKA = false;
174  QualType DesugaredTy = clang::desugarForDiagnostic(ASTCtx, QT, ShouldAKA);
175  if (ShouldAKA)
176  Result.AKA = DesugaredTy.getAsString(PP);
177  }
178  return Result;
179 }
180 
181 HoverInfo::PrintedType printType(const TemplateTypeParmDecl *TTP) {
182  HoverInfo::PrintedType Result;
183  Result.Type = TTP->wasDeclaredWithTypename() ? "typename" : "class";
184  if (TTP->isParameterPack())
185  Result.Type += "...";
186  return Result;
187 }
188 
189 HoverInfo::PrintedType printType(const NonTypeTemplateParmDecl *NTTP,
190  const PrintingPolicy &PP) {
191  auto PrintedType = printType(NTTP->getType(), NTTP->getASTContext(), PP);
192  if (NTTP->isParameterPack()) {
193  PrintedType.Type += "...";
194  if (PrintedType.AKA)
195  *PrintedType.AKA += "...";
196  }
197  return PrintedType;
198 }
199 
200 HoverInfo::PrintedType printType(const TemplateTemplateParmDecl *TTP,
201  const PrintingPolicy &PP) {
202  HoverInfo::PrintedType Result;
203  llvm::raw_string_ostream OS(Result.Type);
204  OS << "template <";
205  llvm::StringRef Sep = "";
206  for (const Decl *Param : *TTP->getTemplateParameters()) {
207  OS << Sep;
208  Sep = ", ";
209  if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
210  OS << printType(TTP).Type;
211  else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
212  OS << printType(NTTP, PP).Type;
213  else if (const auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param))
214  OS << printType(TTPD, PP).Type;
215  }
216  // FIXME: TemplateTemplateParameter doesn't store the info on whether this
217  // param was a "typename" or "class".
218  OS << "> class";
219  OS.flush();
220  return Result;
221 }
222 
223 std::vector<HoverInfo::Param>
224 fetchTemplateParameters(const TemplateParameterList *Params,
225  const PrintingPolicy &PP) {
226  assert(Params);
227  std::vector<HoverInfo::Param> TempParameters;
228 
229  for (const Decl *Param : *Params) {
230  HoverInfo::Param P;
231  if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
232  P.Type = printType(TTP);
233 
234  if (!TTP->getName().empty())
235  P.Name = TTP->getNameAsString();
236 
237  if (TTP->hasDefaultArgument())
238  P.Default = TTP->getDefaultArgument().getAsString(PP);
239  } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
240  P.Type = printType(NTTP, PP);
241 
242  if (IdentifierInfo *II = NTTP->getIdentifier())
243  P.Name = II->getName().str();
244 
245  if (NTTP->hasDefaultArgument()) {
246  P.Default.emplace();
247  llvm::raw_string_ostream Out(*P.Default);
248  NTTP->getDefaultArgument()->printPretty(Out, nullptr, PP);
249  }
250  } else if (const auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param)) {
251  P.Type = printType(TTPD, PP);
252 
253  if (!TTPD->getName().empty())
254  P.Name = TTPD->getNameAsString();
255 
256  if (TTPD->hasDefaultArgument()) {
257  P.Default.emplace();
258  llvm::raw_string_ostream Out(*P.Default);
259  TTPD->getDefaultArgument().getArgument().print(PP, Out,
260  /*IncludeType*/ false);
261  }
262  }
263  TempParameters.push_back(std::move(P));
264  }
265 
266  return TempParameters;
267 }
268 
269 const FunctionDecl *getUnderlyingFunction(const Decl *D) {
270  // Extract lambda from variables.
271  if (const VarDecl *VD = llvm::dyn_cast<VarDecl>(D)) {
272  auto QT = VD->getType();
273  if (!QT.isNull()) {
274  while (!QT->getPointeeType().isNull())
275  QT = QT->getPointeeType();
276 
277  if (const auto *CD = QT->getAsCXXRecordDecl())
278  return CD->getLambdaCallOperator();
279  }
280  }
281 
282  // Non-lambda functions.
283  return D->getAsFunction();
284 }
285 
286 // Returns the decl that should be used for querying comments, either from index
287 // or AST.
288 const NamedDecl *getDeclForComment(const NamedDecl *D) {
289  const NamedDecl *DeclForComment = D;
290  if (const auto *TSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(D)) {
291  // Template may not be instantiated e.g. if the type didn't need to be
292  // complete; fallback to primary template.
293  if (TSD->getTemplateSpecializationKind() == TSK_Undeclared)
294  DeclForComment = TSD->getSpecializedTemplate();
295  else if (const auto *TIP = TSD->getTemplateInstantiationPattern())
296  DeclForComment = TIP;
297  } else if (const auto *TSD =
298  llvm::dyn_cast<VarTemplateSpecializationDecl>(D)) {
299  if (TSD->getTemplateSpecializationKind() == TSK_Undeclared)
300  DeclForComment = TSD->getSpecializedTemplate();
301  else if (const auto *TIP = TSD->getTemplateInstantiationPattern())
302  DeclForComment = TIP;
303  } else if (const auto *FD = D->getAsFunction())
304  if (const auto *TIP = FD->getTemplateInstantiationPattern())
305  DeclForComment = TIP;
306  // Ensure that getDeclForComment(getDeclForComment(X)) = getDeclForComment(X).
307  // This is usually not needed, but in strange cases of comparision operators
308  // being instantiated from spasceship operater, which itself is a template
309  // instantiation the recursrive call is necessary.
310  if (D != DeclForComment)
311  DeclForComment = getDeclForComment(DeclForComment);
312  return DeclForComment;
313 }
314 
315 // Look up information about D from the index, and add it to Hover.
316 void enhanceFromIndex(HoverInfo &Hover, const NamedDecl &ND,
317  const SymbolIndex *Index) {
318  assert(&ND == getDeclForComment(&ND));
319  // We only add documentation, so don't bother if we already have some.
320  if (!Hover.Documentation.empty() || !Index)
321  return;
322 
323  // Skip querying for non-indexable symbols, there's no point.
324  // We're searching for symbols that might be indexed outside this main file.
325  if (!SymbolCollector::shouldCollectSymbol(ND, ND.getASTContext(),
326  SymbolCollector::Options(),
327  /*IsMainFileOnly=*/false))
328  return;
329  auto ID = getSymbolID(&ND);
330  if (!ID)
331  return;
332  LookupRequest Req;
333  Req.IDs.insert(ID);
334  Index->lookup(Req, [&](const Symbol &S) {
335  Hover.Documentation = std::string(S.Documentation);
336  });
337 }
338 
339 // Default argument might exist but be unavailable, in the case of unparsed
340 // arguments for example. This function returns the default argument if it is
341 // available.
342 const Expr *getDefaultArg(const ParmVarDecl *PVD) {
343  // Default argument can be unparsed or uninstantiated. For the former we
344  // can't do much, as token information is only stored in Sema and not
345  // attached to the AST node. For the latter though, it is safe to proceed as
346  // the expression is still valid.
347  if (!PVD->hasDefaultArg() || PVD->hasUnparsedDefaultArg())
348  return nullptr;
349  return PVD->hasUninstantiatedDefaultArg() ? PVD->getUninstantiatedDefaultArg()
350  : PVD->getDefaultArg();
351 }
352 
353 HoverInfo::Param toHoverInfoParam(const ParmVarDecl *PVD,
354  const PrintingPolicy &PP) {
355  HoverInfo::Param Out;
356  Out.Type = printType(PVD->getType(), PVD->getASTContext(), PP);
357  if (!PVD->getName().empty())
358  Out.Name = PVD->getNameAsString();
359  if (const Expr *DefArg = getDefaultArg(PVD)) {
360  Out.Default.emplace();
361  llvm::raw_string_ostream OS(*Out.Default);
362  DefArg->printPretty(OS, nullptr, PP);
363  }
364  return Out;
365 }
366 
367 // Populates Type, ReturnType, and Parameters for function-like decls.
368 void fillFunctionTypeAndParams(HoverInfo &HI, const Decl *D,
369  const FunctionDecl *FD,
370  const PrintingPolicy &PP) {
371  HI.Parameters.emplace();
372  for (const ParmVarDecl *PVD : FD->parameters())
373  HI.Parameters->emplace_back(toHoverInfoParam(PVD, PP));
374 
375  // We don't want any type info, if name already contains it. This is true for
376  // constructors/destructors and conversion operators.
377  const auto NK = FD->getDeclName().getNameKind();
378  if (NK == DeclarationName::CXXConstructorName ||
379  NK == DeclarationName::CXXDestructorName ||
380  NK == DeclarationName::CXXConversionFunctionName)
381  return;
382 
383  HI.ReturnType = printType(FD->getReturnType(), FD->getASTContext(), PP);
384  QualType QT = FD->getType();
385  if (const VarDecl *VD = llvm::dyn_cast<VarDecl>(D)) // Lambdas
386  QT = VD->getType().getDesugaredType(D->getASTContext());
387  HI.Type = printType(QT, D->getASTContext(), PP);
388  // FIXME: handle variadics.
389 }
390 
391 // Non-negative numbers are printed using min digits
392 // 0 => 0x0
393 // 100 => 0x64
394 // Negative numbers are sign-extended to 32/64 bits
395 // -2 => 0xfffffffe
396 // -2^32 => 0xfffffffeffffffff
397 static llvm::FormattedNumber printHex(const llvm::APSInt &V) {
398  uint64_t Bits = V.getExtValue();
399  if (V.isNegative() && V.getMinSignedBits() <= 32)
400  return llvm::format_hex(uint32_t(Bits), 0);
401  return llvm::format_hex(Bits, 0);
402 }
403 
404 llvm::Optional<std::string> printExprValue(const Expr *E,
405  const ASTContext &Ctx) {
406  // InitListExpr has two forms, syntactic and semantic. They are the same thing
407  // (refer to a same AST node) in most cases.
408  // When they are different, RAV returns the syntactic form, and we should feed
409  // the semantic form to EvaluateAsRValue.
410  if (const auto *ILE = llvm::dyn_cast<InitListExpr>(E)) {
411  if (!ILE->isSemanticForm())
412  E = ILE->getSemanticForm();
413  }
414 
415  // Evaluating [[foo]]() as "&foo" isn't useful, and prevents us walking up
416  // to the enclosing call. Evaluating an expression of void type doesn't
417  // produce a meaningful result.
418  QualType T = E->getType();
419  if (T.isNull() || T->isFunctionType() || T->isFunctionPointerType() ||
420  T->isFunctionReferenceType() || T->isVoidType())
421  return llvm::None;
422 
423  Expr::EvalResult Constant;
424  // Attempt to evaluate. If expr is dependent, evaluation crashes!
425  if (E->isValueDependent() || !E->EvaluateAsRValue(Constant, Ctx) ||
426  // Disable printing for record-types, as they are usually confusing and
427  // might make clang crash while printing the expressions.
428  Constant.Val.isStruct() || Constant.Val.isUnion())
429  return llvm::None;
430 
431  // Show enums symbolically, not numerically like APValue::printPretty().
432  if (T->isEnumeralType() && Constant.Val.getInt().getMinSignedBits() <= 64) {
433  // Compare to int64_t to avoid bit-width match requirements.
434  int64_t Val = Constant.Val.getInt().getExtValue();
435  for (const EnumConstantDecl *ECD :
436  T->castAs<EnumType>()->getDecl()->enumerators())
437  if (ECD->getInitVal() == Val)
438  return llvm::formatv("{0} ({1})", ECD->getNameAsString(),
439  printHex(Constant.Val.getInt()))
440  .str();
441  }
442  // Show hex value of integers if they're at least 10 (or negative!)
443  if (T->isIntegralOrEnumerationType() &&
444  Constant.Val.getInt().getMinSignedBits() <= 64 &&
445  Constant.Val.getInt().uge(10))
446  return llvm::formatv("{0} ({1})", Constant.Val.getAsString(Ctx, T),
447  printHex(Constant.Val.getInt()))
448  .str();
449  return Constant.Val.getAsString(Ctx, T);
450 }
451 
452 llvm::Optional<std::string> printExprValue(const SelectionTree::Node *N,
453  const ASTContext &Ctx) {
454  for (; N; N = N->Parent) {
455  // Try to evaluate the first evaluatable enclosing expression.
456  if (const Expr *E = N->ASTNode.get<Expr>()) {
457  // Once we cross an expression of type 'cv void', the evaluated result
458  // has nothing to do with our original cursor position.
459  if (!E->getType().isNull() && E->getType()->isVoidType())
460  break;
461  if (auto Val = printExprValue(E, Ctx))
462  return Val;
463  } else if (N->ASTNode.get<Decl>() || N->ASTNode.get<Stmt>()) {
464  // Refuse to cross certain non-exprs. (TypeLoc are OK as part of Exprs).
465  // This tries to ensure we're showing a value related to the cursor.
466  break;
467  }
468  }
469  return llvm::None;
470 }
471 
472 llvm::Optional<StringRef> fieldName(const Expr *E) {
473  const auto *ME = llvm::dyn_cast<MemberExpr>(E->IgnoreCasts());
474  if (!ME || !llvm::isa<CXXThisExpr>(ME->getBase()->IgnoreCasts()))
475  return llvm::None;
476  const auto *Field = llvm::dyn_cast<FieldDecl>(ME->getMemberDecl());
477  if (!Field || !Field->getDeclName().isIdentifier())
478  return llvm::None;
479  return Field->getDeclName().getAsIdentifierInfo()->getName();
480 }
481 
482 // If CMD is of the form T foo() { return FieldName; } then returns "FieldName".
483 llvm::Optional<StringRef> getterVariableName(const CXXMethodDecl *CMD) {
484  assert(CMD->hasBody());
485  if (CMD->getNumParams() != 0 || CMD->isVariadic())
486  return llvm::None;
487  const auto *Body = llvm::dyn_cast<CompoundStmt>(CMD->getBody());
488  const auto *OnlyReturn = (Body && Body->size() == 1)
489  ? llvm::dyn_cast<ReturnStmt>(Body->body_front())
490  : nullptr;
491  if (!OnlyReturn || !OnlyReturn->getRetValue())
492  return llvm::None;
493  return fieldName(OnlyReturn->getRetValue());
494 }
495 
496 // If CMD is one of the forms:
497 // void foo(T arg) { FieldName = arg; }
498 // R foo(T arg) { FieldName = arg; return *this; }
499 // void foo(T arg) { FieldName = std::move(arg); }
500 // R foo(T arg) { FieldName = std::move(arg); return *this; }
501 // then returns "FieldName"
502 llvm::Optional<StringRef> setterVariableName(const CXXMethodDecl *CMD) {
503  assert(CMD->hasBody());
504  if (CMD->isConst() || CMD->getNumParams() != 1 || CMD->isVariadic())
505  return llvm::None;
506  const ParmVarDecl *Arg = CMD->getParamDecl(0);
507  if (Arg->isParameterPack())
508  return llvm::None;
509 
510  const auto *Body = llvm::dyn_cast<CompoundStmt>(CMD->getBody());
511  if (!Body || Body->size() == 0 || Body->size() > 2)
512  return llvm::None;
513  // If the second statement exists, it must be `return this` or `return *this`.
514  if (Body->size() == 2) {
515  auto *Ret = llvm::dyn_cast<ReturnStmt>(Body->body_back());
516  if (!Ret || !Ret->getRetValue())
517  return llvm::None;
518  const Expr *RetVal = Ret->getRetValue()->IgnoreCasts();
519  if (const auto *UO = llvm::dyn_cast<UnaryOperator>(RetVal)) {
520  if (UO->getOpcode() != UO_Deref)
521  return llvm::None;
522  RetVal = UO->getSubExpr()->IgnoreCasts();
523  }
524  if (!llvm::isa<CXXThisExpr>(RetVal))
525  return llvm::None;
526  }
527  // The first statement must be an assignment of the arg to a field.
528  const Expr *LHS, *RHS;
529  if (const auto *BO = llvm::dyn_cast<BinaryOperator>(Body->body_front())) {
530  if (BO->getOpcode() != BO_Assign)
531  return llvm::None;
532  LHS = BO->getLHS();
533  RHS = BO->getRHS();
534  } else if (const auto *COCE =
535  llvm::dyn_cast<CXXOperatorCallExpr>(Body->body_front())) {
536  if (COCE->getOperator() != OO_Equal || COCE->getNumArgs() != 2)
537  return llvm::None;
538  LHS = COCE->getArg(0);
539  RHS = COCE->getArg(1);
540  } else {
541  return llvm::None;
542  }
543 
544  // Detect the case when the item is moved into the field.
545  if (auto *CE = llvm::dyn_cast<CallExpr>(RHS->IgnoreCasts())) {
546  if (CE->getNumArgs() != 1)
547  return llvm::None;
548  auto *ND = llvm::dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl());
549  if (!ND || !ND->getIdentifier() || ND->getName() != "move" ||
550  !ND->isInStdNamespace())
551  return llvm::None;
552  RHS = CE->getArg(0);
553  }
554 
555  auto *DRE = llvm::dyn_cast<DeclRefExpr>(RHS->IgnoreCasts());
556  if (!DRE || DRE->getDecl() != Arg)
557  return llvm::None;
558  return fieldName(LHS);
559 }
560 
561 std::string synthesizeDocumentation(const NamedDecl *ND) {
562  if (const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(ND)) {
563  // Is this an ordinary, non-static method whose definition is visible?
564  if (CMD->getDeclName().isIdentifier() && !CMD->isStatic() &&
565  (CMD = llvm::dyn_cast_or_null<CXXMethodDecl>(CMD->getDefinition())) &&
566  CMD->hasBody()) {
567  if (const auto GetterField = getterVariableName(CMD))
568  return llvm::formatv("Trivial accessor for `{0}`.", *GetterField);
569  if (const auto SetterField = setterVariableName(CMD))
570  return llvm::formatv("Trivial setter for `{0}`.", *SetterField);
571  }
572  }
573  return "";
574 }
575 
576 /// Generate a \p Hover object given the declaration \p D.
577 HoverInfo getHoverContents(const NamedDecl *D, const PrintingPolicy &PP,
578  const SymbolIndex *Index,
579  const syntax::TokenBuffer &TB) {
580  HoverInfo HI;
581  const ASTContext &Ctx = D->getASTContext();
582 
583  HI.AccessSpecifier = getAccessSpelling(D->getAccess()).str();
584  HI.NamespaceScope = getNamespaceScope(D);
585  if (!HI.NamespaceScope->empty())
586  HI.NamespaceScope->append("::");
587  HI.LocalScope = getLocalScope(D);
588  if (!HI.LocalScope.empty())
589  HI.LocalScope.append("::");
590 
591  HI.Name = printName(Ctx, *D);
592  const auto *CommentD = getDeclForComment(D);
593  HI.Documentation = getDeclComment(Ctx, *CommentD);
594  enhanceFromIndex(HI, *CommentD, Index);
595  if (HI.Documentation.empty())
596  HI.Documentation = synthesizeDocumentation(D);
597 
598  HI.Kind = index::getSymbolInfo(D).Kind;
599 
600  // Fill in template params.
601  if (const TemplateDecl *TD = D->getDescribedTemplate()) {
602  HI.TemplateParameters =
603  fetchTemplateParameters(TD->getTemplateParameters(), PP);
604  D = TD;
605  } else if (const FunctionDecl *FD = D->getAsFunction()) {
606  if (const auto *FTD = FD->getDescribedTemplate()) {
607  HI.TemplateParameters =
608  fetchTemplateParameters(FTD->getTemplateParameters(), PP);
609  D = FTD;
610  }
611  }
612 
613  // Fill in types and params.
614  if (const FunctionDecl *FD = getUnderlyingFunction(D))
615  fillFunctionTypeAndParams(HI, D, FD, PP);
616  else if (const auto *VD = dyn_cast<ValueDecl>(D))
617  HI.Type = printType(VD->getType(), VD->getASTContext(), PP);
618  else if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(D))
619  HI.Type = TTP->wasDeclaredWithTypename() ? "typename" : "class";
620  else if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(D))
621  HI.Type = printType(TTP, PP);
622  else if (const auto *VT = dyn_cast<VarTemplateDecl>(D))
623  HI.Type =
624  printType(VT->getTemplatedDecl()->getType(), VT->getASTContext(), PP);
625  else if (const auto *TN = dyn_cast<TypedefNameDecl>(D))
626  HI.Type = printType(TN->getUnderlyingType(), TN->getASTContext(), PP);
627  else if (const auto *TAT = dyn_cast<TypeAliasTemplateDecl>(D))
628  HI.Type = printType(TAT->getTemplatedDecl()->getUnderlyingType(),
629  TAT->getASTContext(), PP);
630 
631  // Fill in value with evaluated initializer if possible.
632  if (const auto *Var = dyn_cast<VarDecl>(D)) {
633  if (const Expr *Init = Var->getInit())
634  HI.Value = printExprValue(Init, Ctx);
635  } else if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
636  // Dependent enums (e.g. nested in template classes) don't have values yet.
637  if (!ECD->getType()->isDependentType())
638  HI.Value = toString(ECD->getInitVal(), 10);
639  }
640 
641  HI.Definition = printDefinition(D, PP, TB);
642  return HI;
643 }
644 
645 /// Generate a \p Hover object given the macro \p MacroDecl.
646 HoverInfo getHoverContents(const DefinedMacro &Macro, ParsedAST &AST) {
647  HoverInfo HI;
648  SourceManager &SM = AST.getSourceManager();
649  HI.Name = std::string(Macro.Name);
650  HI.Kind = index::SymbolKind::Macro;
651  // FIXME: Populate documentation
652  // FIXME: Populate parameters
653 
654  // Try to get the full definition, not just the name
655  SourceLocation StartLoc = Macro.Info->getDefinitionLoc();
656  SourceLocation EndLoc = Macro.Info->getDefinitionEndLoc();
657  // Ensure that EndLoc is a valid offset. For example it might come from
658  // preamble, and source file might've changed, in such a scenario EndLoc still
659  // stays valid, but getLocForEndOfToken will fail as it is no longer a valid
660  // offset.
661  // Note that this check is just to ensure there's text data inside the range.
662  // It will still succeed even when the data inside the range is irrelevant to
663  // macro definition.
664  if (SM.getPresumedLoc(EndLoc, /*UseLineDirectives=*/false).isValid()) {
665  EndLoc = Lexer::getLocForEndOfToken(EndLoc, 0, SM, AST.getLangOpts());
666  bool Invalid;
667  StringRef Buffer = SM.getBufferData(SM.getFileID(StartLoc), &Invalid);
668  if (!Invalid) {
669  unsigned StartOffset = SM.getFileOffset(StartLoc);
670  unsigned EndOffset = SM.getFileOffset(EndLoc);
671  if (EndOffset <= Buffer.size() && StartOffset < EndOffset)
672  HI.Definition =
673  ("#define " + Buffer.substr(StartOffset, EndOffset - StartOffset))
674  .str();
675  }
676  }
677  return HI;
678 }
679 
680 std::string typeAsDefinition(const HoverInfo::PrintedType &PType) {
681  std::string Result;
682  llvm::raw_string_ostream OS(Result);
683  OS << PType.Type;
684  if (PType.AKA)
685  OS << " // aka: " << *PType.AKA;
686  OS.flush();
687  return Result;
688 }
689 
690 llvm::Optional<HoverInfo> getThisExprHoverContents(const CXXThisExpr *CTE,
691  ASTContext &ASTCtx,
692  const PrintingPolicy &PP) {
693  QualType OriginThisType = CTE->getType()->getPointeeType();
694  QualType ClassType = declaredType(OriginThisType->getAsTagDecl());
695  // For partial specialization class, origin `this` pointee type will be
696  // parsed as `InjectedClassNameType`, which will ouput template arguments
697  // like "type-parameter-0-0". So we retrieve user written class type in this
698  // case.
699  QualType PrettyThisType = ASTCtx.getPointerType(
700  QualType(ClassType.getTypePtr(), OriginThisType.getCVRQualifiers()));
701 
702  HoverInfo HI;
703  HI.Name = "this";
704  HI.Definition = typeAsDefinition(printType(PrettyThisType, ASTCtx, PP));
705  return HI;
706 }
707 
708 /// Generate a HoverInfo object given the deduced type \p QT
709 HoverInfo getDeducedTypeHoverContents(QualType QT, const syntax::Token &Tok,
710  ASTContext &ASTCtx,
711  const PrintingPolicy &PP,
712  const SymbolIndex *Index) {
713  HoverInfo HI;
714  // FIXME: distinguish decltype(auto) vs decltype(expr)
715  HI.Name = tok::getTokenName(Tok.kind());
716  HI.Kind = index::SymbolKind::TypeAlias;
717 
718  if (QT->isUndeducedAutoType()) {
719  HI.Definition = "/* not deduced */";
720  } else {
721  HI.Definition = typeAsDefinition(printType(QT, ASTCtx, PP));
722 
723  if (const auto *D = QT->getAsTagDecl()) {
724  const auto *CommentD = getDeclForComment(D);
725  HI.Documentation = getDeclComment(ASTCtx, *CommentD);
726  enhanceFromIndex(HI, *CommentD, Index);
727  }
728  }
729 
730  return HI;
731 }
732 
733 bool isLiteral(const Expr *E) {
734  // Unfortunately there's no common base Literal classes inherits from
735  // (apart from Expr), therefore these exclusions.
736  return llvm::isa<CompoundLiteralExpr>(E) ||
737  llvm::isa<CXXBoolLiteralExpr>(E) ||
738  llvm::isa<CXXNullPtrLiteralExpr>(E) ||
739  llvm::isa<FixedPointLiteral>(E) || llvm::isa<FloatingLiteral>(E) ||
740  llvm::isa<ImaginaryLiteral>(E) || llvm::isa<IntegerLiteral>(E) ||
741  llvm::isa<StringLiteral>(E) || llvm::isa<UserDefinedLiteral>(E);
742 }
743 
744 llvm::StringLiteral getNameForExpr(const Expr *E) {
745  // FIXME: Come up with names for `special` expressions.
746  //
747  // It's an known issue for GCC5, https://godbolt.org/z/Z_tbgi. Work around
748  // that by using explicit conversion constructor.
749  //
750  // TODO: Once GCC5 is fully retired and not the minimal requirement as stated
751  // in `GettingStarted`, please remove the explicit conversion constructor.
752  return llvm::StringLiteral("expression");
753 }
754 
755 // Generates hover info for `this` and evaluatable expressions.
756 // FIXME: Support hover for literals (esp user-defined)
757 llvm::Optional<HoverInfo> getHoverContents(const Expr *E, ParsedAST &AST,
758  const PrintingPolicy &PP,
759  const SymbolIndex *Index) {
760  // There's not much value in hovering over "42" and getting a hover card
761  // saying "42 is an int", similar for other literals.
762  if (isLiteral(E))
763  return llvm::None;
764 
765  HoverInfo HI;
766  // For `this` expr we currently generate hover with pointee type.
767  if (const CXXThisExpr *CTE = dyn_cast<CXXThisExpr>(E))
768  return getThisExprHoverContents(CTE, AST.getASTContext(), PP);
769  // For expressions we currently print the type and the value, iff it is
770  // evaluatable.
771  if (auto Val = printExprValue(E, AST.getASTContext())) {
772  HI.Type = printType(E->getType(), AST.getASTContext(), PP);
773  HI.Value = *Val;
774  HI.Name = std::string(getNameForExpr(E));
775  return HI;
776  }
777  return llvm::None;
778 }
779 
780 // Generates hover info for attributes.
781 llvm::Optional<HoverInfo> getHoverContents(const Attr *A, ParsedAST &AST) {
782  HoverInfo HI;
783  HI.Name = A->getSpelling();
784  if (A->hasScope())
785  HI.LocalScope = A->getScopeName()->getName().str();
786  {
787  llvm::raw_string_ostream OS(HI.Definition);
788  A->printPretty(OS, AST.getASTContext().getPrintingPolicy());
789  }
790  HI.Documentation = Attr::getDocumentation(A->getKind()).str();
791  return HI;
792 }
793 
794 bool isParagraphBreak(llvm::StringRef Rest) {
795  return Rest.ltrim(" \t").startswith("\n");
796 }
797 
798 bool punctuationIndicatesLineBreak(llvm::StringRef Line) {
799  constexpr llvm::StringLiteral Punctuation = R"txt(.:,;!?)txt";
800 
801  Line = Line.rtrim();
802  return !Line.empty() && Punctuation.contains(Line.back());
803 }
804 
805 bool isHardLineBreakIndicator(llvm::StringRef Rest) {
806  // '-'/'*' md list, '@'/'\' documentation command, '>' md blockquote,
807  // '#' headings, '`' code blocks
808  constexpr llvm::StringLiteral LinebreakIndicators = R"txt(-*@>#`)txt";
809 
810  Rest = Rest.ltrim(" \t");
811  if (Rest.empty())
812  return false;
813 
814  if (LinebreakIndicators.contains(Rest.front()))
815  return true;
816 
817  if (llvm::isDigit(Rest.front())) {
818  llvm::StringRef AfterDigit = Rest.drop_while(llvm::isDigit);
819  if (AfterDigit.startswith(".") || AfterDigit.startswith(")"))
820  return true;
821  }
822  return false;
823 }
824 
825 bool isHardLineBreakAfter(llvm::StringRef Line, llvm::StringRef Rest) {
826  // Should we also consider whether Line is short?
827  return punctuationIndicatesLineBreak(Line) || isHardLineBreakIndicator(Rest);
828 }
829 
830 void addLayoutInfo(const NamedDecl &ND, HoverInfo &HI) {
831  if (ND.isInvalidDecl())
832  return;
833 
834  const auto &Ctx = ND.getASTContext();
835  if (auto *RD = llvm::dyn_cast<RecordDecl>(&ND)) {
836  if (auto Size = Ctx.getTypeSizeInCharsIfKnown(RD->getTypeForDecl()))
837  HI.Size = Size->getQuantity();
838  return;
839  }
840 
841  if (const auto *FD = llvm::dyn_cast<FieldDecl>(&ND)) {
842  const auto *Record = FD->getParent();
843  if (Record)
844  Record = Record->getDefinition();
845  if (Record && !Record->isInvalidDecl() && !Record->isDependentType() &&
846  !FD->isBitField()) {
847  const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Record);
848  HI.Offset = Layout.getFieldOffset(FD->getFieldIndex()) / 8;
849  if (auto Size = Ctx.getTypeSizeInCharsIfKnown(FD->getType())) {
850  HI.Size = FD->isZeroSize(Ctx) ? 0 : Size->getQuantity();
851  unsigned EndOfField = *HI.Offset + *HI.Size;
852 
853  // Calculate padding following the field.
854  if (!Record->isUnion() &&
855  FD->getFieldIndex() + 1 < Layout.getFieldCount()) {
856  // Measure padding up to the next class field.
857  unsigned NextOffset =
858  Layout.getFieldOffset(FD->getFieldIndex() + 1) / 8;
859  if (NextOffset >= EndOfField) // next field could be a bitfield!
860  HI.Padding = NextOffset - EndOfField;
861  } else {
862  // Measure padding up to the end of the object.
863  HI.Padding = Layout.getSize().getQuantity() - EndOfField;
864  }
865  }
866  // Offset in a union is always zero, so not really useful to report.
867  if (Record->isUnion())
868  HI.Offset.reset();
869  }
870  return;
871  }
872 }
873 
874 // If N is passed as argument to a function, fill HI.CalleeArgInfo with
875 // information about that argument.
876 void maybeAddCalleeArgInfo(const SelectionTree::Node *N, HoverInfo &HI,
877  const PrintingPolicy &PP) {
878  const auto &OuterNode = N->outerImplicit();
879  if (!OuterNode.Parent)
880  return;
881  const auto *CE = OuterNode.Parent->ASTNode.get<CallExpr>();
882  if (!CE)
883  return;
884  const FunctionDecl *FD = CE->getDirectCallee();
885  // For non-function-call-like operatators (e.g. operator+, operator<<) it's
886  // not immediattely obvious what the "passed as" would refer to and, given
887  // fixed function signature, the value would be very low anyway, so we choose
888  // to not support that.
889  // Both variadic functions and operator() (especially relevant for lambdas)
890  // should be supported in the future.
891  if (!FD || FD->isOverloadedOperator() || FD->isVariadic())
892  return;
893 
894  // Find argument index for N.
895  for (unsigned I = 0; I < CE->getNumArgs() && I < FD->getNumParams(); ++I) {
896  if (CE->getArg(I) != OuterNode.ASTNode.get<Expr>())
897  continue;
898 
899  // Extract matching argument from function declaration.
900  if (const ParmVarDecl *PVD = FD->getParamDecl(I))
901  HI.CalleeArgInfo.emplace(toHoverInfoParam(PVD, PP));
902  break;
903  }
904  if (!HI.CalleeArgInfo)
905  return;
906 
907  // If we found a matching argument, also figure out if it's a
908  // [const-]reference. For this we need to walk up the AST from the arg itself
909  // to CallExpr and check all implicit casts, constructor calls, etc.
910  HoverInfo::PassType PassType;
911  if (const auto *E = N->ASTNode.get<Expr>()) {
912  if (E->getType().isConstQualified())
913  PassType.PassBy = HoverInfo::PassType::ConstRef;
914  }
915 
916  for (auto *CastNode = N->Parent;
917  CastNode != OuterNode.Parent && !PassType.Converted;
918  CastNode = CastNode->Parent) {
919  if (const auto *ImplicitCast = CastNode->ASTNode.get<ImplicitCastExpr>()) {
920  switch (ImplicitCast->getCastKind()) {
921  case CK_NoOp:
922  case CK_DerivedToBase:
923  case CK_UncheckedDerivedToBase:
924  // If it was a reference before, it's still a reference.
925  if (PassType.PassBy != HoverInfo::PassType::Value)
926  PassType.PassBy = ImplicitCast->getType().isConstQualified()
929  break;
930  case CK_LValueToRValue:
931  case CK_ArrayToPointerDecay:
932  case CK_FunctionToPointerDecay:
933  case CK_NullToPointer:
934  case CK_NullToMemberPointer:
935  // No longer a reference, but we do not show this as type conversion.
936  PassType.PassBy = HoverInfo::PassType::Value;
937  break;
938  default:
939  PassType.PassBy = HoverInfo::PassType::Value;
940  PassType.Converted = true;
941  break;
942  }
943  } else if (const auto *CtorCall =
944  CastNode->ASTNode.get<CXXConstructExpr>()) {
945  // We want to be smart about copy constructors. They should not show up as
946  // type conversion, but instead as passing by value.
947  if (CtorCall->getConstructor()->isCopyConstructor())
948  PassType.PassBy = HoverInfo::PassType::Value;
949  else
950  PassType.Converted = true;
951  } else { // Unknown implicit node, assume type conversion.
952  PassType.PassBy = HoverInfo::PassType::Value;
953  PassType.Converted = true;
954  }
955  }
956 
957  HI.CallPassType.emplace(PassType);
958 }
959 
960 } // namespace
961 
962 llvm::Optional<HoverInfo> getHover(ParsedAST &AST, Position Pos,
963  const format::FormatStyle &Style,
964  const SymbolIndex *Index) {
965  PrintingPolicy PP =
966  getPrintingPolicy(AST.getASTContext().getPrintingPolicy());
967  const SourceManager &SM = AST.getSourceManager();
968  auto CurLoc = sourceLocationInMainFile(SM, Pos);
969  if (!CurLoc) {
970  llvm::consumeError(CurLoc.takeError());
971  return llvm::None;
972  }
973  const auto &TB = AST.getTokens();
974  auto TokensTouchingCursor = syntax::spelledTokensTouching(*CurLoc, TB);
975  // Early exit if there were no tokens around the cursor.
976  if (TokensTouchingCursor.empty())
977  return llvm::None;
978 
979  // Show full header file path if cursor is on include directive.
980  if (const auto MainFilePath =
981  getCanonicalPath(SM.getFileEntryForID(SM.getMainFileID()), SM)) {
982  for (const auto &Inc : AST.getIncludeStructure().MainFileIncludes) {
983  if (Inc.Resolved.empty() || Inc.HashLine != Pos.line)
984  continue;
985  HoverInfo HI;
986  HI.Name = std::string(llvm::sys::path::filename(Inc.Resolved));
987  // FIXME: We don't have a fitting value for Kind.
988  HI.Definition =
989  URIForFile::canonicalize(Inc.Resolved, *MainFilePath).file().str();
990  HI.DefinitionLanguage = "";
991  return HI;
992  }
993  }
994 
995  // To be used as a backup for highlighting the selected token, we use back as
996  // it aligns better with biases elsewhere (editors tend to send the position
997  // for the left of the hovered token).
998  CharSourceRange HighlightRange =
999  TokensTouchingCursor.back().range(SM).toCharRange(SM);
1000  llvm::Optional<HoverInfo> HI;
1001  // Macros and deducedtype only works on identifiers and auto/decltype keywords
1002  // respectively. Therefore they are only trggered on whichever works for them,
1003  // similar to SelectionTree::create().
1004  for (const auto &Tok : TokensTouchingCursor) {
1005  if (Tok.kind() == tok::identifier) {
1006  // Prefer the identifier token as a fallback highlighting range.
1007  HighlightRange = Tok.range(SM).toCharRange(SM);
1008  if (auto M = locateMacroAt(Tok, AST.getPreprocessor())) {
1009  HI = getHoverContents(*M, AST);
1010  break;
1011  }
1012  } else if (Tok.kind() == tok::kw_auto || Tok.kind() == tok::kw_decltype) {
1013  if (auto Deduced = getDeducedType(AST.getASTContext(), Tok.location())) {
1014  HI = getDeducedTypeHoverContents(*Deduced, Tok, AST.getASTContext(), PP,
1015  Index);
1016  HighlightRange = Tok.range(SM).toCharRange(SM);
1017  break;
1018  }
1019 
1020  // If we can't find interesting hover information for this
1021  // auto/decltype keyword, return nothing to avoid showing
1022  // irrelevant or incorrect informations.
1023  return llvm::None;
1024  }
1025  }
1026 
1027  // If it wasn't auto/decltype or macro, look for decls and expressions.
1028  if (!HI) {
1029  auto Offset = SM.getFileOffset(*CurLoc);
1030  // Editors send the position on the left of the hovered character.
1031  // So our selection tree should be biased right. (Tested with VSCode).
1032  SelectionTree ST =
1034  if (const SelectionTree::Node *N = ST.commonAncestor()) {
1035  // FIXME: Fill in HighlightRange with range coming from N->ASTNode.
1036  auto Decls = explicitReferenceTargets(N->ASTNode, DeclRelation::Alias,
1037  AST.getHeuristicResolver());
1038  if (!Decls.empty()) {
1039  HI = getHoverContents(Decls.front(), PP, Index, TB);
1040  // Layout info only shown when hovering on the field/class itself.
1041  if (Decls.front() == N->ASTNode.get<Decl>())
1042  addLayoutInfo(*Decls.front(), *HI);
1043  // Look for a close enclosing expression to show the value of.
1044  if (!HI->Value)
1045  HI->Value = printExprValue(N, AST.getASTContext());
1046  maybeAddCalleeArgInfo(N, *HI, PP);
1047  } else if (const Expr *E = N->ASTNode.get<Expr>()) {
1048  HI = getHoverContents(E, AST, PP, Index);
1049  } else if (const Attr *A = N->ASTNode.get<Attr>()) {
1050  HI = getHoverContents(A, AST);
1051  }
1052  // FIXME: support hovers for other nodes?
1053  // - built-in types
1054  }
1055  }
1056 
1057  if (!HI)
1058  return llvm::None;
1059 
1060  auto Replacements = format::reformat(
1061  Style, HI->Definition, tooling::Range(0, HI->Definition.size()));
1062  if (auto Formatted =
1063  tooling::applyAllReplacements(HI->Definition, Replacements))
1064  HI->Definition = *Formatted;
1065  HI->DefinitionLanguage = getMarkdownLanguage(AST.getASTContext());
1066  HI->SymRange = halfOpenToRange(SM, HighlightRange);
1067 
1068  return HI;
1069 }
1070 
1073 
1074  // Header contains a text of the form:
1075  // variable `var`
1076  //
1077  // class `X`
1078  //
1079  // function `foo`
1080  //
1081  // expression
1082  //
1083  // Note that we are making use of a level-3 heading because VSCode renders
1084  // level 1 and 2 headers in a huge font, see
1085  // https://github.com/microsoft/vscode/issues/88417 for details.
1086  markup::Paragraph &Header = Output.addHeading(3);
1088  Header.appendText(index::getSymbolKindString(Kind)).appendSpace();
1089  assert(!Name.empty() && "hover triggered on a nameless symbol");
1090  Header.appendCode(Name);
1091 
1092  // Put a linebreak after header to increase readability.
1093  Output.addRuler();
1094  // Print Types on their own lines to reduce chances of getting line-wrapped by
1095  // editor, as they might be long.
1096  if (ReturnType) {
1097  // For functions we display signature in a list form, e.g.:
1098  // → `x`
1099  // Parameters:
1100  // - `bool param1`
1101  // - `int param2 = 5`
1102  Output.addParagraph().appendText("→ ").appendCode(
1103  llvm::to_string(*ReturnType));
1104  }
1105 
1106  if (Parameters && !Parameters->empty()) {
1107  Output.addParagraph().appendText("Parameters: ");
1108  markup::BulletList &L = Output.addBulletList();
1109  for (const auto &Param : *Parameters)
1110  L.addItem().addParagraph().appendCode(llvm::to_string(Param));
1111  }
1112 
1113  // Don't print Type after Parameters or ReturnType as this will just duplicate
1114  // the information
1115  if (Type && !ReturnType && !Parameters)
1116  Output.addParagraph().appendText("Type: ").appendCode(
1117  llvm::to_string(*Type));
1118 
1119  if (Value) {
1120  markup::Paragraph &P = Output.addParagraph();
1121  P.appendText("Value = ");
1122  P.appendCode(*Value);
1123  }
1124 
1125  if (Offset)
1126  Output.addParagraph().appendText(
1127  llvm::formatv("Offset: {0} byte{1}", *Offset, *Offset == 1 ? "" : "s")
1128  .str());
1129  if (Size) {
1130  auto &P = Output.addParagraph().appendText(
1131  llvm::formatv("Size: {0} byte{1}", *Size, *Size == 1 ? "" : "s").str());
1132  if (Padding && *Padding != 0)
1133  P.appendText(llvm::formatv(" (+{0} padding)", *Padding).str());
1134  }
1135 
1136  if (CalleeArgInfo) {
1137  assert(CallPassType);
1138  std::string Buffer;
1139  llvm::raw_string_ostream OS(Buffer);
1140  OS << "Passed ";
1141  if (CallPassType->PassBy != HoverInfo::PassType::Value) {
1142  OS << "by ";
1144  OS << "const ";
1145  OS << "reference ";
1146  }
1147  if (CalleeArgInfo->Name)
1148  OS << "as " << CalleeArgInfo->Name;
1149  if (CallPassType->Converted && CalleeArgInfo->Type)
1150  OS << " (converted to " << CalleeArgInfo->Type->Type << ")";
1151  Output.addParagraph().appendText(OS.str());
1152  }
1153 
1154  if (!Documentation.empty())
1156 
1157  if (!Definition.empty()) {
1158  Output.addRuler();
1159  std::string ScopeComment;
1160  // Drop trailing "::".
1161  if (!LocalScope.empty()) {
1162  // Container name, e.g. class, method, function.
1163  // We might want to propagate some info about container type to print
1164  // function foo, class X, method X::bar, etc.
1165  ScopeComment =
1166  "// In " + llvm::StringRef(LocalScope).rtrim(':').str() + '\n';
1167  } else if (NamespaceScope && !NamespaceScope->empty()) {
1168  ScopeComment = "// In namespace " +
1169  llvm::StringRef(*NamespaceScope).rtrim(':').str() + '\n';
1170  }
1171  std::string DefinitionWithAccess = !AccessSpecifier.empty()
1172  ? AccessSpecifier + ": " + Definition
1173  : Definition;
1174  // Note that we don't print anything for global namespace, to not annoy
1175  // non-c++ projects or projects that are not making use of namespaces.
1176  Output.addCodeBlock(ScopeComment + DefinitionWithAccess,
1178  }
1179 
1180  return Output;
1181 }
1182 
1183 // If the backtick at `Offset` starts a probable quoted range, return the range
1184 // (including the quotes).
1185 llvm::Optional<llvm::StringRef> getBacktickQuoteRange(llvm::StringRef Line,
1186  unsigned Offset) {
1187  assert(Line[Offset] == '`');
1188 
1189  // The open-quote is usually preceded by whitespace.
1190  llvm::StringRef Prefix = Line.substr(0, Offset);
1191  constexpr llvm::StringLiteral BeforeStartChars = " \t(=";
1192  if (!Prefix.empty() && !BeforeStartChars.contains(Prefix.back()))
1193  return llvm::None;
1194 
1195  // The quoted string must be nonempty and usually has no leading/trailing ws.
1196  auto Next = Line.find('`', Offset + 1);
1197  if (Next == llvm::StringRef::npos)
1198  return llvm::None;
1199  llvm::StringRef Contents = Line.slice(Offset + 1, Next);
1200  if (Contents.empty() || isWhitespace(Contents.front()) ||
1201  isWhitespace(Contents.back()))
1202  return llvm::None;
1203 
1204  // The close-quote is usually followed by whitespace or punctuation.
1205  llvm::StringRef Suffix = Line.substr(Next + 1);
1206  constexpr llvm::StringLiteral AfterEndChars = " \t)=.,;:";
1207  if (!Suffix.empty() && !AfterEndChars.contains(Suffix.front()))
1208  return llvm::None;
1209 
1210  return Line.slice(Offset, Next + 1);
1211 }
1212 
1214  // Probably this is appendText(Line), but scan for something interesting.
1215  for (unsigned I = 0; I < Line.size(); ++I) {
1216  switch (Line[I]) {
1217  case '`':
1218  if (auto Range = getBacktickQuoteRange(Line, I)) {
1219  Out.appendText(Line.substr(0, I));
1220  Out.appendCode(Range->trim("`"), /*Preserve=*/true);
1221  return parseDocumentationLine(Line.substr(I + Range->size()), Out);
1222  }
1223  break;
1224  }
1225  }
1226  Out.appendText(Line).appendSpace();
1227 }
1228 
1229 void parseDocumentation(llvm::StringRef Input, markup::Document &Output) {
1230  std::vector<llvm::StringRef> ParagraphLines;
1231  auto FlushParagraph = [&] {
1232  if (ParagraphLines.empty())
1233  return;
1234  auto &P = Output.addParagraph();
1235  for (llvm::StringRef Line : ParagraphLines)
1237  ParagraphLines.clear();
1238  };
1239 
1240  llvm::StringRef Line, Rest;
1241  for (std::tie(Line, Rest) = Input.split('\n');
1242  !(Line.empty() && Rest.empty());
1243  std::tie(Line, Rest) = Rest.split('\n')) {
1244 
1245  // After a linebreak remove spaces to avoid 4 space markdown code blocks.
1246  // FIXME: make FlushParagraph handle this.
1247  Line = Line.ltrim();
1248  if (!Line.empty())
1249  ParagraphLines.push_back(Line);
1250 
1251  if (isParagraphBreak(Rest) || isHardLineBreakAfter(Line, Rest)) {
1252  FlushParagraph();
1253  }
1254  }
1255  FlushParagraph();
1256 }
1257 
1258 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
1259  const HoverInfo::PrintedType &T) {
1260  OS << T.Type;
1261  if (T.AKA)
1262  OS << " (aka " << *T.AKA << ")";
1263  return OS;
1264 }
1265 
1266 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
1267  const HoverInfo::Param &P) {
1268  if (P.Type)
1269  OS << P.Type->Type;
1270  if (P.Name)
1271  OS << " " << *P.Name;
1272  if (P.Default)
1273  OS << " = " << *P.Default;
1274  if (P.Type && P.Type->AKA)
1275  OS << " (aka " << *P.Type->AKA << ")";
1276  return OS;
1277 }
1278 
1279 } // namespace clangd
1280 } // namespace clang
Range
CharSourceRange Range
SourceRange for the file name.
Definition: IncludeOrderCheck.cpp:38
clang::clangd::getDeclComment
std::string getDeclComment(const ASTContext &Ctx, const NamedDecl &Decl)
Similar to getDocComment, but returns the comment for a NamedDecl.
Definition: CodeCompletionStrings.cpp:73
clang::clangd::markup::BulletList
Represents a sequence of one or more documents.
Definition: Markup.h:80
Base
std::unique_ptr< GlobalCompilationDatabase > Base
Definition: GlobalCompilationDatabaseTests.cpp:85
Suffix
std::string Suffix
Definition: AddUsing.cpp:113
clang::clangd::locateMacroAt
llvm::Optional< DefinedMacro > locateMacroAt(const syntax::Token &SpelledTok, Preprocessor &PP)
Gets the macro referenced by SpelledTok.
Definition: SourceCode.cpp:973
Selection.h
clang::clangd::Config::Hover
struct clang::clangd::Config::@7 Hover
Configures hover feature.
E
const Expr * E
Definition: AvoidBindCheck.cpp:88
clang::clangd::HoverInfo::Type
llvm::Optional< PrintedType > Type
Printable variable type.
Definition: Hover.h:80
clang::clangd::declaredType
QualType declaredType(const TypeDecl *D)
Definition: AST.cpp:396
clang::doc::MD
static GeneratorRegistry::Add< MDGenerator > MD(MDGenerator::Format, "Generator for MD output.")
clang::clangd::HighlightingModifier::Deduced
@ Deduced
clang::clangd::HoverInfo::Offset
llvm::Optional< uint64_t > Offset
Contains the offset of fields within the enclosing class.
Definition: Hover.h:92
clang::clangd::markup::Paragraph
Represents parts of the markup that can contain strings, like inline code, code block or plain text.
Definition: Markup.h:43
FormatStyle
static cl::opt< std::string > FormatStyle("format-style", cl::desc(R"( Style for formatting code around applied fixes: - 'none' (default) turns off formatting - 'file' (literally 'file', not a placeholder) uses .clang-format file in the closest parent directory - '{ <json> }' specifies options inline, e.g. -format-style='{BasedOnStyle: llvm, IndentWidth: 8}' - 'llvm', 'google', 'webkit', 'mozilla' See clang-format documentation for the up-to-date information about formatting styles and options. This option overrides the 'FormatStyle` option in .clang-tidy file, if any. )"), cl::init("none"), cl::cat(ClangTidyCategory))
clang::clangd::SymbolCollector::shouldCollectSymbol
static bool shouldCollectSymbol(const NamedDecl &ND, const ASTContext &ASTCtx, const Options &Opts, bool IsMainFileSymbol)
Returns true is ND should be collected.
Definition: SymbolCollector.cpp:466
clang::clangd::ParsedAST::getIncludeStructure
const IncludeStructure & getIncludeStructure() const
Definition: ParsedAST.cpp:754
clang::clangd::HoverInfo::Kind
index::SymbolKind Kind
Definition: Hover.h:70
clang::clangd::ParsedAST::getASTContext
ASTContext & getASTContext()
Note that the returned ast will not contain decls from the preamble that were not deserialized during...
Definition: ParsedAST.cpp:697
clang::clangd::markup::Paragraph::appendText
Paragraph & appendText(llvm::StringRef Text)
Append plain text to the end of the string.
Definition: Markup.cpp:420
clang::clangd::Punctuation
@ Punctuation
Definition: FuzzyMatch.h:45
clang::clangd::HoverInfo::CallPassType
llvm::Optional< PassType > CallPassType
Definition: Hover.h:108
Ctx
Context Ctx
Definition: TUScheduler.cpp:495
clang::clangd::markup::Document
A format-agnostic representation for structured text.
Definition: Markup.h:94
clang::clangd::printObjCMethod
std::string printObjCMethod(const ObjCMethodDecl &Method)
Print the Objective-C method name, including the full container name, e.g.
Definition: AST.cpp:294
clang::tidy::cppcoreguidelines::isLiteral
static bool isLiteral(const Expr *E)
Definition: PreferMemberInitializerCheck.cpp:37
clang::tidy::cppcoreguidelines::join
static std::string join(ArrayRef< SpecialMemberFunctionsCheck::SpecialMemberFunctionKind > SMFS, llvm::StringRef AndOr)
Definition: SpecialMemberFunctionsCheck.cpp:78
clang::clangd::HoverInfo::ReturnType
llvm::Optional< PrintedType > ReturnType
Set for functions and lambdas.
Definition: Hover.h:82
FindTarget.h
clang::clangd::IncludeStructure::MainFileIncludes
std::vector< Inclusion > MainFileIncludes
Definition: Headers.h:168
clang::clangd::getDeducedType
llvm::Optional< QualType > getDeducedType(ASTContext &ASTCtx, SourceLocation Loc)
Retrieves the deduced type at a given location (auto, decltype).
Definition: AST.cpp:539
clang::clangd::ParsedAST::getLangOpts
const LangOptions & getLangOpts() const
Definition: ParsedAST.h:80
clang::clangd::HighlightingKind::Macro
@ Macro
Pos
size_t Pos
Definition: NoLintDirectiveHandler.cpp:97
clang::clangd::HoverInfo::Parameters
llvm::Optional< std::vector< Param > > Parameters
Set for functions, lambdas and macros with parameters.
Definition: Hover.h:84
clang::clangd::HoverInfo::Size
llvm::Optional< uint64_t > Size
Contains the byte-size of fields and types where it's interesting.
Definition: Hover.h:90
clang::clangd::printType
std::string printType(const QualType QT, const DeclContext &CurContext, const llvm::StringRef Placeholder)
Returns a QualType as string.
Definition: AST.cpp:352
M
const google::protobuf::Message & M
Definition: Server.cpp:309
clang::clangd::markup::Paragraph::appendSpace
Paragraph & appendSpace()
Ensure there is space between the surrounding chunks.
Definition: Markup.cpp:414
Hover.h
clang::clangd::CompletionItemKind::Constant
@ Constant
clang::clangd::HoverInfo::Name
std::string Name
Name of the symbol, does not contain any "::".
Definition: Hover.h:68
Offset
size_t Offset
Definition: CodeComplete.cpp:1203
ns1::ns2::A
@ A
Definition: CategoricalFeature.h:3
clang::clangd::halfOpenToRange
Range halfOpenToRange(const SourceManager &SM, CharSourceRange R)
Definition: SourceCode.cpp:463
clang::clangd::Position
Definition: Protocol.h:153
ns1::ns2::D
@ D
Definition: CategoricalFeature.h:3
clang::tidy::bugprone::model::MixFlags::Invalid
@ Invalid
Sentinel bit pattern. DO NOT USE!
clang::clangd::HoverInfo::Definition
std::string Definition
Source code containing the definition of the symbol.
Definition: Hover.h:73
clang::clangd::SymbolIndex::lookup
virtual void lookup(const LookupRequest &Req, llvm::function_ref< void(const Symbol &)> Callback) const =0
Looks up symbols with any of the given symbol IDs and applies Callback on each matched symbol.
clang::clangd::printName
std::string printName(const ASTContext &Ctx, const NamedDecl &ND)
Prints unqualified name of the decl for the purpose of displaying it to the user.
Definition: AST.cpp:211
Decl
const FunctionDecl * Decl
Definition: AvoidBindCheck.cpp:100
CodeCompletionStrings.h
clang::clangd::SelectionTree::createRight
static SelectionTree createRight(ASTContext &AST, const syntax::TokenBuffer &Tokens, unsigned Begin, unsigned End)
Definition: Selection.cpp:1039
clang::clangd::Unknown
@ Unknown
Definition: FuzzyMatch.h:56
Line
int Line
Definition: PreprocessorTracker.cpp:514
clang::clangd::getCanonicalPath
llvm::Optional< std::string > getCanonicalPath(const FileEntry *F, const SourceManager &SourceMgr)
Get the canonical path of F.
Definition: SourceCode.cpp:511
clang::clangd::HoverInfo::Padding
llvm::Optional< uint64_t > Padding
Contains the padding following a field within the enclosing class.
Definition: Hover.h:94
clang::tidy::modernize::getTokenName
static StringRef getTokenName(const Token &Tok)
Definition: MacroToEnumCheck.cpp:78
clang::clangd::printQualifiedName
std::string printQualifiedName(const NamedDecl &ND)
Returns the qualified name of ND.
Definition: AST.cpp:172
Markup.h
clang::clangd::getSymbolInfo
std::vector< SymbolDetails > getSymbolInfo(ParsedAST &AST, Position Pos)
Get info about symbols at Pos.
Definition: XRefs.cpp:1514
clang::clangd::HoverInfo
Contains detailed information about a Symbol.
Definition: Hover.h:24
clang::clangd::HoverInfo::AccessSpecifier
std::string AccessSpecifier
Access specifier for declarations inside class/struct/unions, empty for others.
Definition: Hover.h:77
clang::clangd::HoverInfo::PassType::Ref
@ Ref
Definition: Hover.h:100
clang::clangd::toString
static const char * toString(OffsetEncoding OE)
Definition: Protocol.cpp:1374
clang::clangd::HoverInfo::Param::Name
llvm::Optional< std::string > Name
None for unnamed parameters.
Definition: Hover.h:48
clang::clangd::getHover
llvm::Optional< HoverInfo > getHover(ParsedAST &AST, Position Pos, const format::FormatStyle &Style, const SymbolIndex *Index)
Get the hover information when hovering at Pos.
Definition: Hover.cpp:962
clang::clangd::ParsedAST::getHeuristicResolver
const HeuristicResolver * getHeuristicResolver() const
Definition: ParsedAST.h:115
clang::clangd::SelectionTree
Definition: Selection.h:76
clang::clangd::explicitReferenceTargets
llvm::SmallVector< const NamedDecl *, 1 > explicitReferenceTargets(DynTypedNode N, DeclRelationSet Mask, const HeuristicResolver *Resolver)
Find declarations explicitly referenced in the source code defined by N.
Definition: FindTarget.cpp:568
clang::clangd::operator<<
llvm::raw_ostream & operator<<(llvm::raw_ostream &OS, const CodeCompletion &C)
Definition: CodeComplete.cpp:2172
clang::clangd::HoverInfo::NamespaceScope
llvm::Optional< std::string > NamespaceScope
For a variable named Bar, declared in clang::clangd::Foo::getFoo the following fields will hold:
Definition: Hover.h:63
clang::clangd::HoverInfo::Param::Default
llvm::Optional< std::string > Default
None if no default is provided.
Definition: Hover.h:50
clang::clangd::ParsedAST::getPreprocessor
Preprocessor & getPreprocessor()
Definition: ParsedAST.cpp:705
Output
std::string Output
Definition: TraceTests.cpp:159
clang::clangd::SelectionTree::Node
Definition: Selection.h:122
clang::tidy::bugprone::PP
static Preprocessor * PP
Definition: BadSignalToKillThreadCheck.cpp:29
Config
static cl::opt< std::string > Config("config", cl::desc(R"( Specifies a configuration in YAML/JSON format: -config="{Checks:' *', CheckOptions:[{key:x, value:y}]}" When the value is empty, clang-tidy will attempt to find a file named .clang-tidy for each source file in its parent directories. )"), cl::init(""), cl::cat(ClangTidyCategory))
clang::clangd::markup::Paragraph::appendCode
Paragraph & appendCode(llvm::StringRef Code, bool Preserve=false)
Append inline code, this translates to the ` block in markdown.
Definition: Markup.cpp:433
clang::clangd::parseDocumentationLine
void parseDocumentationLine(llvm::StringRef Line, markup::Paragraph &Out)
Definition: Hover.cpp:1213
clang::clangd::SelectionTree::commonAncestor
const Node * commonAncestor() const
Definition: Selection.cpp:1069
clang::clangd::getSymbolID
SymbolID getSymbolID(const Decl *D)
Gets the symbol ID for a declaration. Returned SymbolID might be null.
Definition: AST.cpp:335
SourceCode.h
Index
const SymbolIndex * Index
Definition: Dexp.cpp:98
clang::clangd::SymbolIndex
Interface for symbol indexes that can be used for searching or matching symbols among a set of symbol...
Definition: Index.h:113
Config.h
CE
CaptureExpr CE
Definition: AvoidBindCheck.cpp:67
clang::clangd::HoverInfo::LocalScope
std::string LocalScope
Remaining named contexts in symbol's qualified name, empty string means symbol is not local.
Definition: Hover.h:66
clang::clangd::HoverInfo::DefinitionLanguage
const char * DefinitionLanguage
Definition: Hover.h:74
ID
static char ID
Definition: Logger.cpp:74
clang::clangd::HoverInfo::present
markup::Document present() const
Produce a user-readable information.
Definition: Hover.cpp:1071
clang::clangd::HoverInfo::PrintedType
Contains pretty-printed type and desugared type.
Definition: Hover.h:26
clang::clangd::Range
Definition: Protocol.h:182
clang::clangd::URIForFile::canonicalize
static URIForFile canonicalize(llvm::StringRef AbsPath, llvm::StringRef TUPath)
Canonicalizes AbsPath via URI.
Definition: Protocol.cpp:45
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27
OS
llvm::raw_string_ostream OS
Definition: TraceTests.cpp:160
clang::clangd::HoverInfo::CalleeArgInfo
llvm::Optional< Param > CalleeArgInfo
Definition: Hover.h:97
clang::clangd::ParsedAST::getTokens
const syntax::TokenBuffer & getTokens() const
Tokens recorded while parsing the main file.
Definition: ParsedAST.h:106
LangOpts
const LangOptions * LangOpts
Definition: ExtractFunction.cpp:366
clang::doc::Record
llvm::SmallVector< uint64_t, 1024 > Record
Definition: BitcodeReader.cpp:18
clang::clangd::HoverInfo::Value
llvm::Optional< std::string > Value
Contains the evaluated value of the symbol if available.
Definition: Hover.h:88
clang::clangd::Config::current
static const Config & current()
Returns the Config of the current Context, or an empty configuration.
Definition: Config.cpp:17
clang::clangd::parseDocumentation
void parseDocumentation(llvm::StringRef Input, markup::Document &Output)
Definition: Hover.cpp:1229
clang::clangd::URIForFile::file
llvm::StringRef file() const
Retrieves absolute path to the file.
Definition: Protocol.h:101
SymbolCollector.h
clang::clangd::getBacktickQuoteRange
llvm::Optional< llvm::StringRef > getBacktickQuoteRange(llvm::StringRef Line, unsigned Offset)
Definition: Hover.cpp:1185
clang::clangd::HoverInfo::PassType::Value
@ Value
Definition: Hover.h:100
clang::clangd::ParsedAST
Stores and provides access to parsed AST.
Definition: ParsedAST.h:45
clang::clangd::printObjCContainer
std::string printObjCContainer(const ObjCContainerDecl &C)
Print the Objective-C container name including categories, e.g. MyClass,.
Definition: AST.cpp:314
Field
const FieldDecl * Field
Definition: MemberwiseConstructor.cpp:260
Out
CompiledFragmentImpl & Out
Definition: ConfigCompile.cpp:99
clang::clangd::RefKind::Definition
@ Definition
clang::clangd::ParsedAST::getSourceManager
SourceManager & getSourceManager()
Definition: ParsedAST.h:73
clang::clangd::HoverInfo::Param
Represents parameters of a function, a template or a macro.
Definition: Hover.h:43
clang::clangd::HoverInfo::PassType::ConstRef
@ ConstRef
Definition: Hover.h:100
clang::clangd::HoverInfo::Param::Type
llvm::Optional< PrintedType > Type
The printable parameter type, e.g.
Definition: Hover.h:46
clang::clangd::sourceLocationInMainFile
llvm::Expected< SourceLocation > sourceLocationInMainFile(const SourceManager &SM, Position P)
Return the file location, corresponding to P.
Definition: SourceCode.cpp:453
clang::clangd::HoverInfo::Documentation
std::string Documentation
Definition: Hover.h:71
clang::clangd::Config::ShowAKA
bool ShowAKA
Whether hover show a.k.a type.
Definition: Config.h:132
clang::clangd::DeclRelation::Alias
@ Alias
This declaration is an alias that was referred to.
AST.h
ParsedAST.h