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