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 "Headers.h"
16#include "IncludeCleaner.h"
17#include "ParsedAST.h"
18#include "Selection.h"
19#include "SourceCode.h"
20#include "clang-include-cleaner/Analysis.h"
21#include "clang-include-cleaner/IncludeSpeller.h"
22#include "clang-include-cleaner/Types.h"
23#include "index/SymbolCollector.h"
24#include "support/Markup.h"
25#include "support/Trace.h"
26#include "clang/AST/ASTContext.h"
27#include "clang/AST/ASTDiagnostic.h"
28#include "clang/AST/ASTTypeTraits.h"
29#include "clang/AST/Attr.h"
30#include "clang/AST/Decl.h"
31#include "clang/AST/DeclBase.h"
32#include "clang/AST/DeclCXX.h"
33#include "clang/AST/DeclObjC.h"
34#include "clang/AST/DeclTemplate.h"
35#include "clang/AST/Expr.h"
36#include "clang/AST/ExprCXX.h"
37#include "clang/AST/OperationKinds.h"
38#include "clang/AST/PrettyPrinter.h"
39#include "clang/AST/RecordLayout.h"
40#include "clang/AST/Type.h"
41#include "clang/Basic/CharInfo.h"
42#include "clang/Basic/LLVM.h"
43#include "clang/Basic/SourceLocation.h"
44#include "clang/Basic/SourceManager.h"
45#include "clang/Basic/Specifiers.h"
46#include "clang/Basic/TokenKinds.h"
47#include "clang/Index/IndexSymbol.h"
48#include "clang/Tooling/Syntax/Tokens.h"
49#include "llvm/ADT/ArrayRef.h"
50#include "llvm/ADT/DenseSet.h"
51#include "llvm/ADT/STLExtras.h"
52#include "llvm/ADT/SmallVector.h"
53#include "llvm/ADT/StringExtras.h"
54#include "llvm/ADT/StringRef.h"
55#include "llvm/Support/Casting.h"
56#include "llvm/Support/Error.h"
57#include "llvm/Support/Format.h"
58#include "llvm/Support/ScopedPrinter.h"
59#include "llvm/Support/raw_ostream.h"
60#include <algorithm>
61#include <optional>
62#include <string>
63#include <vector>
64
65namespace clang {
66namespace clangd {
67namespace {
68
69PrintingPolicy getPrintingPolicy(PrintingPolicy Base) {
70 Base.AnonymousTagLocations = false;
71 Base.TerseOutput = true;
72 Base.PolishForDeclaration = true;
73 Base.ConstantsAsWritten = true;
74 Base.SuppressTemplateArgsInCXXConstructors = true;
75 return Base;
76}
77
78/// Given a declaration \p D, return a human-readable string representing the
79/// local scope in which it is declared, i.e. class(es) and method name. Returns
80/// an empty string if it is not local.
81std::string getLocalScope(const Decl *D) {
82 std::vector<std::string> Scopes;
83 const DeclContext *DC = D->getDeclContext();
84
85 // ObjC scopes won't have multiple components for us to join, instead:
86 // - Methods: "-[Class methodParam1:methodParam2]"
87 // - Classes, categories, and protocols: "MyClass(Category)"
88 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
89 return printObjCMethod(*MD);
90 if (const ObjCContainerDecl *CD = dyn_cast<ObjCContainerDecl>(DC))
91 return printObjCContainer(*CD);
92
93 auto GetName = [](const TypeDecl *D) {
94 if (!D->getDeclName().isEmpty()) {
95 PrintingPolicy Policy = D->getASTContext().getPrintingPolicy();
96 Policy.SuppressScope = true;
97 return declaredType(D).getAsString(Policy);
98 }
99 if (auto *RD = dyn_cast<RecordDecl>(D))
100 return ("(anonymous " + RD->getKindName() + ")").str();
101 return std::string("");
102 };
103 while (DC) {
104 if (const TypeDecl *TD = dyn_cast<TypeDecl>(DC))
105 Scopes.push_back(GetName(TD));
106 else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
107 Scopes.push_back(FD->getNameAsString());
108 DC = DC->getParent();
109 }
110
111 return llvm::join(llvm::reverse(Scopes), "::");
112}
113
114/// Returns the human-readable representation for namespace containing the
115/// declaration \p D. Returns empty if it is contained global namespace.
116std::string getNamespaceScope(const Decl *D) {
117 const DeclContext *DC = D->getDeclContext();
118
119 // ObjC does not have the concept of namespaces, so instead we support
120 // local scopes.
121 if (isa<ObjCMethodDecl, ObjCContainerDecl>(DC))
122 return "";
123
124 if (const TagDecl *TD = dyn_cast<TagDecl>(DC))
125 return getNamespaceScope(TD);
126 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
127 return getNamespaceScope(FD);
128 if (const NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(DC)) {
129 // Skip inline/anon namespaces.
130 if (NSD->isInline() || NSD->isAnonymousNamespace())
131 return getNamespaceScope(NSD);
132 }
133 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
134 return printQualifiedName(*ND);
135
136 return "";
137}
138
139std::string printDefinition(const Decl *D, PrintingPolicy PP,
140 const syntax::TokenBuffer &TB) {
141 if (auto *VD = llvm::dyn_cast<VarDecl>(D)) {
142 if (auto *IE = VD->getInit()) {
143 // Initializers might be huge and result in lots of memory allocations in
144 // some catostrophic cases. Such long lists are not useful in hover cards
145 // anyway.
146 if (200 < TB.expandedTokens(IE->getSourceRange()).size())
147 PP.SuppressInitializers = true;
148 }
149 }
150 std::string Definition;
151 llvm::raw_string_ostream OS(Definition);
152 D->print(OS, PP);
153 OS.flush();
154 return Definition;
155}
156
157const char *getMarkdownLanguage(const ASTContext &Ctx) {
158 const auto &LangOpts = Ctx.getLangOpts();
159 if (LangOpts.ObjC && LangOpts.CPlusPlus)
160 return "objective-cpp";
161 return LangOpts.ObjC ? "objective-c" : "cpp";
162}
163
164HoverInfo::PrintedType printType(QualType QT, ASTContext &ASTCtx,
165 const PrintingPolicy &PP) {
166 // TypePrinter doesn't resolve decltypes, so resolve them here.
167 // FIXME: This doesn't handle composite types that contain a decltype in them.
168 // We should rather have a printing policy for that.
169 while (!QT.isNull() && QT->isDecltypeType())
170 QT = QT->castAs<DecltypeType>()->getUnderlyingType();
171 HoverInfo::PrintedType Result;
172 llvm::raw_string_ostream OS(Result.Type);
173 // Special case: if the outer type is a tag type without qualifiers, then
174 // include the tag for extra clarity.
175 // This isn't very idiomatic, so don't attempt it for complex cases, including
176 // pointers/references, template specializations, etc.
177 if (!QT.isNull() && !QT.hasQualifiers() && PP.SuppressTagKeyword) {
178 if (auto *TT = llvm::dyn_cast<TagType>(QT.getTypePtr()))
179 OS << TT->getDecl()->getKindName() << " ";
180 }
181 QT.print(OS, PP);
182 OS.flush();
183
184 const Config &Cfg = Config::current();
185 if (!QT.isNull() && Cfg.Hover.ShowAKA) {
186 bool ShouldAKA = false;
187 QualType DesugaredTy = clang::desugarForDiagnostic(ASTCtx, QT, ShouldAKA);
188 if (ShouldAKA)
189 Result.AKA = DesugaredTy.getAsString(PP);
190 }
191 return Result;
192}
193
194HoverInfo::PrintedType printType(const TemplateTypeParmDecl *TTP) {
195 HoverInfo::PrintedType Result;
196 Result.Type = TTP->wasDeclaredWithTypename() ? "typename" : "class";
197 if (TTP->isParameterPack())
198 Result.Type += "...";
199 return Result;
200}
201
202HoverInfo::PrintedType printType(const NonTypeTemplateParmDecl *NTTP,
203 const PrintingPolicy &PP) {
204 auto PrintedType = printType(NTTP->getType(), NTTP->getASTContext(), PP);
205 if (NTTP->isParameterPack()) {
206 PrintedType.Type += "...";
207 if (PrintedType.AKA)
208 *PrintedType.AKA += "...";
209 }
210 return PrintedType;
211}
212
213HoverInfo::PrintedType printType(const TemplateTemplateParmDecl *TTP,
214 const PrintingPolicy &PP) {
215 HoverInfo::PrintedType Result;
216 llvm::raw_string_ostream OS(Result.Type);
217 OS << "template <";
218 llvm::StringRef Sep = "";
219 for (const Decl *Param : *TTP->getTemplateParameters()) {
220 OS << Sep;
221 Sep = ", ";
222 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
223 OS << printType(TTP).Type;
224 else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
225 OS << printType(NTTP, PP).Type;
226 else if (const auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param))
227 OS << printType(TTPD, PP).Type;
228 }
229 // FIXME: TemplateTemplateParameter doesn't store the info on whether this
230 // param was a "typename" or "class".
231 OS << "> class";
232 OS.flush();
233 return Result;
234}
235
236std::vector<HoverInfo::Param>
237fetchTemplateParameters(const TemplateParameterList *Params,
238 const PrintingPolicy &PP) {
239 assert(Params);
240 std::vector<HoverInfo::Param> TempParameters;
241
242 for (const Decl *Param : *Params) {
243 HoverInfo::Param P;
244 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
245 P.Type = printType(TTP);
246
247 if (!TTP->getName().empty())
248 P.Name = TTP->getNameAsString();
249
250 if (TTP->hasDefaultArgument())
251 P.Default = TTP->getDefaultArgument().getAsString(PP);
252 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
253 P.Type = printType(NTTP, PP);
254
255 if (IdentifierInfo *II = NTTP->getIdentifier())
256 P.Name = II->getName().str();
257
258 if (NTTP->hasDefaultArgument()) {
259 P.Default.emplace();
260 llvm::raw_string_ostream Out(*P.Default);
261 NTTP->getDefaultArgument()->printPretty(Out, nullptr, PP);
262 }
263 } else if (const auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param)) {
264 P.Type = printType(TTPD, PP);
265
266 if (!TTPD->getName().empty())
267 P.Name = TTPD->getNameAsString();
268
269 if (TTPD->hasDefaultArgument()) {
270 P.Default.emplace();
271 llvm::raw_string_ostream Out(*P.Default);
272 TTPD->getDefaultArgument().getArgument().print(PP, Out,
273 /*IncludeType*/ false);
274 }
275 }
276 TempParameters.push_back(std::move(P));
277 }
278
279 return TempParameters;
280}
281
282const FunctionDecl *getUnderlyingFunction(const Decl *D) {
283 // Extract lambda from variables.
284 if (const VarDecl *VD = llvm::dyn_cast<VarDecl>(D)) {
285 auto QT = VD->getType();
286 if (!QT.isNull()) {
287 while (!QT->getPointeeType().isNull())
288 QT = QT->getPointeeType();
289
290 if (const auto *CD = QT->getAsCXXRecordDecl())
291 return CD->getLambdaCallOperator();
292 }
293 }
294
295 // Non-lambda functions.
296 return D->getAsFunction();
297}
298
299// Returns the decl that should be used for querying comments, either from index
300// or AST.
301const NamedDecl *getDeclForComment(const NamedDecl *D) {
302 const NamedDecl *DeclForComment = D;
303 if (const auto *TSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(D)) {
304 // Template may not be instantiated e.g. if the type didn't need to be
305 // complete; fallback to primary template.
306 if (TSD->getTemplateSpecializationKind() == TSK_Undeclared)
307 DeclForComment = TSD->getSpecializedTemplate();
308 else if (const auto *TIP = TSD->getTemplateInstantiationPattern())
309 DeclForComment = TIP;
310 } else if (const auto *TSD =
311 llvm::dyn_cast<VarTemplateSpecializationDecl>(D)) {
312 if (TSD->getTemplateSpecializationKind() == TSK_Undeclared)
313 DeclForComment = TSD->getSpecializedTemplate();
314 else if (const auto *TIP = TSD->getTemplateInstantiationPattern())
315 DeclForComment = TIP;
316 } else if (const auto *FD = D->getAsFunction())
317 if (const auto *TIP = FD->getTemplateInstantiationPattern())
318 DeclForComment = TIP;
319 // Ensure that getDeclForComment(getDeclForComment(X)) = getDeclForComment(X).
320 // This is usually not needed, but in strange cases of comparision operators
321 // being instantiated from spasceship operater, which itself is a template
322 // instantiation the recursrive call is necessary.
323 if (D != DeclForComment)
324 DeclForComment = getDeclForComment(DeclForComment);
325 return DeclForComment;
326}
327
328// Look up information about D from the index, and add it to Hover.
329void enhanceFromIndex(HoverInfo &Hover, const NamedDecl &ND,
330 const SymbolIndex *Index) {
331 assert(&ND == getDeclForComment(&ND));
332 // We only add documentation, so don't bother if we already have some.
333 if (!Hover.Documentation.empty() || !Index)
334 return;
335
336 // Skip querying for non-indexable symbols, there's no point.
337 // We're searching for symbols that might be indexed outside this main file.
338 if (!SymbolCollector::shouldCollectSymbol(ND, ND.getASTContext(),
339 SymbolCollector::Options(),
340 /*IsMainFileOnly=*/false))
341 return;
342 auto ID = getSymbolID(&ND);
343 if (!ID)
344 return;
345 LookupRequest Req;
346 Req.IDs.insert(ID);
347 Index->lookup(Req, [&](const Symbol &S) {
348 Hover.Documentation = std::string(S.Documentation);
349 });
350}
351
352// Default argument might exist but be unavailable, in the case of unparsed
353// arguments for example. This function returns the default argument if it is
354// available.
355const Expr *getDefaultArg(const ParmVarDecl *PVD) {
356 // Default argument can be unparsed or uninstantiated. For the former we
357 // can't do much, as token information is only stored in Sema and not
358 // attached to the AST node. For the latter though, it is safe to proceed as
359 // the expression is still valid.
360 if (!PVD->hasDefaultArg() || PVD->hasUnparsedDefaultArg())
361 return nullptr;
362 return PVD->hasUninstantiatedDefaultArg() ? PVD->getUninstantiatedDefaultArg()
363 : PVD->getDefaultArg();
364}
365
366HoverInfo::Param toHoverInfoParam(const ParmVarDecl *PVD,
367 const PrintingPolicy &PP) {
368 HoverInfo::Param Out;
369 Out.Type = printType(PVD->getType(), PVD->getASTContext(), PP);
370 if (!PVD->getName().empty())
371 Out.Name = PVD->getNameAsString();
372 if (const Expr *DefArg = getDefaultArg(PVD)) {
373 Out.Default.emplace();
374 llvm::raw_string_ostream OS(*Out.Default);
375 DefArg->printPretty(OS, nullptr, PP);
376 }
377 return Out;
378}
379
380// Populates Type, ReturnType, and Parameters for function-like decls.
381void fillFunctionTypeAndParams(HoverInfo &HI, const Decl *D,
382 const FunctionDecl *FD,
383 const PrintingPolicy &PP) {
384 HI.Parameters.emplace();
385 for (const ParmVarDecl *PVD : FD->parameters())
386 HI.Parameters->emplace_back(toHoverInfoParam(PVD, PP));
387
388 // We don't want any type info, if name already contains it. This is true for
389 // constructors/destructors and conversion operators.
390 const auto NK = FD->getDeclName().getNameKind();
391 if (NK == DeclarationName::CXXConstructorName ||
392 NK == DeclarationName::CXXDestructorName ||
393 NK == DeclarationName::CXXConversionFunctionName)
394 return;
395
396 HI.ReturnType = printType(FD->getReturnType(), FD->getASTContext(), PP);
397 QualType QT = FD->getType();
398 if (const VarDecl *VD = llvm::dyn_cast<VarDecl>(D)) // Lambdas
399 QT = VD->getType().getDesugaredType(D->getASTContext());
400 HI.Type = printType(QT, D->getASTContext(), PP);
401 // FIXME: handle variadics.
402}
403
404// Non-negative numbers are printed using min digits
405// 0 => 0x0
406// 100 => 0x64
407// Negative numbers are sign-extended to 32/64 bits
408// -2 => 0xfffffffe
409// -2^32 => 0xffffffff00000000
410static llvm::FormattedNumber printHex(const llvm::APSInt &V) {
411 uint64_t Bits = V.getZExtValue();
412 if (V.isNegative() && V.getSignificantBits() <= 32)
413 return llvm::format_hex(uint32_t(Bits), 0);
414 return llvm::format_hex(Bits, 0);
415}
416
417std::optional<std::string> printExprValue(const Expr *E,
418 const ASTContext &Ctx) {
419 // InitListExpr has two forms, syntactic and semantic. They are the same thing
420 // (refer to a same AST node) in most cases.
421 // When they are different, RAV returns the syntactic form, and we should feed
422 // the semantic form to EvaluateAsRValue.
423 if (const auto *ILE = llvm::dyn_cast<InitListExpr>(E)) {
424 if (!ILE->isSemanticForm())
425 E = ILE->getSemanticForm();
426 }
427
428 // Evaluating [[foo]]() as "&foo" isn't useful, and prevents us walking up
429 // to the enclosing call. Evaluating an expression of void type doesn't
430 // produce a meaningful result.
431 QualType T = E->getType();
432 if (T.isNull() || T->isFunctionType() || T->isFunctionPointerType() ||
433 T->isFunctionReferenceType() || T->isVoidType())
434 return std::nullopt;
435
436 Expr::EvalResult Constant;
437 // Attempt to evaluate. If expr is dependent, evaluation crashes!
438 if (E->isValueDependent() || !E->EvaluateAsRValue(Constant, Ctx) ||
439 // Disable printing for record-types, as they are usually confusing and
440 // might make clang crash while printing the expressions.
441 Constant.Val.isStruct() || Constant.Val.isUnion())
442 return std::nullopt;
443
444 // Show enums symbolically, not numerically like APValue::printPretty().
445 if (T->isEnumeralType() && Constant.Val.isInt() &&
446 Constant.Val.getInt().getSignificantBits() <= 64) {
447 // Compare to int64_t to avoid bit-width match requirements.
448 int64_t Val = Constant.Val.getInt().getExtValue();
449 for (const EnumConstantDecl *ECD :
450 T->castAs<EnumType>()->getDecl()->enumerators())
451 if (ECD->getInitVal() == Val)
452 return llvm::formatv("{0} ({1})", ECD->getNameAsString(),
453 printHex(Constant.Val.getInt()))
454 .str();
455 }
456 // Show hex value of integers if they're at least 10 (or negative!)
457 if (T->isIntegralOrEnumerationType() && Constant.Val.isInt() &&
458 Constant.Val.getInt().getSignificantBits() <= 64 &&
459 Constant.Val.getInt().uge(10))
460 return llvm::formatv("{0} ({1})", Constant.Val.getAsString(Ctx, T),
461 printHex(Constant.Val.getInt()))
462 .str();
463 return Constant.Val.getAsString(Ctx, T);
464}
465
466struct PrintExprResult {
467 /// The evaluation result on expression `Expr`.
468 std::optional<std::string> PrintedValue;
469 /// The Expr object that represents the closest evaluable
470 /// expression.
471 const clang::Expr *TheExpr;
472 /// The node of selection tree where the traversal stops.
473 const SelectionTree::Node *TheNode;
474};
475
476// Seek the closest evaluable expression along the ancestors of node N
477// in a selection tree. If a node in the path can be converted to an evaluable
478// Expr, a possible evaluation would happen and the associated context
479// is returned.
480// If evaluation couldn't be done, return the node where the traversal ends.
481PrintExprResult printExprValue(const SelectionTree::Node *N,
482 const ASTContext &Ctx) {
483 for (; N; N = N->Parent) {
484 // Try to evaluate the first evaluatable enclosing expression.
485 if (const Expr *E = N->ASTNode.get<Expr>()) {
486 // Once we cross an expression of type 'cv void', the evaluated result
487 // has nothing to do with our original cursor position.
488 if (!E->getType().isNull() && E->getType()->isVoidType())
489 break;
490 if (auto Val = printExprValue(E, Ctx))
491 return PrintExprResult{/*PrintedValue=*/std::move(Val), /*Expr=*/E,
492 /*Node=*/N};
493 } else if (N->ASTNode.get<Decl>() || N->ASTNode.get<Stmt>()) {
494 // Refuse to cross certain non-exprs. (TypeLoc are OK as part of Exprs).
495 // This tries to ensure we're showing a value related to the cursor.
496 break;
497 }
498 }
499 return PrintExprResult{/*PrintedValue=*/std::nullopt, /*Expr=*/nullptr,
500 /*Node=*/N};
501}
502
503std::optional<StringRef> fieldName(const Expr *E) {
504 const auto *ME = llvm::dyn_cast<MemberExpr>(E->IgnoreCasts());
505 if (!ME || !llvm::isa<CXXThisExpr>(ME->getBase()->IgnoreCasts()))
506 return std::nullopt;
507 const auto *Field = llvm::dyn_cast<FieldDecl>(ME->getMemberDecl());
508 if (!Field || !Field->getDeclName().isIdentifier())
509 return std::nullopt;
510 return Field->getDeclName().getAsIdentifierInfo()->getName();
511}
512
513// If CMD is of the form T foo() { return FieldName; } then returns "FieldName".
514std::optional<StringRef> getterVariableName(const CXXMethodDecl *CMD) {
515 assert(CMD->hasBody());
516 if (CMD->getNumParams() != 0 || CMD->isVariadic())
517 return std::nullopt;
518 const auto *Body = llvm::dyn_cast<CompoundStmt>(CMD->getBody());
519 const auto *OnlyReturn = (Body && Body->size() == 1)
520 ? llvm::dyn_cast<ReturnStmt>(Body->body_front())
521 : nullptr;
522 if (!OnlyReturn || !OnlyReturn->getRetValue())
523 return std::nullopt;
524 return fieldName(OnlyReturn->getRetValue());
525}
526
527// If CMD is one of the forms:
528// void foo(T arg) { FieldName = arg; }
529// R foo(T arg) { FieldName = arg; return *this; }
530// void foo(T arg) { FieldName = std::move(arg); }
531// R foo(T arg) { FieldName = std::move(arg); return *this; }
532// then returns "FieldName"
533std::optional<StringRef> setterVariableName(const CXXMethodDecl *CMD) {
534 assert(CMD->hasBody());
535 if (CMD->isConst() || CMD->getNumParams() != 1 || CMD->isVariadic())
536 return std::nullopt;
537 const ParmVarDecl *Arg = CMD->getParamDecl(0);
538 if (Arg->isParameterPack())
539 return std::nullopt;
540
541 const auto *Body = llvm::dyn_cast<CompoundStmt>(CMD->getBody());
542 if (!Body || Body->size() == 0 || Body->size() > 2)
543 return std::nullopt;
544 // If the second statement exists, it must be `return this` or `return *this`.
545 if (Body->size() == 2) {
546 auto *Ret = llvm::dyn_cast<ReturnStmt>(Body->body_back());
547 if (!Ret || !Ret->getRetValue())
548 return std::nullopt;
549 const Expr *RetVal = Ret->getRetValue()->IgnoreCasts();
550 if (const auto *UO = llvm::dyn_cast<UnaryOperator>(RetVal)) {
551 if (UO->getOpcode() != UO_Deref)
552 return std::nullopt;
553 RetVal = UO->getSubExpr()->IgnoreCasts();
554 }
555 if (!llvm::isa<CXXThisExpr>(RetVal))
556 return std::nullopt;
557 }
558 // The first statement must be an assignment of the arg to a field.
559 const Expr *LHS, *RHS;
560 if (const auto *BO = llvm::dyn_cast<BinaryOperator>(Body->body_front())) {
561 if (BO->getOpcode() != BO_Assign)
562 return std::nullopt;
563 LHS = BO->getLHS();
564 RHS = BO->getRHS();
565 } else if (const auto *COCE =
566 llvm::dyn_cast<CXXOperatorCallExpr>(Body->body_front())) {
567 if (COCE->getOperator() != OO_Equal || COCE->getNumArgs() != 2)
568 return std::nullopt;
569 LHS = COCE->getArg(0);
570 RHS = COCE->getArg(1);
571 } else {
572 return std::nullopt;
573 }
574
575 // Detect the case when the item is moved into the field.
576 if (auto *CE = llvm::dyn_cast<CallExpr>(RHS->IgnoreCasts())) {
577 if (CE->getNumArgs() != 1)
578 return std::nullopt;
579 auto *ND = llvm::dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl());
580 if (!ND || !ND->getIdentifier() || ND->getName() != "move" ||
581 !ND->isInStdNamespace())
582 return std::nullopt;
583 RHS = CE->getArg(0);
584 }
585
586 auto *DRE = llvm::dyn_cast<DeclRefExpr>(RHS->IgnoreCasts());
587 if (!DRE || DRE->getDecl() != Arg)
588 return std::nullopt;
589 return fieldName(LHS);
590}
591
592std::string synthesizeDocumentation(const NamedDecl *ND) {
593 if (const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(ND)) {
594 // Is this an ordinary, non-static method whose definition is visible?
595 if (CMD->getDeclName().isIdentifier() && !CMD->isStatic() &&
596 (CMD = llvm::dyn_cast_or_null<CXXMethodDecl>(CMD->getDefinition())) &&
597 CMD->hasBody()) {
598 if (const auto GetterField = getterVariableName(CMD))
599 return llvm::formatv("Trivial accessor for `{0}`.", *GetterField);
600 if (const auto SetterField = setterVariableName(CMD))
601 return llvm::formatv("Trivial setter for `{0}`.", *SetterField);
602 }
603 }
604 return "";
605}
606
607/// Generate a \p Hover object given the declaration \p D.
608HoverInfo getHoverContents(const NamedDecl *D, const PrintingPolicy &PP,
609 const SymbolIndex *Index,
610 const syntax::TokenBuffer &TB) {
611 HoverInfo HI;
612 auto &Ctx = D->getASTContext();
613
614 HI.AccessSpecifier = getAccessSpelling(D->getAccess()).str();
615 HI.NamespaceScope = getNamespaceScope(D);
616 if (!HI.NamespaceScope->empty())
617 HI.NamespaceScope->append("::");
618 HI.LocalScope = getLocalScope(D);
619 if (!HI.LocalScope.empty())
620 HI.LocalScope.append("::");
621
622 HI.Name = printName(Ctx, *D);
623 const auto *CommentD = getDeclForComment(D);
624 HI.Documentation = getDeclComment(Ctx, *CommentD);
625 enhanceFromIndex(HI, *CommentD, Index);
626 if (HI.Documentation.empty())
627 HI.Documentation = synthesizeDocumentation(D);
628
629 HI.Kind = index::getSymbolInfo(D).Kind;
630
631 // Fill in template params.
632 if (const TemplateDecl *TD = D->getDescribedTemplate()) {
633 HI.TemplateParameters =
634 fetchTemplateParameters(TD->getTemplateParameters(), PP);
635 D = TD;
636 } else if (const FunctionDecl *FD = D->getAsFunction()) {
637 if (const auto *FTD = FD->getDescribedTemplate()) {
638 HI.TemplateParameters =
639 fetchTemplateParameters(FTD->getTemplateParameters(), PP);
640 D = FTD;
641 }
642 }
643
644 // Fill in types and params.
645 if (const FunctionDecl *FD = getUnderlyingFunction(D))
646 fillFunctionTypeAndParams(HI, D, FD, PP);
647 else if (const auto *VD = dyn_cast<ValueDecl>(D))
648 HI.Type = printType(VD->getType(), Ctx, PP);
649 else if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(D))
650 HI.Type = TTP->wasDeclaredWithTypename() ? "typename" : "class";
651 else if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(D))
652 HI.Type = printType(TTP, PP);
653 else if (const auto *VT = dyn_cast<VarTemplateDecl>(D))
654 HI.Type = printType(VT->getTemplatedDecl()->getType(), Ctx, PP);
655 else if (const auto *TN = dyn_cast<TypedefNameDecl>(D))
656 HI.Type = printType(TN->getUnderlyingType().getDesugaredType(Ctx), Ctx, PP);
657 else if (const auto *TAT = dyn_cast<TypeAliasTemplateDecl>(D))
658 HI.Type = printType(TAT->getTemplatedDecl()->getUnderlyingType(), Ctx, PP);
659
660 // Fill in value with evaluated initializer if possible.
661 if (const auto *Var = dyn_cast<VarDecl>(D); Var && !Var->isInvalidDecl()) {
662 if (const Expr *Init = Var->getInit())
663 HI.Value = printExprValue(Init, Ctx);
664 } else if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
665 // Dependent enums (e.g. nested in template classes) don't have values yet.
666 if (!ECD->getType()->isDependentType())
667 HI.Value = toString(ECD->getInitVal(), 10);
668 }
669
670 HI.Definition = printDefinition(D, PP, TB);
671 return HI;
672}
673
674/// The standard defines __func__ as a "predefined variable".
675std::optional<HoverInfo>
676getPredefinedExprHoverContents(const PredefinedExpr &PE, ASTContext &Ctx,
677 const PrintingPolicy &PP) {
678 HoverInfo HI;
679 HI.Name = PE.getIdentKindName();
680 HI.Kind = index::SymbolKind::Variable;
681 HI.Documentation = "Name of the current function (predefined variable)";
682 if (const StringLiteral *Name = PE.getFunctionName()) {
683 HI.Value.emplace();
684 llvm::raw_string_ostream OS(*HI.Value);
685 Name->outputString(OS);
686 HI.Type = printType(Name->getType(), Ctx, PP);
687 } else {
688 // Inside templates, the approximate type `const char[]` is still useful.
689 QualType StringType = Ctx.getIncompleteArrayType(
690 Ctx.CharTy.withConst(), ArrayType::ArraySizeModifier::Normal,
691 /*IndexTypeQuals=*/0);
692 HI.Type = printType(StringType, Ctx, PP);
693 }
694 return HI;
695}
696
697HoverInfo evaluateMacroExpansion(unsigned int SpellingBeginOffset,
698 unsigned int SpellingEndOffset,
699 llvm::ArrayRef<syntax::Token> Expanded,
700 ParsedAST &AST) {
701 auto &Context = AST.getASTContext();
702 auto &Tokens = AST.getTokens();
703 auto PP = getPrintingPolicy(Context.getPrintingPolicy());
704 auto Tree = SelectionTree::createRight(Context, Tokens, SpellingBeginOffset,
705 SpellingEndOffset);
706
707 // If macro expands to one single token, rule out punctuator or digraph.
708 // E.g., for the case `array L_BRACKET 42 R_BRACKET;` where L_BRACKET and
709 // R_BRACKET expand to
710 // '[' and ']' respectively, we don't want the type of
711 // 'array[42]' when user hovers on L_BRACKET.
712 if (Expanded.size() == 1)
713 if (tok::getPunctuatorSpelling(Expanded[0].kind()))
714 return {};
715
716 auto *StartNode = Tree.commonAncestor();
717 if (!StartNode)
718 return {};
719 // If the common ancestor is partially selected, do evaluate if it has no
720 // children, thus we can disallow evaluation on incomplete expression.
721 // For example,
722 // #define PLUS_2 +2
723 // 40 PL^US_2
724 // In this case we don't want to present 'value: 2' as PLUS_2 actually expands
725 // to a non-value rather than a binary operand.
726 if (StartNode->Selected == SelectionTree::Selection::Partial)
727 if (!StartNode->Children.empty())
728 return {};
729
730 HoverInfo HI;
731 // Attempt to evaluate it from Expr first.
732 auto ExprResult = printExprValue(StartNode, Context);
733 HI.Value = std::move(ExprResult.PrintedValue);
734 if (auto *E = ExprResult.TheExpr)
735 HI.Type = printType(E->getType(), Context, PP);
736
737 // If failed, extract the type from Decl if possible.
738 if (!HI.Value && !HI.Type && ExprResult.TheNode)
739 if (auto *VD = ExprResult.TheNode->ASTNode.get<VarDecl>())
740 HI.Type = printType(VD->getType(), Context, PP);
741
742 return HI;
743}
744
745/// Generate a \p Hover object given the macro \p MacroDecl.
746HoverInfo getHoverContents(const DefinedMacro &Macro, const syntax::Token &Tok,
747 ParsedAST &AST) {
748 HoverInfo HI;
749 SourceManager &SM = AST.getSourceManager();
750 HI.Name = std::string(Macro.Name);
751 HI.Kind = index::SymbolKind::Macro;
752 // FIXME: Populate documentation
753 // FIXME: Populate parameters
754
755 // Try to get the full definition, not just the name
756 SourceLocation StartLoc = Macro.Info->getDefinitionLoc();
757 SourceLocation EndLoc = Macro.Info->getDefinitionEndLoc();
758 // Ensure that EndLoc is a valid offset. For example it might come from
759 // preamble, and source file might've changed, in such a scenario EndLoc still
760 // stays valid, but getLocForEndOfToken will fail as it is no longer a valid
761 // offset.
762 // Note that this check is just to ensure there's text data inside the range.
763 // It will still succeed even when the data inside the range is irrelevant to
764 // macro definition.
765 if (SM.getPresumedLoc(EndLoc, /*UseLineDirectives=*/false).isValid()) {
766 EndLoc = Lexer::getLocForEndOfToken(EndLoc, 0, SM, AST.getLangOpts());
767 bool Invalid;
768 StringRef Buffer = SM.getBufferData(SM.getFileID(StartLoc), &Invalid);
769 if (!Invalid) {
770 unsigned StartOffset = SM.getFileOffset(StartLoc);
771 unsigned EndOffset = SM.getFileOffset(EndLoc);
772 if (EndOffset <= Buffer.size() && StartOffset < EndOffset)
773 HI.Definition =
774 ("#define " + Buffer.substr(StartOffset, EndOffset - StartOffset))
775 .str();
776 }
777 }
778
779 if (auto Expansion = AST.getTokens().expansionStartingAt(&Tok)) {
780 // We drop expansion that's longer than the threshold.
781 // For extremely long expansion text, it's not readable from hover card
782 // anyway.
783 std::string ExpansionText;
784 for (const auto &ExpandedTok : Expansion->Expanded) {
785 ExpansionText += ExpandedTok.text(SM);
786 ExpansionText += " ";
787 if (ExpansionText.size() > 2048) {
788 ExpansionText.clear();
789 break;
790 }
791 }
792
793 if (!ExpansionText.empty()) {
794 if (!HI.Definition.empty()) {
795 HI.Definition += "\n\n";
796 }
797 HI.Definition += "// Expands to\n";
798 HI.Definition += ExpansionText;
799 }
800
801 auto Evaluated = evaluateMacroExpansion(
802 /*SpellingBeginOffset=*/SM.getFileOffset(Tok.location()),
803 /*SpellingEndOffset=*/SM.getFileOffset(Tok.endLocation()),
804 /*Expanded=*/Expansion->Expanded, AST);
805 HI.Value = std::move(Evaluated.Value);
806 HI.Type = std::move(Evaluated.Type);
807 }
808 return HI;
809}
810
811std::string typeAsDefinition(const HoverInfo::PrintedType &PType) {
812 std::string Result;
813 llvm::raw_string_ostream OS(Result);
814 OS << PType.Type;
815 if (PType.AKA)
816 OS << " // aka: " << *PType.AKA;
817 OS.flush();
818 return Result;
819}
820
821std::optional<HoverInfo> getThisExprHoverContents(const CXXThisExpr *CTE,
822 ASTContext &ASTCtx,
823 const PrintingPolicy &PP) {
824 QualType OriginThisType = CTE->getType()->getPointeeType();
825 QualType ClassType = declaredType(OriginThisType->getAsTagDecl());
826 // For partial specialization class, origin `this` pointee type will be
827 // parsed as `InjectedClassNameType`, which will ouput template arguments
828 // like "type-parameter-0-0". So we retrieve user written class type in this
829 // case.
830 QualType PrettyThisType = ASTCtx.getPointerType(
831 QualType(ClassType.getTypePtr(), OriginThisType.getCVRQualifiers()));
832
833 HoverInfo HI;
834 HI.Name = "this";
835 HI.Definition = typeAsDefinition(printType(PrettyThisType, ASTCtx, PP));
836 return HI;
837}
838
839/// Generate a HoverInfo object given the deduced type \p QT
840HoverInfo getDeducedTypeHoverContents(QualType QT, const syntax::Token &Tok,
841 ASTContext &ASTCtx,
842 const PrintingPolicy &PP,
843 const SymbolIndex *Index) {
844 HoverInfo HI;
845 // FIXME: distinguish decltype(auto) vs decltype(expr)
846 HI.Name = tok::getTokenName(Tok.kind());
847 HI.Kind = index::SymbolKind::TypeAlias;
848
849 if (QT->isUndeducedAutoType()) {
850 HI.Definition = "/* not deduced */";
851 } else {
852 HI.Definition = typeAsDefinition(printType(QT, ASTCtx, PP));
853
854 if (const auto *D = QT->getAsTagDecl()) {
855 const auto *CommentD = getDeclForComment(D);
856 HI.Documentation = getDeclComment(ASTCtx, *CommentD);
857 enhanceFromIndex(HI, *CommentD, Index);
858 }
859 }
860
861 return HI;
862}
863
864HoverInfo getStringLiteralContents(const StringLiteral *SL,
865 const PrintingPolicy &PP) {
866 HoverInfo HI;
867
868 HI.Name = "string-literal";
869 HI.Size = (SL->getLength() + 1) * SL->getCharByteWidth() * 8;
870 HI.Type = SL->getType().getAsString(PP).c_str();
871
872 return HI;
873}
874
875bool isLiteral(const Expr *E) {
876 // Unfortunately there's no common base Literal classes inherits from
877 // (apart from Expr), therefore these exclusions.
878 return llvm::isa<CompoundLiteralExpr>(E) ||
879 llvm::isa<CXXBoolLiteralExpr>(E) ||
880 llvm::isa<CXXNullPtrLiteralExpr>(E) ||
881 llvm::isa<FixedPointLiteral>(E) || llvm::isa<FloatingLiteral>(E) ||
882 llvm::isa<ImaginaryLiteral>(E) || llvm::isa<IntegerLiteral>(E) ||
883 llvm::isa<StringLiteral>(E) || llvm::isa<UserDefinedLiteral>(E);
884}
885
886llvm::StringLiteral getNameForExpr(const Expr *E) {
887 // FIXME: Come up with names for `special` expressions.
888 //
889 // It's an known issue for GCC5, https://godbolt.org/z/Z_tbgi. Work around
890 // that by using explicit conversion constructor.
891 //
892 // TODO: Once GCC5 is fully retired and not the minimal requirement as stated
893 // in `GettingStarted`, please remove the explicit conversion constructor.
894 return llvm::StringLiteral("expression");
895}
896
897void maybeAddCalleeArgInfo(const SelectionTree::Node *N, HoverInfo &HI,
898 const PrintingPolicy &PP);
899
900// Generates hover info for `this` and evaluatable expressions.
901// FIXME: Support hover for literals (esp user-defined)
902std::optional<HoverInfo> getHoverContents(const SelectionTree::Node *N,
903 const Expr *E, ParsedAST &AST,
904 const PrintingPolicy &PP,
905 const SymbolIndex *Index) {
906 std::optional<HoverInfo> HI;
907
908 if (const StringLiteral *SL = dyn_cast<StringLiteral>(E)) {
909 // Print the type and the size for string literals
910 HI = getStringLiteralContents(SL, PP);
911 } else if (isLiteral(E)) {
912 // There's not much value in hovering over "42" and getting a hover card
913 // saying "42 is an int", similar for most other literals.
914 // However, if we have CalleeArgInfo, it's still useful to show it.
915 maybeAddCalleeArgInfo(N, HI.emplace(), PP);
916 if (HI->CalleeArgInfo) {
917 // FIXME Might want to show the expression's value here instead?
918 // E.g. if the literal is in hex it might be useful to show the decimal
919 // value here.
920 HI->Name = "literal";
921 return HI;
922 }
923 return std::nullopt;
924 }
925
926 // For `this` expr we currently generate hover with pointee type.
927 if (const CXXThisExpr *CTE = dyn_cast<CXXThisExpr>(E))
928 HI = getThisExprHoverContents(CTE, AST.getASTContext(), PP);
929 if (const PredefinedExpr *PE = dyn_cast<PredefinedExpr>(E))
930 HI = getPredefinedExprHoverContents(*PE, AST.getASTContext(), PP);
931 // For expressions we currently print the type and the value, iff it is
932 // evaluatable.
933 if (auto Val = printExprValue(E, AST.getASTContext())) {
934 HI.emplace();
935 HI->Type = printType(E->getType(), AST.getASTContext(), PP);
936 HI->Value = *Val;
937 HI->Name = std::string(getNameForExpr(E));
938 }
939
940 if (HI)
941 maybeAddCalleeArgInfo(N, *HI, PP);
942
943 return HI;
944}
945
946// Generates hover info for attributes.
947std::optional<HoverInfo> getHoverContents(const Attr *A, ParsedAST &AST) {
948 HoverInfo HI;
949 HI.Name = A->getSpelling();
950 if (A->hasScope())
951 HI.LocalScope = A->getScopeName()->getName().str();
952 {
953 llvm::raw_string_ostream OS(HI.Definition);
954 A->printPretty(OS, AST.getASTContext().getPrintingPolicy());
955 }
956 HI.Documentation = Attr::getDocumentation(A->getKind()).str();
957 return HI;
958}
959
960bool isParagraphBreak(llvm::StringRef Rest) {
961 return Rest.ltrim(" \t").startswith("\n");
962}
963
964bool punctuationIndicatesLineBreak(llvm::StringRef Line) {
965 constexpr llvm::StringLiteral Punctuation = R"txt(.:,;!?)txt";
966
967 Line = Line.rtrim();
968 return !Line.empty() && Punctuation.contains(Line.back());
969}
970
971bool isHardLineBreakIndicator(llvm::StringRef Rest) {
972 // '-'/'*' md list, '@'/'\' documentation command, '>' md blockquote,
973 // '#' headings, '`' code blocks
974 constexpr llvm::StringLiteral LinebreakIndicators = R"txt(-*@\>#`)txt";
975
976 Rest = Rest.ltrim(" \t");
977 if (Rest.empty())
978 return false;
979
980 if (LinebreakIndicators.contains(Rest.front()))
981 return true;
982
983 if (llvm::isDigit(Rest.front())) {
984 llvm::StringRef AfterDigit = Rest.drop_while(llvm::isDigit);
985 if (AfterDigit.startswith(".") || AfterDigit.startswith(")"))
986 return true;
987 }
988 return false;
989}
990
991bool isHardLineBreakAfter(llvm::StringRef Line, llvm::StringRef Rest) {
992 // Should we also consider whether Line is short?
993 return punctuationIndicatesLineBreak(Line) || isHardLineBreakIndicator(Rest);
994}
995
996void addLayoutInfo(const NamedDecl &ND, HoverInfo &HI) {
997 if (ND.isInvalidDecl())
998 return;
999
1000 const auto &Ctx = ND.getASTContext();
1001 if (auto *RD = llvm::dyn_cast<RecordDecl>(&ND)) {
1002 if (auto Size = Ctx.getTypeSizeInCharsIfKnown(RD->getTypeForDecl()))
1003 HI.Size = Size->getQuantity() * 8;
1004 return;
1005 }
1006
1007 if (const auto *FD = llvm::dyn_cast<FieldDecl>(&ND)) {
1008 const auto *Record = FD->getParent();
1009 if (Record)
1010 Record = Record->getDefinition();
1011 if (Record && !Record->isInvalidDecl() && !Record->isDependentType()) {
1012 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Record);
1013 HI.Offset = Layout.getFieldOffset(FD->getFieldIndex());
1014 if (FD->isBitField())
1015 HI.Size = FD->getBitWidthValue(Ctx);
1016 else if (auto Size = Ctx.getTypeSizeInCharsIfKnown(FD->getType()))
1017 HI.Size = FD->isZeroSize(Ctx) ? 0 : Size->getQuantity() * 8;
1018 if (HI.Size) {
1019 unsigned EndOfField = *HI.Offset + *HI.Size;
1020
1021 // Calculate padding following the field.
1022 if (!Record->isUnion() &&
1023 FD->getFieldIndex() + 1 < Layout.getFieldCount()) {
1024 // Measure padding up to the next class field.
1025 unsigned NextOffset = Layout.getFieldOffset(FD->getFieldIndex() + 1);
1026 if (NextOffset >= EndOfField) // next field could be a bitfield!
1027 HI.Padding = NextOffset - EndOfField;
1028 } else {
1029 // Measure padding up to the end of the object.
1030 HI.Padding = Layout.getSize().getQuantity() * 8 - EndOfField;
1031 }
1032 }
1033 // Offset in a union is always zero, so not really useful to report.
1034 if (Record->isUnion())
1035 HI.Offset.reset();
1036 }
1037 return;
1038 }
1039}
1040
1041HoverInfo::PassType::PassMode getPassMode(QualType ParmType) {
1042 if (ParmType->isReferenceType()) {
1043 if (ParmType->getPointeeType().isConstQualified())
1044 return HoverInfo::PassType::ConstRef;
1045 return HoverInfo::PassType::Ref;
1046 }
1047 return HoverInfo::PassType::Value;
1048}
1049
1050// If N is passed as argument to a function, fill HI.CalleeArgInfo with
1051// information about that argument.
1052void maybeAddCalleeArgInfo(const SelectionTree::Node *N, HoverInfo &HI,
1053 const PrintingPolicy &PP) {
1054 const auto &OuterNode = N->outerImplicit();
1055 if (!OuterNode.Parent)
1056 return;
1057
1058 const FunctionDecl *FD = nullptr;
1059 llvm::ArrayRef<const Expr *> Args;
1060
1061 if (const auto *CE = OuterNode.Parent->ASTNode.get<CallExpr>()) {
1062 FD = CE->getDirectCallee();
1063 Args = {CE->getArgs(), CE->getNumArgs()};
1064 } else if (const auto *CE =
1065 OuterNode.Parent->ASTNode.get<CXXConstructExpr>()) {
1066 FD = CE->getConstructor();
1067 Args = {CE->getArgs(), CE->getNumArgs()};
1068 }
1069 if (!FD)
1070 return;
1071
1072 // For non-function-call-like operators (e.g. operator+, operator<<) it's
1073 // not immediately obvious what the "passed as" would refer to and, given
1074 // fixed function signature, the value would be very low anyway, so we choose
1075 // to not support that.
1076 // Both variadic functions and operator() (especially relevant for lambdas)
1077 // should be supported in the future.
1078 if (!FD || FD->isOverloadedOperator() || FD->isVariadic())
1079 return;
1080
1081 HoverInfo::PassType PassType;
1082
1083 auto Parameters = resolveForwardingParameters(FD);
1084
1085 // Find argument index for N.
1086 for (unsigned I = 0; I < Args.size() && I < Parameters.size(); ++I) {
1087 if (Args[I] != OuterNode.ASTNode.get<Expr>())
1088 continue;
1089
1090 // Extract matching argument from function declaration.
1091 if (const ParmVarDecl *PVD = Parameters[I]) {
1092 HI.CalleeArgInfo.emplace(toHoverInfoParam(PVD, PP));
1093 if (N == &OuterNode)
1094 PassType.PassBy = getPassMode(PVD->getType());
1095 }
1096 break;
1097 }
1098 if (!HI.CalleeArgInfo)
1099 return;
1100
1101 // If we found a matching argument, also figure out if it's a
1102 // [const-]reference. For this we need to walk up the AST from the arg itself
1103 // to CallExpr and check all implicit casts, constructor calls, etc.
1104 if (const auto *E = N->ASTNode.get<Expr>()) {
1105 if (E->getType().isConstQualified())
1106 PassType.PassBy = HoverInfo::PassType::ConstRef;
1107 }
1108
1109 for (auto *CastNode = N->Parent;
1110 CastNode != OuterNode.Parent && !PassType.Converted;
1111 CastNode = CastNode->Parent) {
1112 if (const auto *ImplicitCast = CastNode->ASTNode.get<ImplicitCastExpr>()) {
1113 switch (ImplicitCast->getCastKind()) {
1114 case CK_NoOp:
1115 case CK_DerivedToBase:
1116 case CK_UncheckedDerivedToBase:
1117 // If it was a reference before, it's still a reference.
1118 if (PassType.PassBy != HoverInfo::PassType::Value)
1119 PassType.PassBy = ImplicitCast->getType().isConstQualified()
1120 ? HoverInfo::PassType::ConstRef
1121 : HoverInfo::PassType::Ref;
1122 break;
1123 case CK_LValueToRValue:
1124 case CK_ArrayToPointerDecay:
1125 case CK_FunctionToPointerDecay:
1126 case CK_NullToPointer:
1127 case CK_NullToMemberPointer:
1128 // No longer a reference, but we do not show this as type conversion.
1129 PassType.PassBy = HoverInfo::PassType::Value;
1130 break;
1131 default:
1132 PassType.PassBy = HoverInfo::PassType::Value;
1133 PassType.Converted = true;
1134 break;
1135 }
1136 } else if (const auto *CtorCall =
1137 CastNode->ASTNode.get<CXXConstructExpr>()) {
1138 // We want to be smart about copy constructors. They should not show up as
1139 // type conversion, but instead as passing by value.
1140 if (CtorCall->getConstructor()->isCopyConstructor())
1141 PassType.PassBy = HoverInfo::PassType::Value;
1142 else
1143 PassType.Converted = true;
1144 } else if (CastNode->ASTNode.get<MaterializeTemporaryExpr>()) {
1145 // Can't bind a non-const-ref to a temporary, so has to be const-ref
1146 PassType.PassBy = HoverInfo::PassType::ConstRef;
1147 } else { // Unknown implicit node, assume type conversion.
1148 PassType.PassBy = HoverInfo::PassType::Value;
1149 PassType.Converted = true;
1150 }
1151 }
1152
1153 HI.CallPassType.emplace(PassType);
1154}
1155
1156const NamedDecl *pickDeclToUse(llvm::ArrayRef<const NamedDecl *> Candidates) {
1157 if (Candidates.empty())
1158 return nullptr;
1159
1160 // This is e.g the case for
1161 // namespace ns { void foo(); }
1162 // void bar() { using ns::foo; f^oo(); }
1163 // One declaration in Candidates will refer to the using declaration,
1164 // which isn't really useful for Hover. So use the other one,
1165 // which in this example would be the actual declaration of foo.
1166 if (Candidates.size() <= 2) {
1167 if (llvm::isa<UsingDecl>(Candidates.front()))
1168 return Candidates.back();
1169 return Candidates.front();
1170 }
1171
1172 // For something like
1173 // namespace ns { void foo(int); void foo(char); }
1174 // using ns::foo;
1175 // template <typename T> void bar() { fo^o(T{}); }
1176 // we actually want to show the using declaration,
1177 // it's not clear which declaration to pick otherwise.
1178 auto BaseDecls = llvm::make_filter_range(
1179 Candidates, [](const NamedDecl *D) { return llvm::isa<UsingDecl>(D); });
1180 if (std::distance(BaseDecls.begin(), BaseDecls.end()) == 1)
1181 return *BaseDecls.begin();
1182
1183 return Candidates.front();
1184}
1185
1186void maybeAddSymbolProviders(ParsedAST &AST, HoverInfo &HI,
1187 include_cleaner::Symbol Sym) {
1188 trace::Span Tracer("Hover::maybeAddSymbolProviders");
1189
1190 const SourceManager &SM = AST.getSourceManager();
1191 llvm::SmallVector<include_cleaner::Header> RankedProviders =
1192 include_cleaner::headersForSymbol(Sym, SM, AST.getPragmaIncludes().get());
1193 if (RankedProviders.empty())
1194 return;
1195
1196 std::string Result;
1197 include_cleaner::Includes ConvertedIncludes =
1198 convertIncludes(SM, AST.getIncludeStructure().MainFileIncludes);
1199 for (const auto &P : RankedProviders) {
1200 if (P.kind() == include_cleaner::Header::Physical &&
1201 P.physical() == SM.getFileEntryForID(SM.getMainFileID()))
1202 // Main file ranked higher than any #include'd file
1203 break;
1204
1205 // Pick the best-ranked #include'd provider
1206 auto Matches = ConvertedIncludes.match(P);
1207 if (!Matches.empty()) {
1208 Result = Matches[0]->quote();
1209 break;
1210 }
1211 }
1212
1213 if (!Result.empty()) {
1214 HI.Provider = std::move(Result);
1215 return;
1216 }
1217
1218 // Pick the best-ranked non-#include'd provider
1219 const auto &H = RankedProviders.front();
1220 if (H.kind() == include_cleaner::Header::Physical &&
1221 H.physical() == SM.getFileEntryForID(SM.getMainFileID()))
1222 // Do not show main file as provider, otherwise we'll show provider info
1223 // on local variables, etc.
1224 return;
1225
1226 HI.Provider = include_cleaner::spellHeader(
1227 {H, AST.getPreprocessor().getHeaderSearchInfo(),
1228 SM.getFileEntryForID(SM.getMainFileID())});
1229}
1230
1231// FIXME: similar functions are present in FindHeaders.cpp (symbolName)
1232// and IncludeCleaner.cpp (getSymbolName). Introduce a name() method into
1233// include_cleaner::Symbol instead.
1234std::string getSymbolName(include_cleaner::Symbol Sym) {
1235 std::string Name;
1236 switch (Sym.kind()) {
1237 case include_cleaner::Symbol::Declaration:
1238 if (const auto *ND = llvm::dyn_cast<NamedDecl>(&Sym.declaration()))
1239 Name = ND->getDeclName().getAsString();
1240 break;
1241 case include_cleaner::Symbol::Macro:
1242 Name = Sym.macro().Name->getName();
1243 break;
1244 }
1245 return Name;
1246}
1247
1248void maybeAddUsedSymbols(ParsedAST &AST, HoverInfo &HI, const Inclusion &Inc) {
1249 const SourceManager &SM = AST.getSourceManager();
1250 const auto &ConvertedMainFileIncludes =
1251 convertIncludes(SM, AST.getIncludeStructure().MainFileIncludes);
1252 const auto &HoveredInclude = convertIncludes(SM, llvm::ArrayRef{Inc});
1253 llvm::DenseSet<include_cleaner::Symbol> UsedSymbols;
1254 include_cleaner::walkUsed(
1255 AST.getLocalTopLevelDecls(), collectMacroReferences(AST),
1256 AST.getPragmaIncludes().get(), SM,
1257 [&](const include_cleaner::SymbolReference &Ref,
1258 llvm::ArrayRef<include_cleaner::Header> Providers) {
1259 if (Ref.RT != include_cleaner::RefType::Explicit ||
1260 UsedSymbols.contains(Ref.Target))
1261 return;
1262
1263 auto Provider =
1264 firstMatchedProvider(ConvertedMainFileIncludes, Providers);
1265 if (!Provider || HoveredInclude.match(*Provider).empty())
1266 return;
1267
1268 UsedSymbols.insert(Ref.Target);
1269 });
1270
1271 for (const auto &UsedSymbolDecl : UsedSymbols)
1272 HI.UsedSymbolNames.push_back(getSymbolName(UsedSymbolDecl));
1273 llvm::sort(HI.UsedSymbolNames);
1274 HI.UsedSymbolNames.erase(
1275 std::unique(HI.UsedSymbolNames.begin(), HI.UsedSymbolNames.end()),
1276 HI.UsedSymbolNames.end());
1277}
1278
1279} // namespace
1280
1281std::optional<HoverInfo> getHover(ParsedAST &AST, Position Pos,
1282 const format::FormatStyle &Style,
1283 const SymbolIndex *Index) {
1284 static constexpr trace::Metric HoverCountMetric(
1285 "hover", trace::Metric::Counter, "case");
1286 PrintingPolicy PP =
1287 getPrintingPolicy(AST.getASTContext().getPrintingPolicy());
1288 const SourceManager &SM = AST.getSourceManager();
1289 auto CurLoc = sourceLocationInMainFile(SM, Pos);
1290 if (!CurLoc) {
1291 llvm::consumeError(CurLoc.takeError());
1292 return std::nullopt;
1293 }
1294 const auto &TB = AST.getTokens();
1295 auto TokensTouchingCursor = syntax::spelledTokensTouching(*CurLoc, TB);
1296 // Early exit if there were no tokens around the cursor.
1297 if (TokensTouchingCursor.empty())
1298 return std::nullopt;
1299
1300 // Show full header file path if cursor is on include directive.
1301 for (const auto &Inc : AST.getIncludeStructure().MainFileIncludes) {
1302 if (Inc.Resolved.empty() || Inc.HashLine != Pos.line)
1303 continue;
1304 HoverCountMetric.record(1, "include");
1305 HoverInfo HI;
1306 HI.Name = std::string(llvm::sys::path::filename(Inc.Resolved));
1307 // FIXME: We don't have a fitting value for Kind.
1308 HI.Definition =
1309 URIForFile::canonicalize(Inc.Resolved, AST.tuPath()).file().str();
1310 HI.DefinitionLanguage = "";
1311 maybeAddUsedSymbols(AST, HI, Inc);
1312 return HI;
1313 }
1314
1315 // To be used as a backup for highlighting the selected token, we use back as
1316 // it aligns better with biases elsewhere (editors tend to send the position
1317 // for the left of the hovered token).
1318 CharSourceRange HighlightRange =
1319 TokensTouchingCursor.back().range(SM).toCharRange(SM);
1320 std::optional<HoverInfo> HI;
1321 // Macros and deducedtype only works on identifiers and auto/decltype keywords
1322 // respectively. Therefore they are only trggered on whichever works for them,
1323 // similar to SelectionTree::create().
1324 for (const auto &Tok : TokensTouchingCursor) {
1325 if (Tok.kind() == tok::identifier) {
1326 // Prefer the identifier token as a fallback highlighting range.
1327 HighlightRange = Tok.range(SM).toCharRange(SM);
1328 if (auto M = locateMacroAt(Tok, AST.getPreprocessor())) {
1329 HoverCountMetric.record(1, "macro");
1330 HI = getHoverContents(*M, Tok, AST);
1331 if (auto DefLoc = M->Info->getDefinitionLoc(); DefLoc.isValid()) {
1332 include_cleaner::Macro IncludeCleanerMacro{
1333 AST.getPreprocessor().getIdentifierInfo(Tok.text(SM)), DefLoc};
1334 maybeAddSymbolProviders(AST, *HI,
1335 include_cleaner::Symbol{IncludeCleanerMacro});
1336 }
1337 break;
1338 }
1339 } else if (Tok.kind() == tok::kw_auto || Tok.kind() == tok::kw_decltype) {
1340 HoverCountMetric.record(1, "keyword");
1341 if (auto Deduced = getDeducedType(AST.getASTContext(), Tok.location())) {
1342 HI = getDeducedTypeHoverContents(*Deduced, Tok, AST.getASTContext(), PP,
1343 Index);
1344 HighlightRange = Tok.range(SM).toCharRange(SM);
1345 break;
1346 }
1347
1348 // If we can't find interesting hover information for this
1349 // auto/decltype keyword, return nothing to avoid showing
1350 // irrelevant or incorrect informations.
1351 return std::nullopt;
1352 }
1353 }
1354
1355 // If it wasn't auto/decltype or macro, look for decls and expressions.
1356 if (!HI) {
1357 auto Offset = SM.getFileOffset(*CurLoc);
1358 // Editors send the position on the left of the hovered character.
1359 // So our selection tree should be biased right. (Tested with VSCode).
1360 SelectionTree ST =
1361 SelectionTree::createRight(AST.getASTContext(), TB, Offset, Offset);
1362 if (const SelectionTree::Node *N = ST.commonAncestor()) {
1363 // FIXME: Fill in HighlightRange with range coming from N->ASTNode.
1364 auto Decls = explicitReferenceTargets(N->ASTNode, DeclRelation::Alias,
1365 AST.getHeuristicResolver());
1366 if (const auto *DeclToUse = pickDeclToUse(Decls)) {
1367 HoverCountMetric.record(1, "decl");
1368 HI = getHoverContents(DeclToUse, PP, Index, TB);
1369 // Layout info only shown when hovering on the field/class itself.
1370 if (DeclToUse == N->ASTNode.get<Decl>())
1371 addLayoutInfo(*DeclToUse, *HI);
1372 // Look for a close enclosing expression to show the value of.
1373 if (!HI->Value)
1374 HI->Value = printExprValue(N, AST.getASTContext()).PrintedValue;
1375 maybeAddCalleeArgInfo(N, *HI, PP);
1376
1377 if (!isa<NamespaceDecl>(DeclToUse))
1378 maybeAddSymbolProviders(AST, *HI,
1379 include_cleaner::Symbol{*DeclToUse});
1380 } else if (const Expr *E = N->ASTNode.get<Expr>()) {
1381 HoverCountMetric.record(1, "expr");
1382 HI = getHoverContents(N, E, AST, PP, Index);
1383 } else if (const Attr *A = N->ASTNode.get<Attr>()) {
1384 HoverCountMetric.record(1, "attribute");
1385 HI = getHoverContents(A, AST);
1386 }
1387 // FIXME: support hovers for other nodes?
1388 // - built-in types
1389 }
1390 }
1391
1392 if (!HI)
1393 return std::nullopt;
1394
1395 // Reformat Definition
1396 if (!HI->Definition.empty()) {
1397 auto Replacements = format::reformat(
1398 Style, HI->Definition, tooling::Range(0, HI->Definition.size()));
1399 if (auto Formatted =
1400 tooling::applyAllReplacements(HI->Definition, Replacements))
1401 HI->Definition = *Formatted;
1402 }
1403
1404 HI->DefinitionLanguage = getMarkdownLanguage(AST.getASTContext());
1405 HI->SymRange = halfOpenToRange(SM, HighlightRange);
1406
1407 return HI;
1408}
1409
1410// Sizes (and padding) are shown in bytes if possible, otherwise in bits.
1411static std::string formatSize(uint64_t SizeInBits) {
1412 uint64_t Value = SizeInBits % 8 == 0 ? SizeInBits / 8 : SizeInBits;
1413 const char *Unit = Value != 0 && Value == SizeInBits ? "bit" : "byte";
1414 return llvm::formatv("{0} {1}{2}", Value, Unit, Value == 1 ? "" : "s").str();
1415}
1416
1417// Offsets are shown in bytes + bits, so offsets of different fields
1418// can always be easily compared.
1419static std::string formatOffset(uint64_t OffsetInBits) {
1420 const auto Bytes = OffsetInBits / 8;
1421 const auto Bits = OffsetInBits % 8;
1422 auto Offset = formatSize(Bytes * 8);
1423 if (Bits != 0)
1424 Offset += " and " + formatSize(Bits);
1425 return Offset;
1426}
1427
1428markup::Document HoverInfo::present() const {
1429 markup::Document Output;
1430
1431 // Header contains a text of the form:
1432 // variable `var`
1433 //
1434 // class `X`
1435 //
1436 // function `foo`
1437 //
1438 // expression
1439 //
1440 // Note that we are making use of a level-3 heading because VSCode renders
1441 // level 1 and 2 headers in a huge font, see
1442 // https://github.com/microsoft/vscode/issues/88417 for details.
1443 markup::Paragraph &Header = Output.addHeading(3);
1444 if (Kind != index::SymbolKind::Unknown)
1445 Header.appendText(index::getSymbolKindString(Kind)).appendSpace();
1446 assert(!Name.empty() && "hover triggered on a nameless symbol");
1447 Header.appendCode(Name);
1448
1449 if (!Provider.empty()) {
1450 markup::Paragraph &DI = Output.addParagraph();
1451 DI.appendText("provided by");
1452 DI.appendSpace();
1453 DI.appendCode(Provider);
1454 Output.addRuler();
1455 }
1456
1457 // Put a linebreak after header to increase readability.
1458 Output.addRuler();
1459 // Print Types on their own lines to reduce chances of getting line-wrapped by
1460 // editor, as they might be long.
1461 if (ReturnType) {
1462 // For functions we display signature in a list form, e.g.:
1463 // → `x`
1464 // Parameters:
1465 // - `bool param1`
1466 // - `int param2 = 5`
1467 Output.addParagraph().appendText("→ ").appendCode(
1468 llvm::to_string(*ReturnType));
1469 }
1470
1471 if (Parameters && !Parameters->empty()) {
1472 Output.addParagraph().appendText("Parameters: ");
1473 markup::BulletList &L = Output.addBulletList();
1474 for (const auto &Param : *Parameters)
1475 L.addItem().addParagraph().appendCode(llvm::to_string(Param));
1476 }
1477
1478 // Don't print Type after Parameters or ReturnType as this will just duplicate
1479 // the information
1480 if (Type && !ReturnType && !Parameters)
1481 Output.addParagraph().appendText("Type: ").appendCode(
1482 llvm::to_string(*Type));
1483
1484 if (Value) {
1485 markup::Paragraph &P = Output.addParagraph();
1486 P.appendText("Value = ");
1487 P.appendCode(*Value);
1488 }
1489
1490 if (Offset)
1491 Output.addParagraph().appendText("Offset: " + formatOffset(*Offset));
1492 if (Size) {
1493 auto &P = Output.addParagraph().appendText("Size: " + formatSize(*Size));
1494 if (Padding && *Padding != 0) {
1495 P.appendText(
1496 llvm::formatv(" (+{0} padding)", formatSize(*Padding)).str());
1497 }
1498 }
1499
1500 if (CalleeArgInfo) {
1501 assert(CallPassType);
1502 std::string Buffer;
1503 llvm::raw_string_ostream OS(Buffer);
1504 OS << "Passed ";
1505 if (CallPassType->PassBy != HoverInfo::PassType::Value) {
1506 OS << "by ";
1507 if (CallPassType->PassBy == HoverInfo::PassType::ConstRef)
1508 OS << "const ";
1509 OS << "reference ";
1510 }
1511 if (CalleeArgInfo->Name)
1512 OS << "as " << CalleeArgInfo->Name;
1513 else if (CallPassType->PassBy == HoverInfo::PassType::Value)
1514 OS << "by value";
1515 if (CallPassType->Converted && CalleeArgInfo->Type)
1516 OS << " (converted to " << CalleeArgInfo->Type->Type << ")";
1517 Output.addParagraph().appendText(OS.str());
1518 }
1519
1520 if (!Documentation.empty())
1521 parseDocumentation(Documentation, Output);
1522
1523 if (!Definition.empty()) {
1524 Output.addRuler();
1525 std::string Buffer;
1526
1527 if (!Definition.empty()) {
1528 // Append scope comment, dropping trailing "::".
1529 // Note that we don't print anything for global namespace, to not annoy
1530 // non-c++ projects or projects that are not making use of namespaces.
1531 if (!LocalScope.empty()) {
1532 // Container name, e.g. class, method, function.
1533 // We might want to propagate some info about container type to print
1534 // function foo, class X, method X::bar, etc.
1535 Buffer +=
1536 "// In " + llvm::StringRef(LocalScope).rtrim(':').str() + '\n';
1537 } else if (NamespaceScope && !NamespaceScope->empty()) {
1538 Buffer += "// In namespace " +
1539 llvm::StringRef(*NamespaceScope).rtrim(':').str() + '\n';
1540 }
1541
1542 if (!AccessSpecifier.empty()) {
1543 Buffer += AccessSpecifier + ": ";
1544 }
1545
1546 Buffer += Definition;
1547 }
1548
1549 Output.addCodeBlock(Buffer, DefinitionLanguage);
1550 }
1551
1552 if (!UsedSymbolNames.empty()) {
1553 Output.addRuler();
1554 markup::Paragraph &P = Output.addParagraph();
1555 P.appendText("provides ");
1556
1557 const std::vector<std::string>::size_type SymbolNamesLimit = 5;
1558 auto Front = llvm::ArrayRef(UsedSymbolNames).take_front(SymbolNamesLimit);
1559
1560 llvm::interleave(
1561 Front, [&](llvm::StringRef Sym) { P.appendCode(Sym); },
1562 [&] { P.appendText(", "); });
1563 if (UsedSymbolNames.size() > Front.size()) {
1564 P.appendText(" and ");
1565 P.appendText(std::to_string(UsedSymbolNames.size() - Front.size()));
1566 P.appendText(" more");
1567 }
1568 }
1569
1570 return Output;
1571}
1572
1573// If the backtick at `Offset` starts a probable quoted range, return the range
1574// (including the quotes).
1575std::optional<llvm::StringRef> getBacktickQuoteRange(llvm::StringRef Line,
1576 unsigned Offset) {
1577 assert(Line[Offset] == '`');
1578
1579 // The open-quote is usually preceded by whitespace.
1580 llvm::StringRef Prefix = Line.substr(0, Offset);
1581 constexpr llvm::StringLiteral BeforeStartChars = " \t(=";
1582 if (!Prefix.empty() && !BeforeStartChars.contains(Prefix.back()))
1583 return std::nullopt;
1584
1585 // The quoted string must be nonempty and usually has no leading/trailing ws.
1586 auto Next = Line.find('`', Offset + 1);
1587 if (Next == llvm::StringRef::npos)
1588 return std::nullopt;
1589 llvm::StringRef Contents = Line.slice(Offset + 1, Next);
1590 if (Contents.empty() || isWhitespace(Contents.front()) ||
1591 isWhitespace(Contents.back()))
1592 return std::nullopt;
1593
1594 // The close-quote is usually followed by whitespace or punctuation.
1595 llvm::StringRef Suffix = Line.substr(Next + 1);
1596 constexpr llvm::StringLiteral AfterEndChars = " \t)=.,;:";
1597 if (!Suffix.empty() && !AfterEndChars.contains(Suffix.front()))
1598 return std::nullopt;
1599
1600 return Line.slice(Offset, Next + 1);
1601}
1602
1603void parseDocumentationLine(llvm::StringRef Line, markup::Paragraph &Out) {
1604 // Probably this is appendText(Line), but scan for something interesting.
1605 for (unsigned I = 0; I < Line.size(); ++I) {
1606 switch (Line[I]) {
1607 case '`':
1608 if (auto Range = getBacktickQuoteRange(Line, I)) {
1609 Out.appendText(Line.substr(0, I));
1610 Out.appendCode(Range->trim("`"), /*Preserve=*/true);
1611 return parseDocumentationLine(Line.substr(I + Range->size()), Out);
1612 }
1613 break;
1614 }
1615 }
1616 Out.appendText(Line).appendSpace();
1617}
1618
1619void parseDocumentation(llvm::StringRef Input, markup::Document &Output) {
1620 std::vector<llvm::StringRef> ParagraphLines;
1621 auto FlushParagraph = [&] {
1622 if (ParagraphLines.empty())
1623 return;
1624 auto &P = Output.addParagraph();
1625 for (llvm::StringRef Line : ParagraphLines)
1626 parseDocumentationLine(Line, P);
1627 ParagraphLines.clear();
1628 };
1629
1630 llvm::StringRef Line, Rest;
1631 for (std::tie(Line, Rest) = Input.split('\n');
1632 !(Line.empty() && Rest.empty());
1633 std::tie(Line, Rest) = Rest.split('\n')) {
1634
1635 // After a linebreak remove spaces to avoid 4 space markdown code blocks.
1636 // FIXME: make FlushParagraph handle this.
1637 Line = Line.ltrim();
1638 if (!Line.empty())
1639 ParagraphLines.push_back(Line);
1640
1641 if (isParagraphBreak(Rest) || isHardLineBreakAfter(Line, Rest)) {
1642 FlushParagraph();
1643 }
1644 }
1645 FlushParagraph();
1646}
1647
1648llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
1649 const HoverInfo::PrintedType &T) {
1650 OS << T.Type;
1651 if (T.AKA)
1652 OS << " (aka " << *T.AKA << ")";
1653 return OS;
1654}
1655
1656llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
1657 const HoverInfo::Param &P) {
1658 if (P.Type)
1659 OS << P.Type->Type;
1660 if (P.Name)
1661 OS << " " << *P.Name;
1662 if (P.Default)
1663 OS << " = " << *P.Default;
1664 if (P.Type && P.Type->AKA)
1665 OS << " (aka " << *P.Type->AKA << ")";
1666 return OS;
1667}
1668
1669} // namespace clangd
1670} // namespace clang
1671