[AMDGPU][AsmParser][NFC] Translate parsed MIMG instructions to MCInsts automatically.
[llvm-project.git] / clang-tools-extra / clangd / Hover.cpp
blobfbd0be0796165186eb27c2ed2ee045866c1e9f38
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 //===----------------------------------------------------------------------===//
9 #include "Hover.h"
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/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"
61 #include <algorithm>
62 #include <optional>
63 #include <string>
64 #include <vector>
66 namespace clang {
67 namespace clangd {
68 namespace {
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;
76 return Base;
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("");
104 while (DC) {
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
121 // local scopes.
122 if (isa<ObjCMethodDecl, ObjCContainerDecl>(DC))
123 return "";
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);
137 return "";
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
146 // anyway.
147 if (200 < TB.expandedTokens(IE->getSourceRange()).size())
148 PP.SuppressInitializers = true;
151 std::string Definition;
152 llvm::raw_string_ostream OS(Definition);
153 D->print(OS, PP);
154 OS.flush();
155 return 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() << " ";
182 QT.print(OS, PP);
183 OS.flush();
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);
189 if (ShouldAKA)
190 Result.AKA = DesugaredTy.getAsString(PP);
192 return Result;
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 += "...";
200 return Result;
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 += "...";
208 if (PrintedType.AKA)
209 *PrintedType.AKA += "...";
211 return PrintedType;
214 HoverInfo::PrintedType printType(const TemplateTemplateParmDecl *TTP,
215 const PrintingPolicy &PP) {
216 HoverInfo::PrintedType Result;
217 llvm::raw_string_ostream OS(Result.Type);
218 OS << "template <";
219 llvm::StringRef Sep = "";
220 for (const Decl *Param : *TTP->getTemplateParameters()) {
221 OS << Sep;
222 Sep = ", ";
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".
232 OS << "> class";
233 OS.flush();
234 return Result;
237 std::vector<HoverInfo::Param>
238 fetchTemplateParameters(const TemplateParameterList *Params,
239 const PrintingPolicy &PP) {
240 assert(Params);
241 std::vector<HoverInfo::Param> TempParameters;
243 for (const Decl *Param : *Params) {
244 HoverInfo::Param P;
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()) {
260 P.Default.emplace();
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()) {
271 P.Default.emplace();
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();
287 if (!QT.isNull()) {
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
301 // or AST.
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)
335 return;
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))
342 return;
343 auto ID = getSymbolID(&ND);
344 if (!ID)
345 return;
346 LookupRequest Req;
347 Req.IDs.insert(ID);
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
355 // available.
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())
362 return nullptr;
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);
378 return Out;
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)
395 return;
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
406 // 0 => 0x0
407 // 100 => 0x64
408 // Negative numbers are sign-extended to 32/64 bits
409 // -2 => 0xfffffffe
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())
435 return std::nullopt;
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())
443 return std::nullopt;
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()))
455 .str();
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()))
463 .str();
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
471 /// expression.
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
480 // is returned.
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())
490 break;
491 if (auto Val = printExprValue(E, Ctx))
492 return PrintExprResult{/*PrintedValue=*/std::move(Val), /*Expr=*/E,
493 /*Node=*/N};
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.
497 break;
500 return PrintExprResult{/*PrintedValue=*/std::nullopt, /*Expr=*/nullptr,
501 /*Node=*/N};
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()))
507 return std::nullopt;
508 const auto *Field = llvm::dyn_cast<FieldDecl>(ME->getMemberDecl());
509 if (!Field || !Field->getDeclName().isIdentifier())
510 return std::nullopt;
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())
518 return std::nullopt;
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())
522 : nullptr;
523 if (!OnlyReturn || !OnlyReturn->getRetValue())
524 return std::nullopt;
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())
537 return std::nullopt;
538 const ParmVarDecl *Arg = CMD->getParamDecl(0);
539 if (Arg->isParameterPack())
540 return std::nullopt;
542 const auto *Body = llvm::dyn_cast<CompoundStmt>(CMD->getBody());
543 if (!Body || Body->size() == 0 || Body->size() > 2)
544 return std::nullopt;
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())
549 return std::nullopt;
550 const Expr *RetVal = Ret->getRetValue()->IgnoreCasts();
551 if (const auto *UO = llvm::dyn_cast<UnaryOperator>(RetVal)) {
552 if (UO->getOpcode() != UO_Deref)
553 return std::nullopt;
554 RetVal = UO->getSubExpr()->IgnoreCasts();
556 if (!llvm::isa<CXXThisExpr>(RetVal))
557 return std::nullopt;
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)
563 return std::nullopt;
564 LHS = BO->getLHS();
565 RHS = BO->getRHS();
566 } else if (const auto *COCE =
567 llvm::dyn_cast<CXXOperatorCallExpr>(Body->body_front())) {
568 if (COCE->getOperator() != OO_Equal || COCE->getNumArgs() != 2)
569 return std::nullopt;
570 LHS = COCE->getArg(0);
571 RHS = COCE->getArg(1);
572 } else {
573 return std::nullopt;
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)
579 return std::nullopt;
580 auto *ND = llvm::dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl());
581 if (!ND || !ND->getIdentifier() || ND->getName() != "move" ||
582 !ND->isInStdNamespace())
583 return std::nullopt;
584 RHS = CE->getArg(0);
587 auto *DRE = llvm::dyn_cast<DeclRefExpr>(RHS->IgnoreCasts());
588 if (!DRE || DRE->getDecl() != Arg)
589 return std::nullopt;
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())) &&
598 CMD->hasBody()) {
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);
605 return "";
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) {
612 HoverInfo HI;
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);
636 D = TD;
637 } else if (const FunctionDecl *FD = D->getAsFunction()) {
638 if (const auto *FTD = FD->getDescribedTemplate()) {
639 HI.TemplateParameters =
640 fetchTemplateParameters(FTD->getTemplateParameters(), PP);
641 D = FTD;
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);
672 return HI;
675 /// The standard defines __func__ as a "predefined variable".
676 std::optional<HoverInfo>
677 getPredefinedExprHoverContents(const PredefinedExpr &PE, ASTContext &Ctx,
678 const PrintingPolicy &PP) {
679 HoverInfo HI;
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()) {
684 HI.Value.emplace();
685 llvm::raw_string_ostream OS(*HI.Value);
686 Name->outputString(OS);
687 HI.Type = printType(Name->getType(), Ctx, PP);
688 } else {
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);
695 return HI;
698 HoverInfo evaluateMacroExpansion(unsigned int SpellingBeginOffset,
699 unsigned int SpellingEndOffset,
700 llvm::ArrayRef<syntax::Token> Expanded,
701 ParsedAST &AST) {
702 auto &Context = AST.getASTContext();
703 auto &Tokens = AST.getTokens();
704 auto PP = getPrintingPolicy(Context.getPrintingPolicy());
705 auto Tree = SelectionTree::createRight(Context, Tokens, SpellingBeginOffset,
706 SpellingEndOffset);
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()))
715 return {};
717 auto *StartNode = Tree.commonAncestor();
718 if (!StartNode)
719 return {};
720 // If the common ancestor is partially selected, do evaluate if it has no
721 // children, thus we can disallow evaluation on incomplete expression.
722 // For example,
723 // #define PLUS_2 +2
724 // 40 PL^US_2
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())
729 return {};
731 HoverInfo HI;
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);
743 return HI;
746 /// Generate a \p Hover object given the macro \p MacroDecl.
747 HoverInfo getHoverContents(const DefinedMacro &Macro, const syntax::Token &Tok,
748 ParsedAST &AST) {
749 HoverInfo HI;
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
762 // offset.
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
765 // macro definition.
766 if (SM.getPresumedLoc(EndLoc, /*UseLineDirectives=*/false).isValid()) {
767 EndLoc = Lexer::getLocForEndOfToken(EndLoc, 0, SM, AST.getLangOpts());
768 bool Invalid;
769 StringRef Buffer = SM.getBufferData(SM.getFileID(StartLoc), &Invalid);
770 if (!Invalid) {
771 unsigned StartOffset = SM.getFileOffset(StartLoc);
772 unsigned EndOffset = SM.getFileOffset(EndLoc);
773 if (EndOffset <= Buffer.size() && StartOffset < EndOffset)
774 HI.Definition =
775 ("#define " + Buffer.substr(StartOffset, EndOffset - StartOffset))
776 .str();
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
783 // anyway.
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();
790 break;
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);
809 return HI;
812 std::string typeAsDefinition(const HoverInfo::PrintedType &PType) {
813 std::string Result;
814 llvm::raw_string_ostream OS(Result);
815 OS << PType.Type;
816 if (PType.AKA)
817 OS << " // aka: " << *PType.AKA;
818 OS.flush();
819 return Result;
822 std::optional<HoverInfo> getThisExprHoverContents(const CXXThisExpr *CTE,
823 ASTContext &ASTCtx,
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
830 // case.
831 QualType PrettyThisType = ASTCtx.getPointerType(
832 QualType(ClassType.getTypePtr(), OriginThisType.getCVRQualifiers()));
834 HoverInfo HI;
835 HI.Name = "this";
836 HI.Definition = typeAsDefinition(printType(PrettyThisType, ASTCtx, PP));
837 return HI;
840 /// Generate a HoverInfo object given the deduced type \p QT
841 HoverInfo getDeducedTypeHoverContents(QualType QT, const syntax::Token &Tok,
842 ASTContext &ASTCtx,
843 const PrintingPolicy &PP,
844 const SymbolIndex *Index) {
845 HoverInfo HI;
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 */";
852 } else {
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);
862 return HI;
865 HoverInfo getStringLiteralContents(const StringLiteral *SL,
866 const PrintingPolicy &PP) {
867 HoverInfo HI;
869 HI.Name = "string-literal";
870 HI.Size = (SL->getLength() + 1) * SL->getCharByteWidth() * 8;
871 HI.Type = SL->getType().getAsString(PP).c_str();
873 return HI;
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
920 // value here.
921 HI->Name = "literal";
922 return HI;
924 return std::nullopt;
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
933 // evaluatable.
934 if (auto Val = printExprValue(E, AST.getASTContext())) {
935 HI.emplace();
936 HI->Type = printType(E->getType(), AST.getASTContext(), PP);
937 HI->Value = *Val;
938 HI->Name = std::string(getNameForExpr(E));
941 if (HI)
942 maybeAddCalleeArgInfo(N, *HI, PP);
944 return HI;
947 // Generates hover info for attributes.
948 std::optional<HoverInfo> getHoverContents(const Attr *A, ParsedAST &AST) {
949 HoverInfo HI;
950 HI.Name = A->getSpelling();
951 if (A->hasScope())
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();
958 return HI;
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";
968 Line = Line.rtrim();
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");
978 if (Rest.empty())
979 return false;
981 if (LinebreakIndicators.contains(Rest.front()))
982 return true;
984 if (llvm::isDigit(Rest.front())) {
985 llvm::StringRef AfterDigit = Rest.drop_while(llvm::isDigit);
986 if (AfterDigit.startswith(".") || AfterDigit.startswith(")"))
987 return true;
989 return false;
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())
999 return;
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;
1005 return;
1008 if (const auto *FD = llvm::dyn_cast<FieldDecl>(&ND)) {
1009 const auto *Record = FD->getParent();
1010 if (Record)
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;
1019 if (HI.Size) {
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;
1029 } else {
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())
1036 HI.Offset.reset();
1038 return;
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)
1057 return;
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()};
1070 if (!FD)
1071 return;
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())
1080 return;
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>())
1089 continue;
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());
1097 break;
1099 if (!HI.CalleeArgInfo)
1100 return;
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()) {
1115 case CK_NoOp:
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;
1123 break;
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;
1131 break;
1132 default:
1133 PassType.PassBy = HoverInfo::PassType::Value;
1134 PassType.Converted = true;
1135 break;
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;
1143 else
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())
1159 return nullptr;
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); }
1175 // using ns::foo;
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())
1195 return;
1197 std::string Result;
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
1204 break;
1206 // Pick the best-ranked #include'd provider
1207 auto Matches = ConvertedIncludes.match(P);
1208 if (!Matches.empty()) {
1209 Result = Matches[0]->quote();
1210 break;
1214 if (!Result.empty()) {
1215 HI.Provider = std::move(Result);
1216 return;
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.
1225 return;
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) {
1236 std::string Name;
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();
1241 break;
1242 case include_cleaner::Symbol::Macro:
1243 Name = Sym.macro().Name->getName();
1244 break;
1246 return Name;
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))
1262 return;
1264 auto Provider =
1265 firstMatchedProvider(ConvertedMainFileIncludes, Providers);
1266 if (!Provider || HoveredInclude.match(*Provider).empty())
1267 return;
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());
1280 } // namespace
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");
1287 PrintingPolicy PP =
1288 getPrintingPolicy(AST.getASTContext().getPrintingPolicy());
1289 const SourceManager &SM = AST.getSourceManager();
1290 auto CurLoc = sourceLocationInMainFile(SM, Pos);
1291 if (!CurLoc) {
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)
1304 continue;
1305 HoverCountMetric.record(1, "include");
1306 HoverInfo HI;
1307 HI.Name = std::string(llvm::sys::path::filename(Inc.Resolved));
1308 // FIXME: We don't have a fitting value for Kind.
1309 HI.Definition =
1310 URIForFile::canonicalize(Inc.Resolved, AST.tuPath()).file().str();
1311 HI.DefinitionLanguage = "";
1312 maybeAddUsedSymbols(AST, HI, Inc);
1313 return HI;
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});
1338 break;
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,
1344 Index);
1345 HighlightRange = Tok.range(SM).toCharRange(SM);
1346 break;
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.
1357 if (!HI) {
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).
1361 SelectionTree ST =
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.
1374 if (!HI->Value)
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?
1389 // - built-in types
1393 if (!HI)
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);
1408 return HI;
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);
1424 if (Bits != 0)
1425 Offset += " and " + formatSize(Bits);
1426 return Offset;
1429 markup::Document HoverInfo::present() const {
1430 markup::Document Output;
1432 // Header contains a text of the form:
1433 // variable `var`
1435 // class `X`
1437 // function `foo`
1439 // expression
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");
1453 DI.appendSpace();
1454 DI.appendCode(Provider);
1455 Output.addRuler();
1458 // Put a linebreak after header to increase readability.
1459 Output.addRuler();
1460 // Print Types on their own lines to reduce chances of getting line-wrapped by
1461 // editor, as they might be long.
1462 if (ReturnType) {
1463 // For functions we display signature in a list form, e.g.:
1464 // → `x`
1465 // Parameters:
1466 // - `bool param1`
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
1480 // the information
1481 if (Type && !ReturnType && !Parameters)
1482 Output.addParagraph().appendText("Type: ").appendCode(
1483 llvm::to_string(*Type));
1485 if (Value) {
1486 markup::Paragraph &P = Output.addParagraph();
1487 P.appendText("Value = ");
1488 P.appendCode(*Value);
1491 if (Offset)
1492 Output.addParagraph().appendText("Offset: " + formatOffset(*Offset));
1493 if (Size) {
1494 auto &P = Output.addParagraph().appendText("Size: " + formatSize(*Size));
1495 if (Padding && *Padding != 0) {
1496 P.appendText(
1497 llvm::formatv(" (+{0} padding)", formatSize(*Padding)).str());
1501 if (CalleeArgInfo) {
1502 assert(CallPassType);
1503 std::string Buffer;
1504 llvm::raw_string_ostream OS(Buffer);
1505 OS << "Passed ";
1506 if (CallPassType->PassBy != HoverInfo::PassType::Value) {
1507 OS << "by ";
1508 if (CallPassType->PassBy == HoverInfo::PassType::ConstRef)
1509 OS << "const ";
1510 OS << "reference ";
1512 if (CalleeArgInfo->Name)
1513 OS << "as " << CalleeArgInfo->Name;
1514 else if (CallPassType->PassBy == HoverInfo::PassType::Value)
1515 OS << "by 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()) {
1525 Output.addRuler();
1526 std::string Buffer;
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.
1536 Buffer +=
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()) {
1554 Output.addRuler();
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);
1561 llvm::interleave(
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");
1571 return Output;
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,
1577 unsigned Offset) {
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) {
1607 switch (Line[I]) {
1608 case '`':
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);
1614 break;
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())
1624 return;
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();
1639 if (!Line.empty())
1640 ParagraphLines.push_back(Line);
1642 if (isParagraphBreak(Rest) || isHardLineBreakAfter(Line, Rest)) {
1643 FlushParagraph();
1646 FlushParagraph();
1649 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
1650 const HoverInfo::PrintedType &T) {
1651 OS << T.Type;
1652 if (T.AKA)
1653 OS << " (aka " << *T.AKA << ")";
1654 return OS;
1657 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
1658 const HoverInfo::Param &P) {
1659 if (P.Type)
1660 OS << P.Type->Type;
1661 if (P.Name)
1662 OS << " " << *P.Name;
1663 if (P.Default)
1664 OS << " = " << *P.Default;
1665 if (P.Type && P.Type->AKA)
1666 OS << " (aka " << *P.Type->AKA << ")";
1667 return OS;
1670 } // namespace clangd
1671 } // namespace clang