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