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.AnonymousTagLocations =
false;
74 Base.TerseOutput =
true;
75 Base.PolishForDeclaration =
true;
76 Base.ConstantsAsWritten =
true;
77 Base.SuppressTemplateArgsInCXXConstructors =
true;
84std::string getLocalScope(
const Decl *D) {
85 std::vector<std::string> Scopes;
86 const DeclContext *DC =
D->getDeclContext();
91 if (
const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
93 if (
const ObjCContainerDecl *CD = dyn_cast<ObjCContainerDecl>(DC))
96 auto GetName = [](
const TypeDecl *
D) {
97 if (!
D->getDeclName().isEmpty()) {
98 PrintingPolicy Policy =
D->getASTContext().getPrintingPolicy();
99 Policy.SuppressScope =
true;
102 if (
auto *RD = dyn_cast<RecordDecl>(D))
103 return (
"(anonymous " + RD->getKindName() +
")").str();
104 return std::string(
"");
107 if (
const TypeDecl *TD = dyn_cast<TypeDecl>(DC))
108 Scopes.push_back(GetName(TD));
109 else if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
110 Scopes.push_back(FD->getNameAsString());
111 DC = DC->getParent();
114 return llvm::join(llvm::reverse(Scopes),
"::");
119std::string getNamespaceScope(
const Decl *D) {
120 const DeclContext *DC =
D->getDeclContext();
124 if (isa<ObjCMethodDecl, ObjCContainerDecl>(DC))
127 if (
const TagDecl *TD = dyn_cast<TagDecl>(DC))
128 return getNamespaceScope(TD);
129 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
130 return getNamespaceScope(FD);
131 if (
const NamespaceDecl *NSD = dyn_cast<NamespaceDecl>(DC)) {
133 if (NSD->isInline() || NSD->isAnonymousNamespace())
134 return getNamespaceScope(NSD);
136 if (
const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
142std::string printDefinition(
const Decl *D, PrintingPolicy PP,
143 const syntax::TokenBuffer &TB) {
144 if (
auto *VD = llvm::dyn_cast<VarDecl>(D)) {
145 if (
auto *IE = VD->getInit()) {
149 if (200 < TB.expandedTokens(IE->getSourceRange()).size())
150 PP.SuppressInitializers =
true;
159const char *getMarkdownLanguage(
const ASTContext &Ctx) {
160 const auto &LangOpts = Ctx.getLangOpts();
161 if (LangOpts.ObjC && LangOpts.CPlusPlus)
162 return "objective-cpp";
163 return LangOpts.ObjC ?
"objective-c" :
"cpp";
167 const PrintingPolicy &PP) {
171 while (!QT.isNull() && QT->isDecltypeType())
172 QT = QT->castAs<DecltypeType>()->getUnderlyingType();
174 llvm::raw_string_ostream OS(Result.Type);
179 PrintingPolicy Copy(PP);
180 if (!QT.isNull() && !QT.hasQualifiers() && PP.SuppressTagKeyword) {
181 if (
auto *TT = llvm::dyn_cast<TagType>(QT.getTypePtr());
182 TT && TT->isCanonicalUnqualified()) {
183 Copy.SuppressTagKeywordInAnonNames =
true;
184 OS << TT->getDecl()->getKindName() <<
" ";
190 if (!QT.isNull() && Cfg.Hover.ShowAKA) {
191 bool ShouldAKA =
false;
192 QualType DesugaredTy = clang::desugarForDiagnostic(ASTCtx, QT, ShouldAKA);
194 Result.AKA = DesugaredTy.getAsString(Copy);
201 Result.
Type = TTP->wasDeclaredWithTypename() ?
"typename" :
"class";
202 if (TTP->isParameterPack())
203 Result.Type +=
"...";
208 const PrintingPolicy &PP) {
209 auto PrintedType =
printType(NTTP->getType(), NTTP->getASTContext(), PP);
210 if (NTTP->isParameterPack()) {
211 PrintedType.Type +=
"...";
213 *PrintedType.AKA +=
"...";
219 const PrintingPolicy &PP) {
221 llvm::raw_string_ostream OS(Result.Type);
223 llvm::StringRef Sep =
"";
224 for (
const Decl *Param : *TTP->getTemplateParameters()) {
227 if (
const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
229 else if (
const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))
231 else if (
const auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param))
240std::vector<HoverInfo::Param>
241fetchTemplateParameters(
const TemplateParameterList *Params,
242 const PrintingPolicy &PP) {
244 std::vector<HoverInfo::Param> TempParameters;
246 for (
const Decl *Param : *Params) {
248 if (
const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
251 if (!TTP->getName().empty())
252 P.Name = TTP->getNameAsString();
254 if (TTP->hasDefaultArgument()) {
256 llvm::raw_string_ostream Out(*
P.Default);
257 TTP->getDefaultArgument().getArgument().print(PP, Out,
260 }
else if (
const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
263 if (IdentifierInfo *II = NTTP->getIdentifier())
264 P.Name = II->getName().str();
266 if (NTTP->hasDefaultArgument()) {
268 llvm::raw_string_ostream Out(*
P.Default);
269 NTTP->getDefaultArgument().getArgument().print(PP, Out,
272 }
else if (
const auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param)) {
275 if (!TTPD->getName().empty())
276 P.Name = TTPD->getNameAsString();
278 if (TTPD->hasDefaultArgument()) {
280 llvm::raw_string_ostream Out(*
P.Default);
281 TTPD->getDefaultArgument().getArgument().print(PP, Out,
285 TempParameters.push_back(std::move(P));
288 return TempParameters;
291const FunctionDecl *getUnderlyingFunction(
const Decl *D) {
293 if (
const VarDecl *VD = llvm::dyn_cast<VarDecl>(D)) {
294 auto QT = VD->getType();
296 while (!QT->getPointeeType().isNull())
297 QT = QT->getPointeeType();
299 if (
const auto *CD = QT->getAsCXXRecordDecl())
300 return CD->getLambdaCallOperator();
305 return D->getAsFunction();
310const NamedDecl *getDeclForComment(
const NamedDecl *D) {
311 const NamedDecl *DeclForComment =
D;
312 if (
const auto *TSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(D)) {
315 if (TSD->getTemplateSpecializationKind() == TSK_Undeclared)
316 DeclForComment = TSD->getSpecializedTemplate();
317 else if (
const auto *TIP = TSD->getTemplateInstantiationPattern())
318 DeclForComment = TIP;
319 }
else if (
const auto *TSD =
320 llvm::dyn_cast<VarTemplateSpecializationDecl>(D)) {
321 if (TSD->getTemplateSpecializationKind() == TSK_Undeclared)
322 DeclForComment = TSD->getSpecializedTemplate();
323 else if (
const auto *TIP = TSD->getTemplateInstantiationPattern())
324 DeclForComment = TIP;
325 }
else if (
const auto *FD =
D->getAsFunction())
326 if (
const auto *TIP = FD->getTemplateInstantiationPattern())
327 DeclForComment = TIP;
332 if (D != DeclForComment)
333 DeclForComment = getDeclForComment(DeclForComment);
334 return DeclForComment;
340 assert(&ND == getDeclForComment(&ND));
342 if (!
Hover.Documentation.empty() || !Index)
356 Index->lookup(Req, [&](
const Symbol &S) {
357 Hover.Documentation = std::string(S.Documentation);
364const Expr *getDefaultArg(
const ParmVarDecl *PVD) {
369 if (!PVD->hasDefaultArg() || PVD->hasUnparsedDefaultArg())
371 return PVD->hasUninstantiatedDefaultArg() ? PVD->getUninstantiatedDefaultArg()
372 : PVD->getDefaultArg();
376 const PrintingPolicy &PP) {
378 Out.
Type =
printType(PVD->getType(), PVD->getASTContext(), PP);
379 if (!PVD->getName().empty())
380 Out.Name = PVD->getNameAsString();
381 if (
const Expr *DefArg = getDefaultArg(PVD)) {
382 Out.Default.emplace();
383 llvm::raw_string_ostream OS(*Out.Default);
384 DefArg->printPretty(OS,
nullptr, PP);
390void fillFunctionTypeAndParams(
HoverInfo &HI,
const Decl *D,
391 const FunctionDecl *FD,
392 const PrintingPolicy &PP) {
393 HI.Parameters.emplace();
394 for (
const ParmVarDecl *PVD : FD->parameters())
395 HI.Parameters->emplace_back(toHoverInfoParam(PVD, PP));
399 const auto NK = FD->getDeclName().getNameKind();
400 if (NK == DeclarationName::CXXConstructorName ||
401 NK == DeclarationName::CXXDestructorName ||
402 NK == DeclarationName::CXXConversionFunctionName)
405 HI.ReturnType =
printType(FD->getReturnType(), FD->getASTContext(), PP);
406 QualType QT = FD->getType();
407 if (
const VarDecl *VD = llvm::dyn_cast<VarDecl>(D))
408 QT = VD->getType().getDesugaredType(
D->getASTContext());
409 HI.Type =
printType(QT,
D->getASTContext(), PP);
419static llvm::FormattedNumber printHex(
const llvm::APSInt &V) {
420 assert(V.getSignificantBits() <= 64 &&
"Can't print more than 64 bits.");
422 V.getBitWidth() > 64 ? V.trunc(64).getZExtValue() : V.getZExtValue();
423 if (V.isNegative() && V.getSignificantBits() <= 32)
424 return llvm::format_hex(uint32_t(Bits), 0);
425 return llvm::format_hex(Bits, 0);
428std::optional<std::string> printExprValue(
const Expr *E,
429 const ASTContext &Ctx) {
434 if (
const auto *ILE = llvm::dyn_cast<InitListExpr>(E)) {
435 if (!ILE->isSemanticForm())
436 E = ILE->getSemanticForm();
442 QualType
T = E->getType();
443 if (
T.isNull() ||
T->isFunctionType() ||
T->isFunctionPointerType() ||
444 T->isFunctionReferenceType() ||
T->isVoidType())
449 if (E->isValueDependent() || !E->EvaluateAsRValue(
Constant, Ctx) ||
456 if (
T->isEnumeralType() &&
Constant.Val.isInt() &&
457 Constant.Val.getInt().getSignificantBits() <= 64) {
459 int64_t Val =
Constant.Val.getInt().getExtValue();
460 for (
const EnumConstantDecl *ECD :
T->castAsEnumDecl()->enumerators())
461 if (ECD->getInitVal() == Val)
462 return llvm::formatv(
"{0} ({1})", ECD->getNameAsString(),
467 if (
T->isIntegralOrEnumerationType() &&
Constant.Val.isInt() &&
468 Constant.Val.getInt().getSignificantBits() <= 64 &&
470 return llvm::formatv(
"{0} ({1})",
Constant.Val.getAsString(Ctx, T),
473 return Constant.Val.getAsString(Ctx, T);
476struct PrintExprResult {
478 std::optional<std::string> PrintedValue;
481 const clang::Expr *TheExpr;
483 const SelectionTree::Node *TheNode;
492 const ASTContext &Ctx) {
493 for (; N; N = N->Parent) {
495 if (
const Expr *E = N->ASTNode.get<Expr>()) {
498 if (!E->getType().isNull() && E->getType()->isVoidType())
500 if (
auto Val = printExprValue(E, Ctx))
501 return PrintExprResult{std::move(Val), E,
503 }
else if (N->ASTNode.get<Decl>() || N->ASTNode.get<Stmt>()) {
509 return PrintExprResult{std::nullopt,
nullptr,
513std::optional<StringRef> fieldName(
const Expr *E) {
514 const auto *ME = llvm::dyn_cast<MemberExpr>(E->IgnoreCasts());
515 if (!ME || !llvm::isa<CXXThisExpr>(ME->getBase()->IgnoreCasts()))
517 const auto *
Field = llvm::dyn_cast<FieldDecl>(ME->getMemberDecl());
518 if (!
Field || !
Field->getDeclName().isIdentifier())
520 return Field->getDeclName().getAsIdentifierInfo()->getName();
524std::optional<StringRef> getterVariableName(
const CXXMethodDecl *CMD) {
525 assert(CMD->hasBody());
526 if (CMD->getNumParams() != 0 || CMD->isVariadic())
528 const auto *Body = llvm::dyn_cast<CompoundStmt>(CMD->getBody());
529 const auto *OnlyReturn = (Body && Body->size() == 1)
530 ? llvm::dyn_cast<ReturnStmt>(Body->body_front())
532 if (!OnlyReturn || !OnlyReturn->getRetValue())
534 return fieldName(OnlyReturn->getRetValue());
543std::optional<StringRef> setterVariableName(
const CXXMethodDecl *CMD) {
544 assert(CMD->hasBody());
545 if (CMD->isConst() || CMD->getNumParams() != 1 || CMD->isVariadic())
547 const ParmVarDecl *Arg = CMD->getParamDecl(0);
548 if (Arg->isParameterPack())
551 const auto *Body = llvm::dyn_cast<CompoundStmt>(CMD->getBody());
552 if (!Body || Body->size() == 0 || Body->size() > 2)
555 if (Body->size() == 2) {
556 auto *Ret = llvm::dyn_cast<ReturnStmt>(Body->body_back());
557 if (!Ret || !Ret->getRetValue())
559 const Expr *RetVal = Ret->getRetValue()->IgnoreCasts();
560 if (
const auto *UO = llvm::dyn_cast<UnaryOperator>(RetVal)) {
561 if (UO->getOpcode() != UO_Deref)
563 RetVal = UO->getSubExpr()->IgnoreCasts();
565 if (!llvm::isa<CXXThisExpr>(RetVal))
569 const Expr *LHS, *RHS;
570 if (
const auto *BO = llvm::dyn_cast<BinaryOperator>(Body->body_front())) {
571 if (BO->getOpcode() != BO_Assign)
575 }
else if (
const auto *COCE =
576 llvm::dyn_cast<CXXOperatorCallExpr>(Body->body_front())) {
577 if (COCE->getOperator() != OO_Equal || COCE->getNumArgs() != 2)
579 LHS = COCE->getArg(0);
580 RHS = COCE->getArg(1);
586 if (
auto *CE = llvm::dyn_cast<CallExpr>(RHS->IgnoreCasts())) {
587 if (CE->getNumArgs() != 1)
589 auto *ND = llvm::dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl());
590 if (!ND || !ND->getIdentifier() || ND->getName() !=
"move" ||
591 !ND->isInStdNamespace())
596 auto *DRE = llvm::dyn_cast<DeclRefExpr>(RHS->IgnoreCasts());
597 if (!DRE || DRE->getDecl() != Arg)
599 return fieldName(LHS);
602std::string synthesizeDocumentation(
const NamedDecl *ND) {
603 if (
const auto *CMD = llvm::dyn_cast<CXXMethodDecl>(ND)) {
605 if (CMD->getDeclName().isIdentifier() && !CMD->isStatic() &&
606 (CMD = llvm::dyn_cast_or_null<CXXMethodDecl>(CMD->getDefinition())) &&
608 if (
const auto GetterField = getterVariableName(CMD))
609 return llvm::formatv(
"Trivial accessor for `{0}`.", *GetterField);
610 if (
const auto SetterField = setterVariableName(CMD))
611 return llvm::formatv(
"Trivial setter for `{0}`.", *SetterField);
618HoverInfo getHoverContents(
const NamedDecl *D,
const PrintingPolicy &PP,
620 const syntax::TokenBuffer &TB) {
622 auto &Ctx =
D->getASTContext();
624 HI.AccessSpecifier = getAccessSpelling(
D->getAccess()).str();
625 HI.NamespaceScope = getNamespaceScope(D);
626 if (!HI.NamespaceScope->empty())
627 HI.NamespaceScope->append(
"::");
628 HI.LocalScope = getLocalScope(D);
629 if (!HI.LocalScope.empty())
630 HI.LocalScope.append(
"::");
633 const auto *CommentD = getDeclForComment(D);
637 HI.CommentOpts =
D->getASTContext().getLangOpts().CommentOpts;
638 enhanceFromIndex(HI, *CommentD, Index);
639 if (HI.Documentation.empty())
640 HI.Documentation = synthesizeDocumentation(D);
642 HI.Kind = index::getSymbolInfo(D).Kind;
645 if (
const TemplateDecl *TD =
D->getDescribedTemplate()) {
646 HI.TemplateParameters =
647 fetchTemplateParameters(TD->getTemplateParameters(), PP);
649 }
else if (
const FunctionDecl *FD =
D->getAsFunction()) {
650 if (
const auto *FTD = FD->getDescribedTemplate()) {
651 HI.TemplateParameters =
652 fetchTemplateParameters(FTD->getTemplateParameters(), PP);
658 if (
const FunctionDecl *FD = getUnderlyingFunction(D))
659 fillFunctionTypeAndParams(HI, D, FD, PP);
660 else if (
const auto *VD = dyn_cast<ValueDecl>(D))
661 HI.Type =
printType(VD->getType(), Ctx, PP);
662 else if (
const auto *TTP = dyn_cast<TemplateTypeParmDecl>(D))
663 HI.Type = TTP->wasDeclaredWithTypename() ?
"typename" :
"class";
664 else if (
const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(D))
666 else if (
const auto *VT = dyn_cast<VarTemplateDecl>(D))
667 HI.Type =
printType(VT->getTemplatedDecl()->getType(), Ctx, PP);
668 else if (
const auto *TN = dyn_cast<TypedefNameDecl>(D))
669 HI.Type =
printType(TN->getUnderlyingType().getDesugaredType(Ctx), Ctx, PP);
670 else if (
const auto *TAT = dyn_cast<TypeAliasTemplateDecl>(D))
671 HI.Type =
printType(TAT->getTemplatedDecl()->getUnderlyingType(), Ctx, PP);
674 if (
const auto *Var = dyn_cast<VarDecl>(D); Var && !Var->isInvalidDecl()) {
675 if (
const Expr *Init = Var->getInit())
676 HI.Value = printExprValue(Init, Ctx);
677 }
else if (
const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
679 if (!ECD->getType()->isDependentType())
680 HI.Value =
toString(ECD->getInitVal(), 10);
683 HI.Definition = printDefinition(D, PP, TB);
688std::optional<HoverInfo>
689getPredefinedExprHoverContents(
const PredefinedExpr &PE, ASTContext &Ctx,
690 const PrintingPolicy &PP) {
692 HI.
Name = PE.getIdentKindName();
693 HI.Kind = index::SymbolKind::Variable;
694 HI.Documentation =
"Name of the current function (predefined variable)";
695 if (
const StringLiteral *Name = PE.getFunctionName()) {
697 llvm::raw_string_ostream OS(*HI.Value);
698 Name->outputString(OS);
699 HI.Type =
printType(Name->getType(), Ctx, PP);
702 QualType StringType = Ctx.getIncompleteArrayType(Ctx.CharTy.withConst(),
703 ArraySizeModifier::Normal,
705 HI.Type =
printType(StringType, Ctx, PP);
710HoverInfo evaluateMacroExpansion(
unsigned int SpellingBeginOffset,
711 unsigned int SpellingEndOffset,
712 llvm::ArrayRef<syntax::Token> Expanded,
715 auto &Tokens =
AST.getTokens();
716 auto PP = getPrintingPolicy(
Context.getPrintingPolicy());
725 if (Expanded.size() == 1)
726 if (tok::getPunctuatorSpelling(Expanded[0].kind()))
729 auto *StartNode = Tree.commonAncestor();
740 if (!StartNode->Children.empty())
745 auto ExprResult = printExprValue(StartNode,
Context);
746 HI.Value = std::move(ExprResult.PrintedValue);
747 if (
auto *E = ExprResult.TheExpr)
751 if (!HI.Value && !HI.Type && ExprResult.TheNode)
752 if (
auto *VD = ExprResult.TheNode->ASTNode.get<VarDecl>())
762 SourceManager &SM =
AST.getSourceManager();
763 HI.Name = std::string(
Macro.Name);
764 HI.Kind = index::SymbolKind::Macro;
769 SourceLocation StartLoc =
Macro.Info->getDefinitionLoc();
770 SourceLocation EndLoc =
Macro.Info->getDefinitionEndLoc();
778 if (SM.getPresumedLoc(EndLoc,
false).isValid()) {
779 EndLoc = Lexer::getLocForEndOfToken(EndLoc, 0, SM,
AST.getLangOpts());
781 StringRef Buffer = SM.getBufferData(SM.getFileID(StartLoc), &Invalid);
783 unsigned StartOffset = SM.getFileOffset(StartLoc);
784 unsigned EndOffset = SM.getFileOffset(EndLoc);
785 if (EndOffset <= Buffer.size() && StartOffset < EndOffset)
787 (
"#define " + Buffer.substr(StartOffset, EndOffset - StartOffset))
792 if (
auto Expansion =
AST.getTokens().expansionStartingAt(&Tok)) {
796 std::string ExpansionText;
797 for (
const auto &ExpandedTok : Expansion->Expanded) {
798 ExpansionText += ExpandedTok.text(SM);
799 ExpansionText +=
" ";
801 const size_t Limit =
static_cast<size_t>(Cfg.Hover.MacroContentsLimit);
802 if (Limit && ExpansionText.size() > Limit) {
803 ExpansionText.clear();
808 if (!ExpansionText.empty()) {
809 if (!HI.Definition.empty()) {
810 HI.Definition +=
"\n\n";
812 HI.Definition +=
"// Expands to\n";
813 HI.Definition += ExpansionText;
816 auto Evaluated = evaluateMacroExpansion(
817 SM.getFileOffset(Tok.location()),
818 SM.getFileOffset(Tok.endLocation()),
819 Expansion->Expanded,
AST);
820 HI.Value = std::move(Evaluated.Value);
821 HI.Type = std::move(Evaluated.Type);
828 llvm::raw_string_ostream OS(Result);
831 OS <<
" // aka: " << *PType.AKA;
835std::optional<HoverInfo> getThisExprHoverContents(
const CXXThisExpr *CTE,
837 const PrintingPolicy &PP) {
838 QualType OriginThisType = CTE->getType()->getPointeeType();
839 QualType ClassType =
declaredType(OriginThisType->castAsTagDecl());
844 QualType PrettyThisType = ASTCtx.getPointerType(
845 QualType(ClassType.getTypePtr(), OriginThisType.getCVRQualifiers()));
849 HI.Definition = typeAsDefinition(
printType(PrettyThisType, ASTCtx, PP));
854HoverInfo getDeducedTypeHoverContents(QualType QT,
const syntax::Token &Tok,
856 const PrintingPolicy &PP,
860 HI.
Name = tok::getTokenName(Tok.kind());
861 HI.Kind = index::SymbolKind::TypeAlias;
863 if (QT->isUndeducedAutoType()) {
864 HI.Definition =
"/* not deduced */";
866 HI.Definition = typeAsDefinition(
printType(QT, ASTCtx, PP));
868 if (
const auto *D = QT->getAsTagDecl()) {
869 const auto *CommentD = getDeclForComment(D);
871 enhanceFromIndex(HI, *CommentD, Index);
878HoverInfo getStringLiteralContents(
const StringLiteral *SL,
879 const PrintingPolicy &PP) {
882 HI.
Name =
"string-literal";
883 HI.Size = (SL->getLength() + 1) * SL->getCharByteWidth() * 8;
884 HI.Type = SL->getType().getAsString(PP).c_str();
889bool isLiteral(
const Expr *E) {
892 return llvm::isa<CompoundLiteralExpr>(E) ||
893 llvm::isa<CXXBoolLiteralExpr>(E) ||
894 llvm::isa<CXXNullPtrLiteralExpr>(E) ||
895 llvm::isa<FixedPointLiteral>(E) || llvm::isa<FloatingLiteral>(E) ||
896 llvm::isa<ImaginaryLiteral>(E) || llvm::isa<IntegerLiteral>(E) ||
897 llvm::isa<StringLiteral>(E) || llvm::isa<UserDefinedLiteral>(E);
900llvm::StringLiteral getNameForExpr(
const Expr *E) {
908 return llvm::StringLiteral(
"expression");
912 const PrintingPolicy &PP);
918 const PrintingPolicy &PP,
920 std::optional<HoverInfo> HI;
922 if (
const StringLiteral *SL = dyn_cast<StringLiteral>(E)) {
924 HI = getStringLiteralContents(SL, PP);
925 }
else if (isLiteral(E)) {
929 maybeAddCalleeArgInfo(N, HI.emplace(), PP);
930 if (HI->CalleeArgInfo) {
934 HI->Name =
"literal";
941 if (
const CXXThisExpr *CTE = dyn_cast<CXXThisExpr>(E))
942 HI = getThisExprHoverContents(CTE,
AST.getASTContext(), PP);
943 if (
const PredefinedExpr *PE = dyn_cast<PredefinedExpr>(E))
944 HI = getPredefinedExprHoverContents(*PE,
AST.getASTContext(), PP);
947 if (
auto Val = printExprValue(E,
AST.getASTContext())) {
949 HI->Type =
printType(E->getType(),
AST.getASTContext(), PP);
951 HI->Name = std::string(getNameForExpr(E));
955 maybeAddCalleeArgInfo(N, *HI, PP);
961std::optional<HoverInfo> getHoverContents(
const Attr *A,
ParsedAST &
AST) {
963 HI.
Name =
A->getSpelling();
965 HI.LocalScope =
A->getScopeName()->getName().str();
967 llvm::raw_string_ostream OS(HI.Definition);
968 A->printPretty(OS,
AST.getASTContext().getPrintingPolicy());
970 HI.Documentation = Attr::getDocumentation(
A->getKind()).str();
974void addLayoutInfo(
const NamedDecl &ND,
HoverInfo &HI) {
975 if (ND.isInvalidDecl())
978 const auto &Ctx = ND.getASTContext();
979 if (
auto *RD = llvm::dyn_cast<RecordDecl>(&ND)) {
980 CanQualType RT = Ctx.getCanonicalTagType(RD);
981 if (
auto Size = Ctx.getTypeSizeInCharsIfKnown(RT))
982 HI.Size = Size->getQuantity() * 8;
983 if (!RD->isDependentType() && RD->isCompleteDefinition())
984 HI.Align = Ctx.getTypeAlign(RT);
988 if (
const auto *FD = llvm::dyn_cast<FieldDecl>(&ND)) {
989 const auto *
Record = FD->getParent();
992 if (Record && !
Record->isInvalidDecl() && !
Record->isDependentType()) {
993 HI.Align = Ctx.getTypeAlign(FD->getType());
994 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Record);
995 HI.Offset = Layout.getFieldOffset(FD->getFieldIndex());
996 if (FD->isBitField())
997 HI.Size = FD->getBitWidthValue();
998 else if (
auto Size = Ctx.getTypeSizeInCharsIfKnown(FD->getType()))
999 HI.Size = FD->isZeroSize(Ctx) ? 0 : Size->getQuantity() * 8;
1001 unsigned EndOfField = *HI.Offset + *HI.Size;
1004 if (!
Record->isUnion() &&
1005 FD->getFieldIndex() + 1 < Layout.getFieldCount()) {
1007 unsigned NextOffset = Layout.getFieldOffset(FD->getFieldIndex() + 1);
1008 if (NextOffset >= EndOfField)
1009 HI.Padding = NextOffset - EndOfField;
1012 HI.Padding = Layout.getSize().getQuantity() * 8 - EndOfField;
1024 if (ParmType->isReferenceType()) {
1025 if (ParmType->getPointeeType().isConstQualified())
1035 const PrintingPolicy &PP) {
1036 const auto &OuterNode = N->outerImplicit();
1037 if (!OuterNode.Parent)
1040 const FunctionDecl *FD =
nullptr;
1041 llvm::ArrayRef<const Expr *> Args;
1043 if (
const auto *CE = OuterNode.Parent->ASTNode.get<CallExpr>()) {
1044 FD = CE->getDirectCallee();
1045 Args = {CE->getArgs(), CE->getNumArgs()};
1046 }
else if (
const auto *CE =
1047 OuterNode.Parent->ASTNode.get<CXXConstructExpr>()) {
1048 FD = CE->getConstructor();
1049 Args = {CE->getArgs(), CE->getNumArgs()};
1060 if (!FD || FD->isOverloadedOperator() || FD->isVariadic())
1068 for (
unsigned I = 0; I < Args.size() && I < Parameters.size(); ++I) {
1069 if (Args[I] != OuterNode.ASTNode.get<Expr>())
1073 if (
const ParmVarDecl *PVD = Parameters[I]) {
1074 HI.CalleeArgInfo.emplace(toHoverInfoParam(PVD, PP));
1075 if (N == &OuterNode)
1076 PassType.PassBy = getPassMode(PVD->getType());
1080 if (!HI.CalleeArgInfo)
1086 if (
const auto *E = N->ASTNode.get<Expr>()) {
1087 if (E->getType().isConstQualified())
1091 for (
auto *CastNode = N->Parent;
1092 CastNode != OuterNode.Parent && !PassType.Converted;
1093 CastNode = CastNode->Parent) {
1094 if (
const auto *ImplicitCast = CastNode->ASTNode.get<ImplicitCastExpr>()) {
1095 switch (ImplicitCast->getCastKind()) {
1097 case CK_DerivedToBase:
1098 case CK_UncheckedDerivedToBase:
1101 PassType.PassBy = ImplicitCast->getType().isConstQualified()
1105 case CK_LValueToRValue:
1106 case CK_ArrayToPointerDecay:
1107 case CK_FunctionToPointerDecay:
1108 case CK_NullToPointer:
1109 case CK_NullToMemberPointer:
1115 PassType.Converted =
true;
1118 }
else if (
const auto *CtorCall =
1119 CastNode->ASTNode.get<CXXConstructExpr>()) {
1122 if (CtorCall->getConstructor()->isCopyConstructor())
1125 PassType.Converted =
true;
1126 }
else if (CastNode->ASTNode.get<MaterializeTemporaryExpr>()) {
1131 PassType.Converted =
true;
1135 HI.CallPassType.emplace(PassType);
1138const NamedDecl *pickDeclToUse(llvm::ArrayRef<const NamedDecl *> Candidates) {
1139 if (Candidates.empty())
1148 if (Candidates.size() <= 2) {
1149 if (llvm::isa<UsingDecl>(Candidates.front()))
1150 return Candidates.back();
1151 return Candidates.front();
1160 auto BaseDecls = llvm::make_filter_range(
1161 Candidates, [](
const NamedDecl *D) {
return llvm::isa<UsingDecl>(D); });
1162 if (std::distance(BaseDecls.begin(), BaseDecls.end()) == 1)
1163 return *BaseDecls.begin();
1165 return Candidates.front();
1169 include_cleaner::Symbol Sym) {
1170 trace::Span Tracer(
"Hover::maybeAddSymbolProviders");
1172 llvm::SmallVector<include_cleaner::Header> RankedProviders =
1173 include_cleaner::headersForSymbol(Sym,
AST.getPreprocessor(),
1174 &
AST.getPragmaIncludes());
1175 if (RankedProviders.empty())
1178 const SourceManager &SM =
AST.getSourceManager();
1181 for (
const auto &P : RankedProviders) {
1182 if (
P.kind() == include_cleaner::Header::Physical &&
1183 P.physical() == SM.getFileEntryForID(SM.getMainFileID()))
1188 auto Matches = ConvertedIncludes.match(P);
1189 if (!Matches.empty()) {
1190 Result = Matches[0]->quote();
1195 if (!Result.empty()) {
1196 HI.Provider = std::move(Result);
1201 const auto &H = RankedProviders.front();
1202 if (H.kind() == include_cleaner::Header::Physical &&
1203 H.physical() == SM.getFileEntryForID(SM.getMainFileID()))
1208 HI.Provider = include_cleaner::spellHeader(
1209 {H,
AST.getPreprocessor().getHeaderSearchInfo(),
1210 SM.getFileEntryForID(SM.getMainFileID())});
1216std::string getSymbolName(include_cleaner::Symbol Sym) {
1218 switch (Sym.kind()) {
1219 case include_cleaner::Symbol::Declaration:
1220 if (
const auto *ND = llvm::dyn_cast<NamedDecl>(&Sym.declaration()))
1221 Name = ND->getDeclName().getAsString();
1223 case include_cleaner::Symbol::Macro:
1224 Name = Sym.macro().Name->getName();
1232 llvm::DenseSet<include_cleaner::Symbol> UsedSymbols;
1233 include_cleaner::walkUsed(
1235 &
AST.getPragmaIncludes(),
AST.getPreprocessor(),
1236 [&](
const include_cleaner::SymbolReference &
Ref,
1237 llvm::ArrayRef<include_cleaner::Header> Providers) {
1238 if (Ref.RT != include_cleaner::RefType::Explicit ||
1239 UsedSymbols.contains(Ref.Target))
1242 if (isPreferredProvider(Inc, Converted, Providers))
1243 UsedSymbols.insert(Ref.Target);
1246 for (
const auto &UsedSymbolDecl : UsedSymbols)
1247 HI.UsedSymbolNames.push_back(getSymbolName(UsedSymbolDecl));
1248 llvm::sort(HI.UsedSymbolNames);
1249 HI.UsedSymbolNames.erase(llvm::unique(HI.UsedSymbolNames),
1250 HI.UsedSymbolNames.end());
1256 const format::FormatStyle &Style,
1261 getPrintingPolicy(
AST.getASTContext().getPrintingPolicy());
1262 const SourceManager &SM =
AST.getSourceManager();
1265 llvm::consumeError(CurLoc.takeError());
1266 return std::nullopt;
1268 const auto &TB =
AST.getTokens();
1269 auto TokensTouchingCursor = syntax::spelledTokensTouching(*CurLoc, TB);
1271 if (TokensTouchingCursor.empty())
1272 return std::nullopt;
1275 for (
const auto &Inc :
AST.getIncludeStructure().MainFileIncludes) {
1276 if (Inc.Resolved.empty() || Inc.HashLine != Pos.
line)
1278 HoverCountMetric.
record(1,
"include");
1280 HI.
Name = std::string(llvm::sys::path::filename(Inc.Resolved));
1284 HI.
Kind = index::SymbolKind::IncludeDirective;
1285 maybeAddUsedSymbols(
AST, HI, Inc);
1292 CharSourceRange HighlightRange =
1293 TokensTouchingCursor.back().range(SM).toCharRange(SM);
1294 std::optional<HoverInfo> HI;
1298 for (
const auto &Tok : TokensTouchingCursor) {
1299 if (Tok.kind() == tok::identifier) {
1301 HighlightRange = Tok.range(SM).toCharRange(SM);
1303 HoverCountMetric.
record(1,
"macro");
1304 HI = getHoverContents(*M, Tok,
AST);
1305 if (
auto DefLoc = M->Info->getDefinitionLoc(); DefLoc.isValid()) {
1306 include_cleaner::Macro IncludeCleanerMacro{
1307 AST.getPreprocessor().getIdentifierInfo(Tok.text(SM)), DefLoc};
1308 maybeAddSymbolProviders(
AST, *HI,
1309 include_cleaner::Symbol{IncludeCleanerMacro});
1313 }
else if (Tok.kind() == tok::kw_auto || Tok.kind() == tok::kw_decltype) {
1314 HoverCountMetric.
record(1,
"keyword");
1318 HI = getDeducedTypeHoverContents(*
Deduced, Tok,
AST.getASTContext(), PP,
1320 HighlightRange = Tok.range(SM).toCharRange(SM);
1327 return std::nullopt;
1333 auto Offset = SM.getFileOffset(*CurLoc);
1341 AST.getHeuristicResolver());
1342 if (
const auto *DeclToUse = pickDeclToUse(Decls)) {
1343 HoverCountMetric.
record(1,
"decl");
1344 HI = getHoverContents(DeclToUse, PP, Index, TB);
1346 if (DeclToUse == N->ASTNode.get<Decl>())
1347 addLayoutInfo(*DeclToUse, *HI);
1350 HI->Value = printExprValue(N,
AST.getASTContext()).PrintedValue;
1351 maybeAddCalleeArgInfo(N, *HI, PP);
1353 if (!isa<NamespaceDecl>(DeclToUse))
1354 maybeAddSymbolProviders(
AST, *HI,
1355 include_cleaner::Symbol{*DeclToUse});
1356 }
else if (
const Expr *E = N->ASTNode.get<Expr>()) {
1357 HoverCountMetric.
record(1,
"expr");
1358 HI = getHoverContents(N, E,
AST, PP, Index);
1359 }
else if (
const Attr *A = N->ASTNode.get<Attr>()) {
1360 HoverCountMetric.
record(1,
"attribute");
1361 HI = getHoverContents(A,
AST);
1369 return std::nullopt;
1372 if (!HI->Definition.empty()) {
1373 auto Replacements = format::reformat(
1374 Style, HI->Definition, tooling::Range(0, HI->Definition.size()));
1375 if (
auto Formatted =
1376 tooling::applyAllReplacements(HI->Definition, Replacements))
1377 HI->Definition = *Formatted;
1380 HI->DefinitionLanguage = getMarkdownLanguage(
AST.getASTContext());
1388 uint64_t
Value = SizeInBits % 8 == 0 ? SizeInBits / 8 : SizeInBits;
1389 const char *
Unit =
Value != 0 &&
Value == SizeInBits ?
"bit" :
"byte";
1390 return llvm::formatv(
"{0} {1}{2}",
Value,
Unit,
Value == 1 ?
"" :
"s").str();
1396 const auto Bytes = OffsetInBits / 8;
1397 const auto Bits = OffsetInBits % 8;
1404void HoverInfo::calleeArgInfoToMarkupParagraph(markup::Paragraph &P)
const {
1407 llvm::raw_string_ostream OS(Buffer);
1420 OS <<
" (converted to " <<
CalleeArgInfo->Type->Type <<
")";
1421 P.appendText(OS.str());
1424void HoverInfo::usedSymbolNamesToMarkup(markup::Document &Output)
const {
1425 markup::Paragraph &
P = Output.addParagraph();
1426 P.appendText(
"provides ");
1428 const std::vector<std::string>::size_type SymbolNamesLimit = 5;
1429 auto Front = llvm::ArrayRef(
UsedSymbolNames).take_front(SymbolNamesLimit);
1432 Front, [&](llvm::StringRef Sym) {
P.appendCode(Sym); },
1433 [&] {
P.appendText(
", "); });
1435 P.appendText(
" and ");
1437 P.appendText(
" more");
1441void HoverInfo::providerToMarkupParagraph(markup::Document &Output)
const {
1442 markup::Paragraph &DI = Output.addParagraph();
1443 DI.appendText(
"provided by");
1448void HoverInfo::definitionScopeToMarkup(markup::Document &Output)
const {
1458 Buffer +=
"// In " + llvm::StringRef(
LocalScope).rtrim(
':').str() +
'\n';
1460 Buffer +=
"// In namespace " +
1461 llvm::StringRef(*NamespaceScope).rtrim(
':').str() +
'\n';
1474 P.appendText(
"Value = ");
1491markup::Document HoverInfo::presentDoxygen()
const {
1493 markup::Document Output;
1506 markup::Paragraph &Header = Output.addHeading(3);
1507 if (
Kind != index::SymbolKind::Unknown &&
1508 Kind != index::SymbolKind::IncludeDirective)
1509 Header.appendText(index::getSymbolKindString(
Kind)).appendSpace();
1510 assert(!
Name.empty() &&
"hover triggered on a nameless symbol");
1512 if (
Kind == index::SymbolKind::IncludeDirective) {
1513 Header.appendCode(
Name);
1516 Output.addParagraph().appendCode(
Definition);
1520 usedSymbolNamesToMarkup(Output);
1528 definitionScopeToMarkup(Output);
1530 Header.appendCode(
Name);
1534 providerToMarkupParagraph(Output);
1542 if (SymbolDoc.hasBriefCommand()) {
1543 if (
Kind != index::SymbolKind::Parameter &&
1544 Kind != index::SymbolKind::TemplateTypeParm)
1548 Output.addHeading(3).appendText(
"Brief");
1549 SymbolDoc.briefToMarkup(Output.addParagraph());
1562 Output.addHeading(3).appendText(
"Template Parameters");
1563 markup::BulletList &L = Output.addBulletList();
1565 markup::Paragraph &
P = L.addItem().addParagraph();
1566 P.appendCode(llvm::to_string(
Param));
1567 if (SymbolDoc.isTemplateTypeParmDocumented(llvm::to_string(
Param.
Name))) {
1568 P.appendText(
" - ");
1569 SymbolDoc.templateTypeParmDocToMarkup(llvm::to_string(
Param.
Name), P);
1576 Output.addHeading(3).appendText(
"Parameters");
1577 markup::BulletList &L = Output.addBulletList();
1579 markup::Paragraph &
P = L.addItem().addParagraph();
1580 P.appendCode(llvm::to_string(
Param));
1582 if (SymbolDoc.isParameterDocumented(llvm::to_string(
Param.
Name))) {
1583 P.appendText(
" - ");
1584 SymbolDoc.parameterDocToMarkup(llvm::to_string(
Param.
Name), P);
1595 Output.addHeading(3).appendText(
"Returns");
1596 markup::Paragraph &
P = Output.addParagraph();
1599 if (SymbolDoc.hasReturnCommand()) {
1600 P.appendText(
" - ");
1601 SymbolDoc.returnToMarkup(P);
1604 SymbolDoc.retvalsToMarkup(Output);
1608 if (SymbolDoc.hasDetailedDoc()) {
1609 Output.addHeading(3).appendText(
"Details");
1610 SymbolDoc.detailedDocToMarkup(Output);
1618 Output.addParagraph().appendText(
"Type: ").appendCode(
1619 llvm::to_string(*
Type));
1622 valueToMarkupParagraph(Output.addParagraph());
1626 offsetToMarkupParagraph(Output.addParagraph());
1628 sizeToMarkupParagraph(Output.addParagraph());
1632 calleeArgInfoToMarkupParagraph(Output.addParagraph());
1637 usedSymbolNamesToMarkup(Output);
1643markup::Document HoverInfo::presentDefault()
const {
1644 markup::Document Output;
1657 markup::Paragraph &Header = Output.addHeading(3);
1658 if (
Kind != index::SymbolKind::Unknown &&
1659 Kind != index::SymbolKind::IncludeDirective)
1660 Header.appendText(index::getSymbolKindString(
Kind)).appendSpace();
1661 assert(!
Name.empty() &&
"hover triggered on a nameless symbol");
1662 Header.appendCode(
Name);
1665 providerToMarkupParagraph(Output);
1678 Output.addParagraph().appendText(
"→ ").appendCode(
1683 Output.addParagraph().appendText(
"Parameters:");
1684 markup::BulletList &L = Output.addBulletList();
1686 L.addItem().addParagraph().appendCode(llvm::to_string(
Param));
1692 Output.addParagraph().appendText(
"Type: ").appendCode(
1693 llvm::to_string(*
Type));
1696 valueToMarkupParagraph(Output.addParagraph());
1700 offsetToMarkupParagraph(Output.addParagraph());
1702 sizeToMarkupParagraph(Output.addParagraph());
1706 calleeArgInfoToMarkupParagraph(Output.addParagraph());
1714 definitionScopeToMarkup(Output);
1719 usedSymbolNamesToMarkup(Output);
1730 return presentDefault().asMarkdown();
1732 return presentDoxygen().asMarkdown();
1737 return presentDefault().asEscapedMarkdown();
1740 return presentDefault().asPlainText();
1747 assert(Line[Offset] ==
'`');
1750 llvm::StringRef Prefix = Line.substr(0, Offset);
1751 constexpr llvm::StringLiteral BeforeStartChars =
" \t(=";
1752 if (!Prefix.empty() && !BeforeStartChars.contains(Prefix.back()))
1753 return std::nullopt;
1756 auto Next = Line.find_first_of(
"`\n", Offset + 1);
1757 if (Next == llvm::StringRef::npos)
1758 return std::nullopt;
1761 if (Line[Next] ==
'\n')
1762 return std::nullopt;
1764 llvm::StringRef Contents = Line.slice(Offset + 1, Next);
1765 if (Contents.empty() || isWhitespace(Contents.front()) ||
1766 isWhitespace(Contents.back()))
1767 return std::nullopt;
1770 llvm::StringRef Suffix = Line.substr(Next + 1);
1771 constexpr llvm::StringLiteral AfterEndChars =
" \t)=.,;:";
1772 if (!Suffix.empty() && !AfterEndChars.contains(Suffix.front()))
1773 return std::nullopt;
1775 return Line.slice(Offset, Next + 1);
1780 for (
unsigned I = 0; I <
Text.size(); ++I) {
1785 Out.appendCode(
Range->trim(
"`"),
true);
1802 for (std::tie(
Paragraph, Rest) = Input.split(
"\n\n");
1804 std::tie(
Paragraph, Rest) = Rest.split(
"\n\n")) {
1816 OS <<
" (aka " << *T.AKA <<
")";
1825 OS <<
" " << *P.Name;
1827 OS <<
" = " << *P.Default;
1828 if (P.Type && P.Type->AKA)
1829 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::@205014242342057164216030136313205137334246150047 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.