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 
getPrintingPolicy(PrintingPolicy Base)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.
getLocalScope(const Decl * D)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.
getNamespaceScope(const Decl * D)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 
printDefinition(const Decl * D,PrintingPolicy PP,const syntax::TokenBuffer & TB)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 
getMarkdownLanguage(const ASTContext & Ctx)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 
printType(QualType QT,ASTContext & ASTCtx,const PrintingPolicy & PP)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 
printType(const TemplateTypeParmDecl * TTP)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 
printType(const NonTypeTemplateParmDecl * NTTP,const PrintingPolicy & PP)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 
printType(const TemplateTemplateParmDecl * TTP,const PrintingPolicy & PP)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>
fetchTemplateParameters(const TemplateParameterList * Params,const PrintingPolicy & PP)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 
getUnderlyingFunction(const Decl * D)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.
getDeclForComment(const NamedDecl * D)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.
enhanceFromIndex(HoverInfo & Hover,const NamedDecl & ND,const SymbolIndex * Index)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.
getDefaultArg(const ParmVarDecl * PVD)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 
toHoverInfoParam(const ParmVarDecl * PVD,const PrintingPolicy & PP)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.
fillFunctionTypeAndParams(HoverInfo & HI,const Decl * D,const FunctionDecl * FD,const PrintingPolicy & PP)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
printHex(const llvm::APSInt & V)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 
printExprValue(const Expr * E,const ASTContext & Ctx)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 
printExprValue(const SelectionTree::Node * N,const ASTContext & Ctx)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 
fieldName(const Expr * E)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".
getterVariableName(const CXXMethodDecl * CMD)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"
setterVariableName(const CXXMethodDecl * CMD)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 
synthesizeDocumentation(const NamedDecl * ND)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.
getHoverContents(const NamedDecl * D,const PrintingPolicy & PP,const SymbolIndex * Index,const syntax::TokenBuffer & TB)577 HoverInfo getHoverContents(const NamedDecl *D, const PrintingPolicy &PP,
578                            const SymbolIndex *Index,
579                            const syntax::TokenBuffer &TB) {
580   HoverInfo HI;
581   auto &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(), Ctx, 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 = printType(VT->getTemplatedDecl()->getType(), Ctx, PP);
624   else if (const auto *TN = dyn_cast<TypedefNameDecl>(D))
625     HI.Type = printType(TN->getUnderlyingType().getDesugaredType(Ctx), Ctx, PP);
626   else if (const auto *TAT = dyn_cast<TypeAliasTemplateDecl>(D))
627     HI.Type = printType(TAT->getTemplatedDecl()->getUnderlyingType(), Ctx, PP);
628 
629   // Fill in value with evaluated initializer if possible.
630   if (const auto *Var = dyn_cast<VarDecl>(D)) {
631     if (const Expr *Init = Var->getInit())
632       HI.Value = printExprValue(Init, Ctx);
633   } else if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
634     // Dependent enums (e.g. nested in template classes) don't have values yet.
635     if (!ECD->getType()->isDependentType())
636       HI.Value = toString(ECD->getInitVal(), 10);
637   }
638 
639   HI.Definition = printDefinition(D, PP, TB);
640   return HI;
641 }
642 
643 /// Generate a \p Hover object given the macro \p MacroDecl.
getHoverContents(const DefinedMacro & Macro,ParsedAST & AST)644 HoverInfo getHoverContents(const DefinedMacro &Macro, ParsedAST &AST) {
645   HoverInfo HI;
646   SourceManager &SM = AST.getSourceManager();
647   HI.Name = std::string(Macro.Name);
648   HI.Kind = index::SymbolKind::Macro;
649   // FIXME: Populate documentation
650   // FIXME: Populate parameters
651 
652   // Try to get the full definition, not just the name
653   SourceLocation StartLoc = Macro.Info->getDefinitionLoc();
654   SourceLocation EndLoc = Macro.Info->getDefinitionEndLoc();
655   // Ensure that EndLoc is a valid offset. For example it might come from
656   // preamble, and source file might've changed, in such a scenario EndLoc still
657   // stays valid, but getLocForEndOfToken will fail as it is no longer a valid
658   // offset.
659   // Note that this check is just to ensure there's text data inside the range.
660   // It will still succeed even when the data inside the range is irrelevant to
661   // macro definition.
662   if (SM.getPresumedLoc(EndLoc, /*UseLineDirectives=*/false).isValid()) {
663     EndLoc = Lexer::getLocForEndOfToken(EndLoc, 0, SM, AST.getLangOpts());
664     bool Invalid;
665     StringRef Buffer = SM.getBufferData(SM.getFileID(StartLoc), &Invalid);
666     if (!Invalid) {
667       unsigned StartOffset = SM.getFileOffset(StartLoc);
668       unsigned EndOffset = SM.getFileOffset(EndLoc);
669       if (EndOffset <= Buffer.size() && StartOffset < EndOffset)
670         HI.Definition =
671             ("#define " + Buffer.substr(StartOffset, EndOffset - StartOffset))
672                 .str();
673     }
674   }
675   return HI;
676 }
677 
typeAsDefinition(const HoverInfo::PrintedType & PType)678 std::string typeAsDefinition(const HoverInfo::PrintedType &PType) {
679   std::string Result;
680   llvm::raw_string_ostream OS(Result);
681   OS << PType.Type;
682   if (PType.AKA)
683     OS << " // aka: " << *PType.AKA;
684   OS.flush();
685   return Result;
686 }
687 
getThisExprHoverContents(const CXXThisExpr * CTE,ASTContext & ASTCtx,const PrintingPolicy & PP)688 llvm::Optional<HoverInfo> getThisExprHoverContents(const CXXThisExpr *CTE,
689                                                    ASTContext &ASTCtx,
690                                                    const PrintingPolicy &PP) {
691   QualType OriginThisType = CTE->getType()->getPointeeType();
692   QualType ClassType = declaredType(OriginThisType->getAsTagDecl());
693   // For partial specialization class, origin `this` pointee type will be
694   // parsed as `InjectedClassNameType`, which will ouput template arguments
695   // like "type-parameter-0-0". So we retrieve user written class type in this
696   // case.
697   QualType PrettyThisType = ASTCtx.getPointerType(
698       QualType(ClassType.getTypePtr(), OriginThisType.getCVRQualifiers()));
699 
700   HoverInfo HI;
701   HI.Name = "this";
702   HI.Definition = typeAsDefinition(printType(PrettyThisType, ASTCtx, PP));
703   return HI;
704 }
705 
706 /// Generate a HoverInfo object given the deduced type \p QT
getDeducedTypeHoverContents(QualType QT,const syntax::Token & Tok,ASTContext & ASTCtx,const PrintingPolicy & PP,const SymbolIndex * Index)707 HoverInfo getDeducedTypeHoverContents(QualType QT, const syntax::Token &Tok,
708                                       ASTContext &ASTCtx,
709                                       const PrintingPolicy &PP,
710                                       const SymbolIndex *Index) {
711   HoverInfo HI;
712   // FIXME: distinguish decltype(auto) vs decltype(expr)
713   HI.Name = tok::getTokenName(Tok.kind());
714   HI.Kind = index::SymbolKind::TypeAlias;
715 
716   if (QT->isUndeducedAutoType()) {
717     HI.Definition = "/* not deduced */";
718   } else {
719     HI.Definition = typeAsDefinition(printType(QT, ASTCtx, PP));
720 
721     if (const auto *D = QT->getAsTagDecl()) {
722       const auto *CommentD = getDeclForComment(D);
723       HI.Documentation = getDeclComment(ASTCtx, *CommentD);
724       enhanceFromIndex(HI, *CommentD, Index);
725     }
726   }
727 
728   return HI;
729 }
730 
isLiteral(const Expr * E)731 bool isLiteral(const Expr *E) {
732   // Unfortunately there's no common base Literal classes inherits from
733   // (apart from Expr), therefore these exclusions.
734   return llvm::isa<CompoundLiteralExpr>(E) ||
735          llvm::isa<CXXBoolLiteralExpr>(E) ||
736          llvm::isa<CXXNullPtrLiteralExpr>(E) ||
737          llvm::isa<FixedPointLiteral>(E) || llvm::isa<FloatingLiteral>(E) ||
738          llvm::isa<ImaginaryLiteral>(E) || llvm::isa<IntegerLiteral>(E) ||
739          llvm::isa<StringLiteral>(E) || llvm::isa<UserDefinedLiteral>(E);
740 }
741 
getNameForExpr(const Expr * E)742 llvm::StringLiteral getNameForExpr(const Expr *E) {
743   // FIXME: Come up with names for `special` expressions.
744   //
745   // It's an known issue for GCC5, https://godbolt.org/z/Z_tbgi. Work around
746   // that by using explicit conversion constructor.
747   //
748   // TODO: Once GCC5 is fully retired and not the minimal requirement as stated
749   // in `GettingStarted`, please remove the explicit conversion constructor.
750   return llvm::StringLiteral("expression");
751 }
752 
753 // Generates hover info for `this` and evaluatable expressions.
754 // FIXME: Support hover for literals (esp user-defined)
getHoverContents(const Expr * E,ParsedAST & AST,const PrintingPolicy & PP,const SymbolIndex * Index)755 llvm::Optional<HoverInfo> getHoverContents(const Expr *E, ParsedAST &AST,
756                                            const PrintingPolicy &PP,
757                                            const SymbolIndex *Index) {
758   // There's not much value in hovering over "42" and getting a hover card
759   // saying "42 is an int", similar for other literals.
760   if (isLiteral(E))
761     return llvm::None;
762 
763   HoverInfo HI;
764   // For `this` expr we currently generate hover with pointee type.
765   if (const CXXThisExpr *CTE = dyn_cast<CXXThisExpr>(E))
766     return getThisExprHoverContents(CTE, AST.getASTContext(), PP);
767   // For expressions we currently print the type and the value, iff it is
768   // evaluatable.
769   if (auto Val = printExprValue(E, AST.getASTContext())) {
770     HI.Type = printType(E->getType(), AST.getASTContext(), PP);
771     HI.Value = *Val;
772     HI.Name = std::string(getNameForExpr(E));
773     return HI;
774   }
775   return llvm::None;
776 }
777 
778 // Generates hover info for attributes.
getHoverContents(const Attr * A,ParsedAST & AST)779 llvm::Optional<HoverInfo> getHoverContents(const Attr *A, ParsedAST &AST) {
780   HoverInfo HI;
781   HI.Name = A->getSpelling();
782   if (A->hasScope())
783     HI.LocalScope = A->getScopeName()->getName().str();
784   {
785     llvm::raw_string_ostream OS(HI.Definition);
786     A->printPretty(OS, AST.getASTContext().getPrintingPolicy());
787   }
788   HI.Documentation = Attr::getDocumentation(A->getKind()).str();
789   return HI;
790 }
791 
isParagraphBreak(llvm::StringRef Rest)792 bool isParagraphBreak(llvm::StringRef Rest) {
793   return Rest.ltrim(" \t").startswith("\n");
794 }
795 
punctuationIndicatesLineBreak(llvm::StringRef Line)796 bool punctuationIndicatesLineBreak(llvm::StringRef Line) {
797   constexpr llvm::StringLiteral Punctuation = R"txt(.:,;!?)txt";
798 
799   Line = Line.rtrim();
800   return !Line.empty() && Punctuation.contains(Line.back());
801 }
802 
isHardLineBreakIndicator(llvm::StringRef Rest)803 bool isHardLineBreakIndicator(llvm::StringRef Rest) {
804   // '-'/'*' md list, '@'/'\' documentation command, '>' md blockquote,
805   // '#' headings, '`' code blocks
806   constexpr llvm::StringLiteral LinebreakIndicators = R"txt(-*@\>#`)txt";
807 
808   Rest = Rest.ltrim(" \t");
809   if (Rest.empty())
810     return false;
811 
812   if (LinebreakIndicators.contains(Rest.front()))
813     return true;
814 
815   if (llvm::isDigit(Rest.front())) {
816     llvm::StringRef AfterDigit = Rest.drop_while(llvm::isDigit);
817     if (AfterDigit.startswith(".") || AfterDigit.startswith(")"))
818       return true;
819   }
820   return false;
821 }
822 
isHardLineBreakAfter(llvm::StringRef Line,llvm::StringRef Rest)823 bool isHardLineBreakAfter(llvm::StringRef Line, llvm::StringRef Rest) {
824   // Should we also consider whether Line is short?
825   return punctuationIndicatesLineBreak(Line) || isHardLineBreakIndicator(Rest);
826 }
827 
addLayoutInfo(const NamedDecl & ND,HoverInfo & HI)828 void addLayoutInfo(const NamedDecl &ND, HoverInfo &HI) {
829   if (ND.isInvalidDecl())
830     return;
831 
832   const auto &Ctx = ND.getASTContext();
833   if (auto *RD = llvm::dyn_cast<RecordDecl>(&ND)) {
834     if (auto Size = Ctx.getTypeSizeInCharsIfKnown(RD->getTypeForDecl()))
835       HI.Size = Size->getQuantity();
836     return;
837   }
838 
839   if (const auto *FD = llvm::dyn_cast<FieldDecl>(&ND)) {
840     const auto *Record = FD->getParent();
841     if (Record)
842       Record = Record->getDefinition();
843     if (Record && !Record->isInvalidDecl() && !Record->isDependentType() &&
844         !FD->isBitField()) {
845       const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Record);
846       HI.Offset = Layout.getFieldOffset(FD->getFieldIndex()) / 8;
847       if (auto Size = Ctx.getTypeSizeInCharsIfKnown(FD->getType())) {
848         HI.Size = FD->isZeroSize(Ctx) ? 0 : Size->getQuantity();
849         unsigned EndOfField = *HI.Offset + *HI.Size;
850 
851         // Calculate padding following the field.
852         if (!Record->isUnion() &&
853             FD->getFieldIndex() + 1 < Layout.getFieldCount()) {
854           // Measure padding up to the next class field.
855           unsigned NextOffset =
856               Layout.getFieldOffset(FD->getFieldIndex() + 1) / 8;
857           if (NextOffset >= EndOfField) // next field could be a bitfield!
858             HI.Padding = NextOffset - EndOfField;
859         } else {
860           // Measure padding up to the end of the object.
861           HI.Padding = Layout.getSize().getQuantity() - EndOfField;
862         }
863       }
864       // Offset in a union is always zero, so not really useful to report.
865       if (Record->isUnion())
866         HI.Offset.reset();
867     }
868     return;
869   }
870 }
871 
872 // If N is passed as argument to a function, fill HI.CalleeArgInfo with
873 // information about that argument.
maybeAddCalleeArgInfo(const SelectionTree::Node * N,HoverInfo & HI,const PrintingPolicy & PP)874 void maybeAddCalleeArgInfo(const SelectionTree::Node *N, HoverInfo &HI,
875                            const PrintingPolicy &PP) {
876   const auto &OuterNode = N->outerImplicit();
877   if (!OuterNode.Parent)
878     return;
879   const auto *CE = OuterNode.Parent->ASTNode.get<CallExpr>();
880   if (!CE)
881     return;
882   const FunctionDecl *FD = CE->getDirectCallee();
883   // For non-function-call-like operatators (e.g. operator+, operator<<) it's
884   // not immediattely obvious what the "passed as" would refer to and, given
885   // fixed function signature, the value would be very low anyway, so we choose
886   // to not support that.
887   // Both variadic functions and operator() (especially relevant for lambdas)
888   // should be supported in the future.
889   if (!FD || FD->isOverloadedOperator() || FD->isVariadic())
890     return;
891 
892   // Find argument index for N.
893   for (unsigned I = 0; I < CE->getNumArgs() && I < FD->getNumParams(); ++I) {
894     if (CE->getArg(I) != OuterNode.ASTNode.get<Expr>())
895       continue;
896 
897     // Extract matching argument from function declaration.
898     if (const ParmVarDecl *PVD = FD->getParamDecl(I))
899       HI.CalleeArgInfo.emplace(toHoverInfoParam(PVD, PP));
900     break;
901   }
902   if (!HI.CalleeArgInfo)
903     return;
904 
905   // If we found a matching argument, also figure out if it's a
906   // [const-]reference. For this we need to walk up the AST from the arg itself
907   // to CallExpr and check all implicit casts, constructor calls, etc.
908   HoverInfo::PassType PassType;
909   if (const auto *E = N->ASTNode.get<Expr>()) {
910     if (E->getType().isConstQualified())
911       PassType.PassBy = HoverInfo::PassType::ConstRef;
912   }
913 
914   for (auto *CastNode = N->Parent;
915        CastNode != OuterNode.Parent && !PassType.Converted;
916        CastNode = CastNode->Parent) {
917     if (const auto *ImplicitCast = CastNode->ASTNode.get<ImplicitCastExpr>()) {
918       switch (ImplicitCast->getCastKind()) {
919       case CK_NoOp:
920       case CK_DerivedToBase:
921       case CK_UncheckedDerivedToBase:
922         // If it was a reference before, it's still a reference.
923         if (PassType.PassBy != HoverInfo::PassType::Value)
924           PassType.PassBy = ImplicitCast->getType().isConstQualified()
925                                 ? HoverInfo::PassType::ConstRef
926                                 : HoverInfo::PassType::Ref;
927         break;
928       case CK_LValueToRValue:
929       case CK_ArrayToPointerDecay:
930       case CK_FunctionToPointerDecay:
931       case CK_NullToPointer:
932       case CK_NullToMemberPointer:
933         // No longer a reference, but we do not show this as type conversion.
934         PassType.PassBy = HoverInfo::PassType::Value;
935         break;
936       default:
937         PassType.PassBy = HoverInfo::PassType::Value;
938         PassType.Converted = true;
939         break;
940       }
941     } else if (const auto *CtorCall =
942                    CastNode->ASTNode.get<CXXConstructExpr>()) {
943       // We want to be smart about copy constructors. They should not show up as
944       // type conversion, but instead as passing by value.
945       if (CtorCall->getConstructor()->isCopyConstructor())
946         PassType.PassBy = HoverInfo::PassType::Value;
947       else
948         PassType.Converted = true;
949     } else { // Unknown implicit node, assume type conversion.
950       PassType.PassBy = HoverInfo::PassType::Value;
951       PassType.Converted = true;
952     }
953   }
954 
955   HI.CallPassType.emplace(PassType);
956 }
957 
958 } // namespace
959 
getHover(ParsedAST & AST,Position Pos,const format::FormatStyle & Style,const SymbolIndex * Index)960 llvm::Optional<HoverInfo> getHover(ParsedAST &AST, Position Pos,
961                                    const format::FormatStyle &Style,
962                                    const SymbolIndex *Index) {
963   PrintingPolicy PP =
964       getPrintingPolicy(AST.getASTContext().getPrintingPolicy());
965   const SourceManager &SM = AST.getSourceManager();
966   auto CurLoc = sourceLocationInMainFile(SM, Pos);
967   if (!CurLoc) {
968     llvm::consumeError(CurLoc.takeError());
969     return llvm::None;
970   }
971   const auto &TB = AST.getTokens();
972   auto TokensTouchingCursor = syntax::spelledTokensTouching(*CurLoc, TB);
973   // Early exit if there were no tokens around the cursor.
974   if (TokensTouchingCursor.empty())
975     return llvm::None;
976 
977   // Show full header file path if cursor is on include directive.
978   if (const auto MainFilePath =
979           getCanonicalPath(SM.getFileEntryForID(SM.getMainFileID()), SM)) {
980     for (const auto &Inc : AST.getIncludeStructure().MainFileIncludes) {
981       if (Inc.Resolved.empty() || Inc.HashLine != Pos.line)
982         continue;
983       HoverInfo HI;
984       HI.Name = std::string(llvm::sys::path::filename(Inc.Resolved));
985       // FIXME: We don't have a fitting value for Kind.
986       HI.Definition =
987           URIForFile::canonicalize(Inc.Resolved, *MainFilePath).file().str();
988       HI.DefinitionLanguage = "";
989       return HI;
990     }
991   }
992 
993   // To be used as a backup for highlighting the selected token, we use back as
994   // it aligns better with biases elsewhere (editors tend to send the position
995   // for the left of the hovered token).
996   CharSourceRange HighlightRange =
997       TokensTouchingCursor.back().range(SM).toCharRange(SM);
998   llvm::Optional<HoverInfo> HI;
999   // Macros and deducedtype only works on identifiers and auto/decltype keywords
1000   // respectively. Therefore they are only trggered on whichever works for them,
1001   // similar to SelectionTree::create().
1002   for (const auto &Tok : TokensTouchingCursor) {
1003     if (Tok.kind() == tok::identifier) {
1004       // Prefer the identifier token as a fallback highlighting range.
1005       HighlightRange = Tok.range(SM).toCharRange(SM);
1006       if (auto M = locateMacroAt(Tok, AST.getPreprocessor())) {
1007         HI = getHoverContents(*M, AST);
1008         break;
1009       }
1010     } else if (Tok.kind() == tok::kw_auto || Tok.kind() == tok::kw_decltype) {
1011       if (auto Deduced = getDeducedType(AST.getASTContext(), Tok.location())) {
1012         HI = getDeducedTypeHoverContents(*Deduced, Tok, AST.getASTContext(), PP,
1013                                          Index);
1014         HighlightRange = Tok.range(SM).toCharRange(SM);
1015         break;
1016       }
1017 
1018       // If we can't find interesting hover information for this
1019       // auto/decltype keyword, return nothing to avoid showing
1020       // irrelevant or incorrect informations.
1021       return llvm::None;
1022     }
1023   }
1024 
1025   // If it wasn't auto/decltype or macro, look for decls and expressions.
1026   if (!HI) {
1027     auto Offset = SM.getFileOffset(*CurLoc);
1028     // Editors send the position on the left of the hovered character.
1029     // So our selection tree should be biased right. (Tested with VSCode).
1030     SelectionTree ST =
1031         SelectionTree::createRight(AST.getASTContext(), TB, Offset, Offset);
1032     if (const SelectionTree::Node *N = ST.commonAncestor()) {
1033       // FIXME: Fill in HighlightRange with range coming from N->ASTNode.
1034       auto Decls = explicitReferenceTargets(N->ASTNode, DeclRelation::Alias,
1035                                             AST.getHeuristicResolver());
1036       if (!Decls.empty()) {
1037         HI = getHoverContents(Decls.front(), PP, Index, TB);
1038         // Layout info only shown when hovering on the field/class itself.
1039         if (Decls.front() == N->ASTNode.get<Decl>())
1040           addLayoutInfo(*Decls.front(), *HI);
1041         // Look for a close enclosing expression to show the value of.
1042         if (!HI->Value)
1043           HI->Value = printExprValue(N, AST.getASTContext());
1044         maybeAddCalleeArgInfo(N, *HI, PP);
1045       } else if (const Expr *E = N->ASTNode.get<Expr>()) {
1046         HI = getHoverContents(E, AST, PP, Index);
1047       } else if (const Attr *A = N->ASTNode.get<Attr>()) {
1048         HI = getHoverContents(A, AST);
1049       }
1050       // FIXME: support hovers for other nodes?
1051       //  - built-in types
1052     }
1053   }
1054 
1055   if (!HI)
1056     return llvm::None;
1057 
1058   auto Replacements = format::reformat(
1059       Style, HI->Definition, tooling::Range(0, HI->Definition.size()));
1060   if (auto Formatted =
1061           tooling::applyAllReplacements(HI->Definition, Replacements))
1062     HI->Definition = *Formatted;
1063   HI->DefinitionLanguage = getMarkdownLanguage(AST.getASTContext());
1064   HI->SymRange = halfOpenToRange(SM, HighlightRange);
1065 
1066   return HI;
1067 }
1068 
present() const1069 markup::Document HoverInfo::present() const {
1070   markup::Document Output;
1071 
1072   // Header contains a text of the form:
1073   // variable `var`
1074   //
1075   // class `X`
1076   //
1077   // function `foo`
1078   //
1079   // expression
1080   //
1081   // Note that we are making use of a level-3 heading because VSCode renders
1082   // level 1 and 2 headers in a huge font, see
1083   // https://github.com/microsoft/vscode/issues/88417 for details.
1084   markup::Paragraph &Header = Output.addHeading(3);
1085   if (Kind != index::SymbolKind::Unknown)
1086     Header.appendText(index::getSymbolKindString(Kind)).appendSpace();
1087   assert(!Name.empty() && "hover triggered on a nameless symbol");
1088   Header.appendCode(Name);
1089 
1090   // Put a linebreak after header to increase readability.
1091   Output.addRuler();
1092   // Print Types on their own lines to reduce chances of getting line-wrapped by
1093   // editor, as they might be long.
1094   if (ReturnType) {
1095     // For functions we display signature in a list form, e.g.:
1096     // → `x`
1097     // Parameters:
1098     // - `bool param1`
1099     // - `int param2 = 5`
1100     Output.addParagraph().appendText("→ ").appendCode(
1101         llvm::to_string(*ReturnType));
1102   }
1103 
1104   if (Parameters && !Parameters->empty()) {
1105     Output.addParagraph().appendText("Parameters: ");
1106     markup::BulletList &L = Output.addBulletList();
1107     for (const auto &Param : *Parameters)
1108       L.addItem().addParagraph().appendCode(llvm::to_string(Param));
1109   }
1110 
1111   // Don't print Type after Parameters or ReturnType as this will just duplicate
1112   // the information
1113   if (Type && !ReturnType && !Parameters)
1114     Output.addParagraph().appendText("Type: ").appendCode(
1115         llvm::to_string(*Type));
1116 
1117   if (Value) {
1118     markup::Paragraph &P = Output.addParagraph();
1119     P.appendText("Value = ");
1120     P.appendCode(*Value);
1121   }
1122 
1123   if (Offset)
1124     Output.addParagraph().appendText(
1125         llvm::formatv("Offset: {0} byte{1}", *Offset, *Offset == 1 ? "" : "s")
1126             .str());
1127   if (Size) {
1128     auto &P = Output.addParagraph().appendText(
1129         llvm::formatv("Size: {0} byte{1}", *Size, *Size == 1 ? "" : "s").str());
1130     if (Padding && *Padding != 0)
1131       P.appendText(llvm::formatv(" (+{0} padding)", *Padding).str());
1132   }
1133 
1134   if (CalleeArgInfo) {
1135     assert(CallPassType);
1136     std::string Buffer;
1137     llvm::raw_string_ostream OS(Buffer);
1138     OS << "Passed ";
1139     if (CallPassType->PassBy != HoverInfo::PassType::Value) {
1140       OS << "by ";
1141       if (CallPassType->PassBy == HoverInfo::PassType::ConstRef)
1142         OS << "const ";
1143       OS << "reference ";
1144     }
1145     if (CalleeArgInfo->Name)
1146       OS << "as " << CalleeArgInfo->Name;
1147     if (CallPassType->Converted && CalleeArgInfo->Type)
1148       OS << " (converted to " << CalleeArgInfo->Type->Type << ")";
1149     Output.addParagraph().appendText(OS.str());
1150   }
1151 
1152   if (!Documentation.empty())
1153     parseDocumentation(Documentation, Output);
1154 
1155   if (!Definition.empty()) {
1156     Output.addRuler();
1157     std::string ScopeComment;
1158     // Drop trailing "::".
1159     if (!LocalScope.empty()) {
1160       // Container name, e.g. class, method, function.
1161       // We might want to propagate some info about container type to print
1162       // function foo, class X, method X::bar, etc.
1163       ScopeComment =
1164           "// In " + llvm::StringRef(LocalScope).rtrim(':').str() + '\n';
1165     } else if (NamespaceScope && !NamespaceScope->empty()) {
1166       ScopeComment = "// In namespace " +
1167                      llvm::StringRef(*NamespaceScope).rtrim(':').str() + '\n';
1168     }
1169     std::string DefinitionWithAccess = !AccessSpecifier.empty()
1170                                            ? AccessSpecifier + ": " + Definition
1171                                            : Definition;
1172     // Note that we don't print anything for global namespace, to not annoy
1173     // non-c++ projects or projects that are not making use of namespaces.
1174     Output.addCodeBlock(ScopeComment + DefinitionWithAccess,
1175                         DefinitionLanguage);
1176   }
1177 
1178   return Output;
1179 }
1180 
1181 // If the backtick at `Offset` starts a probable quoted range, return the range
1182 // (including the quotes).
getBacktickQuoteRange(llvm::StringRef Line,unsigned Offset)1183 llvm::Optional<llvm::StringRef> getBacktickQuoteRange(llvm::StringRef Line,
1184                                                       unsigned Offset) {
1185   assert(Line[Offset] == '`');
1186 
1187   // The open-quote is usually preceded by whitespace.
1188   llvm::StringRef Prefix = Line.substr(0, Offset);
1189   constexpr llvm::StringLiteral BeforeStartChars = " \t(=";
1190   if (!Prefix.empty() && !BeforeStartChars.contains(Prefix.back()))
1191     return llvm::None;
1192 
1193   // The quoted string must be nonempty and usually has no leading/trailing ws.
1194   auto Next = Line.find('`', Offset + 1);
1195   if (Next == llvm::StringRef::npos)
1196     return llvm::None;
1197   llvm::StringRef Contents = Line.slice(Offset + 1, Next);
1198   if (Contents.empty() || isWhitespace(Contents.front()) ||
1199       isWhitespace(Contents.back()))
1200     return llvm::None;
1201 
1202   // The close-quote is usually followed by whitespace or punctuation.
1203   llvm::StringRef Suffix = Line.substr(Next + 1);
1204   constexpr llvm::StringLiteral AfterEndChars = " \t)=.,;:";
1205   if (!Suffix.empty() && !AfterEndChars.contains(Suffix.front()))
1206     return llvm::None;
1207 
1208   return Line.slice(Offset, Next + 1);
1209 }
1210 
parseDocumentationLine(llvm::StringRef Line,markup::Paragraph & Out)1211 void parseDocumentationLine(llvm::StringRef Line, markup::Paragraph &Out) {
1212   // Probably this is appendText(Line), but scan for something interesting.
1213   for (unsigned I = 0; I < Line.size(); ++I) {
1214     switch (Line[I]) {
1215     case '`':
1216       if (auto Range = getBacktickQuoteRange(Line, I)) {
1217         Out.appendText(Line.substr(0, I));
1218         Out.appendCode(Range->trim("`"), /*Preserve=*/true);
1219         return parseDocumentationLine(Line.substr(I + Range->size()), Out);
1220       }
1221       break;
1222     }
1223   }
1224   Out.appendText(Line).appendSpace();
1225 }
1226 
parseDocumentation(llvm::StringRef Input,markup::Document & Output)1227 void parseDocumentation(llvm::StringRef Input, markup::Document &Output) {
1228   std::vector<llvm::StringRef> ParagraphLines;
1229   auto FlushParagraph = [&] {
1230     if (ParagraphLines.empty())
1231       return;
1232     auto &P = Output.addParagraph();
1233     for (llvm::StringRef Line : ParagraphLines)
1234       parseDocumentationLine(Line, P);
1235     ParagraphLines.clear();
1236   };
1237 
1238   llvm::StringRef Line, Rest;
1239   for (std::tie(Line, Rest) = Input.split('\n');
1240        !(Line.empty() && Rest.empty());
1241        std::tie(Line, Rest) = Rest.split('\n')) {
1242 
1243     // After a linebreak remove spaces to avoid 4 space markdown code blocks.
1244     // FIXME: make FlushParagraph handle this.
1245     Line = Line.ltrim();
1246     if (!Line.empty())
1247       ParagraphLines.push_back(Line);
1248 
1249     if (isParagraphBreak(Rest) || isHardLineBreakAfter(Line, Rest)) {
1250       FlushParagraph();
1251     }
1252   }
1253   FlushParagraph();
1254 }
1255 
operator <<(llvm::raw_ostream & OS,const HoverInfo::PrintedType & T)1256 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
1257                               const HoverInfo::PrintedType &T) {
1258   OS << T.Type;
1259   if (T.AKA)
1260     OS << " (aka " << *T.AKA << ")";
1261   return OS;
1262 }
1263 
operator <<(llvm::raw_ostream & OS,const HoverInfo::Param & P)1264 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
1265                               const HoverInfo::Param &P) {
1266   if (P.Type)
1267     OS << P.Type->Type;
1268   if (P.Name)
1269     OS << " " << *P.Name;
1270   if (P.Default)
1271     OS << " = " << *P.Default;
1272   if (P.Type && P.Type->AKA)
1273     OS << " (aka " << *P.Type->AKA << ")";
1274   return OS;
1275 }
1276 
1277 } // namespace clangd
1278 } // namespace clang
1279