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