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