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