20#include "clang-include-cleaner/Analysis.h"
21#include "clang-include-cleaner/IncludeSpeller.h"
22#include "clang-include-cleaner/Types.h"
26#include "clang/AST/ASTContext.h"
27#include "clang/AST/ASTDiagnostic.h"
28#include "clang/AST/ASTTypeTraits.h"
29#include "clang/AST/Attr.h"
30#include "clang/AST/Decl.h"
31#include "clang/AST/DeclBase.h"
32#include "clang/AST/DeclCXX.h"
33#include "clang/AST/DeclObjC.h"
34#include "clang/AST/DeclTemplate.h"
35#include "clang/AST/Expr.h"
36#include "clang/AST/ExprCXX.h"
37#include "clang/AST/OperationKinds.h"
38#include "clang/AST/PrettyPrinter.h"
39#include "clang/AST/RecordLayout.h"
40#include "clang/AST/Type.h"
41#include "clang/Basic/CharInfo.h"
42#include "clang/Basic/LLVM.h"
43#include "clang/Basic/SourceLocation.h"
44#include "clang/Basic/SourceManager.h"
45#include "clang/Basic/Specifiers.h"
46#include "clang/Basic/TokenKinds.h"
47#include "clang/Index/IndexSymbol.h"
48#include "clang/Tooling/Syntax/Tokens.h"
49#include "llvm/ADT/ArrayRef.h"
50#include "llvm/ADT/DenseSet.h"
51#include "llvm/ADT/STLExtras.h"
52#include "llvm/ADT/SmallVector.h"
53#include "llvm/ADT/StringExtras.h"
54#include "llvm/ADT/StringRef.h"
55#include "llvm/Support/Casting.h"
56#include "llvm/Support/Error.h"
57#include "llvm/Support/Format.h"
58#include "llvm/Support/ScopedPrinter.h"
59#include "llvm/Support/raw_ostream.h"
69PrintingPolicy getPrintingPolicy(PrintingPolicy Base) {
70 Base.AnonymousTagLocations =
false;
71 Base.TerseOutput =
true;
72 Base.PolishForDeclaration =
true;
73 Base.ConstantsAsWritten =
true;
74 Base.SuppressTemplateArgsInCXXConstructors =
true;
81std::string getLocalScope(
const Decl *D) {
82 std::vector<std::string> Scopes;
83 const DeclContext *DC = D->getDeclContext();
88 if (
const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
90 if (
const ObjCContainerDecl *CD = dyn_cast<ObjCContainerDecl>(DC))
93 auto GetName = [](
const TypeDecl *D) {
94 if (!D->getDeclName().isEmpty()) {
95 PrintingPolicy Policy = D->getASTContext().getPrintingPolicy();
96 Policy.SuppressScope =
true;
99 if (
auto *RD = dyn_cast<RecordDecl>(D))
100 return (
"(anonymous " + RD->getKindName() +
")").str();
101 return std::string(
"");
104 if (
const TypeDecl *TD = dyn_cast<TypeDecl>(DC))
105 Scopes.push_back(GetName(TD));
106 else if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
107 Scopes.push_back(FD->getNameAsString());
108 DC = DC->getParent();
111 return llvm::join(llvm::reverse(Scopes),
"::");
116std::string getNamespaceScope(
const Decl *D) {
117 const DeclContext *DC = D->getDeclContext();
121 if (isa<ObjCMethodDecl, ObjCContainerDecl>(DC))
124 if (
const TagDecl *TD = dyn_cast<TagDecl>(DC))
125 return getNamespaceScope(TD);
126 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
127 return getNamespaceScope(FD);
128 if (
const NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(DC)) {
130 if (NSD->isInline() || NSD->isAnonymousNamespace())
131 return getNamespaceScope(NSD);
133 if (
const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
139std::string printDefinition(
const Decl *D, PrintingPolicy PP,
140 const syntax::TokenBuffer &TB) {
141 if (
auto *VD = llvm::dyn_cast<VarDecl>(D)) {
142 if (
auto *IE = VD->getInit()) {
146 if (200 < TB.expandedTokens(IE->getSourceRange()).size())
147 PP.SuppressInitializers =
true;
156const char *getMarkdownLanguage(
const ASTContext &Ctx) {
157 const auto &LangOpts = Ctx.getLangOpts();
158 if (LangOpts.ObjC && LangOpts.CPlusPlus)
159 return "objective-cpp";
160 return LangOpts.ObjC ?
"objective-c" :
"cpp";
163HoverInfo::PrintedType
printType(QualType QT, ASTContext &ASTCtx,
164 const PrintingPolicy &PP) {
168 while (!QT.isNull() && QT->isDecltypeType())
169 QT = QT->castAs<DecltypeType>()->getUnderlyingType();
170 HoverInfo::PrintedType Result;
171 llvm::raw_string_ostream
OS(Result.Type);
176 if (!QT.isNull() && !QT.hasQualifiers() && PP.SuppressTagKeyword) {
177 if (
auto *TT = llvm::dyn_cast<TagType>(QT.getTypePtr()))
178 OS << TT->getDecl()->getKindName() <<
" ";
184 bool ShouldAKA =
false;
185 QualType DesugaredTy = clang::desugarForDiagnostic(ASTCtx, QT, ShouldAKA);
187 Result.AKA = DesugaredTy.getAsString(PP);
192HoverInfo::PrintedType
printType(
const TemplateTypeParmDecl *TTP) {
193 HoverInfo::PrintedType Result;
194 Result.Type = TTP->wasDeclaredWithTypename() ?
"typename" :
"class";
195 if (TTP->isParameterPack())
196 Result.Type +=
"...";
200HoverInfo::PrintedType
printType(
const NonTypeTemplateParmDecl *NTTP,
201 const PrintingPolicy &PP) {
202 auto PrintedType =
printType(NTTP->getType(), NTTP->getASTContext(), PP);
203 if (NTTP->isParameterPack()) {
204 PrintedType.Type +=
"...";
206 *PrintedType.AKA +=
"...";
211HoverInfo::PrintedType
printType(
const TemplateTemplateParmDecl *TTP,
212 const PrintingPolicy &PP) {
213 HoverInfo::PrintedType Result;
214 llvm::raw_string_ostream
OS(Result.Type);
216 llvm::StringRef Sep =
"";
217 for (
const Decl *Param : *TTP->getTemplateParameters()) {
220 if (
const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
222 else if (
const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
224 else if (
const auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param))
233std::vector<HoverInfo::Param>
234fetchTemplateParameters(
const TemplateParameterList *Params,
235 const PrintingPolicy &PP) {
237 std::vector<HoverInfo::Param> TempParameters;
239 for (
const Decl *Param : *Params) {
241 if (
const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
244 if (!TTP->getName().empty())
245 P.Name = TTP->getNameAsString();
247 if (TTP->hasDefaultArgument()) {
249 llvm::raw_string_ostream
Out(*P.Default);
250 TTP->getDefaultArgument().getArgument().print(PP,
Out,
253 }
else if (
const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
256 if (IdentifierInfo *II = NTTP->getIdentifier())
257 P.Name = II->getName().str();
259 if (NTTP->hasDefaultArgument()) {
261 llvm::raw_string_ostream
Out(*P.Default);
262 NTTP->getDefaultArgument().getArgument().print(PP,
Out,
265 }
else if (
const auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param)) {
268 if (!TTPD->getName().empty())
269 P.Name = TTPD->getNameAsString();
271 if (TTPD->hasDefaultArgument()) {
273 llvm::raw_string_ostream
Out(*P.Default);
274 TTPD->getDefaultArgument().getArgument().print(PP,
Out,
278 TempParameters.push_back(std::move(P));
281 return TempParameters;
284const FunctionDecl *getUnderlyingFunction(
const Decl *D) {
286 if (
const VarDecl *VD = llvm::dyn_cast<VarDecl>(D)) {
287 auto QT = VD->getType();
289 while (!QT->getPointeeType().isNull())
290 QT = QT->getPointeeType();
292 if (
const auto *CD = QT->getAsCXXRecordDecl())
293 return CD->getLambdaCallOperator();
298 return D->getAsFunction();
303const NamedDecl *getDeclForComment(
const NamedDecl *D) {
304 const NamedDecl *DeclForComment = D;
305 if (
const auto *TSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(D)) {
308 if (TSD->getTemplateSpecializationKind() == TSK_Undeclared)
309 DeclForComment = TSD->getSpecializedTemplate();
310 else if (
const auto *TIP = TSD->getTemplateInstantiationPattern())
311 DeclForComment = TIP;
312 }
else if (
const auto *TSD =
313 llvm::dyn_cast<VarTemplateSpecializationDecl>(D)) {
314 if (TSD->getTemplateSpecializationKind() == TSK_Undeclared)
315 DeclForComment = TSD->getSpecializedTemplate();
316 else if (
const auto *TIP = TSD->getTemplateInstantiationPattern())
317 DeclForComment = TIP;
318 }
else if (
const auto *FD = D->getAsFunction())
319 if (
const auto *TIP = FD->getTemplateInstantiationPattern())
320 DeclForComment = TIP;
325 if (D != DeclForComment)
326 DeclForComment = getDeclForComment(DeclForComment);
327 return DeclForComment;
331void enhanceFromIndex(HoverInfo &Hover,
const NamedDecl &ND,
332 const SymbolIndex *Index) {
333 assert(&ND == getDeclForComment(&ND));
335 if (!Hover.Documentation.empty() || !Index)
341 SymbolCollector::Options(),
349 Index->lookup(Req, [&](
const Symbol &S) {
350 Hover.Documentation = std::string(S.Documentation);
357const Expr *getDefaultArg(
const ParmVarDecl *PVD) {
362 if (!PVD->hasDefaultArg() || PVD->hasUnparsedDefaultArg())
364 return PVD->hasUninstantiatedDefaultArg() ? PVD->getUninstantiatedDefaultArg()
365 : PVD->getDefaultArg();
368HoverInfo::Param toHoverInfoParam(
const ParmVarDecl *PVD,
369 const PrintingPolicy &PP) {
370 HoverInfo::Param
Out;
371 Out.Type =
printType(PVD->getType(), PVD->getASTContext(), PP);
372 if (!PVD->getName().empty())
373 Out.Name = PVD->getNameAsString();
374 if (
const Expr *DefArg = getDefaultArg(PVD)) {
375 Out.Default.emplace();
376 llvm::raw_string_ostream
OS(*
Out.Default);
377 DefArg->printPretty(
OS,
nullptr, PP);
383void fillFunctionTypeAndParams(HoverInfo &HI,
const Decl *D,
384 const FunctionDecl *FD,
385 const PrintingPolicy &PP) {
386 HI.Parameters.emplace();
387 for (
const ParmVarDecl *PVD : FD->parameters())
388 HI.Parameters->emplace_back(toHoverInfoParam(PVD, PP));
392 const auto NK = FD->getDeclName().getNameKind();
393 if (NK == DeclarationName::CXXConstructorName ||
394 NK == DeclarationName::CXXDestructorName ||
395 NK == DeclarationName::CXXConversionFunctionName)
398 HI.ReturnType =
printType(FD->getReturnType(), FD->getASTContext(), PP);
399 QualType QT = FD->getType();
400 if (
const VarDecl *VD = llvm::dyn_cast<VarDecl>(D))
401 QT = VD->getType().getDesugaredType(D->getASTContext());
402 HI.Type =
printType(QT, D->getASTContext(), PP);
412static llvm::FormattedNumber printHex(
const llvm::APSInt &V) {
413 assert(V.getSignificantBits() <= 64 &&
"Can't print more than 64 bits.");
415 V.getBitWidth() > 64 ? V.trunc(64).getZExtValue() : V.getZExtValue();
416 if (V.isNegative() && V.getSignificantBits() <= 32)
417 return llvm::format_hex(uint32_t(Bits), 0);
418 return llvm::format_hex(Bits, 0);
421std::optional<std::string> printExprValue(
const Expr *
E,
422 const ASTContext &Ctx) {
427 if (
const auto *ILE = llvm::dyn_cast<InitListExpr>(
E)) {
428 if (!ILE->isSemanticForm())
429 E = ILE->getSemanticForm();
435 QualType
T =
E->getType();
436 if (
T.isNull() ||
T->isFunctionType() ||
T->isFunctionPointerType() ||
437 T->isFunctionReferenceType() ||
T->isVoidType())
442 if (
E->isValueDependent() || !
E->EvaluateAsRValue(
Constant, Ctx) ||
449 if (
T->isEnumeralType() &&
Constant.Val.isInt() &&
450 Constant.Val.getInt().getSignificantBits() <= 64) {
452 int64_t Val =
Constant.Val.getInt().getExtValue();
453 for (
const EnumConstantDecl *ECD :
454 T->castAs<EnumType>()->getDecl()->enumerators())
455 if (ECD->getInitVal() == Val)
456 return llvm::formatv(
"{0} ({1})", ECD->getNameAsString(),
461 if (
T->isIntegralOrEnumerationType() &&
Constant.Val.isInt() &&
462 Constant.Val.getInt().getSignificantBits() <= 64 &&
464 return llvm::formatv(
"{0} ({1})",
Constant.Val.getAsString(Ctx, T),
467 return Constant.Val.getAsString(Ctx, T);
470struct PrintExprResult {
485PrintExprResult printExprValue(
const SelectionTree::Node *N,
486 const ASTContext &Ctx) {
487 for (; N; N = N->Parent) {
489 if (
const Expr *
E = N->ASTNode.get<Expr>()) {
492 if (!
E->getType().isNull() &&
E->getType()->isVoidType())
494 if (
auto Val = printExprValue(
E, Ctx))
495 return PrintExprResult{std::move(Val),
E,
497 }
else if (N->ASTNode.get<
Decl>() || N->ASTNode.get<Stmt>()) {
503 return PrintExprResult{std::nullopt,
nullptr,
507std::optional<StringRef> fieldName(
const Expr *
E) {
508 const auto *ME = llvm::dyn_cast<MemberExpr>(
E->IgnoreCasts());
509 if (!ME || !llvm::isa<CXXThisExpr>(ME->getBase()->IgnoreCasts()))
511 const auto *
Field = llvm::dyn_cast<FieldDecl>(ME->getMemberDecl());
512 if (!
Field || !
Field->getDeclName().isIdentifier())
514 return Field->getDeclName().getAsIdentifierInfo()->getName();
518std::optional<StringRef> getterVariableName(
const CXXMethodDecl *CMD) {
519 assert(CMD->hasBody());
520 if (CMD->getNumParams() != 0 || CMD->isVariadic())
522 const auto *Body = llvm::dyn_cast<CompoundStmt>(CMD->getBody());
523 const auto *OnlyReturn = (Body && Body->size() == 1)
524 ? llvm::dyn_cast<ReturnStmt>(Body->body_front())
526 if (!OnlyReturn || !OnlyReturn->getRetValue())
528 return fieldName(OnlyReturn->getRetValue());
537std::optional<StringRef> setterVariableName(
const CXXMethodDecl *CMD) {
538 assert(CMD->hasBody());
539 if (CMD->isConst() || CMD->getNumParams() != 1 || CMD->isVariadic())
541 const ParmVarDecl *Arg = CMD->getParamDecl(0);
542 if (Arg->isParameterPack())
545 const auto *Body = llvm::dyn_cast<CompoundStmt>(CMD->getBody());
546 if (!Body || Body->size() == 0 || Body->size() > 2)
549 if (Body->size() == 2) {
550 auto *Ret = llvm::dyn_cast<ReturnStmt>(Body->body_back());
551 if (!Ret || !Ret->getRetValue())
553 const Expr *RetVal = Ret->getRetValue()->IgnoreCasts();
554 if (
const auto *UO = llvm::dyn_cast<UnaryOperator>(RetVal)) {
555 if (UO->getOpcode() != UO_Deref)
557 RetVal = UO->getSubExpr()->IgnoreCasts();
559 if (!llvm::isa<CXXThisExpr>(RetVal))
563 const Expr *LHS, *RHS;
564 if (
const auto *BO = llvm::dyn_cast<BinaryOperator>(Body->body_front())) {
565 if (BO->getOpcode() != BO_Assign)
569 }
else if (
const auto *COCE =
570 llvm::dyn_cast<CXXOperatorCallExpr>(Body->body_front())) {
571 if (COCE->getOperator() != OO_Equal || COCE->getNumArgs() != 2)
573 LHS = COCE->getArg(0);
574 RHS = COCE->getArg(1);
580 if (
auto *
CE = llvm::dyn_cast<CallExpr>(RHS->IgnoreCasts())) {
581 if (
CE->getNumArgs() != 1)
583 auto *ND = llvm::dyn_cast_or_null<NamedDecl>(
CE->getCalleeDecl());
584 if (!ND || !ND->getIdentifier() || ND->getName() !=
"move" ||
585 !ND->isInStdNamespace())
590 auto *DRE = llvm::dyn_cast<DeclRefExpr>(RHS->IgnoreCasts());
591 if (!DRE || DRE->getDecl() != Arg)
593 return fieldName(LHS);
596std::string synthesizeDocumentation(
const NamedDecl *ND) {
597 if (
const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(ND)) {
599 if (CMD->getDeclName().isIdentifier() && !CMD->isStatic() &&
600 (CMD = llvm::dyn_cast_or_null<CXXMethodDecl>(CMD->getDefinition())) &&
602 if (
const auto GetterField = getterVariableName(CMD))
603 return llvm::formatv(
"Trivial accessor for `{0}`.", *GetterField);
604 if (
const auto SetterField = setterVariableName(CMD))
605 return llvm::formatv(
"Trivial setter for `{0}`.", *SetterField);
612HoverInfo getHoverContents(
const NamedDecl *D,
const PrintingPolicy &PP,
613 const SymbolIndex *Index,
614 const syntax::TokenBuffer &TB) {
616 auto &Ctx = D->getASTContext();
618 HI.AccessSpecifier = getAccessSpelling(D->getAccess()).str();
619 HI.NamespaceScope = getNamespaceScope(D);
620 if (!HI.NamespaceScope->empty())
621 HI.NamespaceScope->append(
"::");
622 HI.LocalScope = getLocalScope(D);
623 if (!HI.LocalScope.empty())
624 HI.LocalScope.append(
"::");
627 const auto *CommentD = getDeclForComment(D);
629 enhanceFromIndex(HI, *CommentD, Index);
630 if (HI.Documentation.empty())
631 HI.Documentation = synthesizeDocumentation(D);
633 HI.Kind = index::getSymbolInfo(D).Kind;
636 if (
const TemplateDecl *TD = D->getDescribedTemplate()) {
637 HI.TemplateParameters =
638 fetchTemplateParameters(TD->getTemplateParameters(), PP);
640 }
else if (
const FunctionDecl *FD = D->getAsFunction()) {
641 if (
const auto *FTD = FD->getDescribedTemplate()) {
642 HI.TemplateParameters =
643 fetchTemplateParameters(FTD->getTemplateParameters(), PP);
649 if (
const FunctionDecl *FD = getUnderlyingFunction(D))
650 fillFunctionTypeAndParams(HI, D, FD, PP);
651 else if (
const auto *VD = dyn_cast<ValueDecl>(D))
652 HI.Type =
printType(VD->getType(), Ctx, PP);
653 else if (
const auto *TTP = dyn_cast<TemplateTypeParmDecl>(D))
654 HI.Type = TTP->wasDeclaredWithTypename() ?
"typename" :
"class";
655 else if (
const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(D))
657 else if (
const auto *VT = dyn_cast<VarTemplateDecl>(D))
658 HI.Type =
printType(VT->getTemplatedDecl()->getType(), Ctx, PP);
659 else if (
const auto *TN = dyn_cast<TypedefNameDecl>(D))
660 HI.Type =
printType(TN->getUnderlyingType().getDesugaredType(Ctx), Ctx, PP);
661 else if (
const auto *TAT = dyn_cast<TypeAliasTemplateDecl>(D))
662 HI.Type =
printType(TAT->getTemplatedDecl()->getUnderlyingType(), Ctx, PP);
665 if (
const auto *Var = dyn_cast<VarDecl>(D); Var && !Var->isInvalidDecl()) {
666 if (
const Expr *Init = Var->getInit())
667 HI.Value = printExprValue(Init, Ctx);
668 }
else if (
const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
670 if (!ECD->getType()->isDependentType())
671 HI.Value =
toString(ECD->getInitVal(), 10);
674 HI.Definition = printDefinition(D, PP, TB);
679std::optional<HoverInfo>
680getPredefinedExprHoverContents(
const PredefinedExpr &PE, ASTContext &Ctx,
681 const PrintingPolicy &PP) {
683 HI.Name = PE.getIdentKindName();
684 HI.Kind = index::SymbolKind::Variable;
685 HI.Documentation =
"Name of the current function (predefined variable)";
686 if (
const StringLiteral *
Name = PE.getFunctionName()) {
688 llvm::raw_string_ostream
OS(*HI.Value);
693 QualType StringType = Ctx.getIncompleteArrayType(Ctx.CharTy.withConst(),
694 ArraySizeModifier::Normal,
696 HI.Type =
printType(StringType, Ctx, PP);
701HoverInfo evaluateMacroExpansion(
unsigned int SpellingBeginOffset,
702 unsigned int SpellingEndOffset,
703 llvm::ArrayRef<syntax::Token> Expanded,
705 auto &Context =
AST.getASTContext();
706 auto &Tokens =
AST.getTokens();
707 auto PP = getPrintingPolicy(Context.getPrintingPolicy());
716 if (Expanded.size() == 1)
717 if (tok::getPunctuatorSpelling(Expanded[0].kind()))
720 auto *StartNode = Tree.commonAncestor();
731 if (!StartNode->Children.empty())
736 auto ExprResult = printExprValue(StartNode, Context);
737 HI.Value = std::move(ExprResult.PrintedValue);
738 if (
auto *
E = ExprResult.TheExpr)
739 HI.Type =
printType(
E->getType(), Context, PP);
742 if (!HI.Value && !HI.Type && ExprResult.TheNode)
743 if (
auto *VD = ExprResult.TheNode->ASTNode.get<VarDecl>())
744 HI.Type =
printType(VD->getType(), Context, PP);
750HoverInfo getHoverContents(
const DefinedMacro &
Macro,
const syntax::Token &Tok,
753 SourceManager &SM =
AST.getSourceManager();
754 HI.Name = std::string(
Macro.Name);
755 HI.Kind = index::SymbolKind::Macro;
760 SourceLocation StartLoc =
Macro.Info->getDefinitionLoc();
761 SourceLocation EndLoc =
Macro.Info->getDefinitionEndLoc();
769 if (SM.getPresumedLoc(EndLoc,
false).isValid()) {
770 EndLoc = Lexer::getLocForEndOfToken(EndLoc, 0, SM,
AST.getLangOpts());
772 StringRef Buffer = SM.getBufferData(SM.getFileID(StartLoc), &Invalid);
774 unsigned StartOffset = SM.getFileOffset(StartLoc);
775 unsigned EndOffset = SM.getFileOffset(EndLoc);
776 if (EndOffset <= Buffer.size() && StartOffset < EndOffset)
778 (
"#define " + Buffer.substr(StartOffset, EndOffset - StartOffset))
783 if (
auto Expansion =
AST.getTokens().expansionStartingAt(&Tok)) {
787 std::string ExpansionText;
788 for (
const auto &ExpandedTok : Expansion->Expanded) {
789 ExpansionText += ExpandedTok.text(SM);
790 ExpansionText +=
" ";
791 if (ExpansionText.size() > 2048) {
792 ExpansionText.clear();
797 if (!ExpansionText.empty()) {
798 if (!HI.Definition.empty()) {
799 HI.Definition +=
"\n\n";
801 HI.Definition +=
"// Expands to\n";
802 HI.Definition += ExpansionText;
805 auto Evaluated = evaluateMacroExpansion(
806 SM.getFileOffset(Tok.location()),
807 SM.getFileOffset(Tok.endLocation()),
808 Expansion->Expanded,
AST);
809 HI.Value = std::move(Evaluated.Value);
810 HI.Type = std::move(Evaluated.Type);
815std::string typeAsDefinition(
const HoverInfo::PrintedType &PType) {
817 llvm::raw_string_ostream
OS(Result);
820 OS <<
" // aka: " << *PType.AKA;
824std::optional<HoverInfo> getThisExprHoverContents(
const CXXThisExpr *CTE,
826 const PrintingPolicy &PP) {
827 QualType OriginThisType = CTE->getType()->getPointeeType();
828 QualType ClassType =
declaredType(OriginThisType->getAsTagDecl());
833 QualType PrettyThisType = ASTCtx.getPointerType(
834 QualType(ClassType.getTypePtr(), OriginThisType.getCVRQualifiers()));
838 HI.Definition = typeAsDefinition(
printType(PrettyThisType, ASTCtx, PP));
843HoverInfo getDeducedTypeHoverContents(QualType QT,
const syntax::Token &Tok,
845 const PrintingPolicy &PP,
846 const SymbolIndex *Index) {
849 HI.Name = tok::getTokenName(Tok.kind());
850 HI.Kind = index::SymbolKind::TypeAlias;
852 if (QT->isUndeducedAutoType()) {
853 HI.Definition =
"/* not deduced */";
855 HI.Definition = typeAsDefinition(
printType(QT, ASTCtx, PP));
857 if (
const auto *D = QT->getAsTagDecl()) {
858 const auto *CommentD = getDeclForComment(D);
860 enhanceFromIndex(HI, *CommentD, Index);
867HoverInfo getStringLiteralContents(
const StringLiteral *SL,
868 const PrintingPolicy &PP) {
871 HI.Name =
"string-literal";
872 HI.Size = (SL->getLength() + 1) * SL->getCharByteWidth() * 8;
873 HI.Type = SL->getType().getAsString(PP).c_str();
878bool isLiteral(
const Expr *
E) {
881 return llvm::isa<CompoundLiteralExpr>(
E) ||
882 llvm::isa<CXXBoolLiteralExpr>(
E) ||
883 llvm::isa<CXXNullPtrLiteralExpr>(
E) ||
884 llvm::isa<FixedPointLiteral>(
E) || llvm::isa<FloatingLiteral>(
E) ||
885 llvm::isa<ImaginaryLiteral>(
E) || llvm::isa<IntegerLiteral>(
E) ||
886 llvm::isa<StringLiteral>(
E) || llvm::isa<UserDefinedLiteral>(
E);
889llvm::StringLiteral getNameForExpr(
const Expr *
E) {
897 return llvm::StringLiteral(
"expression");
900void maybeAddCalleeArgInfo(
const SelectionTree::Node *N, HoverInfo &HI,
901 const PrintingPolicy &PP);
905std::optional<HoverInfo> getHoverContents(
const SelectionTree::Node *N,
906 const Expr *
E, ParsedAST &
AST,
907 const PrintingPolicy &PP,
908 const SymbolIndex *Index) {
909 std::optional<HoverInfo> HI;
911 if (
const StringLiteral *SL = dyn_cast<StringLiteral>(
E)) {
913 HI = getStringLiteralContents(SL, PP);
914 }
else if (isLiteral(
E)) {
918 maybeAddCalleeArgInfo(N, HI.emplace(), PP);
919 if (HI->CalleeArgInfo) {
923 HI->Name =
"literal";
930 if (
const CXXThisExpr *CTE = dyn_cast<CXXThisExpr>(
E))
931 HI = getThisExprHoverContents(CTE,
AST.getASTContext(), PP);
932 if (
const PredefinedExpr *PE = dyn_cast<PredefinedExpr>(
E))
933 HI = getPredefinedExprHoverContents(*PE,
AST.getASTContext(), PP);
936 if (
auto Val = printExprValue(
E,
AST.getASTContext())) {
940 HI->Name = std::string(getNameForExpr(
E));
944 maybeAddCalleeArgInfo(N, *HI, PP);
950std::optional<HoverInfo> getHoverContents(
const Attr *A, ParsedAST &
AST) {
952 HI.Name =
A->getSpelling();
954 HI.LocalScope =
A->getScopeName()->getName().str();
956 llvm::raw_string_ostream
OS(HI.Definition);
957 A->printPretty(
OS,
AST.getASTContext().getPrintingPolicy());
959 HI.Documentation = Attr::getDocumentation(
A->getKind()).str();
963bool isParagraphBreak(llvm::StringRef Rest) {
964 return Rest.ltrim(
" \t").starts_with(
"\n");
967bool punctuationIndicatesLineBreak(llvm::StringRef Line) {
968 constexpr llvm::StringLiteral
Punctuation = R
"txt(.:,;!?)txt";
974bool isHardLineBreakIndicator(llvm::StringRef Rest) {
977 constexpr llvm::StringLiteral LinebreakIndicators = R
"txt(-*@>#`)txt";
979 Rest = Rest.ltrim(" \t");
983 if (LinebreakIndicators.contains(Rest.front()))
986 if (llvm::isDigit(Rest.front())) {
987 llvm::StringRef AfterDigit = Rest.drop_while(llvm::isDigit);
988 if (AfterDigit.starts_with(
".") || AfterDigit.starts_with(
")"))
994bool isHardLineBreakAfter(llvm::StringRef Line, llvm::StringRef Rest) {
996 return punctuationIndicatesLineBreak(Line) || isHardLineBreakIndicator(Rest);
999void addLayoutInfo(
const NamedDecl &ND, HoverInfo &HI) {
1000 if (ND.isInvalidDecl())
1003 const auto &Ctx = ND.getASTContext();
1004 if (
auto *RD = llvm::dyn_cast<RecordDecl>(&ND)) {
1005 if (
auto Size = Ctx.getTypeSizeInCharsIfKnown(RD->getTypeForDecl()))
1006 HI.Size = Size->getQuantity() * 8;
1007 if (!RD->isDependentType() && RD->isCompleteDefinition())
1008 HI.Align = Ctx.getTypeAlign(RD->getTypeForDecl());
1012 if (
const auto *FD = llvm::dyn_cast<FieldDecl>(&ND)) {
1013 const auto *
Record = FD->getParent();
1016 if (Record && !
Record->isInvalidDecl() && !
Record->isDependentType()) {
1017 HI.Align = Ctx.getTypeAlign(FD->getType());
1018 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Record);
1019 HI.Offset = Layout.getFieldOffset(FD->getFieldIndex());
1020 if (FD->isBitField())
1021 HI.Size = FD->getBitWidthValue(Ctx);
1022 else if (
auto Size = Ctx.getTypeSizeInCharsIfKnown(FD->getType()))
1023 HI.Size = FD->isZeroSize(Ctx) ? 0 : Size->getQuantity() * 8;
1025 unsigned EndOfField = *HI.Offset + *HI.Size;
1028 if (!
Record->isUnion() &&
1029 FD->getFieldIndex() + 1 < Layout.getFieldCount()) {
1031 unsigned NextOffset = Layout.getFieldOffset(FD->getFieldIndex() + 1);
1032 if (NextOffset >= EndOfField)
1033 HI.Padding = NextOffset - EndOfField;
1036 HI.Padding = Layout.getSize().getQuantity() * 8 - EndOfField;
1048 if (ParmType->isReferenceType()) {
1049 if (ParmType->getPointeeType().isConstQualified())
1058void maybeAddCalleeArgInfo(
const SelectionTree::Node *N, HoverInfo &HI,
1059 const PrintingPolicy &PP) {
1060 const auto &OuterNode = N->outerImplicit();
1061 if (!OuterNode.Parent)
1064 const FunctionDecl *FD =
nullptr;
1065 llvm::ArrayRef<const Expr *>
Args;
1067 if (
const auto *
CE = OuterNode.Parent->ASTNode.get<CallExpr>()) {
1068 FD =
CE->getDirectCallee();
1069 Args = {
CE->getArgs(),
CE->getNumArgs()};
1070 }
else if (
const auto *
CE =
1071 OuterNode.Parent->ASTNode.get<CXXConstructExpr>()) {
1072 FD =
CE->getConstructor();
1073 Args = {
CE->getArgs(),
CE->getNumArgs()};
1084 if (!FD || FD->isOverloadedOperator() || FD->isVariadic())
1087 HoverInfo::PassType PassType;
1092 for (
unsigned I = 0; I <
Args.size() && I <
Parameters.size(); ++I) {
1093 if (
Args[I] != OuterNode.ASTNode.get<Expr>())
1097 if (
const ParmVarDecl *PVD =
Parameters[I]) {
1098 HI.CalleeArgInfo.emplace(toHoverInfoParam(PVD, PP));
1099 if (N == &OuterNode)
1100 PassType.PassBy = getPassMode(PVD->getType());
1104 if (!HI.CalleeArgInfo)
1110 if (
const auto *
E = N->ASTNode.get<Expr>()) {
1111 if (
E->getType().isConstQualified())
1115 for (
auto *CastNode = N->Parent;
1116 CastNode != OuterNode.Parent && !PassType.Converted;
1117 CastNode = CastNode->Parent) {
1118 if (
const auto *ImplicitCast = CastNode->ASTNode.get<ImplicitCastExpr>()) {
1119 switch (ImplicitCast->getCastKind()) {
1121 case CK_DerivedToBase:
1122 case CK_UncheckedDerivedToBase:
1125 PassType.PassBy = ImplicitCast->getType().isConstQualified()
1129 case CK_LValueToRValue:
1130 case CK_ArrayToPointerDecay:
1131 case CK_FunctionToPointerDecay:
1132 case CK_NullToPointer:
1133 case CK_NullToMemberPointer:
1139 PassType.Converted =
true;
1142 }
else if (
const auto *CtorCall =
1143 CastNode->ASTNode.get<CXXConstructExpr>()) {
1146 if (CtorCall->getConstructor()->isCopyConstructor())
1149 PassType.Converted =
true;
1150 }
else if (CastNode->ASTNode.get<MaterializeTemporaryExpr>()) {
1155 PassType.Converted =
true;
1159 HI.CallPassType.emplace(PassType);
1162const NamedDecl *pickDeclToUse(llvm::ArrayRef<const NamedDecl *> Candidates) {
1163 if (Candidates.empty())
1172 if (Candidates.size() <= 2) {
1173 if (llvm::isa<UsingDecl>(Candidates.front()))
1174 return Candidates.back();
1175 return Candidates.front();
1184 auto BaseDecls = llvm::make_filter_range(
1185 Candidates, [](
const NamedDecl *D) {
return llvm::isa<UsingDecl>(D); });
1186 if (std::distance(BaseDecls.begin(), BaseDecls.end()) == 1)
1187 return *BaseDecls.begin();
1189 return Candidates.front();
1192void maybeAddSymbolProviders(ParsedAST &
AST, HoverInfo &HI,
1193 include_cleaner::Symbol Sym) {
1194 trace::Span Tracer(
"Hover::maybeAddSymbolProviders");
1196 const SourceManager &SM =
AST.getSourceManager();
1197 llvm::SmallVector<include_cleaner::Header> RankedProviders =
1198 include_cleaner::headersForSymbol(Sym, SM, &
AST.getPragmaIncludes());
1199 if (RankedProviders.empty())
1204 for (
const auto &P : RankedProviders) {
1205 if (P.kind() == include_cleaner::Header::Physical &&
1206 P.physical() == SM.getFileEntryForID(SM.getMainFileID()))
1211 auto Matches = ConvertedIncludes.match(P);
1212 if (!Matches.empty()) {
1213 Result = Matches[0]->quote();
1218 if (!Result.empty()) {
1219 HI.Provider = std::move(Result);
1224 const auto &H = RankedProviders.front();
1225 if (H.kind() == include_cleaner::Header::Physical &&
1226 H.physical() == SM.getFileEntryForID(SM.getMainFileID()))
1231 HI.Provider = include_cleaner::spellHeader(
1232 {H,
AST.getPreprocessor().getHeaderSearchInfo(),
1233 SM.getFileEntryForID(SM.getMainFileID())});
1239std::string getSymbolName(include_cleaner::Symbol Sym) {
1241 switch (Sym.kind()) {
1242 case include_cleaner::Symbol::Declaration:
1243 if (
const auto *ND = llvm::dyn_cast<NamedDecl>(&Sym.declaration()))
1244 Name = ND->getDeclName().getAsString();
1246 case include_cleaner::Symbol::Macro:
1247 Name = Sym.macro().Name->getName();
1253void maybeAddUsedSymbols(ParsedAST &
AST, HoverInfo &HI,
const Inclusion &Inc) {
1255 llvm::DenseSet<include_cleaner::Symbol> UsedSymbols;
1256 include_cleaner::walkUsed(
1258 &
AST.getPragmaIncludes(),
AST.getPreprocessor(),
1259 [&](
const include_cleaner::SymbolReference &Ref,
1260 llvm::ArrayRef<include_cleaner::Header> Providers) {
1261 if (Ref.RT != include_cleaner::RefType::Explicit ||
1262 UsedSymbols.contains(Ref.Target))
1265 if (isPreferredProvider(Inc, Converted, Providers))
1266 UsedSymbols.insert(Ref.Target);
1269 for (
const auto &UsedSymbolDecl : UsedSymbols)
1270 HI.UsedSymbolNames.push_back(getSymbolName(UsedSymbolDecl));
1271 llvm::sort(HI.UsedSymbolNames);
1272 HI.UsedSymbolNames.erase(
1273 std::unique(HI.UsedSymbolNames.begin(), HI.UsedSymbolNames.end()),
1274 HI.UsedSymbolNames.end());
1280 const format::FormatStyle &Style,
1285 getPrintingPolicy(
AST.getASTContext().getPrintingPolicy());
1286 const SourceManager &SM =
AST.getSourceManager();
1289 llvm::consumeError(CurLoc.takeError());
1290 return std::nullopt;
1292 const auto &TB =
AST.getTokens();
1293 auto TokensTouchingCursor = syntax::spelledTokensTouching(*CurLoc, TB);
1295 if (TokensTouchingCursor.empty())
1296 return std::nullopt;
1299 for (
const auto &Inc :
AST.getIncludeStructure().MainFileIncludes) {
1300 if (Inc.Resolved.empty() || Inc.HashLine !=
Pos.line)
1302 HoverCountMetric.
record(1,
"include");
1304 HI.
Name = std::string(llvm::sys::path::filename(Inc.Resolved));
1309 maybeAddUsedSymbols(
AST, HI, Inc);
1316 CharSourceRange HighlightRange =
1317 TokensTouchingCursor.back().range(SM).toCharRange(SM);
1318 std::optional<HoverInfo> HI;
1322 for (
const auto &Tok : TokensTouchingCursor) {
1323 if (Tok.kind() == tok::identifier) {
1325 HighlightRange = Tok.range(SM).toCharRange(SM);
1327 HoverCountMetric.
record(1,
"macro");
1328 HI = getHoverContents(*
M, Tok,
AST);
1329 if (
auto DefLoc =
M->Info->getDefinitionLoc(); DefLoc.isValid()) {
1330 include_cleaner::Macro IncludeCleanerMacro{
1331 AST.getPreprocessor().getIdentifierInfo(Tok.
text(SM)), DefLoc};
1332 maybeAddSymbolProviders(
AST, *HI,
1333 include_cleaner::Symbol{IncludeCleanerMacro});
1337 }
else if (Tok.kind() == tok::kw_auto || Tok.kind() == tok::kw_decltype) {
1338 HoverCountMetric.
record(1,
"keyword");
1340 HI = getDeducedTypeHoverContents(*
Deduced, Tok,
AST.getASTContext(), PP,
1342 HighlightRange = Tok.range(SM).toCharRange(SM);
1349 return std::nullopt;
1355 auto Offset = SM.getFileOffset(*CurLoc);
1363 AST.getHeuristicResolver());
1364 if (
const auto *DeclToUse = pickDeclToUse(Decls)) {
1365 HoverCountMetric.
record(1,
"decl");
1366 HI = getHoverContents(DeclToUse, PP, Index, TB);
1368 if (DeclToUse == N->ASTNode.get<
Decl>())
1369 addLayoutInfo(*DeclToUse, *HI);
1372 HI->Value = printExprValue(N,
AST.getASTContext()).PrintedValue;
1373 maybeAddCalleeArgInfo(N, *HI, PP);
1375 if (!isa<NamespaceDecl>(DeclToUse))
1376 maybeAddSymbolProviders(
AST, *HI,
1377 include_cleaner::Symbol{*DeclToUse});
1378 }
else if (
const Expr *
E = N->ASTNode.get<Expr>()) {
1379 HoverCountMetric.
record(1,
"expr");
1380 HI = getHoverContents(N,
E,
AST, PP, Index);
1381 }
else if (
const Attr *A = N->ASTNode.get<Attr>()) {
1382 HoverCountMetric.
record(1,
"attribute");
1383 HI = getHoverContents(A,
AST);
1391 return std::nullopt;
1394 if (!HI->Definition.empty()) {
1395 auto Replacements = format::reformat(
1396 Style, HI->Definition, tooling::Range(0, HI->Definition.size()));
1397 if (
auto Formatted =
1398 tooling::applyAllReplacements(HI->Definition, Replacements))
1399 HI->Definition = *Formatted;
1402 HI->DefinitionLanguage = getMarkdownLanguage(
AST.getASTContext());
1410 uint64_t
Value = SizeInBits % 8 == 0 ? SizeInBits / 8 : SizeInBits;
1411 const char *
Unit =
Value != 0 &&
Value == SizeInBits ?
"bit" :
"byte";
1412 return llvm::formatv(
"{0} {1}{2}",
Value,
Unit,
Value == 1 ?
"" :
"s").str();
1418 const auto Bytes = OffsetInBits / 8;
1419 const auto Bits = OffsetInBits % 8;
1442 if (
Kind != index::SymbolKind::Unknown)
1443 Header.appendText(index::getSymbolKindString(
Kind)).appendSpace();
1444 assert(!
Name.empty() &&
"hover triggered on a nameless symbol");
1445 Header.appendCode(
Name);
1465 Output.addParagraph().appendText(
"→ ").appendCode(
1470 Output.addParagraph().appendText(
"Parameters: ");
1473 L.addItem().addParagraph().appendCode(llvm::to_string(
Param));
1479 Output.addParagraph().appendText(
"Type: ").appendCode(
1480 llvm::to_string(*
Type));
1503 llvm::raw_string_ostream
OS(Buffer);
1517 Output.addParagraph().appendText(
OS.str());
1536 "// In " + llvm::StringRef(
LocalScope).rtrim(
':').str() +
'\n';
1538 Buffer +=
"// In namespace " +
1539 llvm::StringRef(*NamespaceScope).rtrim(
':').str() +
'\n';
1557 const std::vector<std::string>::size_type SymbolNamesLimit = 5;
1558 auto Front = llvm::ArrayRef(
UsedSymbolNames).take_front(SymbolNamesLimit);
1561 Front, [&](llvm::StringRef Sym) { P.
appendCode(Sym); },
1580 llvm::StringRef Prefix =
Line.substr(0,
Offset);
1581 constexpr llvm::StringLiteral BeforeStartChars =
" \t(=";
1582 if (!Prefix.empty() && !BeforeStartChars.contains(Prefix.back()))
1583 return std::nullopt;
1587 if (Next == llvm::StringRef::npos)
1588 return std::nullopt;
1589 llvm::StringRef Contents =
Line.slice(
Offset + 1, Next);
1590 if (Contents.empty() || isWhitespace(Contents.front()) ||
1591 isWhitespace(Contents.back()))
1592 return std::nullopt;
1595 llvm::StringRef
Suffix =
Line.substr(Next + 1);
1596 constexpr llvm::StringLiteral AfterEndChars =
" \t)=.,;:";
1597 if (!
Suffix.empty() && !AfterEndChars.contains(
Suffix.front()))
1598 return std::nullopt;
1605 for (
unsigned I = 0; I <
Line.size(); ++I) {
1609 Out.appendText(
Line.substr(0, I));
1610 Out.appendCode(
Range->trim(
"`"),
true);
1616 Out.appendText(
Line).appendSpace();
1620 std::vector<llvm::StringRef> ParagraphLines;
1621 auto FlushParagraph = [&] {
1622 if (ParagraphLines.empty())
1624 auto &P =
Output.addParagraph();
1625 for (llvm::StringRef
Line : ParagraphLines)
1627 ParagraphLines.clear();
1630 llvm::StringRef
Line, Rest;
1631 for (std::tie(
Line, Rest) = Input.split(
'\n');
1632 !(
Line.empty() && Rest.empty());
1633 std::tie(
Line, Rest) = Rest.split(
'\n')) {
1639 ParagraphLines.push_back(
Line);
1641 if (isParagraphBreak(Rest) || isHardLineBreakAfter(
Line, Rest)) {
1652 OS <<
" (aka " << *T.AKA <<
")";
1665 OS <<
" (aka " << *P.
Type->AKA <<
")";
ArrayRef< const ParmVarDecl * > Parameters
const FunctionDecl * Decl
llvm::SmallString< 256U > Name
CompiledFragmentImpl & Out
std::optional< std::string > PrintedValue
The evaluation result on expression Expr.
const SelectionTree::Node * TheNode
The node of selection tree where the traversal stops.
const clang::Expr * TheExpr
The Expr object that represents the closest evaluable expression.
Include Cleaner is clangd functionality for providing diagnostics for misuse of transitive headers an...
const google::protobuf::Message & M
Stores and provides access to parsed AST.
static SelectionTree createRight(ASTContext &AST, const syntax::TokenBuffer &Tokens, unsigned Begin, unsigned End)
const Node * commonAncestor() const
static bool shouldCollectSymbol(const NamedDecl &ND, const ASTContext &ASTCtx, const Options &Opts, bool IsMainFileSymbol)
Returns true is ND should be collected.
Interface for symbol indexes that can be used for searching or matching symbols among a set of symbol...
Represents a sequence of one or more documents.
A format-agnostic representation for structured text.
Represents parts of the markup that can contain strings, like inline code, code block or plain text.
Paragraph & appendText(llvm::StringRef Text)
Append plain text to the end of the string.
Paragraph & appendSpace()
Ensure there is space between the surrounding chunks.
Paragraph & appendCode(llvm::StringRef Code, bool Preserve=false)
Append inline code, this translates to the ` block in markdown.
SmallVector< const ParmVarDecl * > resolveForwardingParameters(const FunctionDecl *D, unsigned MaxDepth)
Recursively resolves the parameters of a FunctionDecl that forwards its parameters to another functio...
std::string printObjCMethod(const ObjCMethodDecl &Method)
Print the Objective-C method name, including the full container name, e.g.
SymbolID getSymbolID(const Decl *D)
Gets the symbol ID for a declaration. Returned SymbolID might be null.
Range halfOpenToRange(const SourceManager &SM, CharSourceRange R)
std::string printType(const QualType QT, const DeclContext &CurContext, const llvm::StringRef Placeholder)
Returns a QualType as string.
std::string printName(const ASTContext &Ctx, const NamedDecl &ND)
Prints unqualified name of the decl for the purpose of displaying it to the user.
std::string getDeclComment(const ASTContext &Ctx, const NamedDecl &Decl)
Similar to getDocComment, but returns the comment for a NamedDecl.
std::string printObjCContainer(const ObjCContainerDecl &C)
Print the Objective-C container name including categories, e.g. MyClass,.
void parseDocumentationLine(llvm::StringRef Line, markup::Paragraph &Out)
std::optional< llvm::StringRef > getBacktickQuoteRange(llvm::StringRef Line, unsigned Offset)
llvm::SmallVector< const NamedDecl *, 1 > explicitReferenceTargets(DynTypedNode N, DeclRelationSet Mask, const HeuristicResolver *Resolver)
Find declarations explicitly referenced in the source code defined by N.
std::vector< include_cleaner::SymbolReference > collectMacroReferences(ParsedAST &AST)
include_cleaner::Includes convertIncludes(const ParsedAST &AST)
Converts the clangd include representation to include-cleaner include representation.
static const char * toString(OffsetEncoding OE)
llvm::raw_ostream & operator<<(llvm::raw_ostream &OS, const CodeCompletion &C)
std::optional< DefinedMacro > locateMacroAt(const syntax::Token &SpelledTok, Preprocessor &PP)
Gets the macro referenced by SpelledTok.
std::optional< HoverInfo > getHover(ParsedAST &AST, Position Pos, const format::FormatStyle &Style, const SymbolIndex *Index)
Get the hover information when hovering at Pos.
static std::string formatOffset(uint64_t OffsetInBits)
static std::string formatSize(uint64_t SizeInBits)
llvm::Expected< SourceLocation > sourceLocationInMainFile(const SourceManager &SM, Position P)
Return the file location, corresponding to P.
QualType declaredType(const TypeDecl *D)
void parseDocumentation(llvm::StringRef Input, markup::Document &Output)
std::string printQualifiedName(const NamedDecl &ND)
Returns the qualified name of ND.
@ Alias
This declaration is an alias that was referred to.
std::optional< QualType > getDeducedType(ASTContext &ASTCtx, SourceLocation Loc)
Retrieves the deduced type at a given location (auto, decltype).
llvm::SmallVector< uint64_t, 1024 > Record
@ Invalid
Sentinel bit pattern. DO NOT USE!
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
static const Config & current()
Returns the Config of the current Context, or an empty configuration.
bool ShowAKA
Whether hover show a.k.a type.
struct clang::clangd::Config::@7 Hover
Configures hover feature.
Represents parameters of a function, a template or a macro.
std::optional< PrintedType > Type
The printable parameter type, e.g.
std::optional< std::string > Default
std::nullopt if no default is provided.
std::optional< std::string > Name
std::nullopt for unnamed parameters.
Contains pretty-printed type and desugared type.
Contains detailed information about a Symbol.
std::optional< PrintedType > ReturnType
Set for functions and lambdas.
std::optional< uint64_t > Padding
Contains the padding following a field within the enclosing class.
std::optional< uint64_t > Offset
Contains the offset of fields within the enclosing class.
std::string Provider
Header providing the symbol (best match). Contains ""<>.
std::optional< PassType > CallPassType
std::optional< std::vector< Param > > Parameters
Set for functions, lambdas and macros with parameters.
const char * DefinitionLanguage
std::string Name
Name of the symbol, does not contain any "::".
std::optional< PrintedType > Type
Printable variable type.
markup::Document present() const
Produce a user-readable information.
std::optional< uint64_t > Align
Contains the alignment of fields and types where it's interesting.
std::optional< uint64_t > Size
Contains the bit-size of fields and types where it's interesting.
std::vector< std::string > UsedSymbolNames
std::optional< std::string > Value
Contains the evaluated value of the symbol if available.
std::string Definition
Source code containing the definition of the symbol.
std::optional< std::string > NamespaceScope
For a variable named Bar, declared in clang::clangd::Foo::getFoo the following fields will hold:
std::string Documentation
std::string AccessSpecifier
Access specifier for declarations inside class/struct/unions, empty for others.
std::optional< Param > CalleeArgInfo
std::string LocalScope
Remaining named contexts in symbol's qualified name, empty string means symbol is not local.
StringRef text() const
The token text.
static URIForFile canonicalize(llvm::StringRef AbsPath, llvm::StringRef TUPath)
Canonicalizes AbsPath via URI.
llvm::StringRef file() const
Retrieves absolute path to the file.
Represents measurements of clangd events, e.g.
@ Counter
An aggregate number whose rate of change over time is meaningful.
void record(double Value, llvm::StringRef Label="") const
Records a measurement for this metric to active tracer.