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