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"
|
221
|
25 #include "clang/AST/DeclObjC.h"
|
150
|
26 #include "clang/AST/DeclTemplate.h"
|
|
27 #include "clang/AST/Expr.h"
|
|
28 #include "clang/AST/ExprCXX.h"
|
173
|
29 #include "clang/AST/OperationKinds.h"
|
150
|
30 #include "clang/AST/PrettyPrinter.h"
|
221
|
31 #include "clang/AST/RecursiveASTVisitor.h"
|
150
|
32 #include "clang/AST/Type.h"
|
173
|
33 #include "clang/Basic/SourceLocation.h"
|
150
|
34 #include "clang/Basic/Specifiers.h"
|
173
|
35 #include "clang/Basic/TokenKinds.h"
|
150
|
36 #include "clang/Index/IndexSymbol.h"
|
173
|
37 #include "clang/Tooling/Syntax/Tokens.h"
|
150
|
38 #include "llvm/ADT/None.h"
|
|
39 #include "llvm/ADT/Optional.h"
|
|
40 #include "llvm/ADT/STLExtras.h"
|
|
41 #include "llvm/ADT/SmallVector.h"
|
|
42 #include "llvm/ADT/StringExtras.h"
|
|
43 #include "llvm/ADT/StringRef.h"
|
|
44 #include "llvm/Support/Casting.h"
|
|
45 #include "llvm/Support/ErrorHandling.h"
|
221
|
46 #include "llvm/Support/Format.h"
|
150
|
47 #include "llvm/Support/raw_ostream.h"
|
|
48 #include <string>
|
|
49
|
|
50 namespace clang {
|
|
51 namespace clangd {
|
|
52 namespace {
|
|
53
|
221
|
54 PrintingPolicy getPrintingPolicy(PrintingPolicy Base) {
|
|
55 Base.AnonymousTagLocations = false;
|
|
56 Base.TerseOutput = true;
|
|
57 Base.PolishForDeclaration = true;
|
|
58 Base.ConstantsAsWritten = true;
|
|
59 Base.SuppressTemplateArgsInCXXConstructors = true;
|
|
60 return Base;
|
150
|
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();
|
221
|
69
|
|
70 // ObjC scopes won't have multiple components for us to join, instead:
|
|
71 // - Methods: "-[Class methodParam1:methodParam2]"
|
|
72 // - Classes, categories, and protocols: "MyClass(Category)"
|
|
73 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
|
|
74 return printObjCMethod(*MD);
|
|
75 else if (const ObjCContainerDecl *CD = dyn_cast<ObjCContainerDecl>(DC))
|
|
76 return printObjCContainer(*CD);
|
|
77
|
150
|
78 auto GetName = [](const TypeDecl *D) {
|
|
79 if (!D->getDeclName().isEmpty()) {
|
|
80 PrintingPolicy Policy = D->getASTContext().getPrintingPolicy();
|
|
81 Policy.SuppressScope = true;
|
|
82 return declaredType(D).getAsString(Policy);
|
|
83 }
|
|
84 if (auto RD = dyn_cast<RecordDecl>(D))
|
|
85 return ("(anonymous " + RD->getKindName() + ")").str();
|
|
86 return std::string("");
|
|
87 };
|
|
88 while (DC) {
|
|
89 if (const TypeDecl *TD = dyn_cast<TypeDecl>(DC))
|
|
90 Scopes.push_back(GetName(TD));
|
|
91 else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
|
|
92 Scopes.push_back(FD->getNameAsString());
|
|
93 DC = DC->getParent();
|
|
94 }
|
|
95
|
|
96 return llvm::join(llvm::reverse(Scopes), "::");
|
|
97 }
|
|
98
|
|
99 /// Returns the human-readable representation for namespace containing the
|
|
100 /// declaration \p D. Returns empty if it is contained global namespace.
|
|
101 std::string getNamespaceScope(const Decl *D) {
|
|
102 const DeclContext *DC = D->getDeclContext();
|
|
103
|
221
|
104 // ObjC does not have the concept of namespaces, so instead we support
|
|
105 // local scopes.
|
|
106 if (isa<ObjCMethodDecl, ObjCContainerDecl>(DC))
|
|
107 return "";
|
|
108
|
150
|
109 if (const TagDecl *TD = dyn_cast<TagDecl>(DC))
|
|
110 return getNamespaceScope(TD);
|
|
111 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
|
|
112 return getNamespaceScope(FD);
|
|
113 if (const NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(DC)) {
|
|
114 // Skip inline/anon namespaces.
|
|
115 if (NSD->isInline() || NSD->isAnonymousNamespace())
|
|
116 return getNamespaceScope(NSD);
|
|
117 }
|
|
118 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
|
|
119 return printQualifiedName(*ND);
|
|
120
|
|
121 return "";
|
|
122 }
|
|
123
|
221
|
124 std::string printDefinition(const Decl *D, const PrintingPolicy &PP) {
|
150
|
125 std::string Definition;
|
|
126 llvm::raw_string_ostream OS(Definition);
|
221
|
127 D->print(OS, PP);
|
150
|
128 OS.flush();
|
|
129 return Definition;
|
|
130 }
|
|
131
|
221
|
132 std::string printType(QualType QT, const PrintingPolicy &PP) {
|
150
|
133 // TypePrinter doesn't resolve decltypes, so resolve them here.
|
|
134 // FIXME: This doesn't handle composite types that contain a decltype in them.
|
|
135 // We should rather have a printing policy for that.
|
221
|
136 while (!QT.isNull() && QT->isDecltypeType())
|
|
137 QT = QT->getAs<DecltypeType>()->getUnderlyingType();
|
|
138 std::string Result;
|
|
139 llvm::raw_string_ostream OS(Result);
|
|
140 // Special case: if the outer type is a tag type without qualifiers, then
|
|
141 // include the tag for extra clarity.
|
|
142 // This isn't very idiomatic, so don't attempt it for complex cases, including
|
|
143 // pointers/references, template specializations, etc.
|
|
144 if (!QT.isNull() && !QT.hasQualifiers() && PP.SuppressTagKeyword) {
|
|
145 if (auto *TT = llvm::dyn_cast<TagType>(QT.getTypePtr()))
|
|
146 OS << TT->getDecl()->getKindName() << " ";
|
|
147 }
|
|
148 OS.flush();
|
|
149 QT.print(OS, PP);
|
|
150 return Result;
|
150
|
151 }
|
|
152
|
173
|
153 std::string printType(const TemplateTypeParmDecl *TTP) {
|
|
154 std::string Res = TTP->wasDeclaredWithTypename() ? "typename" : "class";
|
|
155 if (TTP->isParameterPack())
|
|
156 Res += "...";
|
|
157 return Res;
|
|
158 }
|
|
159
|
|
160 std::string printType(const NonTypeTemplateParmDecl *NTTP,
|
|
161 const PrintingPolicy &PP) {
|
|
162 std::string Res = printType(NTTP->getType(), PP);
|
|
163 if (NTTP->isParameterPack())
|
|
164 Res += "...";
|
|
165 return Res;
|
|
166 }
|
|
167
|
|
168 std::string printType(const TemplateTemplateParmDecl *TTP,
|
|
169 const PrintingPolicy &PP) {
|
|
170 std::string Res;
|
|
171 llvm::raw_string_ostream OS(Res);
|
|
172 OS << "template <";
|
|
173 llvm::StringRef Sep = "";
|
|
174 for (const Decl *Param : *TTP->getTemplateParameters()) {
|
|
175 OS << Sep;
|
|
176 Sep = ", ";
|
|
177 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
|
|
178 OS << printType(TTP);
|
|
179 else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
|
|
180 OS << printType(NTTP, PP);
|
|
181 else if (const auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param))
|
|
182 OS << printType(TTPD, PP);
|
|
183 }
|
|
184 // FIXME: TemplateTemplateParameter doesn't store the info on whether this
|
|
185 // param was a "typename" or "class".
|
|
186 OS << "> class";
|
|
187 return OS.str();
|
|
188 }
|
|
189
|
150
|
190 std::vector<HoverInfo::Param>
|
|
191 fetchTemplateParameters(const TemplateParameterList *Params,
|
|
192 const PrintingPolicy &PP) {
|
|
193 assert(Params);
|
|
194 std::vector<HoverInfo::Param> TempParameters;
|
|
195
|
|
196 for (const Decl *Param : *Params) {
|
|
197 HoverInfo::Param P;
|
|
198 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
|
173
|
199 P.Type = printType(TTP);
|
150
|
200
|
|
201 if (!TTP->getName().empty())
|
|
202 P.Name = TTP->getNameAsString();
|
173
|
203
|
150
|
204 if (TTP->hasDefaultArgument())
|
|
205 P.Default = TTP->getDefaultArgument().getAsString(PP);
|
|
206 } else if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
|
173
|
207 P.Type = printType(NTTP, PP);
|
|
208
|
150
|
209 if (IdentifierInfo *II = NTTP->getIdentifier())
|
|
210 P.Name = II->getName().str();
|
|
211
|
|
212 if (NTTP->hasDefaultArgument()) {
|
|
213 P.Default.emplace();
|
|
214 llvm::raw_string_ostream Out(*P.Default);
|
|
215 NTTP->getDefaultArgument()->printPretty(Out, nullptr, PP);
|
|
216 }
|
|
217 } else if (const auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param)) {
|
173
|
218 P.Type = printType(TTPD, PP);
|
|
219
|
150
|
220 if (!TTPD->getName().empty())
|
|
221 P.Name = TTPD->getNameAsString();
|
173
|
222
|
150
|
223 if (TTPD->hasDefaultArgument()) {
|
|
224 P.Default.emplace();
|
|
225 llvm::raw_string_ostream Out(*P.Default);
|
221
|
226 TTPD->getDefaultArgument().getArgument().print(PP, Out,
|
|
227 /*IncludeType*/ false);
|
150
|
228 }
|
|
229 }
|
|
230 TempParameters.push_back(std::move(P));
|
|
231 }
|
|
232
|
|
233 return TempParameters;
|
|
234 }
|
|
235
|
|
236 const FunctionDecl *getUnderlyingFunction(const Decl *D) {
|
|
237 // Extract lambda from variables.
|
|
238 if (const VarDecl *VD = llvm::dyn_cast<VarDecl>(D)) {
|
|
239 auto QT = VD->getType();
|
|
240 if (!QT.isNull()) {
|
|
241 while (!QT->getPointeeType().isNull())
|
|
242 QT = QT->getPointeeType();
|
|
243
|
|
244 if (const auto *CD = QT->getAsCXXRecordDecl())
|
|
245 return CD->getLambdaCallOperator();
|
|
246 }
|
|
247 }
|
|
248
|
|
249 // Non-lambda functions.
|
|
250 return D->getAsFunction();
|
|
251 }
|
|
252
|
|
253 // Returns the decl that should be used for querying comments, either from index
|
|
254 // or AST.
|
|
255 const NamedDecl *getDeclForComment(const NamedDecl *D) {
|
|
256 if (const auto *TSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(D)) {
|
|
257 // Template may not be instantiated e.g. if the type didn't need to be
|
|
258 // complete; fallback to primary template.
|
|
259 if (TSD->getTemplateSpecializationKind() == TSK_Undeclared)
|
|
260 return TSD->getSpecializedTemplate();
|
|
261 if (const auto *TIP = TSD->getTemplateInstantiationPattern())
|
|
262 return TIP;
|
|
263 }
|
|
264 if (const auto *TSD = llvm::dyn_cast<VarTemplateSpecializationDecl>(D)) {
|
|
265 if (TSD->getTemplateSpecializationKind() == TSK_Undeclared)
|
|
266 return TSD->getSpecializedTemplate();
|
|
267 if (const auto *TIP = TSD->getTemplateInstantiationPattern())
|
|
268 return TIP;
|
|
269 }
|
|
270 if (const auto *FD = D->getAsFunction())
|
|
271 if (const auto *TIP = FD->getTemplateInstantiationPattern())
|
|
272 return TIP;
|
|
273 return D;
|
|
274 }
|
|
275
|
|
276 // Look up information about D from the index, and add it to Hover.
|
|
277 void enhanceFromIndex(HoverInfo &Hover, const NamedDecl &ND,
|
|
278 const SymbolIndex *Index) {
|
|
279 assert(&ND == getDeclForComment(&ND));
|
|
280 // We only add documentation, so don't bother if we already have some.
|
|
281 if (!Hover.Documentation.empty() || !Index)
|
|
282 return;
|
|
283
|
|
284 // Skip querying for non-indexable symbols, there's no point.
|
|
285 // We're searching for symbols that might be indexed outside this main file.
|
|
286 if (!SymbolCollector::shouldCollectSymbol(ND, ND.getASTContext(),
|
|
287 SymbolCollector::Options(),
|
|
288 /*IsMainFileOnly=*/false))
|
|
289 return;
|
|
290 auto ID = getSymbolID(&ND);
|
|
291 if (!ID)
|
|
292 return;
|
|
293 LookupRequest Req;
|
221
|
294 Req.IDs.insert(ID);
|
150
|
295 Index->lookup(Req, [&](const Symbol &S) {
|
|
296 Hover.Documentation = std::string(S.Documentation);
|
|
297 });
|
|
298 }
|
|
299
|
|
300 // Default argument might exist but be unavailable, in the case of unparsed
|
|
301 // arguments for example. This function returns the default argument if it is
|
|
302 // available.
|
|
303 const Expr *getDefaultArg(const ParmVarDecl *PVD) {
|
173
|
304 // Default argument can be unparsed or uninstantiated. For the former we
|
150
|
305 // can't do much, as token information is only stored in Sema and not
|
|
306 // attached to the AST node. For the latter though, it is safe to proceed as
|
|
307 // the expression is still valid.
|
|
308 if (!PVD->hasDefaultArg() || PVD->hasUnparsedDefaultArg())
|
|
309 return nullptr;
|
|
310 return PVD->hasUninstantiatedDefaultArg() ? PVD->getUninstantiatedDefaultArg()
|
|
311 : PVD->getDefaultArg();
|
|
312 }
|
|
313
|
221
|
314 HoverInfo::Param toHoverInfoParam(const ParmVarDecl *PVD,
|
|
315 const PrintingPolicy &PP) {
|
|
316 HoverInfo::Param Out;
|
|
317 Out.Type = printType(PVD->getType(), PP);
|
|
318 if (!PVD->getName().empty())
|
|
319 Out.Name = PVD->getNameAsString();
|
|
320 if (const Expr *DefArg = getDefaultArg(PVD)) {
|
|
321 Out.Default.emplace();
|
|
322 llvm::raw_string_ostream OS(*Out.Default);
|
|
323 DefArg->printPretty(OS, nullptr, PP);
|
|
324 }
|
|
325 return Out;
|
|
326 }
|
|
327
|
150
|
328 // Populates Type, ReturnType, and Parameters for function-like decls.
|
|
329 void fillFunctionTypeAndParams(HoverInfo &HI, const Decl *D,
|
|
330 const FunctionDecl *FD,
|
221
|
331 const PrintingPolicy &PP) {
|
150
|
332 HI.Parameters.emplace();
|
221
|
333 for (const ParmVarDecl *PVD : FD->parameters())
|
|
334 HI.Parameters->emplace_back(toHoverInfoParam(PVD, PP));
|
150
|
335
|
|
336 // We don't want any type info, if name already contains it. This is true for
|
|
337 // constructors/destructors and conversion operators.
|
|
338 const auto NK = FD->getDeclName().getNameKind();
|
|
339 if (NK == DeclarationName::CXXConstructorName ||
|
|
340 NK == DeclarationName::CXXDestructorName ||
|
|
341 NK == DeclarationName::CXXConversionFunctionName)
|
|
342 return;
|
|
343
|
221
|
344 HI.ReturnType = printType(FD->getReturnType(), PP);
|
150
|
345 QualType QT = FD->getType();
|
|
346 if (const VarDecl *VD = llvm::dyn_cast<VarDecl>(D)) // Lambdas
|
|
347 QT = VD->getType().getDesugaredType(D->getASTContext());
|
221
|
348 HI.Type = printType(QT, PP);
|
150
|
349 // FIXME: handle variadics.
|
|
350 }
|
|
351
|
221
|
352 // Non-negative numbers are printed using min digits
|
|
353 // 0 => 0x0
|
|
354 // 100 => 0x64
|
|
355 // Negative numbers are sign-extended to 32/64 bits
|
|
356 // -2 => 0xfffffffe
|
|
357 // -2^32 => 0xfffffffeffffffff
|
|
358 static llvm::FormattedNumber printHex(const llvm::APSInt &V) {
|
|
359 uint64_t Bits = V.getExtValue();
|
|
360 if (V.isNegative() && V.getMinSignedBits() <= 32)
|
|
361 return llvm::format_hex(uint32_t(Bits), 0);
|
|
362 return llvm::format_hex(Bits, 0);
|
|
363 }
|
|
364
|
150
|
365 llvm::Optional<std::string> printExprValue(const Expr *E,
|
|
366 const ASTContext &Ctx) {
|
221
|
367 // InitListExpr has two forms, syntactic and semantic. They are the same thing
|
|
368 // (refer to a same AST node) in most cases.
|
|
369 // When they are different, RAV returns the syntactic form, and we should feed
|
|
370 // the semantic form to EvaluateAsRValue.
|
|
371 if (const auto *ILE = llvm::dyn_cast<InitListExpr>(E)) {
|
|
372 if (!ILE->isSemanticForm())
|
|
373 E = ILE->getSemanticForm();
|
|
374 }
|
|
375
|
150
|
376 // Evaluating [[foo]]() as "&foo" isn't useful, and prevents us walking up
|
221
|
377 // to the enclosing call. Evaluating an expression of void type doesn't
|
|
378 // produce a meaningful result.
|
150
|
379 QualType T = E->getType();
|
|
380 if (T.isNull() || T->isFunctionType() || T->isFunctionPointerType() ||
|
221
|
381 T->isFunctionReferenceType() || T->isVoidType())
|
150
|
382 return llvm::None;
|
221
|
383
|
|
384 Expr::EvalResult Constant;
|
150
|
385 // Attempt to evaluate. If expr is dependent, evaluation crashes!
|
221
|
386 if (E->isValueDependent() || !E->EvaluateAsRValue(Constant, Ctx) ||
|
|
387 // Disable printing for record-types, as they are usually confusing and
|
|
388 // might make clang crash while printing the expressions.
|
|
389 Constant.Val.isStruct() || Constant.Val.isUnion())
|
150
|
390 return llvm::None;
|
|
391
|
|
392 // Show enums symbolically, not numerically like APValue::printPretty().
|
|
393 if (T->isEnumeralType() && Constant.Val.getInt().getMinSignedBits() <= 64) {
|
|
394 // Compare to int64_t to avoid bit-width match requirements.
|
|
395 int64_t Val = Constant.Val.getInt().getExtValue();
|
|
396 for (const EnumConstantDecl *ECD :
|
|
397 T->castAs<EnumType>()->getDecl()->enumerators())
|
|
398 if (ECD->getInitVal() == Val)
|
221
|
399 return llvm::formatv("{0} ({1})", ECD->getNameAsString(),
|
|
400 printHex(Constant.Val.getInt()))
|
|
401 .str();
|
150
|
402 }
|
221
|
403 // Show hex value of integers if they're at least 10 (or negative!)
|
|
404 if (T->isIntegralOrEnumerationType() &&
|
|
405 Constant.Val.getInt().getMinSignedBits() <= 64 &&
|
|
406 Constant.Val.getInt().uge(10))
|
|
407 return llvm::formatv("{0} ({1})", Constant.Val.getAsString(Ctx, T),
|
|
408 printHex(Constant.Val.getInt()))
|
|
409 .str();
|
|
410 return Constant.Val.getAsString(Ctx, T);
|
150
|
411 }
|
|
412
|
|
413 llvm::Optional<std::string> printExprValue(const SelectionTree::Node *N,
|
|
414 const ASTContext &Ctx) {
|
|
415 for (; N; N = N->Parent) {
|
|
416 // Try to evaluate the first evaluatable enclosing expression.
|
|
417 if (const Expr *E = N->ASTNode.get<Expr>()) {
|
221
|
418 // Once we cross an expression of type 'cv void', the evaluated result
|
|
419 // has nothing to do with our original cursor position.
|
|
420 if (!E->getType().isNull() && E->getType()->isVoidType())
|
|
421 break;
|
150
|
422 if (auto Val = printExprValue(E, Ctx))
|
|
423 return Val;
|
|
424 } else if (N->ASTNode.get<Decl>() || N->ASTNode.get<Stmt>()) {
|
|
425 // Refuse to cross certain non-exprs. (TypeLoc are OK as part of Exprs).
|
|
426 // This tries to ensure we're showing a value related to the cursor.
|
|
427 break;
|
|
428 }
|
|
429 }
|
|
430 return llvm::None;
|
|
431 }
|
|
432
|
173
|
433 llvm::Optional<StringRef> fieldName(const Expr *E) {
|
|
434 const auto *ME = llvm::dyn_cast<MemberExpr>(E->IgnoreCasts());
|
|
435 if (!ME || !llvm::isa<CXXThisExpr>(ME->getBase()->IgnoreCasts()))
|
|
436 return llvm::None;
|
221
|
437 const auto *Field = llvm::dyn_cast<FieldDecl>(ME->getMemberDecl());
|
173
|
438 if (!Field || !Field->getDeclName().isIdentifier())
|
|
439 return llvm::None;
|
|
440 return Field->getDeclName().getAsIdentifierInfo()->getName();
|
|
441 }
|
|
442
|
|
443 // If CMD is of the form T foo() { return FieldName; } then returns "FieldName".
|
|
444 llvm::Optional<StringRef> getterVariableName(const CXXMethodDecl *CMD) {
|
|
445 assert(CMD->hasBody());
|
|
446 if (CMD->getNumParams() != 0 || CMD->isVariadic())
|
|
447 return llvm::None;
|
|
448 const auto *Body = llvm::dyn_cast<CompoundStmt>(CMD->getBody());
|
|
449 const auto *OnlyReturn = (Body && Body->size() == 1)
|
|
450 ? llvm::dyn_cast<ReturnStmt>(Body->body_front())
|
|
451 : nullptr;
|
|
452 if (!OnlyReturn || !OnlyReturn->getRetValue())
|
|
453 return llvm::None;
|
|
454 return fieldName(OnlyReturn->getRetValue());
|
|
455 }
|
|
456
|
|
457 // If CMD is one of the forms:
|
|
458 // void foo(T arg) { FieldName = arg; }
|
|
459 // R foo(T arg) { FieldName = arg; return *this; }
|
221
|
460 // void foo(T arg) { FieldName = std::move(arg); }
|
|
461 // R foo(T arg) { FieldName = std::move(arg); return *this; }
|
173
|
462 // then returns "FieldName"
|
|
463 llvm::Optional<StringRef> setterVariableName(const CXXMethodDecl *CMD) {
|
|
464 assert(CMD->hasBody());
|
|
465 if (CMD->isConst() || CMD->getNumParams() != 1 || CMD->isVariadic())
|
|
466 return llvm::None;
|
|
467 const ParmVarDecl *Arg = CMD->getParamDecl(0);
|
|
468 if (Arg->isParameterPack())
|
|
469 return llvm::None;
|
|
470
|
|
471 const auto *Body = llvm::dyn_cast<CompoundStmt>(CMD->getBody());
|
|
472 if (!Body || Body->size() == 0 || Body->size() > 2)
|
|
473 return llvm::None;
|
|
474 // If the second statement exists, it must be `return this` or `return *this`.
|
|
475 if (Body->size() == 2) {
|
|
476 auto *Ret = llvm::dyn_cast<ReturnStmt>(Body->body_back());
|
|
477 if (!Ret || !Ret->getRetValue())
|
|
478 return llvm::None;
|
|
479 const Expr *RetVal = Ret->getRetValue()->IgnoreCasts();
|
|
480 if (const auto *UO = llvm::dyn_cast<UnaryOperator>(RetVal)) {
|
|
481 if (UO->getOpcode() != UO_Deref)
|
|
482 return llvm::None;
|
|
483 RetVal = UO->getSubExpr()->IgnoreCasts();
|
|
484 }
|
|
485 if (!llvm::isa<CXXThisExpr>(RetVal))
|
|
486 return llvm::None;
|
|
487 }
|
|
488 // The first statement must be an assignment of the arg to a field.
|
|
489 const Expr *LHS, *RHS;
|
|
490 if (const auto *BO = llvm::dyn_cast<BinaryOperator>(Body->body_front())) {
|
|
491 if (BO->getOpcode() != BO_Assign)
|
|
492 return llvm::None;
|
|
493 LHS = BO->getLHS();
|
|
494 RHS = BO->getRHS();
|
|
495 } else if (const auto *COCE =
|
|
496 llvm::dyn_cast<CXXOperatorCallExpr>(Body->body_front())) {
|
|
497 if (COCE->getOperator() != OO_Equal || COCE->getNumArgs() != 2)
|
|
498 return llvm::None;
|
|
499 LHS = COCE->getArg(0);
|
|
500 RHS = COCE->getArg(1);
|
|
501 } else {
|
|
502 return llvm::None;
|
|
503 }
|
221
|
504
|
|
505 // Detect the case when the item is moved into the field.
|
|
506 if (auto *CE = llvm::dyn_cast<CallExpr>(RHS->IgnoreCasts())) {
|
|
507 if (CE->getNumArgs() != 1)
|
|
508 return llvm::None;
|
|
509 auto *ND = llvm::dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl());
|
|
510 if (!ND || !ND->getIdentifier() || ND->getName() != "move" ||
|
|
511 !ND->isInStdNamespace())
|
|
512 return llvm::None;
|
|
513 RHS = CE->getArg(0);
|
|
514 }
|
|
515
|
173
|
516 auto *DRE = llvm::dyn_cast<DeclRefExpr>(RHS->IgnoreCasts());
|
|
517 if (!DRE || DRE->getDecl() != Arg)
|
|
518 return llvm::None;
|
|
519 return fieldName(LHS);
|
|
520 }
|
|
521
|
|
522 std::string synthesizeDocumentation(const NamedDecl *ND) {
|
|
523 if (const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(ND)) {
|
|
524 // Is this an ordinary, non-static method whose definition is visible?
|
|
525 if (CMD->getDeclName().isIdentifier() && !CMD->isStatic() &&
|
|
526 (CMD = llvm::dyn_cast_or_null<CXXMethodDecl>(CMD->getDefinition())) &&
|
|
527 CMD->hasBody()) {
|
|
528 if (const auto GetterField = getterVariableName(CMD))
|
|
529 return llvm::formatv("Trivial accessor for `{0}`.", *GetterField);
|
|
530 if (const auto SetterField = setterVariableName(CMD))
|
|
531 return llvm::formatv("Trivial setter for `{0}`.", *SetterField);
|
|
532 }
|
|
533 }
|
|
534 return "";
|
|
535 }
|
|
536
|
150
|
537 /// Generate a \p Hover object given the declaration \p D.
|
221
|
538 HoverInfo getHoverContents(const NamedDecl *D, const PrintingPolicy &PP,
|
|
539 const SymbolIndex *Index) {
|
150
|
540 HoverInfo HI;
|
|
541 const ASTContext &Ctx = D->getASTContext();
|
|
542
|
221
|
543 HI.AccessSpecifier = getAccessSpelling(D->getAccess()).str();
|
150
|
544 HI.NamespaceScope = getNamespaceScope(D);
|
|
545 if (!HI.NamespaceScope->empty())
|
|
546 HI.NamespaceScope->append("::");
|
|
547 HI.LocalScope = getLocalScope(D);
|
|
548 if (!HI.LocalScope.empty())
|
|
549 HI.LocalScope.append("::");
|
|
550
|
|
551 HI.Name = printName(Ctx, *D);
|
|
552 const auto *CommentD = getDeclForComment(D);
|
|
553 HI.Documentation = getDeclComment(Ctx, *CommentD);
|
|
554 enhanceFromIndex(HI, *CommentD, Index);
|
173
|
555 if (HI.Documentation.empty())
|
|
556 HI.Documentation = synthesizeDocumentation(D);
|
150
|
557
|
|
558 HI.Kind = index::getSymbolInfo(D).Kind;
|
|
559
|
|
560 // Fill in template params.
|
|
561 if (const TemplateDecl *TD = D->getDescribedTemplate()) {
|
|
562 HI.TemplateParameters =
|
221
|
563 fetchTemplateParameters(TD->getTemplateParameters(), PP);
|
150
|
564 D = TD;
|
|
565 } else if (const FunctionDecl *FD = D->getAsFunction()) {
|
|
566 if (const auto *FTD = FD->getDescribedTemplate()) {
|
|
567 HI.TemplateParameters =
|
221
|
568 fetchTemplateParameters(FTD->getTemplateParameters(), PP);
|
150
|
569 D = FTD;
|
|
570 }
|
|
571 }
|
|
572
|
|
573 // Fill in types and params.
|
|
574 if (const FunctionDecl *FD = getUnderlyingFunction(D))
|
221
|
575 fillFunctionTypeAndParams(HI, D, FD, PP);
|
150
|
576 else if (const auto *VD = dyn_cast<ValueDecl>(D))
|
221
|
577 HI.Type = printType(VD->getType(), PP);
|
173
|
578 else if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(D))
|
|
579 HI.Type = TTP->wasDeclaredWithTypename() ? "typename" : "class";
|
|
580 else if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(D))
|
221
|
581 HI.Type = printType(TTP, PP);
|
150
|
582
|
|
583 // Fill in value with evaluated initializer if possible.
|
|
584 if (const auto *Var = dyn_cast<VarDecl>(D)) {
|
|
585 if (const Expr *Init = Var->getInit())
|
|
586 HI.Value = printExprValue(Init, Ctx);
|
|
587 } else if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
|
|
588 // Dependent enums (e.g. nested in template classes) don't have values yet.
|
|
589 if (!ECD->getType()->isDependentType())
|
|
590 HI.Value = ECD->getInitVal().toString(10);
|
|
591 }
|
|
592
|
221
|
593 HI.Definition = printDefinition(D, PP);
|
150
|
594 return HI;
|
|
595 }
|
|
596
|
|
597 /// Generate a \p Hover object given the macro \p MacroDecl.
|
|
598 HoverInfo getHoverContents(const DefinedMacro &Macro, ParsedAST &AST) {
|
|
599 HoverInfo HI;
|
|
600 SourceManager &SM = AST.getSourceManager();
|
|
601 HI.Name = std::string(Macro.Name);
|
|
602 HI.Kind = index::SymbolKind::Macro;
|
|
603 // FIXME: Populate documentation
|
173
|
604 // FIXME: Populate parameters
|
150
|
605
|
|
606 // Try to get the full definition, not just the name
|
|
607 SourceLocation StartLoc = Macro.Info->getDefinitionLoc();
|
|
608 SourceLocation EndLoc = Macro.Info->getDefinitionEndLoc();
|
221
|
609 // Ensure that EndLoc is a valid offset. For example it might come from
|
|
610 // preamble, and source file might've changed, in such a scenario EndLoc still
|
|
611 // stays valid, but getLocForEndOfToken will fail as it is no longer a valid
|
|
612 // offset.
|
|
613 // Note that this check is just to ensure there's text data inside the range.
|
|
614 // It will still succeed even when the data inside the range is irrelevant to
|
|
615 // macro definition.
|
|
616 if (SM.getPresumedLoc(EndLoc, /*UseLineDirectives=*/false).isValid()) {
|
150
|
617 EndLoc = Lexer::getLocForEndOfToken(EndLoc, 0, SM, AST.getLangOpts());
|
|
618 bool Invalid;
|
|
619 StringRef Buffer = SM.getBufferData(SM.getFileID(StartLoc), &Invalid);
|
|
620 if (!Invalid) {
|
|
621 unsigned StartOffset = SM.getFileOffset(StartLoc);
|
|
622 unsigned EndOffset = SM.getFileOffset(EndLoc);
|
|
623 if (EndOffset <= Buffer.size() && StartOffset < EndOffset)
|
|
624 HI.Definition =
|
|
625 ("#define " + Buffer.substr(StartOffset, EndOffset - StartOffset))
|
|
626 .str();
|
|
627 }
|
|
628 }
|
|
629 return HI;
|
|
630 }
|
|
631
|
221
|
632 llvm::Optional<HoverInfo> getThisExprHoverContents(const CXXThisExpr *CTE,
|
|
633 ASTContext &ASTCtx,
|
|
634 const PrintingPolicy &PP) {
|
|
635 QualType OriginThisType = CTE->getType()->getPointeeType();
|
|
636 QualType ClassType = declaredType(OriginThisType->getAsTagDecl());
|
|
637 // For partial specialization class, origin `this` pointee type will be
|
|
638 // parsed as `InjectedClassNameType`, which will ouput template arguments
|
|
639 // like "type-parameter-0-0". So we retrieve user written class type in this
|
|
640 // case.
|
|
641 QualType PrettyThisType = ASTCtx.getPointerType(
|
|
642 QualType(ClassType.getTypePtr(), OriginThisType.getCVRQualifiers()));
|
|
643
|
|
644 HoverInfo HI;
|
|
645 HI.Name = "this";
|
|
646 HI.Definition = printType(PrettyThisType, PP);
|
|
647 return HI;
|
|
648 }
|
|
649
|
|
650 /// Generate a HoverInfo object given the deduced type \p QT
|
|
651 HoverInfo getDeducedTypeHoverContents(QualType QT, const syntax::Token &Tok,
|
|
652 ASTContext &ASTCtx,
|
|
653 const PrintingPolicy &PP,
|
|
654 const SymbolIndex *Index) {
|
|
655 HoverInfo HI;
|
|
656 // FIXME: distinguish decltype(auto) vs decltype(expr)
|
|
657 HI.Name = tok::getTokenName(Tok.kind());
|
|
658 HI.Kind = index::SymbolKind::TypeAlias;
|
|
659
|
|
660 if (QT->isUndeducedAutoType()) {
|
|
661 HI.Definition = "/* not deduced */";
|
|
662 } else {
|
|
663 HI.Definition = printType(QT, PP);
|
|
664
|
|
665 if (const auto *D = QT->getAsTagDecl()) {
|
|
666 const auto *CommentD = getDeclForComment(D);
|
|
667 HI.Documentation = getDeclComment(ASTCtx, *CommentD);
|
|
668 enhanceFromIndex(HI, *CommentD, Index);
|
|
669 }
|
|
670 }
|
|
671
|
|
672 return HI;
|
|
673 }
|
|
674
|
150
|
675 bool isLiteral(const Expr *E) {
|
|
676 // Unfortunately there's no common base Literal classes inherits from
|
221
|
677 // (apart from Expr), therefore these exclusions.
|
150
|
678 return llvm::isa<CharacterLiteral>(E) || llvm::isa<CompoundLiteralExpr>(E) ||
|
|
679 llvm::isa<CXXBoolLiteralExpr>(E) ||
|
|
680 llvm::isa<CXXNullPtrLiteralExpr>(E) ||
|
|
681 llvm::isa<FixedPointLiteral>(E) || llvm::isa<FloatingLiteral>(E) ||
|
|
682 llvm::isa<ImaginaryLiteral>(E) || llvm::isa<IntegerLiteral>(E) ||
|
|
683 llvm::isa<StringLiteral>(E) || llvm::isa<UserDefinedLiteral>(E);
|
|
684 }
|
|
685
|
|
686 llvm::StringLiteral getNameForExpr(const Expr *E) {
|
|
687 // FIXME: Come up with names for `special` expressions.
|
|
688 //
|
|
689 // It's an known issue for GCC5, https://godbolt.org/z/Z_tbgi. Work around
|
|
690 // that by using explicit conversion constructor.
|
|
691 //
|
|
692 // TODO: Once GCC5 is fully retired and not the minimal requirement as stated
|
|
693 // in `GettingStarted`, please remove the explicit conversion constructor.
|
|
694 return llvm::StringLiteral("expression");
|
|
695 }
|
|
696
|
221
|
697 // Generates hover info for `this` and evaluatable expressions.
|
150
|
698 // FIXME: Support hover for literals (esp user-defined)
|
221
|
699 llvm::Optional<HoverInfo> getHoverContents(const Expr *E, ParsedAST &AST,
|
|
700 const PrintingPolicy &PP,
|
|
701 const SymbolIndex *Index) {
|
150
|
702 // There's not much value in hovering over "42" and getting a hover card
|
|
703 // saying "42 is an int", similar for other literals.
|
|
704 if (isLiteral(E))
|
|
705 return llvm::None;
|
|
706
|
|
707 HoverInfo HI;
|
221
|
708 // For `this` expr we currently generate hover with pointee type.
|
|
709 if (const CXXThisExpr *CTE = dyn_cast<CXXThisExpr>(E))
|
|
710 return getThisExprHoverContents(CTE, AST.getASTContext(), PP);
|
150
|
711 // For expressions we currently print the type and the value, iff it is
|
|
712 // evaluatable.
|
|
713 if (auto Val = printExprValue(E, AST.getASTContext())) {
|
221
|
714 HI.Type = printType(E->getType(), PP);
|
150
|
715 HI.Value = *Val;
|
|
716 HI.Name = std::string(getNameForExpr(E));
|
|
717 return HI;
|
|
718 }
|
|
719 return llvm::None;
|
|
720 }
|
173
|
721
|
|
722 bool isParagraphBreak(llvm::StringRef Rest) {
|
|
723 return Rest.ltrim(" \t").startswith("\n");
|
|
724 }
|
|
725
|
|
726 bool punctuationIndicatesLineBreak(llvm::StringRef Line) {
|
|
727 constexpr llvm::StringLiteral Punctuation = R"txt(.:,;!?)txt";
|
|
728
|
|
729 Line = Line.rtrim();
|
|
730 return !Line.empty() && Punctuation.contains(Line.back());
|
|
731 }
|
|
732
|
|
733 bool isHardLineBreakIndicator(llvm::StringRef Rest) {
|
|
734 // '-'/'*' md list, '@'/'\' documentation command, '>' md blockquote,
|
|
735 // '#' headings, '`' code blocks
|
|
736 constexpr llvm::StringLiteral LinebreakIndicators = R"txt(-*@\>#`)txt";
|
|
737
|
|
738 Rest = Rest.ltrim(" \t");
|
|
739 if (Rest.empty())
|
|
740 return false;
|
|
741
|
|
742 if (LinebreakIndicators.contains(Rest.front()))
|
|
743 return true;
|
|
744
|
|
745 if (llvm::isDigit(Rest.front())) {
|
|
746 llvm::StringRef AfterDigit = Rest.drop_while(llvm::isDigit);
|
|
747 if (AfterDigit.startswith(".") || AfterDigit.startswith(")"))
|
|
748 return true;
|
|
749 }
|
|
750 return false;
|
|
751 }
|
|
752
|
|
753 bool isHardLineBreakAfter(llvm::StringRef Line, llvm::StringRef Rest) {
|
|
754 // Should we also consider whether Line is short?
|
|
755 return punctuationIndicatesLineBreak(Line) || isHardLineBreakIndicator(Rest);
|
|
756 }
|
|
757
|
|
758 void addLayoutInfo(const NamedDecl &ND, HoverInfo &HI) {
|
221
|
759 if (ND.isInvalidDecl())
|
|
760 return;
|
|
761
|
173
|
762 const auto &Ctx = ND.getASTContext();
|
|
763 if (auto *RD = llvm::dyn_cast<RecordDecl>(&ND)) {
|
|
764 if (auto Size = Ctx.getTypeSizeInCharsIfKnown(RD->getTypeForDecl()))
|
|
765 HI.Size = Size->getQuantity();
|
|
766 return;
|
|
767 }
|
|
768
|
|
769 if (const auto *FD = llvm::dyn_cast<FieldDecl>(&ND)) {
|
|
770 const auto *Record = FD->getParent();
|
|
771 if (Record)
|
|
772 Record = Record->getDefinition();
|
221
|
773 if (Record && !Record->isInvalidDecl() && !Record->isDependentType()) {
|
|
774 HI.Offset = Ctx.getFieldOffset(FD) / 8;
|
|
775 if (auto Size = Ctx.getTypeSizeInCharsIfKnown(FD->getType()))
|
173
|
776 HI.Size = Size->getQuantity();
|
|
777 }
|
|
778 return;
|
|
779 }
|
|
780 }
|
|
781
|
221
|
782 // If N is passed as argument to a function, fill HI.CalleeArgInfo with
|
|
783 // information about that argument.
|
|
784 void maybeAddCalleeArgInfo(const SelectionTree::Node *N, HoverInfo &HI,
|
|
785 const PrintingPolicy &PP) {
|
|
786 const auto &OuterNode = N->outerImplicit();
|
|
787 if (!OuterNode.Parent)
|
|
788 return;
|
|
789 const auto *CE = OuterNode.Parent->ASTNode.get<CallExpr>();
|
|
790 if (!CE)
|
|
791 return;
|
|
792 const FunctionDecl *FD = CE->getDirectCallee();
|
|
793 // For non-function-call-like operatators (e.g. operator+, operator<<) it's
|
|
794 // not immediattely obvious what the "passed as" would refer to and, given
|
|
795 // fixed function signature, the value would be very low anyway, so we choose
|
|
796 // to not support that.
|
|
797 // Both variadic functions and operator() (especially relevant for lambdas)
|
|
798 // should be supported in the future.
|
|
799 if (!FD || FD->isOverloadedOperator() || FD->isVariadic())
|
|
800 return;
|
|
801
|
|
802 // Find argument index for N.
|
|
803 for (unsigned I = 0; I < CE->getNumArgs() && I < FD->getNumParams(); ++I) {
|
|
804 if (CE->getArg(I) != OuterNode.ASTNode.get<Expr>())
|
|
805 continue;
|
|
806
|
|
807 // Extract matching argument from function declaration.
|
|
808 if (const ParmVarDecl *PVD = FD->getParamDecl(I))
|
|
809 HI.CalleeArgInfo.emplace(toHoverInfoParam(PVD, PP));
|
|
810 break;
|
|
811 }
|
|
812 if (!HI.CalleeArgInfo)
|
|
813 return;
|
|
814
|
|
815 // If we found a matching argument, also figure out if it's a
|
|
816 // [const-]reference. For this we need to walk up the AST from the arg itself
|
|
817 // to CallExpr and check all implicit casts, constructor calls, etc.
|
|
818 HoverInfo::PassType PassType;
|
|
819 if (const auto *E = N->ASTNode.get<Expr>()) {
|
|
820 if (E->getType().isConstQualified())
|
|
821 PassType.PassBy = HoverInfo::PassType::ConstRef;
|
|
822 }
|
|
823
|
|
824 for (auto *CastNode = N->Parent;
|
|
825 CastNode != OuterNode.Parent && !PassType.Converted;
|
|
826 CastNode = CastNode->Parent) {
|
|
827 if (const auto *ImplicitCast = CastNode->ASTNode.get<ImplicitCastExpr>()) {
|
|
828 switch (ImplicitCast->getCastKind()) {
|
|
829 case CK_NoOp:
|
|
830 case CK_DerivedToBase:
|
|
831 case CK_UncheckedDerivedToBase:
|
|
832 // If it was a reference before, it's still a reference.
|
|
833 if (PassType.PassBy != HoverInfo::PassType::Value)
|
|
834 PassType.PassBy = ImplicitCast->getType().isConstQualified()
|
|
835 ? HoverInfo::PassType::ConstRef
|
|
836 : HoverInfo::PassType::Ref;
|
|
837 break;
|
|
838 case CK_LValueToRValue:
|
|
839 case CK_ArrayToPointerDecay:
|
|
840 case CK_FunctionToPointerDecay:
|
|
841 case CK_NullToPointer:
|
|
842 case CK_NullToMemberPointer:
|
|
843 // No longer a reference, but we do not show this as type conversion.
|
|
844 PassType.PassBy = HoverInfo::PassType::Value;
|
|
845 break;
|
|
846 default:
|
|
847 PassType.PassBy = HoverInfo::PassType::Value;
|
|
848 PassType.Converted = true;
|
|
849 break;
|
|
850 }
|
|
851 } else if (const auto *CtorCall =
|
|
852 CastNode->ASTNode.get<CXXConstructExpr>()) {
|
|
853 // We want to be smart about copy constructors. They should not show up as
|
|
854 // type conversion, but instead as passing by value.
|
|
855 if (CtorCall->getConstructor()->isCopyConstructor())
|
|
856 PassType.PassBy = HoverInfo::PassType::Value;
|
|
857 else
|
|
858 PassType.Converted = true;
|
|
859 } else { // Unknown implicit node, assume type conversion.
|
|
860 PassType.PassBy = HoverInfo::PassType::Value;
|
|
861 PassType.Converted = true;
|
|
862 }
|
|
863 }
|
|
864
|
|
865 HI.CallPassType.emplace(PassType);
|
|
866 }
|
|
867
|
150
|
868 } // namespace
|
|
869
|
|
870 llvm::Optional<HoverInfo> getHover(ParsedAST &AST, Position Pos,
|
|
871 format::FormatStyle Style,
|
|
872 const SymbolIndex *Index) {
|
221
|
873 PrintingPolicy PP =
|
|
874 getPrintingPolicy(AST.getASTContext().getPrintingPolicy());
|
150
|
875 const SourceManager &SM = AST.getSourceManager();
|
173
|
876 auto CurLoc = sourceLocationInMainFile(SM, Pos);
|
|
877 if (!CurLoc) {
|
|
878 llvm::consumeError(CurLoc.takeError());
|
|
879 return llvm::None;
|
|
880 }
|
|
881 const auto &TB = AST.getTokens();
|
|
882 auto TokensTouchingCursor = syntax::spelledTokensTouching(*CurLoc, TB);
|
|
883 // Early exit if there were no tokens around the cursor.
|
|
884 if (TokensTouchingCursor.empty())
|
|
885 return llvm::None;
|
150
|
886
|
173
|
887 // To be used as a backup for highlighting the selected token, we use back as
|
|
888 // it aligns better with biases elsewhere (editors tend to send the position
|
|
889 // for the left of the hovered token).
|
|
890 CharSourceRange HighlightRange =
|
|
891 TokensTouchingCursor.back().range(SM).toCharRange(SM);
|
|
892 llvm::Optional<HoverInfo> HI;
|
|
893 // Macros and deducedtype only works on identifiers and auto/decltype keywords
|
|
894 // respectively. Therefore they are only trggered on whichever works for them,
|
|
895 // similar to SelectionTree::create().
|
|
896 for (const auto &Tok : TokensTouchingCursor) {
|
|
897 if (Tok.kind() == tok::identifier) {
|
|
898 // Prefer the identifier token as a fallback highlighting range.
|
|
899 HighlightRange = Tok.range(SM).toCharRange(SM);
|
|
900 if (auto M = locateMacroAt(Tok, AST.getPreprocessor())) {
|
|
901 HI = getHoverContents(*M, AST);
|
|
902 break;
|
|
903 }
|
|
904 } else if (Tok.kind() == tok::kw_auto || Tok.kind() == tok::kw_decltype) {
|
|
905 if (auto Deduced = getDeducedType(AST.getASTContext(), Tok.location())) {
|
221
|
906 HI = getDeducedTypeHoverContents(*Deduced, Tok, AST.getASTContext(), PP,
|
|
907 Index);
|
173
|
908 HighlightRange = Tok.range(SM).toCharRange(SM);
|
|
909 break;
|
|
910 }
|
221
|
911
|
|
912 // If we can't find interesting hover information for this
|
|
913 // auto/decltype keyword, return nothing to avoid showing
|
|
914 // irrelevant or incorrect informations.
|
|
915 return llvm::None;
|
150
|
916 }
|
173
|
917 }
|
|
918
|
|
919 // If it wasn't auto/decltype or macro, look for decls and expressions.
|
|
920 if (!HI) {
|
|
921 auto Offset = SM.getFileOffset(*CurLoc);
|
|
922 // Editors send the position on the left of the hovered character.
|
|
923 // So our selection tree should be biased right. (Tested with VSCode).
|
|
924 SelectionTree ST =
|
|
925 SelectionTree::createRight(AST.getASTContext(), TB, Offset, Offset);
|
150
|
926 std::vector<const Decl *> Result;
|
173
|
927 if (const SelectionTree::Node *N = ST.commonAncestor()) {
|
|
928 // FIXME: Fill in HighlightRange with range coming from N->ASTNode.
|
221
|
929 auto Decls = explicitReferenceTargets(N->ASTNode, DeclRelation::Alias,
|
|
930 AST.getHeuristicResolver());
|
150
|
931 if (!Decls.empty()) {
|
221
|
932 HI = getHoverContents(Decls.front(), PP, Index);
|
173
|
933 // Layout info only shown when hovering on the field/class itself.
|
|
934 if (Decls.front() == N->ASTNode.get<Decl>())
|
|
935 addLayoutInfo(*Decls.front(), *HI);
|
150
|
936 // Look for a close enclosing expression to show the value of.
|
|
937 if (!HI->Value)
|
|
938 HI->Value = printExprValue(N, AST.getASTContext());
|
221
|
939 maybeAddCalleeArgInfo(N, *HI, PP);
|
150
|
940 } else if (const Expr *E = N->ASTNode.get<Expr>()) {
|
221
|
941 HI = getHoverContents(E, AST, PP, Index);
|
150
|
942 }
|
|
943 // FIXME: support hovers for other nodes?
|
|
944 // - built-in types
|
|
945 }
|
|
946 }
|
|
947
|
|
948 if (!HI)
|
|
949 return llvm::None;
|
|
950
|
|
951 auto Replacements = format::reformat(
|
|
952 Style, HI->Definition, tooling::Range(0, HI->Definition.size()));
|
|
953 if (auto Formatted =
|
|
954 tooling::applyAllReplacements(HI->Definition, Replacements))
|
|
955 HI->Definition = *Formatted;
|
173
|
956 HI->SymRange = halfOpenToRange(SM, HighlightRange);
|
150
|
957
|
|
958 return HI;
|
|
959 }
|
|
960
|
|
961 markup::Document HoverInfo::present() const {
|
|
962 markup::Document Output;
|
|
963 // Header contains a text of the form:
|
|
964 // variable `var`
|
|
965 //
|
|
966 // class `X`
|
|
967 //
|
|
968 // function `foo`
|
|
969 //
|
|
970 // expression
|
|
971 //
|
|
972 // Note that we are making use of a level-3 heading because VSCode renders
|
|
973 // level 1 and 2 headers in a huge font, see
|
|
974 // https://github.com/microsoft/vscode/issues/88417 for details.
|
|
975 markup::Paragraph &Header = Output.addHeading(3);
|
|
976 if (Kind != index::SymbolKind::Unknown)
|
173
|
977 Header.appendText(index::getSymbolKindString(Kind)).appendSpace();
|
150
|
978 assert(!Name.empty() && "hover triggered on a nameless symbol");
|
|
979 Header.appendCode(Name);
|
|
980
|
|
981 // Put a linebreak after header to increase readability.
|
|
982 Output.addRuler();
|
|
983 // Print Types on their own lines to reduce chances of getting line-wrapped by
|
|
984 // editor, as they might be long.
|
|
985 if (ReturnType) {
|
|
986 // For functions we display signature in a list form, e.g.:
|
|
987 // → `x`
|
|
988 // Parameters:
|
|
989 // - `bool param1`
|
|
990 // - `int param2 = 5`
|
173
|
991 Output.addParagraph().appendText("→ ").appendCode(*ReturnType);
|
150
|
992 if (Parameters && !Parameters->empty()) {
|
173
|
993 Output.addParagraph().appendText("Parameters: ");
|
150
|
994 markup::BulletList &L = Output.addBulletList();
|
|
995 for (const auto &Param : *Parameters) {
|
|
996 std::string Buffer;
|
|
997 llvm::raw_string_ostream OS(Buffer);
|
|
998 OS << Param;
|
|
999 L.addItem().addParagraph().appendCode(std::move(OS.str()));
|
|
1000 }
|
|
1001 }
|
|
1002 } else if (Type) {
|
|
1003 Output.addParagraph().appendText("Type: ").appendCode(*Type);
|
|
1004 }
|
|
1005
|
|
1006 if (Value) {
|
|
1007 markup::Paragraph &P = Output.addParagraph();
|
173
|
1008 P.appendText("Value = ");
|
150
|
1009 P.appendCode(*Value);
|
|
1010 }
|
|
1011
|
173
|
1012 if (Offset)
|
|
1013 Output.addParagraph().appendText(
|
|
1014 llvm::formatv("Offset: {0} byte{1}", *Offset, *Offset == 1 ? "" : "s")
|
|
1015 .str());
|
|
1016 if (Size)
|
|
1017 Output.addParagraph().appendText(
|
|
1018 llvm::formatv("Size: {0} byte{1}", *Size, *Size == 1 ? "" : "s").str());
|
|
1019
|
221
|
1020 if (CalleeArgInfo) {
|
|
1021 assert(CallPassType);
|
|
1022 std::string Buffer;
|
|
1023 llvm::raw_string_ostream OS(Buffer);
|
|
1024 OS << "Passed ";
|
|
1025 if (CallPassType->PassBy != HoverInfo::PassType::Value) {
|
|
1026 OS << "by ";
|
|
1027 if (CallPassType->PassBy == HoverInfo::PassType::ConstRef)
|
|
1028 OS << "const ";
|
|
1029 OS << "reference ";
|
|
1030 }
|
|
1031 if (CalleeArgInfo->Name)
|
|
1032 OS << "as " << CalleeArgInfo->Name;
|
|
1033 if (CallPassType->Converted && CalleeArgInfo->Type)
|
|
1034 OS << " (converted to " << CalleeArgInfo->Type << ")";
|
|
1035 Output.addParagraph().appendText(OS.str());
|
|
1036 }
|
|
1037
|
150
|
1038 if (!Documentation.empty())
|
173
|
1039 parseDocumentation(Documentation, Output);
|
150
|
1040
|
|
1041 if (!Definition.empty()) {
|
|
1042 Output.addRuler();
|
|
1043 std::string ScopeComment;
|
|
1044 // Drop trailing "::".
|
|
1045 if (!LocalScope.empty()) {
|
|
1046 // Container name, e.g. class, method, function.
|
173
|
1047 // We might want to propagate some info about container type to print
|
150
|
1048 // function foo, class X, method X::bar, etc.
|
|
1049 ScopeComment =
|
|
1050 "// In " + llvm::StringRef(LocalScope).rtrim(':').str() + '\n';
|
|
1051 } else if (NamespaceScope && !NamespaceScope->empty()) {
|
|
1052 ScopeComment = "// In namespace " +
|
|
1053 llvm::StringRef(*NamespaceScope).rtrim(':').str() + '\n';
|
|
1054 }
|
221
|
1055 std::string DefinitionWithAccess = !AccessSpecifier.empty()
|
|
1056 ? AccessSpecifier + ": " + Definition
|
|
1057 : Definition;
|
150
|
1058 // Note that we don't print anything for global namespace, to not annoy
|
|
1059 // non-c++ projects or projects that are not making use of namespaces.
|
221
|
1060 Output.addCodeBlock(ScopeComment + DefinitionWithAccess);
|
150
|
1061 }
|
221
|
1062
|
150
|
1063 return Output;
|
|
1064 }
|
|
1065
|
173
|
1066 // If the backtick at `Offset` starts a probable quoted range, return the range
|
|
1067 // (including the quotes).
|
|
1068 llvm::Optional<llvm::StringRef> getBacktickQuoteRange(llvm::StringRef Line,
|
|
1069 unsigned Offset) {
|
|
1070 assert(Line[Offset] == '`');
|
|
1071
|
|
1072 // The open-quote is usually preceded by whitespace.
|
|
1073 llvm::StringRef Prefix = Line.substr(0, Offset);
|
|
1074 constexpr llvm::StringLiteral BeforeStartChars = " \t(=";
|
|
1075 if (!Prefix.empty() && !BeforeStartChars.contains(Prefix.back()))
|
|
1076 return llvm::None;
|
|
1077
|
|
1078 // The quoted string must be nonempty and usually has no leading/trailing ws.
|
|
1079 auto Next = Line.find('`', Offset + 1);
|
|
1080 if (Next == llvm::StringRef::npos)
|
|
1081 return llvm::None;
|
|
1082 llvm::StringRef Contents = Line.slice(Offset + 1, Next);
|
|
1083 if (Contents.empty() || isWhitespace(Contents.front()) ||
|
|
1084 isWhitespace(Contents.back()))
|
|
1085 return llvm::None;
|
|
1086
|
|
1087 // The close-quote is usually followed by whitespace or punctuation.
|
|
1088 llvm::StringRef Suffix = Line.substr(Next + 1);
|
|
1089 constexpr llvm::StringLiteral AfterEndChars = " \t)=.,;:";
|
|
1090 if (!Suffix.empty() && !AfterEndChars.contains(Suffix.front()))
|
|
1091 return llvm::None;
|
|
1092
|
221
|
1093 return Line.slice(Offset, Next + 1);
|
173
|
1094 }
|
|
1095
|
|
1096 void parseDocumentationLine(llvm::StringRef Line, markup::Paragraph &Out) {
|
|
1097 // Probably this is appendText(Line), but scan for something interesting.
|
|
1098 for (unsigned I = 0; I < Line.size(); ++I) {
|
|
1099 switch (Line[I]) {
|
221
|
1100 case '`':
|
|
1101 if (auto Range = getBacktickQuoteRange(Line, I)) {
|
|
1102 Out.appendText(Line.substr(0, I));
|
|
1103 Out.appendCode(Range->trim("`"), /*Preserve=*/true);
|
|
1104 return parseDocumentationLine(Line.substr(I + Range->size()), Out);
|
|
1105 }
|
|
1106 break;
|
173
|
1107 }
|
|
1108 }
|
|
1109 Out.appendText(Line).appendSpace();
|
|
1110 }
|
|
1111
|
|
1112 void parseDocumentation(llvm::StringRef Input, markup::Document &Output) {
|
|
1113 std::vector<llvm::StringRef> ParagraphLines;
|
|
1114 auto FlushParagraph = [&] {
|
|
1115 if (ParagraphLines.empty())
|
|
1116 return;
|
|
1117 auto &P = Output.addParagraph();
|
|
1118 for (llvm::StringRef Line : ParagraphLines)
|
|
1119 parseDocumentationLine(Line, P);
|
|
1120 ParagraphLines.clear();
|
|
1121 };
|
|
1122
|
|
1123 llvm::StringRef Line, Rest;
|
|
1124 for (std::tie(Line, Rest) = Input.split('\n');
|
|
1125 !(Line.empty() && Rest.empty());
|
|
1126 std::tie(Line, Rest) = Rest.split('\n')) {
|
|
1127
|
|
1128 // After a linebreak remove spaces to avoid 4 space markdown code blocks.
|
|
1129 // FIXME: make FlushParagraph handle this.
|
|
1130 Line = Line.ltrim();
|
|
1131 if (!Line.empty())
|
|
1132 ParagraphLines.push_back(Line);
|
|
1133
|
|
1134 if (isParagraphBreak(Rest) || isHardLineBreakAfter(Line, Rest)) {
|
|
1135 FlushParagraph();
|
|
1136 }
|
|
1137 }
|
|
1138 FlushParagraph();
|
|
1139 }
|
|
1140
|
150
|
1141 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
|
|
1142 const HoverInfo::Param &P) {
|
|
1143 std::vector<llvm::StringRef> Output;
|
|
1144 if (P.Type)
|
|
1145 Output.push_back(*P.Type);
|
|
1146 if (P.Name)
|
|
1147 Output.push_back(*P.Name);
|
|
1148 OS << llvm::join(Output, " ");
|
|
1149 if (P.Default)
|
|
1150 OS << " = " << *P.Default;
|
|
1151 return OS;
|
|
1152 }
|
|
1153
|
|
1154 } // namespace clangd
|
|
1155 } // namespace clang
|