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