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