150
|
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"
|
|
12 #include "CodeCompletionStrings.h"
|
|
13 #include "FindTarget.h"
|
|
14 #include "ParsedAST.h"
|
|
15 #include "Selection.h"
|
|
16 #include "SourceCode.h"
|
|
17 #include "index/SymbolCollector.h"
|
173
|
18 #include "support/Logger.h"
|
|
19 #include "support/Markup.h"
|
150
|
20 #include "clang/AST/ASTContext.h"
|
|
21 #include "clang/AST/ASTTypeTraits.h"
|
|
22 #include "clang/AST/Decl.h"
|
|
23 #include "clang/AST/DeclBase.h"
|
173
|
24 #include "clang/AST/DeclCXX.h"
|
150
|
25 #include "clang/AST/DeclTemplate.h"
|
|
26 #include "clang/AST/Expr.h"
|
|
27 #include "clang/AST/ExprCXX.h"
|
173
|
28 #include "clang/AST/OperationKinds.h"
|
150
|
29 #include "clang/AST/PrettyPrinter.h"
|
|
30 #include "clang/AST/Type.h"
|
173
|
31 #include "clang/Basic/SourceLocation.h"
|
150
|
32 #include "clang/Basic/Specifiers.h"
|
173
|
33 #include "clang/Basic/TokenKinds.h"
|
150
|
34 #include "clang/Index/IndexSymbol.h"
|
173
|
35 #include "clang/Tooling/Syntax/Tokens.h"
|
150
|
36 #include "llvm/ADT/None.h"
|
|
37 #include "llvm/ADT/Optional.h"
|
|
38 #include "llvm/ADT/STLExtras.h"
|
|
39 #include "llvm/ADT/SmallVector.h"
|
|
40 #include "llvm/ADT/StringExtras.h"
|
|
41 #include "llvm/ADT/StringRef.h"
|
|
42 #include "llvm/Support/Casting.h"
|
|
43 #include "llvm/Support/ErrorHandling.h"
|
|
44 #include "llvm/Support/raw_ostream.h"
|
|
45 #include <string>
|
|
46
|
|
47 namespace clang {
|
|
48 namespace clangd {
|
|
49 namespace {
|
|
50
|
|
51 PrintingPolicy printingPolicyForDecls(PrintingPolicy Base) {
|
|
52 PrintingPolicy Policy(Base);
|
|
53
|
|
54 Policy.AnonymousTagLocations = false;
|
|
55 Policy.TerseOutput = true;
|
|
56 Policy.PolishForDeclaration = true;
|
|
57 Policy.ConstantsAsWritten = true;
|
|
58 Policy.SuppressTagKeyword = false;
|
|
59
|
|
60 return Policy;
|
|
61 }
|
|
62
|
|
63 /// Given a declaration \p D, return a human-readable string representing the
|
|
64 /// local scope in which it is declared, i.e. class(es) and method name. Returns
|
|
65 /// an empty string if it is not local.
|
|
66 std::string getLocalScope(const Decl *D) {
|
|
67 std::vector<std::string> Scopes;
|
|
68 const DeclContext *DC = D->getDeclContext();
|
|
69 auto GetName = [](const TypeDecl *D) {
|
|
70 if (!D->getDeclName().isEmpty()) {
|
|
71 PrintingPolicy Policy = D->getASTContext().getPrintingPolicy();
|
|
72 Policy.SuppressScope = true;
|
|
73 return declaredType(D).getAsString(Policy);
|
|
74 }
|
|
75 if (auto RD = dyn_cast<RecordDecl>(D))
|
|
76 return ("(anonymous " + RD->getKindName() + ")").str();
|
|
77 return std::string("");
|
|
78 };
|
|
79 while (DC) {
|
|
80 if (const TypeDecl *TD = dyn_cast<TypeDecl>(DC))
|
|
81 Scopes.push_back(GetName(TD));
|
|
82 else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
|
|
83 Scopes.push_back(FD->getNameAsString());
|
|
84 DC = DC->getParent();
|
|
85 }
|
|
86
|
|
87 return llvm::join(llvm::reverse(Scopes), "::");
|
|
88 }
|
|
89
|
|
90 /// Returns the human-readable representation for namespace containing the
|
|
91 /// declaration \p D. Returns empty if it is contained global namespace.
|
|
92 std::string getNamespaceScope(const Decl *D) {
|
|
93 const DeclContext *DC = D->getDeclContext();
|
|
94
|
|
95 if (const TagDecl *TD = dyn_cast<TagDecl>(DC))
|
|
96 return getNamespaceScope(TD);
|
|
97 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
|
|
98 return getNamespaceScope(FD);
|
|
99 if (const NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(DC)) {
|
|
100 // Skip inline/anon namespaces.
|
|
101 if (NSD->isInline() || NSD->isAnonymousNamespace())
|
|
102 return getNamespaceScope(NSD);
|
|
103 }
|
|
104 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
|
|
105 return printQualifiedName(*ND);
|
|
106
|
|
107 return "";
|
|
108 }
|
|
109
|
|
110 std::string printDefinition(const Decl *D) {
|
|
111 std::string Definition;
|
|
112 llvm::raw_string_ostream OS(Definition);
|
|
113 PrintingPolicy Policy =
|
|
114 printingPolicyForDecls(D->getASTContext().getPrintingPolicy());
|
|
115 Policy.IncludeTagDefinition = false;
|
|
116 Policy.SuppressTemplateArgsInCXXConstructors = true;
|
|
117 Policy.SuppressTagKeyword = true;
|
|
118 D->print(OS, Policy);
|
|
119 OS.flush();
|
|
120 return Definition;
|
|
121 }
|
|
122
|
|
123 std::string printType(QualType QT, const PrintingPolicy &Policy) {
|
|
124 // TypePrinter doesn't resolve decltypes, so resolve them here.
|
|
125 // FIXME: This doesn't handle composite types that contain a decltype in them.
|
|
126 // We should rather have a printing policy for that.
|
|
127 while (const auto *DT = QT->getAs<DecltypeType>())
|
|
128 QT = DT->getUnderlyingType();
|
|
129 return QT.getAsString(Policy);
|
|
130 }
|
|
131
|
173
|
132 std::string printType(const TemplateTypeParmDecl *TTP) {
|
|
133 std::string Res = TTP->wasDeclaredWithTypename() ? "typename" : "class";
|
|
134 if (TTP->isParameterPack())
|
|
135 Res += "...";
|
|
136 return Res;
|
|
137 }
|
|
138
|
|
139 std::string printType(const NonTypeTemplateParmDecl *NTTP,
|
|
140 const PrintingPolicy &PP) {
|
|
141 std::string Res = printType(NTTP->getType(), PP);
|
|
142 if (NTTP->isParameterPack())
|
|
143 Res += "...";
|
|
144 return Res;
|
|
145 }
|
|
146
|
|
147 std::string printType(const TemplateTemplateParmDecl *TTP,
|
|
148 const PrintingPolicy &PP) {
|
|
149 std::string Res;
|
|
150 llvm::raw_string_ostream OS(Res);
|
|
151 OS << "template <";
|
|
152 llvm::StringRef Sep = "";
|
|
153 for (const Decl *Param : *TTP->getTemplateParameters()) {
|
|
154 OS << Sep;
|
|
155 Sep = ", ";
|
|
156 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
|
|
157 OS << printType(TTP);
|
|
158 else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
|
|
159 OS << printType(NTTP, PP);
|
|
160 else if (const auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param))
|
|
161 OS << printType(TTPD, PP);
|
|
162 }
|
|
163 // FIXME: TemplateTemplateParameter doesn't store the info on whether this
|
|
164 // param was a "typename" or "class".
|
|
165 OS << "> class";
|
|
166 return OS.str();
|
|
167 }
|
|
168
|
150
|
169 std::vector<HoverInfo::Param>
|
|
170 fetchTemplateParameters(const TemplateParameterList *Params,
|
|
171 const PrintingPolicy &PP) {
|
|
172 assert(Params);
|
|
173 std::vector<HoverInfo::Param> TempParameters;
|
|
174
|
|
175 for (const Decl *Param : *Params) {
|
|
176 HoverInfo::Param P;
|
|
177 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
|
173
|
178 P.Type = printType(TTP);
|
150
|
179
|
|
180 if (!TTP->getName().empty())
|
|
181 P.Name = TTP->getNameAsString();
|
173
|
182
|
150
|
183 if (TTP->hasDefaultArgument())
|
|
184 P.Default = TTP->getDefaultArgument().getAsString(PP);
|
|
185 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
|
173
|
186 P.Type = printType(NTTP, PP);
|
|
187
|
150
|
188 if (IdentifierInfo *II = NTTP->getIdentifier())
|
|
189 P.Name = II->getName().str();
|
|
190
|
|
191 if (NTTP->hasDefaultArgument()) {
|
|
192 P.Default.emplace();
|
|
193 llvm::raw_string_ostream Out(*P.Default);
|
|
194 NTTP->getDefaultArgument()->printPretty(Out, nullptr, PP);
|
|
195 }
|
|
196 } else if (const auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param)) {
|
173
|
197 P.Type = printType(TTPD, PP);
|
|
198
|
150
|
199 if (!TTPD->getName().empty())
|
|
200 P.Name = TTPD->getNameAsString();
|
173
|
201
|
150
|
202 if (TTPD->hasDefaultArgument()) {
|
|
203 P.Default.emplace();
|
|
204 llvm::raw_string_ostream Out(*P.Default);
|
|
205 TTPD->getDefaultArgument().getArgument().print(PP, Out);
|
|
206 }
|
|
207 }
|
|
208 TempParameters.push_back(std::move(P));
|
|
209 }
|
|
210
|
|
211 return TempParameters;
|
|
212 }
|
|
213
|
|
214 const FunctionDecl *getUnderlyingFunction(const Decl *D) {
|
|
215 // Extract lambda from variables.
|
|
216 if (const VarDecl *VD = llvm::dyn_cast<VarDecl>(D)) {
|
|
217 auto QT = VD->getType();
|
|
218 if (!QT.isNull()) {
|
|
219 while (!QT->getPointeeType().isNull())
|
|
220 QT = QT->getPointeeType();
|
|
221
|
|
222 if (const auto *CD = QT->getAsCXXRecordDecl())
|
|
223 return CD->getLambdaCallOperator();
|
|
224 }
|
|
225 }
|
|
226
|
|
227 // Non-lambda functions.
|
|
228 return D->getAsFunction();
|
|
229 }
|
|
230
|
|
231 // Returns the decl that should be used for querying comments, either from index
|
|
232 // or AST.
|
|
233 const NamedDecl *getDeclForComment(const NamedDecl *D) {
|
|
234 if (const auto *TSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(D)) {
|
|
235 // Template may not be instantiated e.g. if the type didn't need to be
|
|
236 // complete; fallback to primary template.
|
|
237 if (TSD->getTemplateSpecializationKind() == TSK_Undeclared)
|
|
238 return TSD->getSpecializedTemplate();
|
|
239 if (const auto *TIP = TSD->getTemplateInstantiationPattern())
|
|
240 return TIP;
|
|
241 }
|
|
242 if (const auto *TSD = llvm::dyn_cast<VarTemplateSpecializationDecl>(D)) {
|
|
243 if (TSD->getTemplateSpecializationKind() == TSK_Undeclared)
|
|
244 return TSD->getSpecializedTemplate();
|
|
245 if (const auto *TIP = TSD->getTemplateInstantiationPattern())
|
|
246 return TIP;
|
|
247 }
|
|
248 if (const auto *FD = D->getAsFunction())
|
|
249 if (const auto *TIP = FD->getTemplateInstantiationPattern())
|
|
250 return TIP;
|
|
251 return D;
|
|
252 }
|
|
253
|
|
254 // Look up information about D from the index, and add it to Hover.
|
|
255 void enhanceFromIndex(HoverInfo &Hover, const NamedDecl &ND,
|
|
256 const SymbolIndex *Index) {
|
|
257 assert(&ND == getDeclForComment(&ND));
|
|
258 // We only add documentation, so don't bother if we already have some.
|
|
259 if (!Hover.Documentation.empty() || !Index)
|
|
260 return;
|
|
261
|
|
262 // Skip querying for non-indexable symbols, there's no point.
|
|
263 // We're searching for symbols that might be indexed outside this main file.
|
|
264 if (!SymbolCollector::shouldCollectSymbol(ND, ND.getASTContext(),
|
|
265 SymbolCollector::Options(),
|
|
266 /*IsMainFileOnly=*/false))
|
|
267 return;
|
|
268 auto ID = getSymbolID(&ND);
|
|
269 if (!ID)
|
|
270 return;
|
|
271 LookupRequest Req;
|
|
272 Req.IDs.insert(*ID);
|
|
273 Index->lookup(Req, [&](const Symbol &S) {
|
|
274 Hover.Documentation = std::string(S.Documentation);
|
|
275 });
|
|
276 }
|
|
277
|
|
278 // Default argument might exist but be unavailable, in the case of unparsed
|
|
279 // arguments for example. This function returns the default argument if it is
|
|
280 // available.
|
|
281 const Expr *getDefaultArg(const ParmVarDecl *PVD) {
|
173
|
282 // Default argument can be unparsed or uninstantiated. For the former we
|
150
|
283 // can't do much, as token information is only stored in Sema and not
|
|
284 // attached to the AST node. For the latter though, it is safe to proceed as
|
|
285 // the expression is still valid.
|
|
286 if (!PVD->hasDefaultArg() || PVD->hasUnparsedDefaultArg())
|
|
287 return nullptr;
|
|
288 return PVD->hasUninstantiatedDefaultArg() ? PVD->getUninstantiatedDefaultArg()
|
|
289 : PVD->getDefaultArg();
|
|
290 }
|
|
291
|
|
292 // Populates Type, ReturnType, and Parameters for function-like decls.
|
|
293 void fillFunctionTypeAndParams(HoverInfo &HI, const Decl *D,
|
|
294 const FunctionDecl *FD,
|
|
295 const PrintingPolicy &Policy) {
|
|
296 HI.Parameters.emplace();
|
|
297 for (const ParmVarDecl *PVD : FD->parameters()) {
|
|
298 HI.Parameters->emplace_back();
|
|
299 auto &P = HI.Parameters->back();
|
|
300 if (!PVD->getType().isNull()) {
|
|
301 P.Type = printType(PVD->getType(), Policy);
|
|
302 } else {
|
|
303 std::string Param;
|
|
304 llvm::raw_string_ostream OS(Param);
|
|
305 PVD->dump(OS);
|
|
306 OS.flush();
|
|
307 elog("Got param with null type: {0}", Param);
|
|
308 }
|
|
309 if (!PVD->getName().empty())
|
|
310 P.Name = PVD->getNameAsString();
|
|
311 if (const Expr *DefArg = getDefaultArg(PVD)) {
|
|
312 P.Default.emplace();
|
|
313 llvm::raw_string_ostream Out(*P.Default);
|
|
314 DefArg->printPretty(Out, nullptr, Policy);
|
|
315 }
|
|
316 }
|
|
317
|
|
318 // We don't want any type info, if name already contains it. This is true for
|
|
319 // constructors/destructors and conversion operators.
|
|
320 const auto NK = FD->getDeclName().getNameKind();
|
|
321 if (NK == DeclarationName::CXXConstructorName ||
|
|
322 NK == DeclarationName::CXXDestructorName ||
|
|
323 NK == DeclarationName::CXXConversionFunctionName)
|
|
324 return;
|
|
325
|
|
326 HI.ReturnType = printType(FD->getReturnType(), Policy);
|
|
327 QualType QT = FD->getType();
|
|
328 if (const VarDecl *VD = llvm::dyn_cast<VarDecl>(D)) // Lambdas
|
|
329 QT = VD->getType().getDesugaredType(D->getASTContext());
|
|
330 HI.Type = printType(QT, Policy);
|
|
331 // FIXME: handle variadics.
|
|
332 }
|
|
333
|
|
334 llvm::Optional<std::string> printExprValue(const Expr *E,
|
|
335 const ASTContext &Ctx) {
|
|
336 Expr::EvalResult Constant;
|
|
337 // Evaluating [[foo]]() as "&foo" isn't useful, and prevents us walking up
|
|
338 // to the enclosing call.
|
|
339 QualType T = E->getType();
|
|
340 if (T.isNull() || T->isFunctionType() || T->isFunctionPointerType() ||
|
|
341 T->isFunctionReferenceType())
|
|
342 return llvm::None;
|
|
343 // Attempt to evaluate. If expr is dependent, evaluation crashes!
|
|
344 if (E->isValueDependent() || !E->EvaluateAsRValue(Constant, Ctx))
|
|
345 return llvm::None;
|
|
346
|
|
347 // Show enums symbolically, not numerically like APValue::printPretty().
|
|
348 if (T->isEnumeralType() && Constant.Val.getInt().getMinSignedBits() <= 64) {
|
|
349 // Compare to int64_t to avoid bit-width match requirements.
|
|
350 int64_t Val = Constant.Val.getInt().getExtValue();
|
|
351 for (const EnumConstantDecl *ECD :
|
|
352 T->castAs<EnumType>()->getDecl()->enumerators())
|
|
353 if (ECD->getInitVal() == Val)
|
|
354 return llvm::formatv("{0} ({1})", ECD->getNameAsString(), Val).str();
|
|
355 }
|
|
356 return Constant.Val.getAsString(Ctx, E->getType());
|
|
357 }
|
|
358
|
|
359 llvm::Optional<std::string> printExprValue(const SelectionTree::Node *N,
|
|
360 const ASTContext &Ctx) {
|
|
361 for (; N; N = N->Parent) {
|
|
362 // Try to evaluate the first evaluatable enclosing expression.
|
|
363 if (const Expr *E = N->ASTNode.get<Expr>()) {
|
|
364 if (auto Val = printExprValue(E, Ctx))
|
|
365 return Val;
|
|
366 } else if (N->ASTNode.get<Decl>() || N->ASTNode.get<Stmt>()) {
|
|
367 // Refuse to cross certain non-exprs. (TypeLoc are OK as part of Exprs).
|
|
368 // This tries to ensure we're showing a value related to the cursor.
|
|
369 break;
|
|
370 }
|
|
371 }
|
|
372 return llvm::None;
|
|
373 }
|
|
374
|
173
|
375 llvm::Optional<StringRef> fieldName(const Expr *E) {
|
|
376 const auto *ME = llvm::dyn_cast<MemberExpr>(E->IgnoreCasts());
|
|
377 if (!ME || !llvm::isa<CXXThisExpr>(ME->getBase()->IgnoreCasts()))
|
|
378 return llvm::None;
|
|
379 const auto *Field =
|
|
380 llvm::dyn_cast<FieldDecl>(ME->getMemberDecl());
|
|
381 if (!Field || !Field->getDeclName().isIdentifier())
|
|
382 return llvm::None;
|
|
383 return Field->getDeclName().getAsIdentifierInfo()->getName();
|
|
384 }
|
|
385
|
|
386 // If CMD is of the form T foo() { return FieldName; } then returns "FieldName".
|
|
387 llvm::Optional<StringRef> getterVariableName(const CXXMethodDecl *CMD) {
|
|
388 assert(CMD->hasBody());
|
|
389 if (CMD->getNumParams() != 0 || CMD->isVariadic())
|
|
390 return llvm::None;
|
|
391 const auto *Body = llvm::dyn_cast<CompoundStmt>(CMD->getBody());
|
|
392 const auto *OnlyReturn = (Body && Body->size() == 1)
|
|
393 ? llvm::dyn_cast<ReturnStmt>(Body->body_front())
|
|
394 : nullptr;
|
|
395 if (!OnlyReturn || !OnlyReturn->getRetValue())
|
|
396 return llvm::None;
|
|
397 return fieldName(OnlyReturn->getRetValue());
|
|
398 }
|
|
399
|
|
400 // If CMD is one of the forms:
|
|
401 // void foo(T arg) { FieldName = arg; }
|
|
402 // R foo(T arg) { FieldName = arg; return *this; }
|
|
403 // then returns "FieldName"
|
|
404 llvm::Optional<StringRef> setterVariableName(const CXXMethodDecl *CMD) {
|
|
405 assert(CMD->hasBody());
|
|
406 if (CMD->isConst() || CMD->getNumParams() != 1 || CMD->isVariadic())
|
|
407 return llvm::None;
|
|
408 const ParmVarDecl *Arg = CMD->getParamDecl(0);
|
|
409 if (Arg->isParameterPack())
|
|
410 return llvm::None;
|
|
411
|
|
412 const auto *Body = llvm::dyn_cast<CompoundStmt>(CMD->getBody());
|
|
413 if (!Body || Body->size() == 0 || Body->size() > 2)
|
|
414 return llvm::None;
|
|
415 // If the second statement exists, it must be `return this` or `return *this`.
|
|
416 if (Body->size() == 2) {
|
|
417 auto *Ret = llvm::dyn_cast<ReturnStmt>(Body->body_back());
|
|
418 if (!Ret || !Ret->getRetValue())
|
|
419 return llvm::None;
|
|
420 const Expr *RetVal = Ret->getRetValue()->IgnoreCasts();
|
|
421 if (const auto *UO = llvm::dyn_cast<UnaryOperator>(RetVal)) {
|
|
422 if (UO->getOpcode() != UO_Deref)
|
|
423 return llvm::None;
|
|
424 RetVal = UO->getSubExpr()->IgnoreCasts();
|
|
425 }
|
|
426 if (!llvm::isa<CXXThisExpr>(RetVal))
|
|
427 return llvm::None;
|
|
428 }
|
|
429 // The first statement must be an assignment of the arg to a field.
|
|
430 const Expr *LHS, *RHS;
|
|
431 if (const auto *BO = llvm::dyn_cast<BinaryOperator>(Body->body_front())) {
|
|
432 if (BO->getOpcode() != BO_Assign)
|
|
433 return llvm::None;
|
|
434 LHS = BO->getLHS();
|
|
435 RHS = BO->getRHS();
|
|
436 } else if (const auto *COCE =
|
|
437 llvm::dyn_cast<CXXOperatorCallExpr>(Body->body_front())) {
|
|
438 if (COCE->getOperator() != OO_Equal || COCE->getNumArgs() != 2)
|
|
439 return llvm::None;
|
|
440 LHS = COCE->getArg(0);
|
|
441 RHS = COCE->getArg(1);
|
|
442 } else {
|
|
443 return llvm::None;
|
|
444 }
|
|
445 auto *DRE = llvm::dyn_cast<DeclRefExpr>(RHS->IgnoreCasts());
|
|
446 if (!DRE || DRE->getDecl() != Arg)
|
|
447 return llvm::None;
|
|
448 return fieldName(LHS);
|
|
449 }
|
|
450
|
|
451 std::string synthesizeDocumentation(const NamedDecl *ND) {
|
|
452 if (const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(ND)) {
|
|
453 // Is this an ordinary, non-static method whose definition is visible?
|
|
454 if (CMD->getDeclName().isIdentifier() && !CMD->isStatic() &&
|
|
455 (CMD = llvm::dyn_cast_or_null<CXXMethodDecl>(CMD->getDefinition())) &&
|
|
456 CMD->hasBody()) {
|
|
457 if (const auto GetterField = getterVariableName(CMD))
|
|
458 return llvm::formatv("Trivial accessor for `{0}`.", *GetterField);
|
|
459 if (const auto SetterField = setterVariableName(CMD))
|
|
460 return llvm::formatv("Trivial setter for `{0}`.", *SetterField);
|
|
461 }
|
|
462 }
|
|
463 return "";
|
|
464 }
|
|
465
|
150
|
466 /// Generate a \p Hover object given the declaration \p D.
|
|
467 HoverInfo getHoverContents(const NamedDecl *D, const SymbolIndex *Index) {
|
|
468 HoverInfo HI;
|
|
469 const ASTContext &Ctx = D->getASTContext();
|
|
470
|
|
471 HI.NamespaceScope = getNamespaceScope(D);
|
|
472 if (!HI.NamespaceScope->empty())
|
|
473 HI.NamespaceScope->append("::");
|
|
474 HI.LocalScope = getLocalScope(D);
|
|
475 if (!HI.LocalScope.empty())
|
|
476 HI.LocalScope.append("::");
|
|
477
|
|
478 PrintingPolicy Policy = printingPolicyForDecls(Ctx.getPrintingPolicy());
|
|
479 HI.Name = printName(Ctx, *D);
|
|
480 const auto *CommentD = getDeclForComment(D);
|
|
481 HI.Documentation = getDeclComment(Ctx, *CommentD);
|
|
482 enhanceFromIndex(HI, *CommentD, Index);
|
173
|
483 if (HI.Documentation.empty())
|
|
484 HI.Documentation = synthesizeDocumentation(D);
|
150
|
485
|
|
486 HI.Kind = index::getSymbolInfo(D).Kind;
|
|
487
|
|
488 // Fill in template params.
|
|
489 if (const TemplateDecl *TD = D->getDescribedTemplate()) {
|
|
490 HI.TemplateParameters =
|
|
491 fetchTemplateParameters(TD->getTemplateParameters(), Policy);
|
|
492 D = TD;
|
|
493 } else if (const FunctionDecl *FD = D->getAsFunction()) {
|
|
494 if (const auto *FTD = FD->getDescribedTemplate()) {
|
|
495 HI.TemplateParameters =
|
|
496 fetchTemplateParameters(FTD->getTemplateParameters(), Policy);
|
|
497 D = FTD;
|
|
498 }
|
|
499 }
|
|
500
|
|
501 // Fill in types and params.
|
|
502 if (const FunctionDecl *FD = getUnderlyingFunction(D))
|
|
503 fillFunctionTypeAndParams(HI, D, FD, Policy);
|
|
504 else if (const auto *VD = dyn_cast<ValueDecl>(D))
|
|
505 HI.Type = printType(VD->getType(), Policy);
|
173
|
506 else if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(D))
|
|
507 HI.Type = TTP->wasDeclaredWithTypename() ? "typename" : "class";
|
|
508 else if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(D))
|
|
509 HI.Type = printType(TTP, Policy);
|
150
|
510
|
|
511 // Fill in value with evaluated initializer if possible.
|
|
512 if (const auto *Var = dyn_cast<VarDecl>(D)) {
|
|
513 if (const Expr *Init = Var->getInit())
|
|
514 HI.Value = printExprValue(Init, Ctx);
|
|
515 } else if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
|
|
516 // Dependent enums (e.g. nested in template classes) don't have values yet.
|
|
517 if (!ECD->getType()->isDependentType())
|
|
518 HI.Value = ECD->getInitVal().toString(10);
|
|
519 }
|
|
520
|
|
521 HI.Definition = printDefinition(D);
|
|
522 return HI;
|
|
523 }
|
|
524
|
|
525 /// Generate a \p Hover object given the type \p T.
|
|
526 HoverInfo getHoverContents(QualType T, ASTContext &ASTCtx,
|
|
527 const SymbolIndex *Index) {
|
|
528 HoverInfo HI;
|
|
529
|
|
530 if (const auto *D = T->getAsTagDecl()) {
|
|
531 HI.Name = printName(ASTCtx, *D);
|
|
532 HI.Kind = index::getSymbolInfo(D).Kind;
|
|
533
|
|
534 const auto *CommentD = getDeclForComment(D);
|
|
535 HI.Documentation = getDeclComment(ASTCtx, *CommentD);
|
|
536 enhanceFromIndex(HI, *CommentD, Index);
|
|
537 } else {
|
|
538 // Builtin types
|
|
539 auto Policy = printingPolicyForDecls(ASTCtx.getPrintingPolicy());
|
|
540 Policy.SuppressTagKeyword = true;
|
|
541 HI.Name = T.getAsString(Policy);
|
|
542 }
|
|
543 return HI;
|
|
544 }
|
|
545
|
|
546 /// Generate a \p Hover object given the macro \p MacroDecl.
|
|
547 HoverInfo getHoverContents(const DefinedMacro &Macro, ParsedAST &AST) {
|
|
548 HoverInfo HI;
|
|
549 SourceManager &SM = AST.getSourceManager();
|
|
550 HI.Name = std::string(Macro.Name);
|
|
551 HI.Kind = index::SymbolKind::Macro;
|
|
552 // FIXME: Populate documentation
|
173
|
553 // FIXME: Populate parameters
|
150
|
554
|
|
555 // Try to get the full definition, not just the name
|
|
556 SourceLocation StartLoc = Macro.Info->getDefinitionLoc();
|
|
557 SourceLocation EndLoc = Macro.Info->getDefinitionEndLoc();
|
|
558 if (EndLoc.isValid()) {
|
|
559 EndLoc = Lexer::getLocForEndOfToken(EndLoc, 0, SM, AST.getLangOpts());
|
|
560 bool Invalid;
|
|
561 StringRef Buffer = SM.getBufferData(SM.getFileID(StartLoc), &Invalid);
|
|
562 if (!Invalid) {
|
|
563 unsigned StartOffset = SM.getFileOffset(StartLoc);
|
|
564 unsigned EndOffset = SM.getFileOffset(EndLoc);
|
|
565 if (EndOffset <= Buffer.size() && StartOffset < EndOffset)
|
|
566 HI.Definition =
|
|
567 ("#define " + Buffer.substr(StartOffset, EndOffset - StartOffset))
|
|
568 .str();
|
|
569 }
|
|
570 }
|
|
571 return HI;
|
|
572 }
|
|
573
|
|
574 bool isLiteral(const Expr *E) {
|
|
575 // Unfortunately there's no common base Literal classes inherits from
|
|
576 // (apart from Expr), therefore this is a nasty blacklist.
|
|
577 return llvm::isa<CharacterLiteral>(E) || llvm::isa<CompoundLiteralExpr>(E) ||
|
|
578 llvm::isa<CXXBoolLiteralExpr>(E) ||
|
|
579 llvm::isa<CXXNullPtrLiteralExpr>(E) ||
|
|
580 llvm::isa<FixedPointLiteral>(E) || llvm::isa<FloatingLiteral>(E) ||
|
|
581 llvm::isa<ImaginaryLiteral>(E) || llvm::isa<IntegerLiteral>(E) ||
|
|
582 llvm::isa<StringLiteral>(E) || llvm::isa<UserDefinedLiteral>(E);
|
|
583 }
|
|
584
|
|
585 llvm::StringLiteral getNameForExpr(const Expr *E) {
|
|
586 // FIXME: Come up with names for `special` expressions.
|
|
587 //
|
|
588 // It's an known issue for GCC5, https://godbolt.org/z/Z_tbgi. Work around
|
|
589 // that by using explicit conversion constructor.
|
|
590 //
|
|
591 // TODO: Once GCC5 is fully retired and not the minimal requirement as stated
|
|
592 // in `GettingStarted`, please remove the explicit conversion constructor.
|
|
593 return llvm::StringLiteral("expression");
|
|
594 }
|
|
595
|
|
596 // Generates hover info for evaluatable expressions.
|
|
597 // FIXME: Support hover for literals (esp user-defined)
|
|
598 llvm::Optional<HoverInfo> getHoverContents(const Expr *E, ParsedAST &AST) {
|
|
599 // There's not much value in hovering over "42" and getting a hover card
|
|
600 // saying "42 is an int", similar for other literals.
|
|
601 if (isLiteral(E))
|
|
602 return llvm::None;
|
|
603
|
|
604 HoverInfo HI;
|
|
605 // For expressions we currently print the type and the value, iff it is
|
|
606 // evaluatable.
|
|
607 if (auto Val = printExprValue(E, AST.getASTContext())) {
|
|
608 auto Policy =
|
|
609 printingPolicyForDecls(AST.getASTContext().getPrintingPolicy());
|
|
610 Policy.SuppressTagKeyword = true;
|
|
611 HI.Type = printType(E->getType(), Policy);
|
|
612 HI.Value = *Val;
|
|
613 HI.Name = std::string(getNameForExpr(E));
|
|
614 return HI;
|
|
615 }
|
|
616 return llvm::None;
|
|
617 }
|
173
|
618
|
|
619 bool isParagraphBreak(llvm::StringRef Rest) {
|
|
620 return Rest.ltrim(" \t").startswith("\n");
|
|
621 }
|
|
622
|
|
623 bool punctuationIndicatesLineBreak(llvm::StringRef Line) {
|
|
624 constexpr llvm::StringLiteral Punctuation = R"txt(.:,;!?)txt";
|
|
625
|
|
626 Line = Line.rtrim();
|
|
627 return !Line.empty() && Punctuation.contains(Line.back());
|
|
628 }
|
|
629
|
|
630 bool isHardLineBreakIndicator(llvm::StringRef Rest) {
|
|
631 // '-'/'*' md list, '@'/'\' documentation command, '>' md blockquote,
|
|
632 // '#' headings, '`' code blocks
|
|
633 constexpr llvm::StringLiteral LinebreakIndicators = R"txt(-*@\>#`)txt";
|
|
634
|
|
635 Rest = Rest.ltrim(" \t");
|
|
636 if (Rest.empty())
|
|
637 return false;
|
|
638
|
|
639 if (LinebreakIndicators.contains(Rest.front()))
|
|
640 return true;
|
|
641
|
|
642 if (llvm::isDigit(Rest.front())) {
|
|
643 llvm::StringRef AfterDigit = Rest.drop_while(llvm::isDigit);
|
|
644 if (AfterDigit.startswith(".") || AfterDigit.startswith(")"))
|
|
645 return true;
|
|
646 }
|
|
647 return false;
|
|
648 }
|
|
649
|
|
650 bool isHardLineBreakAfter(llvm::StringRef Line, llvm::StringRef Rest) {
|
|
651 // Should we also consider whether Line is short?
|
|
652 return punctuationIndicatesLineBreak(Line) || isHardLineBreakIndicator(Rest);
|
|
653 }
|
|
654
|
|
655 void addLayoutInfo(const NamedDecl &ND, HoverInfo &HI) {
|
|
656 const auto &Ctx = ND.getASTContext();
|
|
657
|
|
658 if (auto *RD = llvm::dyn_cast<RecordDecl>(&ND)) {
|
|
659 if (auto Size = Ctx.getTypeSizeInCharsIfKnown(RD->getTypeForDecl()))
|
|
660 HI.Size = Size->getQuantity();
|
|
661 return;
|
|
662 }
|
|
663
|
|
664 if (const auto *FD = llvm::dyn_cast<FieldDecl>(&ND)) {
|
|
665 const auto *Record = FD->getParent();
|
|
666 if (Record)
|
|
667 Record = Record->getDefinition();
|
|
668 if (Record && !Record->isDependentType()) {
|
|
669 uint64_t OffsetBits = Ctx.getFieldOffset(FD);
|
|
670 if (auto Size = Ctx.getTypeSizeInCharsIfKnown(FD->getType())) {
|
|
671 HI.Size = Size->getQuantity();
|
|
672 HI.Offset = OffsetBits / 8;
|
|
673 }
|
|
674 }
|
|
675 return;
|
|
676 }
|
|
677 }
|
|
678
|
150
|
679 } // namespace
|
|
680
|
|
681 llvm::Optional<HoverInfo> getHover(ParsedAST &AST, Position Pos,
|
|
682 format::FormatStyle Style,
|
|
683 const SymbolIndex *Index) {
|
|
684 const SourceManager &SM = AST.getSourceManager();
|
173
|
685 auto CurLoc = sourceLocationInMainFile(SM, Pos);
|
|
686 if (!CurLoc) {
|
|
687 llvm::consumeError(CurLoc.takeError());
|
|
688 return llvm::None;
|
|
689 }
|
|
690 const auto &TB = AST.getTokens();
|
|
691 auto TokensTouchingCursor = syntax::spelledTokensTouching(*CurLoc, TB);
|
|
692 // Early exit if there were no tokens around the cursor.
|
|
693 if (TokensTouchingCursor.empty())
|
|
694 return llvm::None;
|
150
|
695
|
173
|
696 // To be used as a backup for highlighting the selected token, we use back as
|
|
697 // it aligns better with biases elsewhere (editors tend to send the position
|
|
698 // for the left of the hovered token).
|
|
699 CharSourceRange HighlightRange =
|
|
700 TokensTouchingCursor.back().range(SM).toCharRange(SM);
|
|
701 llvm::Optional<HoverInfo> HI;
|
|
702 // Macros and deducedtype only works on identifiers and auto/decltype keywords
|
|
703 // respectively. Therefore they are only trggered on whichever works for them,
|
|
704 // similar to SelectionTree::create().
|
|
705 for (const auto &Tok : TokensTouchingCursor) {
|
|
706 if (Tok.kind() == tok::identifier) {
|
|
707 // Prefer the identifier token as a fallback highlighting range.
|
|
708 HighlightRange = Tok.range(SM).toCharRange(SM);
|
|
709 if (auto M = locateMacroAt(Tok, AST.getPreprocessor())) {
|
|
710 HI = getHoverContents(*M, AST);
|
|
711 break;
|
|
712 }
|
|
713 } else if (Tok.kind() == tok::kw_auto || Tok.kind() == tok::kw_decltype) {
|
|
714 if (auto Deduced = getDeducedType(AST.getASTContext(), Tok.location())) {
|
|
715 HI = getHoverContents(*Deduced, AST.getASTContext(), Index);
|
|
716 HighlightRange = Tok.range(SM).toCharRange(SM);
|
|
717 break;
|
|
718 }
|
150
|
719 }
|
173
|
720 }
|
|
721
|
|
722 // If it wasn't auto/decltype or macro, look for decls and expressions.
|
|
723 if (!HI) {
|
|
724 auto Offset = SM.getFileOffset(*CurLoc);
|
|
725 // Editors send the position on the left of the hovered character.
|
|
726 // So our selection tree should be biased right. (Tested with VSCode).
|
|
727 SelectionTree ST =
|
|
728 SelectionTree::createRight(AST.getASTContext(), TB, Offset, Offset);
|
150
|
729 std::vector<const Decl *> Result;
|
173
|
730 if (const SelectionTree::Node *N = ST.commonAncestor()) {
|
|
731 // FIXME: Fill in HighlightRange with range coming from N->ASTNode.
|
150
|
732 auto Decls = explicitReferenceTargets(N->ASTNode, DeclRelation::Alias);
|
|
733 if (!Decls.empty()) {
|
|
734 HI = getHoverContents(Decls.front(), Index);
|
173
|
735 // Layout info only shown when hovering on the field/class itself.
|
|
736 if (Decls.front() == N->ASTNode.get<Decl>())
|
|
737 addLayoutInfo(*Decls.front(), *HI);
|
150
|
738 // Look for a close enclosing expression to show the value of.
|
|
739 if (!HI->Value)
|
|
740 HI->Value = printExprValue(N, AST.getASTContext());
|
|
741 } else if (const Expr *E = N->ASTNode.get<Expr>()) {
|
|
742 HI = getHoverContents(E, AST);
|
|
743 }
|
|
744 // FIXME: support hovers for other nodes?
|
|
745 // - built-in types
|
|
746 }
|
|
747 }
|
|
748
|
|
749 if (!HI)
|
|
750 return llvm::None;
|
|
751
|
|
752 auto Replacements = format::reformat(
|
|
753 Style, HI->Definition, tooling::Range(0, HI->Definition.size()));
|
|
754 if (auto Formatted =
|
|
755 tooling::applyAllReplacements(HI->Definition, Replacements))
|
|
756 HI->Definition = *Formatted;
|
173
|
757 HI->SymRange = halfOpenToRange(SM, HighlightRange);
|
150
|
758
|
|
759 return HI;
|
|
760 }
|
|
761
|
|
762 markup::Document HoverInfo::present() const {
|
|
763 markup::Document Output;
|
|
764 // Header contains a text of the form:
|
|
765 // variable `var`
|
|
766 //
|
|
767 // class `X`
|
|
768 //
|
|
769 // function `foo`
|
|
770 //
|
|
771 // expression
|
|
772 //
|
|
773 // Note that we are making use of a level-3 heading because VSCode renders
|
|
774 // level 1 and 2 headers in a huge font, see
|
|
775 // https://github.com/microsoft/vscode/issues/88417 for details.
|
|
776 markup::Paragraph &Header = Output.addHeading(3);
|
|
777 if (Kind != index::SymbolKind::Unknown)
|
173
|
778 Header.appendText(index::getSymbolKindString(Kind)).appendSpace();
|
150
|
779 assert(!Name.empty() && "hover triggered on a nameless symbol");
|
|
780 Header.appendCode(Name);
|
|
781
|
|
782 // Put a linebreak after header to increase readability.
|
|
783 Output.addRuler();
|
|
784 // Print Types on their own lines to reduce chances of getting line-wrapped by
|
|
785 // editor, as they might be long.
|
|
786 if (ReturnType) {
|
|
787 // For functions we display signature in a list form, e.g.:
|
|
788 // → `x`
|
|
789 // Parameters:
|
|
790 // - `bool param1`
|
|
791 // - `int param2 = 5`
|
173
|
792 Output.addParagraph().appendText("→ ").appendCode(*ReturnType);
|
150
|
793 if (Parameters && !Parameters->empty()) {
|
173
|
794 Output.addParagraph().appendText("Parameters: ");
|
150
|
795 markup::BulletList &L = Output.addBulletList();
|
|
796 for (const auto &Param : *Parameters) {
|
|
797 std::string Buffer;
|
|
798 llvm::raw_string_ostream OS(Buffer);
|
|
799 OS << Param;
|
|
800 L.addItem().addParagraph().appendCode(std::move(OS.str()));
|
|
801 }
|
|
802 }
|
|
803 } else if (Type) {
|
|
804 Output.addParagraph().appendText("Type: ").appendCode(*Type);
|
|
805 }
|
|
806
|
|
807 if (Value) {
|
|
808 markup::Paragraph &P = Output.addParagraph();
|
173
|
809 P.appendText("Value = ");
|
150
|
810 P.appendCode(*Value);
|
|
811 }
|
|
812
|
173
|
813 if (Offset)
|
|
814 Output.addParagraph().appendText(
|
|
815 llvm::formatv("Offset: {0} byte{1}", *Offset, *Offset == 1 ? "" : "s")
|
|
816 .str());
|
|
817 if (Size)
|
|
818 Output.addParagraph().appendText(
|
|
819 llvm::formatv("Size: {0} byte{1}", *Size, *Size == 1 ? "" : "s").str());
|
|
820
|
150
|
821 if (!Documentation.empty())
|
173
|
822 parseDocumentation(Documentation, Output);
|
150
|
823
|
|
824 if (!Definition.empty()) {
|
|
825 Output.addRuler();
|
|
826 std::string ScopeComment;
|
|
827 // Drop trailing "::".
|
|
828 if (!LocalScope.empty()) {
|
|
829 // Container name, e.g. class, method, function.
|
173
|
830 // We might want to propagate some info about container type to print
|
150
|
831 // function foo, class X, method X::bar, etc.
|
|
832 ScopeComment =
|
|
833 "// In " + llvm::StringRef(LocalScope).rtrim(':').str() + '\n';
|
|
834 } else if (NamespaceScope && !NamespaceScope->empty()) {
|
|
835 ScopeComment = "// In namespace " +
|
|
836 llvm::StringRef(*NamespaceScope).rtrim(':').str() + '\n';
|
|
837 }
|
|
838 // Note that we don't print anything for global namespace, to not annoy
|
|
839 // non-c++ projects or projects that are not making use of namespaces.
|
|
840 Output.addCodeBlock(ScopeComment + Definition);
|
|
841 }
|
|
842 return Output;
|
|
843 }
|
|
844
|
173
|
845 // If the backtick at `Offset` starts a probable quoted range, return the range
|
|
846 // (including the quotes).
|
|
847 llvm::Optional<llvm::StringRef> getBacktickQuoteRange(llvm::StringRef Line,
|
|
848 unsigned Offset) {
|
|
849 assert(Line[Offset] == '`');
|
|
850
|
|
851 // The open-quote is usually preceded by whitespace.
|
|
852 llvm::StringRef Prefix = Line.substr(0, Offset);
|
|
853 constexpr llvm::StringLiteral BeforeStartChars = " \t(=";
|
|
854 if (!Prefix.empty() && !BeforeStartChars.contains(Prefix.back()))
|
|
855 return llvm::None;
|
|
856
|
|
857 // The quoted string must be nonempty and usually has no leading/trailing ws.
|
|
858 auto Next = Line.find('`', Offset + 1);
|
|
859 if (Next == llvm::StringRef::npos)
|
|
860 return llvm::None;
|
|
861 llvm::StringRef Contents = Line.slice(Offset + 1, Next);
|
|
862 if (Contents.empty() || isWhitespace(Contents.front()) ||
|
|
863 isWhitespace(Contents.back()))
|
|
864 return llvm::None;
|
|
865
|
|
866 // The close-quote is usually followed by whitespace or punctuation.
|
|
867 llvm::StringRef Suffix = Line.substr(Next + 1);
|
|
868 constexpr llvm::StringLiteral AfterEndChars = " \t)=.,;:";
|
|
869 if (!Suffix.empty() && !AfterEndChars.contains(Suffix.front()))
|
|
870 return llvm::None;
|
|
871
|
|
872 return Line.slice(Offset, Next+1);
|
|
873 }
|
|
874
|
|
875 void parseDocumentationLine(llvm::StringRef Line, markup::Paragraph &Out) {
|
|
876 // Probably this is appendText(Line), but scan for something interesting.
|
|
877 for (unsigned I = 0; I < Line.size(); ++I) {
|
|
878 switch (Line[I]) {
|
|
879 case '`':
|
|
880 if (auto Range = getBacktickQuoteRange(Line, I)) {
|
|
881 Out.appendText(Line.substr(0, I));
|
|
882 Out.appendCode(Range->trim("`"), /*Preserve=*/true);
|
|
883 return parseDocumentationLine(Line.substr(I+Range->size()), Out);
|
|
884 }
|
|
885 break;
|
|
886 }
|
|
887 }
|
|
888 Out.appendText(Line).appendSpace();
|
|
889 }
|
|
890
|
|
891 void parseDocumentation(llvm::StringRef Input, markup::Document &Output) {
|
|
892 std::vector<llvm::StringRef> ParagraphLines;
|
|
893 auto FlushParagraph = [&] {
|
|
894 if (ParagraphLines.empty())
|
|
895 return;
|
|
896 auto &P = Output.addParagraph();
|
|
897 for (llvm::StringRef Line : ParagraphLines)
|
|
898 parseDocumentationLine(Line, P);
|
|
899 ParagraphLines.clear();
|
|
900 };
|
|
901
|
|
902 llvm::StringRef Line, Rest;
|
|
903 for (std::tie(Line, Rest) = Input.split('\n');
|
|
904 !(Line.empty() && Rest.empty());
|
|
905 std::tie(Line, Rest) = Rest.split('\n')) {
|
|
906
|
|
907 // After a linebreak remove spaces to avoid 4 space markdown code blocks.
|
|
908 // FIXME: make FlushParagraph handle this.
|
|
909 Line = Line.ltrim();
|
|
910 if (!Line.empty())
|
|
911 ParagraphLines.push_back(Line);
|
|
912
|
|
913 if (isParagraphBreak(Rest) || isHardLineBreakAfter(Line, Rest)) {
|
|
914 FlushParagraph();
|
|
915 }
|
|
916 }
|
|
917 FlushParagraph();
|
|
918 }
|
|
919
|
150
|
920 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
|
|
921 const HoverInfo::Param &P) {
|
|
922 std::vector<llvm::StringRef> Output;
|
|
923 if (P.Type)
|
|
924 Output.push_back(*P.Type);
|
|
925 if (P.Name)
|
|
926 Output.push_back(*P.Name);
|
|
927 OS << llvm::join(Output, " ");
|
|
928 if (P.Default)
|
|
929 OS << " = " << *P.Default;
|
|
930 return OS;
|
|
931 }
|
|
932
|
|
933 } // namespace clangd
|
|
934 } // namespace clang
|