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