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