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