22#include "clang-include-cleaner/Analysis.h"
23#include "clang-include-cleaner/IncludeSpeller.h"
24#include "clang-include-cleaner/Types.h"
28#include "clang/AST/ASTContext.h"
29#include "clang/AST/ASTDiagnostic.h"
30#include "clang/AST/ASTTypeTraits.h"
31#include "clang/AST/Attr.h"
32#include "clang/AST/Decl.h"
33#include "clang/AST/DeclBase.h"
34#include "clang/AST/DeclCXX.h"
35#include "clang/AST/DeclObjC.h"
36#include "clang/AST/DeclTemplate.h"
37#include "clang/AST/Expr.h"
38#include "clang/AST/ExprCXX.h"
39#include "clang/AST/OperationKinds.h"
40#include "clang/AST/PrettyPrinter.h"
41#include "clang/AST/RecordLayout.h"
42#include "clang/AST/Type.h"
43#include "clang/Basic/CharInfo.h"
44#include "clang/Basic/LLVM.h"
45#include "clang/Basic/LangOptions.h"
46#include "clang/Basic/SourceLocation.h"
47#include "clang/Basic/SourceManager.h"
48#include "clang/Basic/Specifiers.h"
49#include "clang/Basic/TokenKinds.h"
50#include "clang/Index/IndexSymbol.h"
51#include "clang/Tooling/Syntax/Tokens.h"
52#include "llvm/ADT/ArrayRef.h"
53#include "llvm/ADT/DenseSet.h"
54#include "llvm/ADT/STLExtras.h"
55#include "llvm/ADT/SmallVector.h"
56#include "llvm/ADT/StringExtras.h"
57#include "llvm/ADT/StringRef.h"
58#include "llvm/Support/Casting.h"
59#include "llvm/Support/Error.h"
60#include "llvm/Support/Format.h"
61#include "llvm/Support/ScopedPrinter.h"
62#include "llvm/Support/raw_ostream.h"
72PrintingPolicy getPrintingPolicy(PrintingPolicy Base) {
73 Base.AnonymousTagNameStyle =
74 llvm::to_underlying(PrintingPolicy::AnonymousTagMode::Plain);
75 Base.TerseOutput =
true;
76 Base.PolishForDeclaration =
true;
77 Base.ConstantsAsWritten =
true;
78 Base.SuppressTemplateArgsInCXXConstructors =
true;
85std::string getLocalScope(
const Decl *D) {
86 std::vector<std::string> Scopes;
87 const DeclContext *DC =
D->getDeclContext();
92 if (
const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
94 if (
const ObjCContainerDecl *CD = dyn_cast<ObjCContainerDecl>(DC))
97 auto GetName = [](
const TypeDecl *
D) {
98 if (!
D->getDeclName().isEmpty()) {
99 PrintingPolicy Policy =
D->getASTContext().getPrintingPolicy();
100 Policy.SuppressScope =
true;
103 if (
auto *RD = dyn_cast<RecordDecl>(D))
104 return (
"(anonymous " + RD->getKindName() +
")").str();
105 return std::string(
"");
108 if (
const TypeDecl *TD = dyn_cast<TypeDecl>(DC))
109 Scopes.push_back(GetName(TD));
110 else if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
111 Scopes.push_back(FD->getNameAsString());
112 DC = DC->getParent();
115 return llvm::join(llvm::reverse(Scopes),
"::");
120std::string getNamespaceScope(
const Decl *D) {
121 const DeclContext *DC =
D->getDeclContext();
125 if (isa<ObjCMethodDecl, ObjCContainerDecl>(DC))
128 if (
const TagDecl *TD = dyn_cast<TagDecl>(DC))
129 return getNamespaceScope(TD);
130 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
131 return getNamespaceScope(FD);
132 if (
const NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(DC)) {
134 if (NSD->isInline() || NSD->isAnonymousNamespace())
135 return getNamespaceScope(NSD);
137 if (
const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
143std::string printDefinition(
const Decl *D, PrintingPolicy PP,
144 const syntax::TokenBuffer &TB) {
145 if (
auto *VD = llvm::dyn_cast<VarDecl>(D)) {
146 if (
auto *IE = VD->getInit()) {
150 if (200 < TB.expandedTokens(IE->getSourceRange()).size())
151 PP.SuppressInitializers =
true;
160const char *getMarkdownLanguage(
const ASTContext &Ctx) {
161 const auto &LangOpts = Ctx.getLangOpts();
162 if (LangOpts.ObjC && LangOpts.CPlusPlus)
163 return "objective-cpp";
164 return LangOpts.ObjC ?
"objective-c" :
"cpp";
168 const PrintingPolicy &PP) {
172 while (!QT.isNull() && QT->isDecltypeType())
173 QT = QT->castAs<DecltypeType>()->getUnderlyingType();
175 llvm::raw_string_ostream OS(Result.Type);
180 PrintingPolicy Copy(PP);
181 if (!QT.isNull() && !QT.hasQualifiers() && PP.SuppressTagKeyword) {
182 if (
auto *TT = llvm::dyn_cast<TagType>(QT.getTypePtr());
183 TT && TT->isCanonicalUnqualified()) {
184 Copy.SuppressTagKeywordInAnonNames =
true;
185 OS << TT->getDecl()->getKindName() <<
" ";
191 if (!QT.isNull() && Cfg.Hover.ShowAKA) {
192 bool ShouldAKA =
false;
193 QualType DesugaredTy = clang::desugarForDiagnostic(ASTCtx, QT, ShouldAKA);
195 Result.AKA = DesugaredTy.getAsString(Copy);
202 Result.
Type = TTP->wasDeclaredWithTypename() ?
"typename" :
"class";
203 if (TTP->isParameterPack())
204 Result.Type +=
"...";
209 const PrintingPolicy &PP) {
210 auto PrintedType =
printType(NTTP->getType(), NTTP->getASTContext(), PP);
211 if (NTTP->isParameterPack()) {
212 PrintedType.Type +=
"...";
214 *PrintedType.AKA +=
"...";
220 const PrintingPolicy &PP) {
222 llvm::raw_string_ostream OS(Result.Type);
224 llvm::StringRef Sep =
"";
225 for (
const Decl *Param : *TTP->getTemplateParameters()) {
228 if (
const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
230 else if (
const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
232 else if (
const auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param))
241std::vector<HoverInfo::Param>
242fetchTemplateParameters(
const TemplateParameterList *Params,
243 const PrintingPolicy &PP) {
245 std::vector<HoverInfo::Param> TempParameters;
247 for (
const Decl *Param : *Params) {
249 if (
const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
252 if (!TTP->getName().empty())
253 P.Name = TTP->getNameAsString();
255 if (TTP->hasDefaultArgument()) {
257 llvm::raw_string_ostream Out(*
P.Default);
258 TTP->getDefaultArgument().getArgument().print(PP, Out,
261 }
else if (
const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
264 if (IdentifierInfo *II = NTTP->getIdentifier())
265 P.Name = II->getName().str();
267 if (NTTP->hasDefaultArgument()) {
269 llvm::raw_string_ostream Out(*
P.Default);
270 NTTP->getDefaultArgument().getArgument().print(PP, Out,
273 }
else if (
const auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param)) {
276 if (!TTPD->getName().empty())
277 P.Name = TTPD->getNameAsString();
279 if (TTPD->hasDefaultArgument()) {
281 llvm::raw_string_ostream Out(*
P.Default);
282 TTPD->getDefaultArgument().getArgument().print(PP, Out,
286 TempParameters.push_back(std::move(P));
289 return TempParameters;
292const FunctionDecl *getUnderlyingFunction(
const Decl *D) {
294 if (
const VarDecl *VD = llvm::dyn_cast<VarDecl>(D)) {
295 auto QT = VD->getType();
297 while (!QT->getPointeeType().isNull())
298 QT = QT->getPointeeType();
300 if (
const auto *CD = QT->getAsCXXRecordDecl())
301 return CD->getLambdaCallOperator();
306 return D->getAsFunction();
311const NamedDecl *getDeclForComment(
const NamedDecl *D) {
312 const NamedDecl *DeclForComment =
D;
313 if (
const auto *TSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(D)) {
316 if (TSD->getTemplateSpecializationKind() == TSK_Undeclared)
317 DeclForComment = TSD->getSpecializedTemplate();
318 else if (
const auto *TIP = TSD->getTemplateInstantiationPattern())
319 DeclForComment = TIP;
320 }
else if (
const auto *TSD =
321 llvm::dyn_cast<VarTemplateSpecializationDecl>(D)) {
322 if (TSD->getTemplateSpecializationKind() == TSK_Undeclared)
323 DeclForComment = TSD->getSpecializedTemplate();
324 else if (
const auto *TIP = TSD->getTemplateInstantiationPattern())
325 DeclForComment = TIP;
326 }
else if (
const auto *FD =
D->getAsFunction())
327 if (
const auto *TIP = FD->getTemplateInstantiationPattern())
328 DeclForComment = TIP;
333 if (D != DeclForComment)
334 DeclForComment = getDeclForComment(DeclForComment);
335 return DeclForComment;
341 assert(&ND == getDeclForComment(&ND));
343 if (!
Hover.Documentation.empty() || !Index)
357 Index->lookup(Req, [&](
const Symbol &S) {
358 Hover.Documentation = std::string(S.Documentation);
365const Expr *getDefaultArg(
const ParmVarDecl *PVD) {
370 if (!PVD->hasDefaultArg() || PVD->hasUnparsedDefaultArg())
372 return PVD->hasUninstantiatedDefaultArg() ? PVD->getUninstantiatedDefaultArg()
373 : PVD->getDefaultArg();
377 const PrintingPolicy &PP) {
379 Out.
Type =
printType(PVD->getType(), PVD->getASTContext(), PP);
380 if (!PVD->getName().empty())
381 Out.Name = PVD->getNameAsString();
382 if (
const Expr *DefArg = getDefaultArg(PVD)) {
383 Out.Default.emplace();
384 llvm::raw_string_ostream OS(*Out.Default);
385 DefArg->printPretty(OS,
nullptr, PP);
391void fillFunctionTypeAndParams(
HoverInfo &HI,
const Decl *D,
392 const FunctionDecl *FD,
393 const PrintingPolicy &PP) {
394 HI.Parameters.emplace();
395 for (
const ParmVarDecl *PVD : FD->parameters())
396 HI.Parameters->emplace_back(toHoverInfoParam(PVD, PP));
400 const auto NK = FD->getDeclName().getNameKind();
401 if (NK == DeclarationName::CXXConstructorName ||
402 NK == DeclarationName::CXXDestructorName ||
403 NK == DeclarationName::CXXConversionFunctionName)
406 HI.ReturnType =
printType(FD->getReturnType(), FD->getASTContext(), PP);
407 QualType QT = FD->getType();
408 if (
const VarDecl *VD = llvm::dyn_cast<VarDecl>(D))
409 QT = VD->getType().getDesugaredType(
D->getASTContext());
410 HI.Type =
printType(QT,
D->getASTContext(), PP);
420static llvm::FormattedNumber printHex(
const llvm::APSInt &V) {
421 assert(V.getSignificantBits() <= 64 &&
"Can't print more than 64 bits.");
423 V.getBitWidth() > 64 ? V.trunc(64).getZExtValue() : V.getZExtValue();
424 if (V.isNegative() && V.getSignificantBits() <= 32)
425 return llvm::format_hex(uint32_t(Bits), 0);
426 return llvm::format_hex(Bits, 0);
429std::optional<std::string> printExprValue(
const Expr *E,
430 const ASTContext &Ctx) {
435 if (
const auto *ILE = llvm::dyn_cast<InitListExpr>(E)) {
436 if (!ILE->isSemanticForm())
437 E = ILE->getSemanticForm();
443 QualType
T = E->getType();
444 if (
T.isNull() ||
T->isFunctionType() ||
T->isFunctionPointerType() ||
445 T->isFunctionReferenceType() ||
T->isVoidType())
450 if (E->isValueDependent() || !E->EvaluateAsRValue(
Constant, Ctx) ||
457 if (
T->isEnumeralType() &&
Constant.Val.isInt() &&
458 Constant.Val.getInt().getSignificantBits() <= 64) {
460 int64_t Val =
Constant.Val.getInt().getExtValue();
461 for (
const EnumConstantDecl *ECD :
T->castAsEnumDecl()->enumerators())
462 if (ECD->getInitVal() == Val)
463 return llvm::formatv(
"{0} ({1})", ECD->getNameAsString(),
468 if (
T->isIntegralOrEnumerationType() &&
Constant.Val.isInt() &&
469 Constant.Val.getInt().getSignificantBits() <= 64 &&
471 return llvm::formatv(
"{0} ({1})",
Constant.Val.getAsString(Ctx, T),
474 return Constant.Val.getAsString(Ctx, T);
477struct PrintExprResult {
479 std::optional<std::string> PrintedValue;
482 const clang::Expr *TheExpr;
484 const SelectionTree::Node *TheNode;
493 const ASTContext &Ctx) {
494 for (; N; N = N->Parent) {
496 if (
const Expr *E = N->ASTNode.get<Expr>()) {
499 if (!E->getType().isNull() && E->getType()->isVoidType())
501 if (
auto Val = printExprValue(E, Ctx))
502 return PrintExprResult{std::move(Val), E,
504 }
else if (N->ASTNode.get<Decl>() || N->ASTNode.get<Stmt>()) {
510 return PrintExprResult{std::nullopt,
nullptr,
514std::optional<StringRef> fieldName(
const Expr *E) {
515 const auto *ME = llvm::dyn_cast<MemberExpr>(E->IgnoreCasts());
516 if (!ME || !llvm::isa<CXXThisExpr>(ME->getBase()->IgnoreCasts()))
518 const auto *
Field = llvm::dyn_cast<FieldDecl>(ME->getMemberDecl());
519 if (!
Field || !
Field->getDeclName().isIdentifier())
521 return Field->getDeclName().getAsIdentifierInfo()->getName();
525std::optional<StringRef> getterVariableName(
const CXXMethodDecl *CMD) {
526 assert(CMD->hasBody());
527 if (CMD->getNumParams() != 0 || CMD->isVariadic())
529 const auto *Body = llvm::dyn_cast<CompoundStmt>(CMD->getBody());
530 const auto *OnlyReturn = (Body && Body->size() == 1)
531 ? llvm::dyn_cast<ReturnStmt>(Body->body_front())
533 if (!OnlyReturn || !OnlyReturn->getRetValue())
535 return fieldName(OnlyReturn->getRetValue());
544std::optional<StringRef> setterVariableName(
const CXXMethodDecl *CMD) {
545 assert(CMD->hasBody());
546 if (CMD->isConst() || CMD->getNumParams() != 1 || CMD->isVariadic())
548 const ParmVarDecl *Arg = CMD->getParamDecl(0);
549 if (Arg->isParameterPack())
552 const auto *Body = llvm::dyn_cast<CompoundStmt>(CMD->getBody());
553 if (!Body || Body->size() == 0 || Body->size() > 2)
556 if (Body->size() == 2) {
557 auto *Ret = llvm::dyn_cast<ReturnStmt>(Body->body_back());
558 if (!Ret || !Ret->getRetValue())
560 const Expr *RetVal = Ret->getRetValue()->IgnoreCasts();
561 if (
const auto *UO = llvm::dyn_cast<UnaryOperator>(RetVal)) {
562 if (UO->getOpcode() != UO_Deref)
564 RetVal = UO->getSubExpr()->IgnoreCasts();
566 if (!llvm::isa<CXXThisExpr>(RetVal))
570 const Expr *LHS, *RHS;
571 if (
const auto *BO = llvm::dyn_cast<BinaryOperator>(Body->body_front())) {
572 if (BO->getOpcode() != BO_Assign)
576 }
else if (
const auto *COCE =
577 llvm::dyn_cast<CXXOperatorCallExpr>(Body->body_front())) {
578 if (COCE->getOperator() != OO_Equal || COCE->getNumArgs() != 2)
580 LHS = COCE->getArg(0);
581 RHS = COCE->getArg(1);
587 if (
auto *CE = llvm::dyn_cast<CallExpr>(RHS->IgnoreCasts())) {
588 if (CE->getNumArgs() != 1)
590 auto *ND = llvm::dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl());
591 if (!ND || !ND->getIdentifier() || ND->getName() !=
"move" ||
592 !ND->isInStdNamespace())
597 auto *DRE = llvm::dyn_cast<DeclRefExpr>(RHS->IgnoreCasts());
598 if (!DRE || DRE->getDecl() != Arg)
600 return fieldName(LHS);
603std::string synthesizeDocumentation(
const NamedDecl *ND) {
604 if (
const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(ND)) {
606 if (CMD->getDeclName().isIdentifier() && !CMD->isStatic() &&
607 (CMD = llvm::dyn_cast_or_null<CXXMethodDecl>(CMD->getDefinition())) &&
609 if (
const auto GetterField = getterVariableName(CMD))
610 return llvm::formatv(
"Trivial accessor for `{0}`.", *GetterField);
611 if (
const auto SetterField = setterVariableName(CMD))
612 return llvm::formatv(
"Trivial setter for `{0}`.", *SetterField);
619HoverInfo getHoverContents(
const NamedDecl *D,
const PrintingPolicy &PP,
621 const syntax::TokenBuffer &TB) {
623 auto &Ctx =
D->getASTContext();
625 HI.AccessSpecifier = getAccessSpelling(
D->getAccess()).str();
626 HI.NamespaceScope = getNamespaceScope(D);
627 if (!HI.NamespaceScope->empty())
628 HI.NamespaceScope->append(
"::");
629 HI.LocalScope = getLocalScope(D);
630 if (!HI.LocalScope.empty())
631 HI.LocalScope.append(
"::");
634 const auto *CommentD = getDeclForComment(D);
638 HI.CommentOpts =
D->getASTContext().getLangOpts().CommentOpts;
639 enhanceFromIndex(HI, *CommentD, Index);
640 if (HI.Documentation.empty())
641 HI.Documentation = synthesizeDocumentation(D);
643 HI.Kind = index::getSymbolInfo(D).Kind;
646 if (
const TemplateDecl *TD =
D->getDescribedTemplate()) {
647 HI.TemplateParameters =
648 fetchTemplateParameters(TD->getTemplateParameters(), PP);
650 }
else if (
const FunctionDecl *FD =
D->getAsFunction()) {
651 if (
const auto *FTD = FD->getDescribedTemplate()) {
652 HI.TemplateParameters =
653 fetchTemplateParameters(FTD->getTemplateParameters(), PP);
659 if (
const FunctionDecl *FD = getUnderlyingFunction(D))
660 fillFunctionTypeAndParams(HI, D, FD, PP);
661 else if (
const auto *VD = dyn_cast<ValueDecl>(D))
662 HI.Type =
printType(VD->getType(), Ctx, PP);
663 else if (
const auto *TTP = dyn_cast<TemplateTypeParmDecl>(D))
664 HI.Type = TTP->wasDeclaredWithTypename() ?
"typename" :
"class";
665 else if (
const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(D))
667 else if (
const auto *VT = dyn_cast<VarTemplateDecl>(D))
668 HI.Type =
printType(VT->getTemplatedDecl()->getType(), Ctx, PP);
669 else if (
const auto *TN = dyn_cast<TypedefNameDecl>(D))
670 HI.Type =
printType(TN->getUnderlyingType().getDesugaredType(Ctx), Ctx, PP);
671 else if (
const auto *TAT = dyn_cast<TypeAliasTemplateDecl>(D))
672 HI.Type =
printType(TAT->getTemplatedDecl()->getUnderlyingType(), Ctx, PP);
675 if (
const auto *Var = dyn_cast<VarDecl>(D); Var && !Var->isInvalidDecl()) {
676 if (
const Expr *Init = Var->getInit())
677 HI.Value = printExprValue(Init, Ctx);
678 }
else if (
const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
680 if (!ECD->getType()->isDependentType())
681 HI.Value =
toString(ECD->getInitVal(), 10);
684 HI.Definition = printDefinition(D, PP, TB);
689std::optional<HoverInfo>
690getPredefinedExprHoverContents(
const PredefinedExpr &PE, ASTContext &Ctx,
691 const PrintingPolicy &PP) {
693 HI.
Name = PE.getIdentKindName();
694 HI.Kind = index::SymbolKind::Variable;
695 HI.Documentation =
"Name of the current function (predefined variable)";
696 if (
const StringLiteral *Name = PE.getFunctionName()) {
698 llvm::raw_string_ostream OS(*HI.Value);
699 Name->outputString(OS);
700 HI.Type =
printType(Name->getType(), Ctx, PP);
703 QualType StringType = Ctx.getIncompleteArrayType(Ctx.CharTy.withConst(),
704 ArraySizeModifier::Normal,
706 HI.Type =
printType(StringType, Ctx, PP);
711HoverInfo evaluateMacroExpansion(
unsigned int SpellingBeginOffset,
712 unsigned int SpellingEndOffset,
713 llvm::ArrayRef<syntax::Token> Expanded,
716 auto &Tokens =
AST.getTokens();
717 auto PP = getPrintingPolicy(
Context.getPrintingPolicy());
726 if (Expanded.size() == 1)
727 if (tok::getPunctuatorSpelling(Expanded[0].kind()))
730 auto *StartNode = Tree.commonAncestor();
741 if (!StartNode->Children.empty())
746 auto ExprResult = printExprValue(StartNode,
Context);
747 HI.Value = std::move(ExprResult.PrintedValue);
748 if (
auto *E = ExprResult.TheExpr)
752 if (!HI.Value && !HI.Type && ExprResult.TheNode)
753 if (
auto *VD = ExprResult.TheNode->ASTNode.get<VarDecl>())
763 SourceManager &SM =
AST.getSourceManager();
764 HI.Name = std::string(
Macro.Name);
765 HI.Kind = index::SymbolKind::Macro;
770 SourceLocation StartLoc =
Macro.Info->getDefinitionLoc();
771 SourceLocation EndLoc =
Macro.Info->getDefinitionEndLoc();
779 if (SM.getPresumedLoc(EndLoc,
false).isValid()) {
780 EndLoc = Lexer::getLocForEndOfToken(EndLoc, 0, SM,
AST.getLangOpts());
782 StringRef Buffer = SM.getBufferData(SM.getFileID(StartLoc), &Invalid);
784 unsigned StartOffset = SM.getFileOffset(StartLoc);
785 unsigned EndOffset = SM.getFileOffset(EndLoc);
786 if (EndOffset <= Buffer.size() && StartOffset < EndOffset)
788 (
"#define " + Buffer.substr(StartOffset, EndOffset - StartOffset))
793 if (
auto Expansion =
AST.getTokens().expansionStartingAt(&Tok)) {
797 std::string ExpansionText;
798 for (
const auto &ExpandedTok : Expansion->Expanded) {
799 ExpansionText += ExpandedTok.text(SM);
800 ExpansionText +=
" ";
802 const size_t Limit =
static_cast<size_t>(Cfg.Hover.MacroContentsLimit);
803 if (Limit && ExpansionText.size() > Limit) {
804 ExpansionText.clear();
809 if (!ExpansionText.empty()) {
810 if (!HI.Definition.empty()) {
811 HI.Definition +=
"\n\n";
813 HI.Definition +=
"// Expands to\n";
814 HI.Definition += ExpansionText;
817 auto Evaluated = evaluateMacroExpansion(
818 SM.getFileOffset(Tok.location()),
819 SM.getFileOffset(Tok.endLocation()),
820 Expansion->Expanded,
AST);
821 HI.Value = std::move(Evaluated.Value);
822 HI.Type = std::move(Evaluated.Type);
829 llvm::raw_string_ostream OS(Result);
832 OS <<
" // aka: " << *PType.AKA;
836std::optional<HoverInfo> getThisExprHoverContents(
const CXXThisExpr *CTE,
838 const PrintingPolicy &PP) {
839 QualType OriginThisType = CTE->getType()->getPointeeType();
840 QualType ClassType =
declaredType(OriginThisType->castAsTagDecl());
845 QualType PrettyThisType = ASTCtx.getPointerType(
846 QualType(ClassType.getTypePtr(), OriginThisType.getCVRQualifiers()));
850 HI.Definition = typeAsDefinition(
printType(PrettyThisType, ASTCtx, PP));
855HoverInfo getDeducedTypeHoverContents(QualType QT,
const syntax::Token &Tok,
857 const PrintingPolicy &PP,
861 HI.
Name = tok::getTokenName(Tok.kind());
862 HI.Kind = index::SymbolKind::TypeAlias;
864 if (QT->isUndeducedAutoType()) {
865 HI.Definition =
"/* not deduced */";
867 HI.Definition = typeAsDefinition(
printType(QT, ASTCtx, PP));
869 if (
const auto *D = QT->getAsTagDecl()) {
870 const auto *CommentD = getDeclForComment(D);
872 enhanceFromIndex(HI, *CommentD, Index);
879HoverInfo getStringLiteralContents(
const StringLiteral *SL,
880 const PrintingPolicy &PP) {
883 HI.
Name =
"string-literal";
884 HI.Size = (SL->getLength() + 1) * SL->getCharByteWidth() * 8;
885 HI.Type = SL->getType().getAsString(PP).c_str();
890bool isLiteral(
const Expr *E) {
893 return llvm::isa<CompoundLiteralExpr>(E) ||
894 llvm::isa<CXXBoolLiteralExpr>(E) ||
895 llvm::isa<CXXNullPtrLiteralExpr>(E) ||
896 llvm::isa<FixedPointLiteral>(E) || llvm::isa<FloatingLiteral>(E) ||
897 llvm::isa<ImaginaryLiteral>(E) || llvm::isa<IntegerLiteral>(E) ||
898 llvm::isa<StringLiteral>(E) || llvm::isa<UserDefinedLiteral>(E);
901llvm::StringLiteral getNameForExpr(
const Expr *E) {
909 return llvm::StringLiteral(
"expression");
913 const PrintingPolicy &PP);
919 const PrintingPolicy &PP,
921 std::optional<HoverInfo> HI;
923 if (
const StringLiteral *SL = dyn_cast<StringLiteral>(E)) {
925 HI = getStringLiteralContents(SL, PP);
926 }
else if (isLiteral(E)) {
930 maybeAddCalleeArgInfo(N, HI.emplace(), PP);
931 if (HI->CalleeArgInfo) {
935 HI->Name =
"literal";
942 if (
const CXXThisExpr *CTE = dyn_cast<CXXThisExpr>(E))
943 HI = getThisExprHoverContents(CTE,
AST.getASTContext(), PP);
944 if (
const PredefinedExpr *PE = dyn_cast<PredefinedExpr>(E))
945 HI = getPredefinedExprHoverContents(*PE,
AST.getASTContext(), PP);
948 if (
auto Val = printExprValue(E,
AST.getASTContext())) {
950 HI->Type =
printType(E->getType(),
AST.getASTContext(), PP);
952 HI->Name = std::string(getNameForExpr(E));
956 maybeAddCalleeArgInfo(N, *HI, PP);
962std::optional<HoverInfo> getHoverContents(
const Attr *A,
ParsedAST &
AST) {
964 HI.
Name =
A->getSpelling();
966 HI.LocalScope =
A->getScopeName()->getName().str();
968 llvm::raw_string_ostream OS(HI.Definition);
969 A->printPretty(OS,
AST.getASTContext().getPrintingPolicy());
971 HI.Documentation = Attr::getDocumentation(
A->getKind()).str();
975void addLayoutInfo(
const NamedDecl &ND,
HoverInfo &HI) {
976 if (ND.isInvalidDecl())
979 const auto &Ctx = ND.getASTContext();
980 if (
auto *RD = llvm::dyn_cast<RecordDecl>(&ND)) {
981 CanQualType RT = Ctx.getCanonicalTagType(RD);
982 if (
auto Size = Ctx.getTypeSizeInCharsIfKnown(RT))
983 HI.Size = Size->getQuantity() * 8;
984 if (!RD->isDependentType() && RD->isCompleteDefinition())
985 HI.Align = Ctx.getTypeAlign(RT);
989 if (
const auto *FD = llvm::dyn_cast<FieldDecl>(&ND)) {
990 const auto *
Record = FD->getParent();
993 if (Record && !
Record->isInvalidDecl() && !
Record->isDependentType()) {
994 HI.Align = Ctx.getTypeAlign(FD->getType());
995 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Record);
996 HI.Offset = Layout.getFieldOffset(FD->getFieldIndex());
997 if (FD->isBitField())
998 HI.Size = FD->getBitWidthValue();
999 else if (
auto Size = Ctx.getTypeSizeInCharsIfKnown(FD->getType()))
1000 HI.Size = FD->isZeroSize(Ctx) ? 0 : Size->getQuantity() * 8;
1002 unsigned EndOfField = *HI.Offset + *HI.Size;
1005 if (!
Record->isUnion() &&
1006 FD->getFieldIndex() + 1 < Layout.getFieldCount()) {
1008 unsigned NextOffset = Layout.getFieldOffset(FD->getFieldIndex() + 1);
1009 if (NextOffset >= EndOfField)
1010 HI.Padding = NextOffset - EndOfField;
1013 HI.Padding = Layout.getSize().getQuantity() * 8 - EndOfField;
1025 if (ParmType->isReferenceType()) {
1026 if (ParmType->getPointeeType().isConstQualified())
1036 const PrintingPolicy &PP) {
1037 const auto &OuterNode = N->outerImplicit();
1038 if (!OuterNode.Parent)
1041 const FunctionDecl *FD =
nullptr;
1042 llvm::ArrayRef<const Expr *> Args;
1044 if (
const auto *CE = OuterNode.Parent->ASTNode.get<CallExpr>()) {
1045 FD = CE->getDirectCallee();
1046 Args = {CE->getArgs(), CE->getNumArgs()};
1047 }
else if (
const auto *CE =
1048 OuterNode.Parent->ASTNode.get<CXXConstructExpr>()) {
1049 FD = CE->getConstructor();
1050 Args = {CE->getArgs(), CE->getNumArgs()};
1061 if (!FD || FD->isOverloadedOperator() || FD->isVariadic())
1069 for (
unsigned I = 0; I < Args.size() && I < Parameters.size(); ++I) {
1070 if (Args[I] != OuterNode.ASTNode.get<Expr>())
1074 if (
const ParmVarDecl *PVD = Parameters[I]) {
1075 HI.CalleeArgInfo.emplace(toHoverInfoParam(PVD, PP));
1076 if (N == &OuterNode)
1077 PassType.PassBy = getPassMode(PVD->getType());
1081 if (!HI.CalleeArgInfo)
1087 if (
const auto *E = N->ASTNode.get<Expr>()) {
1088 if (E->getType().isConstQualified())
1092 for (
auto *CastNode = N->Parent;
1093 CastNode != OuterNode.Parent && !PassType.Converted;
1094 CastNode = CastNode->Parent) {
1095 if (
const auto *ImplicitCast = CastNode->ASTNode.get<ImplicitCastExpr>()) {
1096 switch (ImplicitCast->getCastKind()) {
1098 case CK_DerivedToBase:
1099 case CK_UncheckedDerivedToBase:
1102 PassType.PassBy = ImplicitCast->getType().isConstQualified()
1106 case CK_LValueToRValue:
1107 case CK_ArrayToPointerDecay:
1108 case CK_FunctionToPointerDecay:
1109 case CK_NullToPointer:
1110 case CK_NullToMemberPointer:
1116 PassType.Converted =
true;
1119 }
else if (
const auto *CtorCall =
1120 CastNode->ASTNode.get<CXXConstructExpr>()) {
1123 if (CtorCall->getConstructor()->isCopyConstructor())
1126 PassType.Converted =
true;
1127 }
else if (CastNode->ASTNode.get<MaterializeTemporaryExpr>()) {
1132 PassType.Converted =
true;
1136 HI.CallPassType.emplace(PassType);
1139const NamedDecl *pickDeclToUse(llvm::ArrayRef<const NamedDecl *> Candidates) {
1140 if (Candidates.empty())
1149 if (Candidates.size() <= 2) {
1150 if (llvm::isa<UsingDecl>(Candidates.front()))
1151 return Candidates.back();
1152 return Candidates.front();
1161 auto BaseDecls = llvm::make_filter_range(
1162 Candidates, [](
const NamedDecl *D) {
return llvm::isa<UsingDecl>(D); });
1163 if (std::distance(BaseDecls.begin(), BaseDecls.end()) == 1)
1164 return *BaseDecls.begin();
1166 return Candidates.front();
1170 include_cleaner::Symbol Sym) {
1171 trace::Span Tracer(
"Hover::maybeAddSymbolProviders");
1173 llvm::SmallVector<include_cleaner::Header> RankedProviders =
1174 include_cleaner::headersForSymbol(Sym,
AST.getPreprocessor(),
1175 &
AST.getPragmaIncludes());
1176 if (RankedProviders.empty())
1179 const SourceManager &SM =
AST.getSourceManager();
1182 for (
const auto &P : RankedProviders) {
1183 if (
P.kind() == include_cleaner::Header::Physical &&
1184 P.physical() == SM.getFileEntryForID(SM.getMainFileID()))
1189 auto Matches = ConvertedIncludes.match(P);
1190 if (!Matches.empty()) {
1191 Result = Matches[0]->quote();
1196 if (!Result.empty()) {
1197 HI.Provider = std::move(Result);
1202 const auto &H = RankedProviders.front();
1203 if (H.kind() == include_cleaner::Header::Physical &&
1204 H.physical() == SM.getFileEntryForID(SM.getMainFileID()))
1209 HI.Provider = include_cleaner::spellHeader(
1210 {H,
AST.getPreprocessor().getHeaderSearchInfo(),
1211 SM.getFileEntryForID(SM.getMainFileID())});
1217std::string getSymbolName(include_cleaner::Symbol Sym) {
1219 switch (Sym.kind()) {
1220 case include_cleaner::Symbol::Declaration:
1221 if (
const auto *ND = llvm::dyn_cast<NamedDecl>(&Sym.declaration()))
1222 Name = ND->getDeclName().getAsString();
1224 case include_cleaner::Symbol::Macro:
1225 Name = Sym.macro().Name->getName();
1233 llvm::DenseSet<include_cleaner::Symbol> UsedSymbols;
1234 include_cleaner::walkUsed(
1236 &
AST.getPragmaIncludes(),
AST.getPreprocessor(),
1237 [&](
const include_cleaner::SymbolReference &
Ref,
1238 llvm::ArrayRef<include_cleaner::Header> Providers) {
1239 if (Ref.RT != include_cleaner::RefType::Explicit ||
1240 UsedSymbols.contains(Ref.Target))
1243 if (isPreferredProvider(Inc, Converted, Providers))
1244 UsedSymbols.insert(Ref.Target);
1247 for (
const auto &UsedSymbolDecl : UsedSymbols)
1248 HI.UsedSymbolNames.push_back(getSymbolName(UsedSymbolDecl));
1249 llvm::sort(HI.UsedSymbolNames);
1250 HI.UsedSymbolNames.erase(llvm::unique(HI.UsedSymbolNames),
1251 HI.UsedSymbolNames.end());
1257 const format::FormatStyle &Style,
1262 getPrintingPolicy(
AST.getASTContext().getPrintingPolicy());
1263 const SourceManager &SM =
AST.getSourceManager();
1266 llvm::consumeError(CurLoc.takeError());
1267 return std::nullopt;
1269 const auto &TB =
AST.getTokens();
1270 auto TokensTouchingCursor = syntax::spelledTokensTouching(*CurLoc, TB);
1272 if (TokensTouchingCursor.empty())
1273 return std::nullopt;
1276 for (
const auto &Inc :
AST.getIncludeStructure().MainFileIncludes) {
1277 if (Inc.Resolved.empty() || Inc.HashLine != Pos.
line)
1279 HoverCountMetric.
record(1,
"include");
1281 HI.
Name = std::string(llvm::sys::path::filename(Inc.Resolved));
1285 HI.
Kind = index::SymbolKind::IncludeDirective;
1286 maybeAddUsedSymbols(
AST, HI, Inc);
1293 CharSourceRange HighlightRange =
1294 TokensTouchingCursor.back().range(SM).toCharRange(SM);
1295 std::optional<HoverInfo> HI;
1299 for (
const auto &Tok : TokensTouchingCursor) {
1300 if (Tok.kind() == tok::identifier) {
1302 HighlightRange = Tok.range(SM).toCharRange(SM);
1304 HoverCountMetric.
record(1,
"macro");
1305 HI = getHoverContents(*M, Tok,
AST);
1306 if (
auto DefLoc = M->Info->getDefinitionLoc(); DefLoc.isValid()) {
1307 include_cleaner::Macro IncludeCleanerMacro{
1308 AST.getPreprocessor().getIdentifierInfo(Tok.text(SM)), DefLoc};
1309 maybeAddSymbolProviders(
AST, *HI,
1310 include_cleaner::Symbol{IncludeCleanerMacro});
1314 }
else if (Tok.kind() == tok::kw_auto || Tok.kind() == tok::kw_decltype) {
1315 HoverCountMetric.
record(1,
"keyword");
1319 HI = getDeducedTypeHoverContents(*
Deduced, Tok,
AST.getASTContext(), PP,
1321 HighlightRange = Tok.range(SM).toCharRange(SM);
1328 return std::nullopt;
1334 auto Offset = SM.getFileOffset(*CurLoc);
1342 AST.getHeuristicResolver());
1343 if (
const auto *DeclToUse = pickDeclToUse(Decls)) {
1344 HoverCountMetric.
record(1,
"decl");
1345 HI = getHoverContents(DeclToUse, PP, Index, TB);
1347 if (DeclToUse == N->ASTNode.get<Decl>())
1348 addLayoutInfo(*DeclToUse, *HI);
1351 HI->Value = printExprValue(N,
AST.getASTContext()).PrintedValue;
1352 maybeAddCalleeArgInfo(N, *HI, PP);
1354 if (!isa<NamespaceDecl>(DeclToUse))
1355 maybeAddSymbolProviders(
AST, *HI,
1356 include_cleaner::Symbol{*DeclToUse});
1357 }
else if (
const Expr *E = N->ASTNode.get<Expr>()) {
1358 HoverCountMetric.
record(1,
"expr");
1359 HI = getHoverContents(N, E,
AST, PP, Index);
1360 }
else if (
const Attr *A = N->ASTNode.get<Attr>()) {
1361 HoverCountMetric.
record(1,
"attribute");
1362 HI = getHoverContents(A,
AST);
1370 return std::nullopt;
1373 if (!HI->Definition.empty()) {
1374 auto Replacements = format::reformat(
1375 Style, HI->Definition, tooling::Range(0, HI->Definition.size()));
1376 if (
auto Formatted =
1377 tooling::applyAllReplacements(HI->Definition, Replacements))
1378 HI->Definition = *Formatted;
1381 HI->DefinitionLanguage = getMarkdownLanguage(
AST.getASTContext());
1389 uint64_t
Value = SizeInBits % 8 == 0 ? SizeInBits / 8 : SizeInBits;
1390 const char *
Unit =
Value != 0 &&
Value == SizeInBits ?
"bit" :
"byte";
1391 return llvm::formatv(
"{0} {1}{2}",
Value,
Unit,
Value == 1 ?
"" :
"s").str();
1397 const auto Bytes = OffsetInBits / 8;
1398 const auto Bits = OffsetInBits % 8;
1405void HoverInfo::calleeArgInfoToMarkupParagraph(markup::Paragraph &P)
const {
1408 llvm::raw_string_ostream OS(Buffer);
1421 OS <<
" (converted to " <<
CalleeArgInfo->Type->Type <<
")";
1422 P.appendText(OS.str());
1425void HoverInfo::usedSymbolNamesToMarkup(markup::Document &Output)
const {
1426 markup::Paragraph &
P = Output.addParagraph();
1427 P.appendText(
"provides ");
1429 const std::vector<std::string>::size_type SymbolNamesLimit = 5;
1430 auto Front = llvm::ArrayRef(
UsedSymbolNames).take_front(SymbolNamesLimit);
1433 Front, [&](llvm::StringRef Sym) {
P.appendCode(Sym); },
1434 [&] {
P.appendText(
", "); });
1436 P.appendText(
" and ");
1438 P.appendText(
" more");
1442void HoverInfo::providerToMarkupParagraph(markup::Document &Output)
const {
1443 markup::Paragraph &DI = Output.addParagraph();
1444 DI.appendText(
"provided by");
1449void HoverInfo::definitionScopeToMarkup(markup::Document &Output)
const {
1459 Buffer +=
"// In " + llvm::StringRef(
LocalScope).rtrim(
':').str() +
'\n';
1461 Buffer +=
"// In namespace " +
1462 llvm::StringRef(*NamespaceScope).rtrim(
':').str() +
'\n';
1475 P.appendText(
"Value = ");
1492markup::Document HoverInfo::presentDoxygen()
const {
1494 markup::Document Output;
1507 markup::Paragraph &Header = Output.addHeading(3);
1508 if (
Kind != index::SymbolKind::Unknown &&
1509 Kind != index::SymbolKind::IncludeDirective)
1510 Header.appendText(index::getSymbolKindString(
Kind)).appendSpace();
1511 assert(!
Name.empty() &&
"hover triggered on a nameless symbol");
1513 if (
Kind == index::SymbolKind::IncludeDirective) {
1514 Header.appendCode(
Name);
1517 Output.addParagraph().appendCode(
Definition);
1521 usedSymbolNamesToMarkup(Output);
1529 definitionScopeToMarkup(Output);
1531 Header.appendCode(
Name);
1535 providerToMarkupParagraph(Output);
1543 if (SymbolDoc.hasBriefCommand()) {
1544 if (
Kind != index::SymbolKind::Parameter &&
1545 Kind != index::SymbolKind::TemplateTypeParm)
1549 Output.addHeading(3).appendText(
"Brief");
1550 SymbolDoc.briefToMarkup(Output.addParagraph());
1563 Output.addHeading(3).appendText(
"Template Parameters");
1564 markup::BulletList &L = Output.addBulletList();
1566 markup::Paragraph &
P = L.addItem().addParagraph();
1567 P.appendCode(llvm::to_string(
Param));
1568 if (SymbolDoc.isTemplateTypeParmDocumented(llvm::to_string(
Param.
Name))) {
1569 P.appendText(
" - ");
1570 SymbolDoc.templateTypeParmDocToMarkup(llvm::to_string(
Param.
Name), P);
1577 Output.addHeading(3).appendText(
"Parameters");
1578 markup::BulletList &L = Output.addBulletList();
1580 markup::Paragraph &
P = L.addItem().addParagraph();
1581 P.appendCode(llvm::to_string(
Param));
1583 if (SymbolDoc.isParameterDocumented(llvm::to_string(
Param.
Name))) {
1584 P.appendText(
" - ");
1585 SymbolDoc.parameterDocToMarkup(llvm::to_string(
Param.
Name), P);
1596 Output.addHeading(3).appendText(
"Returns");
1597 markup::Paragraph &
P = Output.addParagraph();
1600 if (SymbolDoc.hasReturnCommand()) {
1601 P.appendText(
" - ");
1602 SymbolDoc.returnToMarkup(P);
1605 SymbolDoc.retvalsToMarkup(Output);
1609 if (SymbolDoc.hasDetailedDoc()) {
1610 Output.addHeading(3).appendText(
"Details");
1611 SymbolDoc.detailedDocToMarkup(Output);
1619 Output.addParagraph().appendText(
"Type: ").appendCode(
1620 llvm::to_string(*
Type));
1623 valueToMarkupParagraph(Output.addParagraph());
1627 offsetToMarkupParagraph(Output.addParagraph());
1629 sizeToMarkupParagraph(Output.addParagraph());
1633 calleeArgInfoToMarkupParagraph(Output.addParagraph());
1638 usedSymbolNamesToMarkup(Output);
1644markup::Document HoverInfo::presentDefault()
const {
1645 markup::Document Output;
1658 markup::Paragraph &Header = Output.addHeading(3);
1659 if (
Kind != index::SymbolKind::Unknown &&
1660 Kind != index::SymbolKind::IncludeDirective)
1661 Header.appendText(index::getSymbolKindString(
Kind)).appendSpace();
1662 assert(!
Name.empty() &&
"hover triggered on a nameless symbol");
1663 Header.appendCode(
Name);
1666 providerToMarkupParagraph(Output);
1679 Output.addParagraph().appendText(
"→ ").appendCode(
1684 Output.addParagraph().appendText(
"Parameters:");
1685 markup::BulletList &L = Output.addBulletList();
1687 L.addItem().addParagraph().appendCode(llvm::to_string(
Param));
1693 Output.addParagraph().appendText(
"Type: ").appendCode(
1694 llvm::to_string(*
Type));
1697 valueToMarkupParagraph(Output.addParagraph());
1701 offsetToMarkupParagraph(Output.addParagraph());
1703 sizeToMarkupParagraph(Output.addParagraph());
1707 calleeArgInfoToMarkupParagraph(Output.addParagraph());
1715 definitionScopeToMarkup(Output);
1720 usedSymbolNamesToMarkup(Output);
1731 return presentDefault().asMarkdown();
1733 return presentDoxygen().asMarkdown();
1738 return presentDefault().asEscapedMarkdown();
1741 return presentDefault().asPlainText();
1748 assert(Line[Offset] ==
'`');
1751 llvm::StringRef Prefix = Line.substr(0, Offset);
1752 constexpr llvm::StringLiteral BeforeStartChars =
" \t(=";
1753 if (!Prefix.empty() && !BeforeStartChars.contains(Prefix.back()))
1754 return std::nullopt;
1757 auto Next = Line.find_first_of(
"`\n", Offset + 1);
1758 if (Next == llvm::StringRef::npos)
1759 return std::nullopt;
1762 if (Line[Next] ==
'\n')
1763 return std::nullopt;
1765 llvm::StringRef Contents = Line.slice(Offset + 1, Next);
1766 if (Contents.empty() || isWhitespace(Contents.front()) ||
1767 isWhitespace(Contents.back()))
1768 return std::nullopt;
1771 llvm::StringRef Suffix = Line.substr(Next + 1);
1772 constexpr llvm::StringLiteral AfterEndChars =
" \t)=.,;:";
1773 if (!Suffix.empty() && !AfterEndChars.contains(Suffix.front()))
1774 return std::nullopt;
1776 return Line.slice(Offset, Next + 1);
1781 for (
unsigned I = 0; I <
Text.size(); ++I) {
1786 Out.appendCode(
Range->trim(
"`"),
true);
1803 for (std::tie(
Paragraph, Rest) = Input.split(
"\n\n");
1805 std::tie(
Paragraph, Rest) = Rest.split(
"\n\n")) {
1817 OS <<
" (aka " << *T.AKA <<
")";
1826 OS <<
" " << *P.Name;
1828 OS <<
" = " << *P.Default;
1829 if (P.Type && P.Type->AKA)
1830 OS <<
" (aka " << *P.Type->AKA <<
")";
Include Cleaner is clangd functionality for providing diagnostics for misuse of transitive headers an...
A context is an immutable container for per-request data that must be propagated through layers that ...
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 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.
Records an event whose duration is the lifetime of the Span object.
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
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 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,.
std::string printType(const QualType QT, const DeclContext &CurContext, const llvm::StringRef Placeholder, bool FullyQualify)
Returns a QualType as string.
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)
std::optional< QualType > getDeducedType(ASTContext &ASTCtx, const HeuristicResolver *Resolver, SourceLocation Loc)
Retrieves the deduced type at a given location (auto, decltype).
llvm::raw_ostream & operator<<(llvm::raw_ostream &OS, const CodeCompletion &C)
void parseDocumentationParagraph(llvm::StringRef Text, markup::Paragraph &Out)
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.
llvm::SmallVector< uint64_t, 1024 > Record
cppcoreguidelines::ProBoundsAvoidUncheckedContainerAccessCheck P
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Settings that express user/project preferences and control clangd behavior.
static const Config & current()
Returns the Config of the current Context, or an empty configuration.
@ Markdown
Treat comments as Markdown.
@ Doxygen
Treat comments as doxygen.
@ PlainText
Treat comments as plain text.
struct clang::clangd::Config::@340212122325041323223256240301061135214102252040 Documentation
CommentFormatPolicy CommentFormat
Represents parameters of a function, a template or a macro.
std::optional< PrintedType > Type
The printable parameter type, e.g.
std::optional< std::string > Name
std::nullopt for unnamed parameters.
Contains pretty-printed type and desugared type.
std::string Type
Pretty-printed 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::string present(MarkupKind Kind) const
Produce a user-readable information based on the specified markup kind.
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.
std::optional< std::vector< Param > > TemplateParameters
Set for all templates(function, class, variable).
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
CommentOptions CommentOpts
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.
llvm::DenseSet< SymbolID > IDs
int line
Line position in a document (zero-based).
Represents a symbol occurrence in the source file.
The class presents a C++ symbol, e.g.
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.