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