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 if (Ctx.getLangOpts().CPlusPlus)
670 HI.AccessSpecifier = getAccessSpelling(D->getAccess()).str();
671 HI.NamespaceScope = getNamespaceScope(D);
672 if (!HI.NamespaceScope->empty())
673 HI.NamespaceScope->append("::");
674 HI.LocalScope = getLocalScope(D);
675 if (!HI.LocalScope.empty())
676 HI.LocalScope.append("::");
677
678 HI.Name = printName(Ctx, *D);
679 const auto *CommentD = getDeclForComment(D);
680 HI.Documentation = getDeclComment(Ctx, *CommentD);
681 // save the language options to be able to create the comment::CommandTraits
682 // to parse the documentation
683 HI.CommentOpts = D->getASTContext().getLangOpts().CommentOpts;
684 enhanceFromIndex(HI, *CommentD, Index);
685 if (HI.Documentation.empty())
686 HI.Documentation = synthesizeDocumentation(Ctx, D);
687
688 HI.Kind = index::getSymbolInfo(D).Kind;
689
690 // Fill in template params.
691 if (const TemplateDecl *TD = D->getDescribedTemplate()) {
692 HI.TemplateParameters =
693 fetchTemplateParameters(TD->getTemplateParameters(), PP);
694 D = TD;
695 } else if (const FunctionDecl *FD = D->getAsFunction()) {
696 if (const auto *FTD = FD->getDescribedTemplate()) {
697 HI.TemplateParameters =
698 fetchTemplateParameters(FTD->getTemplateParameters(), PP);
699 D = FTD;
700 }
701 }
702
703 // Fill in types and params.
704 if (const FunctionDecl *FD = getUnderlyingFunction(D))
705 fillFunctionTypeAndParams(HI, D, FD, PP);
706 else if (const auto *VD = dyn_cast<ValueDecl>(D))
707 HI.Type = printType(VD->getType(), Ctx, PP);
708 else if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(D))
709 HI.Type = TTP->wasDeclaredWithTypename() ? "typename" : "class";
710 else if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(D))
711 HI.Type = printType(TTP, PP);
712 else if (const auto *VT = dyn_cast<VarTemplateDecl>(D))
713 HI.Type = printType(VT->getTemplatedDecl()->getType(), Ctx, PP);
714 else if (const auto *TN = dyn_cast<TypedefNameDecl>(D))
715 HI.Type = printType(TN->getUnderlyingType().getDesugaredType(Ctx), Ctx, PP);
716 else if (const auto *TAT = dyn_cast<TypeAliasTemplateDecl>(D))
717 HI.Type = printType(TAT->getTemplatedDecl()->getUnderlyingType(), Ctx, PP);
718
719 // Fill in value with evaluated initializer if possible.
720 if (const auto *Var = dyn_cast<VarDecl>(D); Var && !Var->isInvalidDecl()) {
721 if (const Expr *Init = Var->getInit())
722 HI.Value = printExprValue(Init, Ctx);
723 } else if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
724 // Dependent enums (e.g. nested in template classes) don't have values yet.
725 if (!ECD->getType()->isDependentType())
726 HI.Value = toString(ECD->getInitVal(), 10);
727 }
728
729 HI.Definition = printDefinition(D, PP, TB);
730 return HI;
731}
732
733/// The standard defines __func__ as a "predefined variable".
734std::optional<HoverInfo>
735getPredefinedExprHoverContents(const PredefinedExpr &PE, ASTContext &Ctx,
736 const PrintingPolicy &PP) {
737 HoverInfo HI;
738 HI.Name = PE.getIdentKindName();
739 HI.Kind = index::SymbolKind::Variable;
740 HI.Documentation = "Name of the current function (predefined variable)";
741 if (const StringLiteral *Name = PE.getFunctionName()) {
742 HI.Value.emplace();
743 llvm::raw_string_ostream OS(*HI.Value);
744 Name->outputString(OS);
745 HI.Type = printType(Name->getType(), Ctx, PP);
746 } else {
747 // Inside templates, the approximate type `const char[]` is still useful.
748 QualType StringType = Ctx.getIncompleteArrayType(Ctx.CharTy.withConst(),
749 ArraySizeModifier::Normal,
750 /*IndexTypeQuals=*/0);
751 HI.Type = printType(StringType, Ctx, PP);
752 }
753 return HI;
754}
755
756HoverInfo evaluateMacroExpansion(unsigned int SpellingBeginOffset,
757 unsigned int SpellingEndOffset,
758 llvm::ArrayRef<syntax::Token> Expanded,
759 ParsedAST &AST) {
760 auto &Context = AST.getASTContext();
761 auto &Tokens = AST.getTokens();
762 auto PP = getPrintingPolicy(Context.getPrintingPolicy());
763 auto Tree = SelectionTree::createRight(Context, Tokens, SpellingBeginOffset,
764 SpellingEndOffset);
765
766 // If macro expands to one single token, rule out punctuator or digraph.
767 // E.g., for the case `array L_BRACKET 42 R_BRACKET;` where L_BRACKET and
768 // R_BRACKET expand to
769 // '[' and ']' respectively, we don't want the type of
770 // 'array[42]' when user hovers on L_BRACKET.
771 if (Expanded.size() == 1)
772 if (tok::getPunctuatorSpelling(Expanded[0].kind()))
773 return {};
774
775 auto *StartNode = Tree.commonAncestor();
776 if (!StartNode)
777 return {};
778 // If the common ancestor is partially selected, do evaluate if it has no
779 // children, thus we can disallow evaluation on incomplete expression.
780 // For example,
781 // #define PLUS_2 +2
782 // 40 PL^US_2
783 // In this case we don't want to present 'value: 2' as PLUS_2 actually expands
784 // to a non-value rather than a binary operand.
785 if (StartNode->Selected == SelectionTree::Selection::Partial)
786 if (!StartNode->Children.empty())
787 return {};
788
789 HoverInfo HI;
790 // Attempt to evaluate it from Expr first.
791 auto ExprResult = printExprValue(StartNode, Context);
792 HI.Value = std::move(ExprResult.PrintedValue);
793 if (auto *E = ExprResult.TheExpr)
794 HI.Type = printType(E->getType(), Context, PP);
795
796 // If failed, extract the type from Decl if possible.
797 if (!HI.Value && !HI.Type && ExprResult.TheNode)
798 if (auto *VD = ExprResult.TheNode->ASTNode.get<VarDecl>())
799 HI.Type = printType(VD->getType(), Context, PP);
800
801 return HI;
802}
803
804/// Generate a \p Hover object given the macro \p MacroDecl.
805HoverInfo getHoverContents(const DefinedMacro &Macro, const syntax::Token &Tok,
806 ParsedAST &AST) {
807 HoverInfo HI;
808 SourceManager &SM = AST.getSourceManager();
809 HI.Name = std::string(Macro.Name);
810 HI.Kind = index::SymbolKind::Macro;
811 // FIXME: Populate documentation
812 // FIXME: Populate parameters
813
814 // Try to get the full definition, not just the name
815 SourceLocation StartLoc = Macro.Info->getDefinitionLoc();
816 SourceLocation EndLoc = Macro.Info->getDefinitionEndLoc();
817 // Ensure that EndLoc is a valid offset. For example it might come from
818 // preamble, and source file might've changed, in such a scenario EndLoc still
819 // stays valid, but getLocForEndOfToken will fail as it is no longer a valid
820 // offset.
821 // Note that this check is just to ensure there's text data inside the range.
822 // It will still succeed even when the data inside the range is irrelevant to
823 // macro definition.
824 if (SM.getPresumedLoc(EndLoc, /*UseLineDirectives=*/false).isValid()) {
825 EndLoc = Lexer::getLocForEndOfToken(EndLoc, 0, SM, AST.getLangOpts());
826 bool Invalid;
827 StringRef Buffer = SM.getBufferData(SM.getFileID(StartLoc), &Invalid);
828 if (!Invalid) {
829 unsigned StartOffset = SM.getFileOffset(StartLoc);
830 unsigned EndOffset = SM.getFileOffset(EndLoc);
831 if (EndOffset <= Buffer.size() && StartOffset < EndOffset)
832 HI.Definition =
833 ("#define " + Buffer.substr(StartOffset, EndOffset - StartOffset))
834 .str();
835 }
836 }
837
838 if (auto Expansion = AST.getTokens().expansionStartingAt(&Tok)) {
839 // We drop expansion that's longer than the threshold.
840 // For extremely long expansion text, it's not readable from hover card
841 // anyway.
842 std::string ExpansionText;
843 for (const auto &ExpandedTok : Expansion->Expanded) {
844 ExpansionText += ExpandedTok.text(SM);
845 ExpansionText += " ";
846 const Config &Cfg = Config::current();
847 const size_t Limit = static_cast<size_t>(Cfg.Hover.MacroContentsLimit);
848 if (Limit && ExpansionText.size() > Limit) {
849 ExpansionText.clear();
850 break;
851 }
852 }
853
854 if (!ExpansionText.empty()) {
855 if (!HI.Definition.empty()) {
856 HI.Definition += "\n\n";
857 }
858 HI.Definition += "// Expands to\n";
859 HI.Definition += ExpansionText;
860 }
861
862 auto Evaluated = evaluateMacroExpansion(
863 /*SpellingBeginOffset=*/SM.getFileOffset(Tok.location()),
864 /*SpellingEndOffset=*/SM.getFileOffset(Tok.endLocation()),
865 /*Expanded=*/Expansion->Expanded, AST);
866 HI.Value = std::move(Evaluated.Value);
867 HI.Type = std::move(Evaluated.Type);
868 }
869 return HI;
870}
871
872std::string typeAsDefinition(const HoverInfo::PrintedType &PType) {
873 std::string Result;
874 llvm::raw_string_ostream OS(Result);
875 OS << PType.Type;
876 if (PType.AKA)
877 OS << " // aka: " << *PType.AKA;
878 return Result;
879}
880
881std::optional<HoverInfo> getThisExprHoverContents(const CXXThisExpr *CTE,
882 ASTContext &ASTCtx,
883 const PrintingPolicy &PP) {
884 QualType OriginThisType = CTE->getType()->getPointeeType();
885 QualType ClassType = declaredType(OriginThisType->castAsTagDecl());
886 // For partial specialization class, origin `this` pointee type will be
887 // parsed as `InjectedClassNameType`, which will ouput template arguments
888 // like "type-parameter-0-0". So we retrieve user written class type in this
889 // case.
890 QualType PrettyThisType = ASTCtx.getPointerType(
891 QualType(ClassType.getTypePtr(), OriginThisType.getCVRQualifiers()));
892
893 HoverInfo HI;
894 HI.Name = "this";
895 HI.Definition = typeAsDefinition(printType(PrettyThisType, ASTCtx, PP));
896 return HI;
897}
898
899/// Generate a HoverInfo object given the deduced type \p QT
900HoverInfo getDeducedTypeHoverContents(QualType QT, const syntax::Token &Tok,
901 ASTContext &ASTCtx,
902 const PrintingPolicy &PP,
903 const SymbolIndex *Index) {
904 HoverInfo HI;
905 // FIXME: distinguish decltype(auto) vs decltype(expr)
906 HI.Name = tok::getTokenName(Tok.kind());
907 HI.Kind = index::SymbolKind::TypeAlias;
908
909 if (QT->isUndeducedAutoType()) {
910 HI.Definition = "/* not deduced */";
911 } else {
912 HI.Definition = typeAsDefinition(printType(QT, ASTCtx, PP));
913
914 if (const auto *D = QT->getAsTagDecl()) {
915 const auto *CommentD = getDeclForComment(D);
916 HI.Documentation = getDeclComment(ASTCtx, *CommentD);
917 enhanceFromIndex(HI, *CommentD, Index);
918 }
919 }
920
921 return HI;
922}
923
924HoverInfo getStringLiteralContents(const StringLiteral *SL,
925 const PrintingPolicy &PP) {
926 HoverInfo HI;
927
928 HI.Name = "string-literal";
929 HI.Size = (SL->getLength() + 1) * SL->getCharByteWidth() * 8;
930 HI.Type = SL->getType().getAsString(PP).c_str();
931
932 return HI;
933}
934
935bool isLiteral(const Expr *E) {
936 // Unfortunately there's no common base Literal classes inherits from
937 // (apart from Expr), therefore these exclusions.
938 return llvm::isa<CompoundLiteralExpr>(E) ||
939 llvm::isa<CXXBoolLiteralExpr>(E) ||
940 llvm::isa<CXXNullPtrLiteralExpr>(E) ||
941 llvm::isa<FixedPointLiteral>(E) || llvm::isa<FloatingLiteral>(E) ||
942 llvm::isa<ImaginaryLiteral>(E) || llvm::isa<IntegerLiteral>(E) ||
943 llvm::isa<StringLiteral>(E) || llvm::isa<UserDefinedLiteral>(E);
944}
945
946llvm::StringLiteral getNameForExpr(const Expr *E) {
947 // FIXME: Come up with names for `special` expressions.
948 //
949 // It's an known issue for GCC5, https://godbolt.org/z/Z_tbgi. Work around
950 // that by using explicit conversion constructor.
951 //
952 // TODO: Once GCC5 is fully retired and not the minimal requirement as stated
953 // in `GettingStarted`, please remove the explicit conversion constructor.
954 return llvm::StringLiteral("expression");
955}
956
957void maybeAddCalleeArgInfo(const SelectionTree::Node *N, HoverInfo &HI,
958 const PrintingPolicy &PP);
959
960// Generates hover info for `this` and evaluatable expressions.
961// FIXME: Support hover for literals (esp user-defined)
962std::optional<HoverInfo> getHoverContents(const SelectionTree::Node *N,
963 const Expr *E, ParsedAST &AST,
964 const PrintingPolicy &PP,
965 const SymbolIndex *Index) {
966 std::optional<HoverInfo> HI;
967
968 if (const auto *VecExpr = dyn_cast<ExtVectorElementExpr>(E)) {
969 HI.emplace();
970 HI->Name = VecExpr->getAccessor().getName().str();
971 HI->Type = printType(VecExpr->getType(), AST.getASTContext(), PP);
972 return HI;
973 }
974 if (const auto *MatExpr = dyn_cast<MatrixElementExpr>(E)) {
975 HI.emplace();
976 HI->Name = MatExpr->getAccessor().getName().str();
977 HI->Type = printType(MatExpr->getType(), AST.getASTContext(), PP);
978 return HI;
979 }
980
981 if (const StringLiteral *SL = dyn_cast<StringLiteral>(E)) {
982 // Print the type and the size for string literals
983 HI = getStringLiteralContents(SL, PP);
984 } else if (isLiteral(E)) {
985 // There's not much value in hovering over "42" and getting a hover card
986 // saying "42 is an int", similar for most other literals.
987 // However, if we have CalleeArgInfo, it's still useful to show it.
988 maybeAddCalleeArgInfo(N, HI.emplace(), PP);
989 if (HI->CalleeArgInfo) {
990 // FIXME Might want to show the expression's value here instead?
991 // E.g. if the literal is in hex it might be useful to show the decimal
992 // value here.
993 HI->Name = "literal";
994 return HI;
995 }
996 return std::nullopt;
997 }
998
999 // For `this` expr we currently generate hover with pointee type.
1000 if (const CXXThisExpr *CTE = dyn_cast<CXXThisExpr>(E))
1001 HI = getThisExprHoverContents(CTE, AST.getASTContext(), PP);
1002 if (const PredefinedExpr *PE = dyn_cast<PredefinedExpr>(E))
1003 HI = getPredefinedExprHoverContents(*PE, AST.getASTContext(), PP);
1004 // For expressions we currently print the type and the value, iff it is
1005 // evaluatable.
1006 if (auto Val = printExprValue(E, AST.getASTContext())) {
1007 HI.emplace();
1008 HI->Type = printType(E->getType(), AST.getASTContext(), PP);
1009 HI->Value = *Val;
1010 HI->Name = std::string(getNameForExpr(E));
1011 }
1012
1013 if (HI)
1014 maybeAddCalleeArgInfo(N, *HI, PP);
1015
1016 return HI;
1017}
1018
1019// Generates hover info for attributes.
1020std::optional<HoverInfo> getHoverContents(const Attr *A, ParsedAST &AST) {
1021 HoverInfo HI;
1022 HI.Name = A->getSpelling();
1023 if (A->hasScope())
1024 HI.LocalScope = A->getScopeName()->getName().str();
1025 {
1026 llvm::raw_string_ostream OS(HI.Definition);
1027 A->printPretty(OS, AST.getASTContext().getPrintingPolicy());
1028 }
1029 HI.Documentation = Attr::getDocumentation(A->getKind()).str();
1030 return HI;
1031}
1032
1033void addLayoutInfo(const NamedDecl &ND, HoverInfo &HI) {
1034 if (ND.isInvalidDecl())
1035 return;
1036
1037 const auto &Ctx = ND.getASTContext();
1038 if (auto *RD = llvm::dyn_cast<RecordDecl>(&ND)) {
1039 CanQualType RT = Ctx.getCanonicalTagType(RD);
1040 if (auto Size = Ctx.getTypeSizeInCharsIfKnown(RT))
1041 HI.Size = Size->getQuantity() * 8;
1042 if (!RD->isDependentType() && RD->isCompleteDefinition())
1043 HI.Align = Ctx.getTypeAlign(RT);
1044 return;
1045 }
1046
1047 if (const auto *FD = llvm::dyn_cast<FieldDecl>(&ND)) {
1048 const auto *Record = FD->getParent();
1049 if (Record)
1050 Record = Record->getDefinition();
1051 if (Record && !Record->isInvalidDecl() && !Record->isDependentType()) {
1052 HI.Align = Ctx.getTypeAlign(FD->getType());
1053 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Record);
1054 HI.Offset = Layout.getFieldOffset(FD->getFieldIndex());
1055 if (FD->isBitField())
1056 HI.Size = FD->getBitWidthValue();
1057 else if (auto Size = Ctx.getTypeSizeInCharsIfKnown(FD->getType()))
1058 HI.Size = FD->isZeroSize(Ctx) ? 0 : Size->getQuantity() * 8;
1059 if (HI.Size) {
1060 unsigned EndOfField = *HI.Offset + *HI.Size;
1061
1062 // Calculate padding following the field.
1063 if (!Record->isUnion() &&
1064 FD->getFieldIndex() + 1 < Layout.getFieldCount()) {
1065 // Measure padding up to the next class field.
1066 unsigned NextOffset = Layout.getFieldOffset(FD->getFieldIndex() + 1);
1067 if (NextOffset >= EndOfField) // next field could be a bitfield!
1068 HI.Padding = NextOffset - EndOfField;
1069 } else {
1070 // Measure padding up to the end of the object.
1071 HI.Padding = Layout.getSize().getQuantity() * 8 - EndOfField;
1072 }
1073 }
1074 // Offset in a union is always zero, so not really useful to report.
1075 if (Record->isUnion())
1076 HI.Offset.reset();
1077 }
1078 return;
1079 }
1080}
1081
1082HoverInfo::PassType::PassMode getPassMode(QualType ParmType) {
1083 if (ParmType->isReferenceType()) {
1084 if (ParmType->getPointeeType().isConstQualified())
1087 }
1089}
1090
1091// If N is passed as argument to a function, fill HI.CalleeArgInfo with
1092// information about that argument.
1093void maybeAddCalleeArgInfo(const SelectionTree::Node *N, HoverInfo &HI,
1094 const PrintingPolicy &PP) {
1095 const auto &OuterNode = N->outerImplicit();
1096 if (!OuterNode.Parent)
1097 return;
1098
1099 const FunctionDecl *FD = nullptr;
1100 llvm::ArrayRef<const Expr *> Args;
1101
1102 if (const auto *CE = OuterNode.Parent->ASTNode.get<CallExpr>()) {
1103 FD = CE->getDirectCallee();
1104 Args = {CE->getArgs(), CE->getNumArgs()};
1105 } else if (const auto *CE =
1106 OuterNode.Parent->ASTNode.get<CXXConstructExpr>()) {
1107 FD = CE->getConstructor();
1108 Args = {CE->getArgs(), CE->getNumArgs()};
1109 }
1110 if (!FD)
1111 return;
1112
1113 // For non-function-call-like operators (e.g. operator+, operator<<) it's
1114 // not immediately obvious what the "passed as" would refer to and, given
1115 // fixed function signature, the value would be very low anyway, so we choose
1116 // to not support that.
1117 // Both variadic functions and operator() (especially relevant for lambdas)
1118 // should be supported in the future.
1119 if (!FD || FD->isOverloadedOperator() || FD->isVariadic())
1120 return;
1121
1122 HoverInfo::PassType PassType;
1123
1124 auto Parameters = resolveForwardingParameters(FD);
1125
1126 // Find argument index for N.
1127 for (unsigned I = 0; I < Args.size() && I < Parameters.size(); ++I) {
1128 if (Args[I] != OuterNode.ASTNode.get<Expr>())
1129 continue;
1130
1131 // Extract matching argument from function declaration.
1132 if (const ParmVarDecl *PVD = Parameters[I]) {
1133 HI.CalleeArgInfo.emplace(toHoverInfoParam(PVD, PP));
1134 if (N == &OuterNode)
1135 PassType.PassBy = getPassMode(PVD->getType());
1136 }
1137 break;
1138 }
1139 if (!HI.CalleeArgInfo)
1140 return;
1141
1142 // If we found a matching argument, also figure out if it's a
1143 // [const-]reference. For this we need to walk up the AST from the arg itself
1144 // to CallExpr and check all implicit casts, constructor calls, etc.
1145 if (const auto *E = N->ASTNode.get<Expr>()) {
1146 if (E->getType().isConstQualified())
1147 PassType.PassBy = HoverInfo::PassType::ConstRef;
1148 }
1149
1150 for (auto *CastNode = N->Parent;
1151 CastNode != OuterNode.Parent && !PassType.Converted;
1152 CastNode = CastNode->Parent) {
1153 if (const auto *ImplicitCast = CastNode->ASTNode.get<ImplicitCastExpr>()) {
1154 switch (ImplicitCast->getCastKind()) {
1155 case CK_NoOp:
1156 case CK_DerivedToBase:
1157 case CK_UncheckedDerivedToBase:
1158 // If it was a reference before, it's still a reference.
1159 if (PassType.PassBy != HoverInfo::PassType::Value)
1160 PassType.PassBy = ImplicitCast->getType().isConstQualified()
1163 break;
1164 case CK_LValueToRValue:
1165 case CK_ArrayToPointerDecay:
1166 case CK_FunctionToPointerDecay:
1167 case CK_NullToPointer:
1168 case CK_NullToMemberPointer:
1169 // No longer a reference, but we do not show this as type conversion.
1170 PassType.PassBy = HoverInfo::PassType::Value;
1171 break;
1172 default:
1173 PassType.PassBy = HoverInfo::PassType::Value;
1174 PassType.Converted = true;
1175 break;
1176 }
1177 } else if (const auto *CtorCall =
1178 CastNode->ASTNode.get<CXXConstructExpr>()) {
1179 // We want to be smart about copy constructors. They should not show up as
1180 // type conversion, but instead as passing by value.
1181 if (CtorCall->getConstructor()->isCopyConstructor())
1182 PassType.PassBy = HoverInfo::PassType::Value;
1183 else
1184 PassType.Converted = true;
1185 } else if (CastNode->ASTNode.get<MaterializeTemporaryExpr>()) {
1186 // Can't bind a non-const-ref to a temporary, so has to be const-ref
1187 PassType.PassBy = HoverInfo::PassType::ConstRef;
1188 } else { // Unknown implicit node, assume type conversion.
1189 PassType.PassBy = HoverInfo::PassType::Value;
1190 PassType.Converted = true;
1191 }
1192 }
1193
1194 HI.CallPassType.emplace(PassType);
1195}
1196
1197const NamedDecl *pickDeclToUse(llvm::ArrayRef<const NamedDecl *> Candidates) {
1198 if (Candidates.empty())
1199 return nullptr;
1200
1201 // This is e.g the case for
1202 // namespace ns { void foo(); }
1203 // void bar() { using ns::foo; f^oo(); }
1204 // One declaration in Candidates will refer to the using declaration,
1205 // which isn't really useful for Hover. So use the other one,
1206 // which in this example would be the actual declaration of foo.
1207 if (Candidates.size() <= 2) {
1208 if (llvm::isa<UsingDecl>(Candidates.front()))
1209 return Candidates.back();
1210 return Candidates.front();
1211 }
1212
1213 // For something like
1214 // namespace ns { void foo(int); void foo(char); }
1215 // using ns::foo;
1216 // template <typename T> void bar() { fo^o(T{}); }
1217 // we actually want to show the using declaration,
1218 // it's not clear which declaration to pick otherwise.
1219 auto BaseDecls = llvm::make_filter_range(
1220 Candidates, [](const NamedDecl *D) { return llvm::isa<UsingDecl>(D); });
1221 if (std::distance(BaseDecls.begin(), BaseDecls.end()) == 1)
1222 return *BaseDecls.begin();
1223
1224 return Candidates.front();
1225}
1226
1227void maybeAddSymbolProviders(ParsedAST &AST, HoverInfo &HI,
1228 include_cleaner::Symbol Sym) {
1229 trace::Span Tracer("Hover::maybeAddSymbolProviders");
1230
1231 llvm::SmallVector<include_cleaner::Header> RankedProviders =
1232 include_cleaner::headersForSymbol(Sym, AST.getPreprocessor(),
1233 &AST.getPragmaIncludes());
1234 if (RankedProviders.empty())
1235 return;
1236
1237 const SourceManager &SM = AST.getSourceManager();
1238 std::string Result;
1239 include_cleaner::Includes ConvertedIncludes = convertIncludes(AST);
1240 for (const auto &P : RankedProviders) {
1241 if (P.kind() == include_cleaner::Header::Physical &&
1242 P.physical() == SM.getFileEntryForID(SM.getMainFileID()))
1243 // Main file ranked higher than any #include'd file
1244 break;
1245
1246 // Pick the best-ranked #include'd provider
1247 auto Matches = ConvertedIncludes.match(P);
1248 if (!Matches.empty()) {
1249 Result = Matches[0]->quote();
1250 break;
1251 }
1252 }
1253
1254 if (!Result.empty()) {
1255 HI.Provider = std::move(Result);
1256 return;
1257 }
1258
1259 // Pick the best-ranked non-#include'd provider
1260 const auto &H = RankedProviders.front();
1261 if (H.kind() == include_cleaner::Header::Physical &&
1262 H.physical() == SM.getFileEntryForID(SM.getMainFileID()))
1263 // Do not show main file as provider, otherwise we'll show provider info
1264 // on local variables, etc.
1265 return;
1266
1267 HI.Provider = include_cleaner::spellHeader(
1268 {H, AST.getPreprocessor().getHeaderSearchInfo(),
1269 SM.getFileEntryForID(SM.getMainFileID())});
1270}
1271
1272// FIXME: similar functions are present in FindHeaders.cpp (symbolName)
1273// and IncludeCleaner.cpp (getSymbolName). Introduce a name() method into
1274// include_cleaner::Symbol instead.
1275std::string getSymbolName(include_cleaner::Symbol Sym) {
1276 std::string Name;
1277 switch (Sym.kind()) {
1278 case include_cleaner::Symbol::Declaration:
1279 if (const auto *ND = llvm::dyn_cast<NamedDecl>(&Sym.declaration()))
1280 Name = ND->getDeclName().getAsString();
1281 break;
1282 case include_cleaner::Symbol::Macro:
1283 Name = Sym.macro().Name->getName();
1284 break;
1285 }
1286 return Name;
1287}
1288
1289void maybeAddUsedSymbols(ParsedAST &AST, HoverInfo &HI, const Inclusion &Inc) {
1290 auto Converted = convertIncludes(AST);
1291 llvm::DenseSet<include_cleaner::Symbol> UsedSymbols;
1292 include_cleaner::walkUsed(
1293 AST.getLocalTopLevelDecls(), collectMacroReferences(AST),
1294 &AST.getPragmaIncludes(), AST.getPreprocessor(),
1295 [&](const include_cleaner::SymbolReference &Ref,
1296 llvm::ArrayRef<include_cleaner::Header> Providers) {
1297 if (Ref.RT != include_cleaner::RefType::Explicit ||
1298 UsedSymbols.contains(Ref.Target))
1299 return;
1300
1301 if (isPreferredProvider(Inc, Converted, Providers))
1302 UsedSymbols.insert(Ref.Target);
1303 });
1304
1305 for (const auto &UsedSymbolDecl : UsedSymbols)
1306 HI.UsedSymbolNames.push_back(getSymbolName(UsedSymbolDecl));
1307 llvm::sort(HI.UsedSymbolNames);
1308 HI.UsedSymbolNames.erase(llvm::unique(HI.UsedSymbolNames),
1309 HI.UsedSymbolNames.end());
1310}
1311
1312} // namespace
1313
1314std::optional<HoverInfo> getHover(ParsedAST &AST, Position Pos,
1315 const format::FormatStyle &Style,
1316 const SymbolIndex *Index) {
1317 static constexpr trace::Metric HoverCountMetric(
1318 "hover", trace::Metric::Counter, "case");
1319 PrintingPolicy PP =
1320 getPrintingPolicy(AST.getASTContext().getPrintingPolicy());
1321 const SourceManager &SM = AST.getSourceManager();
1322 auto CurLoc = sourceLocationInMainFile(SM, Pos);
1323 if (!CurLoc) {
1324 llvm::consumeError(CurLoc.takeError());
1325 return std::nullopt;
1326 }
1327 const auto &TB = AST.getTokens();
1328 auto TokensTouchingCursor = syntax::spelledTokensTouching(*CurLoc, TB);
1329 // Early exit if there were no tokens around the cursor.
1330 if (TokensTouchingCursor.empty())
1331 return std::nullopt;
1332
1333 // Show full header file path if cursor is on include directive.
1334 for (const auto &Inc : AST.getIncludeStructure().MainFileIncludes) {
1335 if (Inc.Resolved.empty() || Inc.HashLine != Pos.line)
1336 continue;
1337 HoverCountMetric.record(1, "include");
1338 HoverInfo HI;
1339 HI.Name = std::string(llvm::sys::path::filename(Inc.Resolved));
1340 HI.Definition =
1341 URIForFile::canonicalize(Inc.Resolved, AST.tuPath()).file().str();
1342 HI.DefinitionLanguage = "";
1343 HI.Kind = index::SymbolKind::IncludeDirective;
1344 maybeAddUsedSymbols(AST, HI, Inc);
1345 return HI;
1346 }
1347
1348 // To be used as a backup for highlighting the selected token, we use back as
1349 // it aligns better with biases elsewhere (editors tend to send the position
1350 // for the left of the hovered token).
1351 CharSourceRange HighlightRange =
1352 TokensTouchingCursor.back().range(SM).toCharRange(SM);
1353 std::optional<HoverInfo> HI;
1354 // Macros and deducedtype only works on identifiers and auto/decltype keywords
1355 // respectively. Therefore they are only trggered on whichever works for them,
1356 // similar to SelectionTree::create().
1357 for (const auto &Tok : TokensTouchingCursor) {
1358 if (Tok.kind() == tok::identifier) {
1359 // Prefer the identifier token as a fallback highlighting range.
1360 HighlightRange = Tok.range(SM).toCharRange(SM);
1361 if (auto M = locateMacroAt(Tok, AST.getPreprocessor())) {
1362 HoverCountMetric.record(1, "macro");
1363 HI = getHoverContents(*M, Tok, AST);
1364 if (auto DefLoc = M->Info->getDefinitionLoc(); DefLoc.isValid()) {
1365 include_cleaner::Macro IncludeCleanerMacro{
1366 AST.getPreprocessor().getIdentifierInfo(Tok.text(SM)), DefLoc};
1367 maybeAddSymbolProviders(AST, *HI,
1368 include_cleaner::Symbol{IncludeCleanerMacro});
1369 }
1370 break;
1371 }
1372 } else if (Tok.kind() == tok::kw_auto || Tok.kind() == tok::kw_decltype) {
1373 HoverCountMetric.record(1, "keyword");
1374 if (auto Deduced =
1375 getDeducedType(AST.getASTContext(), AST.getHeuristicResolver(),
1376 Tok.location())) {
1377 HI = getDeducedTypeHoverContents(*Deduced, Tok, AST.getASTContext(), PP,
1378 Index);
1379 HighlightRange = Tok.range(SM).toCharRange(SM);
1380 break;
1381 }
1382
1383 // If we can't find interesting hover information for this
1384 // auto/decltype keyword, return nothing to avoid showing
1385 // irrelevant or incorrect informations.
1386 return std::nullopt;
1387 }
1388 }
1389
1390 // If it wasn't auto/decltype or macro, look for decls and expressions.
1391 if (!HI) {
1392 auto Offset = SM.getFileOffset(*CurLoc);
1393 // Editors send the position on the left of the hovered character.
1394 // So our selection tree should be biased right. (Tested with VSCode).
1395 SelectionTree ST =
1396 SelectionTree::createRight(AST.getASTContext(), TB, Offset, Offset);
1397 if (const SelectionTree::Node *N = ST.commonAncestor()) {
1398 // FIXME: Fill in HighlightRange with range coming from N->ASTNode.
1399 auto Decls = explicitReferenceTargets(N->ASTNode, DeclRelation::Alias,
1400 AST.getHeuristicResolver());
1401 if (const auto *DeclToUse = pickDeclToUse(Decls)) {
1402 HoverCountMetric.record(1, "decl");
1403 HI = getHoverContents(DeclToUse, PP, Index, TB);
1404 // Layout info only shown when hovering on the field/class itself.
1405 if (DeclToUse == N->ASTNode.get<Decl>())
1406 addLayoutInfo(*DeclToUse, *HI);
1407 // Look for a close enclosing expression to show the value of.
1408 if (!HI->Value)
1409 HI->Value = printExprValue(N, AST.getASTContext()).PrintedValue;
1410 maybeAddCalleeArgInfo(N, *HI, PP);
1411
1412 if (!isa<NamespaceDecl>(DeclToUse))
1413 maybeAddSymbolProviders(AST, *HI,
1414 include_cleaner::Symbol{*DeclToUse});
1415 } else if (const Expr *E = N->ASTNode.get<Expr>()) {
1416 HoverCountMetric.record(1, "expr");
1417 HI = getHoverContents(N, E, AST, PP, Index);
1418 } else if (const Attr *A = N->ASTNode.get<Attr>()) {
1419 HoverCountMetric.record(1, "attribute");
1420 HI = getHoverContents(A, AST);
1421 }
1422 // FIXME: support hovers for other nodes?
1423 // - built-in types
1424 }
1425 }
1426
1427 if (!HI)
1428 return std::nullopt;
1429
1430 // Reformat Definition
1431 if (!HI->Definition.empty()) {
1432 auto Replacements = format::reformat(
1433 Style, HI->Definition, tooling::Range(0, HI->Definition.size()));
1434 if (auto Formatted =
1435 tooling::applyAllReplacements(HI->Definition, Replacements))
1436 HI->Definition = *Formatted;
1437 }
1438
1439 HI->DefinitionLanguage = getMarkdownLanguage(AST.getASTContext());
1440 HI->SymRange = halfOpenToRange(SM, HighlightRange);
1441
1442 return HI;
1443}
1444
1445// Sizes (and padding) are shown in bytes if possible, otherwise in bits.
1446static std::string formatSize(uint64_t SizeInBits) {
1447 uint64_t Value = SizeInBits % 8 == 0 ? SizeInBits / 8 : SizeInBits;
1448 const char *Unit = Value != 0 && Value == SizeInBits ? "bit" : "byte";
1449 return llvm::formatv("{0} {1}{2}", Value, Unit, Value == 1 ? "" : "s").str();
1450}
1451
1452// Offsets are shown in bytes + bits, so offsets of different fields
1453// can always be easily compared.
1454static std::string formatOffset(uint64_t OffsetInBits) {
1455 const auto Bytes = OffsetInBits / 8;
1456 const auto Bits = OffsetInBits % 8;
1457 auto Offset = formatSize(Bytes * 8);
1458 if (Bits != 0)
1459 Offset += " and " + formatSize(Bits);
1460 return Offset;
1461}
1462
1463void HoverInfo::calleeArgInfoToMarkupParagraph(markup::Paragraph &P) const {
1464 assert(CallPassType);
1465 std::string Buffer;
1466 llvm::raw_string_ostream OS(Buffer);
1467 OS << "Passed ";
1469 OS << "by ";
1471 OS << "const ";
1472 OS << "reference ";
1473 }
1474 if (CalleeArgInfo->Name)
1475 OS << "as " << CalleeArgInfo->Name;
1476 else if (CallPassType->PassBy == HoverInfo::PassType::Value)
1477 OS << "by value";
1478 if (CallPassType->Converted && CalleeArgInfo->Type)
1479 OS << " (converted to " << CalleeArgInfo->Type->Type << ")";
1480 P.appendText(OS.str());
1481}
1482
1483void HoverInfo::usedSymbolNamesToMarkup(markup::Document &Output) const {
1484 markup::Paragraph &P = Output.addParagraph();
1485 P.appendText("provides ");
1486
1487 const std::vector<std::string>::size_type SymbolNamesLimit = 5;
1488 auto Front = llvm::ArrayRef(UsedSymbolNames).take_front(SymbolNamesLimit);
1489
1490 llvm::interleave(
1491 Front, [&](llvm::StringRef Sym) { P.appendCode(Sym); },
1492 [&] { P.appendText(", "); });
1493 if (UsedSymbolNames.size() > Front.size()) {
1494 P.appendText(" and ");
1495 P.appendText(std::to_string(UsedSymbolNames.size() - Front.size()));
1496 P.appendText(" more");
1497 }
1498}
1499
1500void HoverInfo::providerToMarkupParagraph(markup::Document &Output) const {
1501 markup::Paragraph &DI = Output.addParagraph();
1502 DI.appendText("provided by");
1503 DI.appendSpace();
1504 DI.appendCode(Provider);
1505}
1506
1507void HoverInfo::definitionScopeToMarkup(markup::Document &Output) const {
1508 std::string Buffer;
1509
1510 // Append scope comment, dropping trailing "::".
1511 // Note that we don't print anything for global namespace, to not annoy
1512 // non-c++ projects or projects that are not making use of namespaces.
1513 if (!LocalScope.empty()) {
1514 // Container name, e.g. class, method, function.
1515 // We might want to propagate some info about container type to print
1516 // function foo, class X, method X::bar, etc.
1517 Buffer += "// In " + llvm::StringRef(LocalScope).rtrim(':').str() + '\n';
1518 } else if (NamespaceScope && !NamespaceScope->empty()) {
1519 Buffer += "// In namespace " +
1520 llvm::StringRef(*NamespaceScope).rtrim(':').str() + '\n';
1521 }
1522
1523 if (!AccessSpecifier.empty()) {
1524 Buffer += AccessSpecifier + ": ";
1525 }
1526
1527 Buffer += Definition;
1528
1529 Output.addCodeBlock(Buffer, DefinitionLanguage);
1530}
1531
1532void HoverInfo::valueToMarkupParagraph(markup::Paragraph &P) const {
1533 P.appendText("Value = ");
1534 P.appendCode(*Value);
1535}
1536
1537void HoverInfo::offsetToMarkupParagraph(markup::Paragraph &P) const {
1538 P.appendText("Offset: " + formatOffset(*Offset));
1539}
1540
1541void HoverInfo::sizeToMarkupParagraph(markup::Paragraph &P) const {
1542 P.appendText("Size: " + formatSize(*Size));
1543 if (Padding && *Padding != 0) {
1544 P.appendText(llvm::formatv(" (+{0} padding)", formatSize(*Padding)).str());
1545 }
1546 if (Align)
1547 P.appendText(", alignment " + formatSize(*Align));
1548}
1549
1550markup::Document HoverInfo::presentDoxygen() const {
1551
1552 markup::Document Output;
1553 // Header contains a text of the form:
1554 // variable `var`
1555 //
1556 // class `X`
1557 //
1558 // function `foo`
1559 //
1560 // expression
1561 //
1562 // Note that we are making use of a level-3 heading because VSCode renders
1563 // level 1 and 2 headers in a huge font, see
1564 // https://github.com/microsoft/vscode/issues/88417 for details.
1565 markup::Paragraph &Header = Output.addHeading(3);
1566 if (Kind != index::SymbolKind::Unknown &&
1567 Kind != index::SymbolKind::IncludeDirective)
1568 Header.appendText(index::getSymbolKindString(Kind)).appendSpace();
1569 assert(!Name.empty() && "hover triggered on a nameless symbol");
1570
1571 if (Kind == index::SymbolKind::IncludeDirective) {
1572 Header.appendCode(Name);
1573
1574 if (!Definition.empty())
1575 Output.addParagraph().appendCode(Definition);
1576
1577 if (!UsedSymbolNames.empty()) {
1578 Output.addRuler();
1579 usedSymbolNamesToMarkup(Output);
1580 }
1581
1582 return Output;
1583 }
1584
1585 if (!Definition.empty()) {
1586 Output.addRuler();
1587 definitionScopeToMarkup(Output);
1588 } else {
1589 Header.appendCode(Name);
1590 }
1591
1592 if (!Provider.empty()) {
1593 providerToMarkupParagraph(Output);
1594 }
1595
1596 // Put a linebreak after header to increase readability.
1597 Output.addRuler();
1598
1599 SymbolDocCommentVisitor SymbolDoc(Documentation, CommentOpts);
1600
1601 if (SymbolDoc.hasBriefCommand()) {
1602 if (Kind != index::SymbolKind::Parameter &&
1603 Kind != index::SymbolKind::TemplateTypeParm)
1604 // Only add a "Brief" heading if we are not documenting a parameter.
1605 // Parameters only have a brief section and adding the brief header would
1606 // be redundant.
1607 Output.addHeading(3).appendText("Brief");
1608 SymbolDoc.briefToMarkup(Output.addParagraph());
1609 Output.addRuler();
1610 }
1611
1612 // For functions we display signature in a list form, e.g.:
1613 // Template Parameters:
1614 // - `typename T` - description
1615 // Parameters:
1616 // - `bool param1` - description
1617 // - `int param2 = 5` - description
1618 // Returns
1619 // `type` - description
1620 if (TemplateParameters && !TemplateParameters->empty()) {
1621 Output.addHeading(3).appendText("Template Parameters");
1622 markup::BulletList &L = Output.addBulletList();
1623 for (const auto &Param : *TemplateParameters) {
1624 markup::Paragraph &P = L.addItem().addParagraph();
1625 P.appendCode(llvm::to_string(Param));
1626 if (SymbolDoc.isTemplateTypeParmDocumented(llvm::to_string(Param.Name))) {
1627 P.appendText(" - ");
1628 SymbolDoc.templateTypeParmDocToMarkup(llvm::to_string(Param.Name), P);
1629 }
1630 }
1631 Output.addRuler();
1632 }
1633
1634 if (Parameters && !Parameters->empty()) {
1635 Output.addHeading(3).appendText("Parameters");
1636 markup::BulletList &L = Output.addBulletList();
1637 for (const auto &Param : *Parameters) {
1638 markup::Paragraph &P = L.addItem().addParagraph();
1639 P.appendCode(llvm::to_string(Param));
1640
1641 if (SymbolDoc.isParameterDocumented(llvm::to_string(Param.Name))) {
1642 P.appendText(" - ");
1643 SymbolDoc.parameterDocToMarkup(llvm::to_string(Param.Name), P);
1644 }
1645 }
1646 Output.addRuler();
1647 }
1648
1649 // Print Types on their own lines to reduce chances of getting line-wrapped by
1650 // editor, as they might be long.
1651 if (ReturnType &&
1652 ((ReturnType->Type != "void" && !ReturnType->AKA.has_value()) ||
1653 (ReturnType->AKA.has_value() && ReturnType->AKA != "void"))) {
1654 Output.addHeading(3).appendText("Returns");
1655 markup::Paragraph &P = Output.addParagraph();
1656 P.appendCode(llvm::to_string(*ReturnType));
1657
1658 if (SymbolDoc.hasReturnCommand()) {
1659 P.appendText(" - ");
1660 SymbolDoc.returnToMarkup(P);
1661 }
1662
1663 SymbolDoc.retvalsToMarkup(Output);
1664 Output.addRuler();
1665 }
1666
1667 if (SymbolDoc.hasDetailedDoc()) {
1668 Output.addHeading(3).appendText("Details");
1669 SymbolDoc.detailedDocToMarkup(Output);
1670 }
1671
1672 Output.addRuler();
1673
1674 // Don't print Type after Parameters or ReturnType as this will just duplicate
1675 // the information
1676 if (Type && !ReturnType && !Parameters)
1677 Output.addParagraph().appendText("Type: ").appendCode(
1678 llvm::to_string(*Type));
1679
1680 if (Value) {
1681 valueToMarkupParagraph(Output.addParagraph());
1682 }
1683
1684 if (Offset)
1685 offsetToMarkupParagraph(Output.addParagraph());
1686 if (Size) {
1687 sizeToMarkupParagraph(Output.addParagraph());
1688 }
1689
1690 if (CalleeArgInfo) {
1691 calleeArgInfoToMarkupParagraph(Output.addParagraph());
1692 }
1693
1694 if (!UsedSymbolNames.empty()) {
1695 Output.addRuler();
1696 usedSymbolNamesToMarkup(Output);
1697 }
1698
1699 return Output;
1700}
1701
1702markup::Document HoverInfo::presentDefault() const {
1703 markup::Document Output;
1704 // Header contains a text of the form:
1705 // variable `var`
1706 //
1707 // class `X`
1708 //
1709 // function `foo`
1710 //
1711 // expression
1712 //
1713 // Note that we are making use of a level-3 heading because VSCode renders
1714 // level 1 and 2 headers in a huge font, see
1715 // https://github.com/microsoft/vscode/issues/88417 for details.
1716 markup::Paragraph &Header = Output.addHeading(3);
1717 if (Kind != index::SymbolKind::Unknown &&
1718 Kind != index::SymbolKind::IncludeDirective)
1719 Header.appendText(index::getSymbolKindString(Kind)).appendSpace();
1720 assert(!Name.empty() && "hover triggered on a nameless symbol");
1721 Header.appendCode(Name);
1722
1723 if (!Provider.empty()) {
1724 providerToMarkupParagraph(Output);
1725 }
1726
1727 // Put a linebreak after header to increase readability.
1728 Output.addRuler();
1729 // Print Types on their own lines to reduce chances of getting line-wrapped by
1730 // editor, as they might be long.
1731 if (ReturnType) {
1732 // For functions we display signature in a list form, e.g.:
1733 // → `x`
1734 // Parameters:
1735 // - `bool param1`
1736 // - `int param2 = 5`
1737 Output.addParagraph().appendText("→ ").appendCode(
1738 llvm::to_string(*ReturnType));
1739 }
1740
1741 if (Parameters && !Parameters->empty()) {
1742 Output.addParagraph().appendText("Parameters:");
1743 markup::BulletList &L = Output.addBulletList();
1744 for (const auto &Param : *Parameters)
1745 L.addItem().addParagraph().appendCode(llvm::to_string(Param));
1746 }
1747
1748 // Don't print Type after Parameters or ReturnType as this will just duplicate
1749 // the information
1750 if (Type && !ReturnType && !Parameters)
1751 Output.addParagraph().appendText("Type: ").appendCode(
1752 llvm::to_string(*Type));
1753
1754 if (Value) {
1755 valueToMarkupParagraph(Output.addParagraph());
1756 }
1757
1758 if (Offset)
1759 offsetToMarkupParagraph(Output.addParagraph());
1760 if (Size) {
1761 sizeToMarkupParagraph(Output.addParagraph());
1762 }
1763
1764 if (CalleeArgInfo) {
1765 calleeArgInfoToMarkupParagraph(Output.addParagraph());
1766 }
1767
1768 if (!Documentation.empty())
1770
1771 if (!Definition.empty()) {
1772 Output.addRuler();
1773 definitionScopeToMarkup(Output);
1774 }
1775
1776 if (!UsedSymbolNames.empty()) {
1777 Output.addRuler();
1778 usedSymbolNamesToMarkup(Output);
1779 }
1780
1781 return Output;
1782}
1783
1785 if (Kind == MarkupKind::Markdown) {
1786 const Config &Cfg = Config::current();
1787 if (Cfg.Documentation.CommentFormat ==
1789 return presentDefault().asMarkdown();
1791 return presentDoxygen().asMarkdown();
1792 if (Cfg.Documentation.CommentFormat ==
1794 // If the user prefers plain text, we use the present() method to generate
1795 // the plain text output.
1796 return presentDefault().asEscapedMarkdown();
1797 }
1798
1799 return presentDefault().asPlainText();
1800}
1801
1802// If the backtick at `Offset` starts a probable quoted range, return the range
1803// (including the quotes).
1804std::optional<llvm::StringRef> getBacktickQuoteRange(llvm::StringRef Line,
1805 unsigned Offset) {
1806 assert(Line[Offset] == '`');
1807
1808 // The open-quote is usually preceded by whitespace.
1809 llvm::StringRef Prefix = Line.substr(0, Offset);
1810 constexpr llvm::StringLiteral BeforeStartChars = " \t(=";
1811 if (!Prefix.empty() && !BeforeStartChars.contains(Prefix.back()))
1812 return std::nullopt;
1813
1814 // The quoted string must be nonempty and usually has no leading/trailing ws.
1815 auto Next = Line.find_first_of("`\n", Offset + 1);
1816 if (Next == llvm::StringRef::npos)
1817 return std::nullopt;
1818
1819 // There should be no newline in the quoted string.
1820 if (Line[Next] == '\n')
1821 return std::nullopt;
1822
1823 llvm::StringRef Contents = Line.slice(Offset + 1, Next);
1824 if (Contents.empty() || isWhitespace(Contents.front()) ||
1825 isWhitespace(Contents.back()))
1826 return std::nullopt;
1827
1828 // The close-quote is usually followed by whitespace or punctuation.
1829 llvm::StringRef Suffix = Line.substr(Next + 1);
1830 constexpr llvm::StringLiteral AfterEndChars = " \t)=.,;:";
1831 if (!Suffix.empty() && !AfterEndChars.contains(Suffix.front()))
1832 return std::nullopt;
1833
1834 return Line.slice(Offset, Next + 1);
1835}
1836
1838 // Probably this is appendText(Line), but scan for something interesting.
1839 for (unsigned I = 0; I < Text.size(); ++I) {
1840 switch (Text[I]) {
1841 case '`':
1842 if (auto Range = getBacktickQuoteRange(Text, I)) {
1843 Out.appendText(Text.substr(0, I));
1844 Out.appendCode(Range->trim("`"), /*Preserve=*/true);
1845 return parseDocumentationParagraph(Text.substr(I + Range->size()), Out);
1846 }
1847 break;
1848 }
1849 }
1850 Out.appendText(Text);
1851}
1852
1853void parseDocumentation(llvm::StringRef Input, markup::Document &Output) {
1854 // A documentation string is treated as a sequence of paragraphs,
1855 // where the paragraphs are separated by at least one empty line
1856 // (meaning 2 consecutive newline characters).
1857 // Possible leading empty lines (introduced by an odd number > 1 of
1858 // empty lines between 2 paragraphs) will be removed later in the Markup
1859 // renderer.
1860 llvm::StringRef Paragraph, Rest;
1861 for (std::tie(Paragraph, Rest) = Input.split("\n\n");
1862 !(Paragraph.empty() && Rest.empty());
1863 std::tie(Paragraph, Rest) = Rest.split("\n\n")) {
1864
1865 // The Paragraph will be empty if there is an even number of newline
1866 // characters between two paragraphs, so we skip it.
1867 if (!Paragraph.empty())
1868 parseDocumentationParagraph(Paragraph, Output.addParagraph());
1869 }
1870}
1871llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
1872 const HoverInfo::PrintedType &T) {
1873 OS << T.Type;
1874 if (T.AKA)
1875 OS << " (aka " << *T.AKA << ")";
1876 return OS;
1877}
1878
1879llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
1880 const HoverInfo::Param &P) {
1881 if (P.Type)
1882 OS << P.Type->Type;
1883 if (P.Name)
1884 OS << " " << *P.Name;
1885 if (P.Default)
1886 OS << " = " << *P.Default;
1887 if (P.Type && P.Type->AKA)
1888 OS << " (aka " << *P.Type->AKA << ")";
1889 return OS;
1890}
1891
1892} // namespace clangd
1893} // 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:1804
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:1837
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:1314
static std::string formatOffset(uint64_t OffsetInBits)
Definition Hover.cpp:1454
static std::string formatSize(uint64_t SizeInBits)
Definition Hover.cpp:1446
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:1853
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:1784
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