9#include "../clang-tidy/utils/DesignatedInitializers.h"
15#include "clang/AST/ASTDiagnostic.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclarationName.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/RecursiveASTVisitor.h"
21#include "clang/AST/Stmt.h"
22#include "clang/AST/StmtVisitor.h"
23#include "clang/AST/Type.h"
24#include "clang/Basic/Builtins.h"
25#include "clang/Basic/OperatorKinds.h"
26#include "clang/Basic/SourceManager.h"
27#include "llvm/ADT/DenseSet.h"
28#include "llvm/ADT/StringExtras.h"
29#include "llvm/ADT/StringRef.h"
30#include "llvm/ADT/Twine.h"
31#include "llvm/Support/Casting.h"
32#include "llvm/Support/SaveAndRestore.h"
33#include "llvm/Support/ScopedPrinter.h"
34#include "llvm/Support/raw_ostream.h"
45void stripLeadingUnderscores(StringRef &
Name) {
Name =
Name.ltrim(
'_'); }
49template <
typename Ty,
typename =
decltype(((Ty *)
nullptr)->getDecl())>
50const NamedDecl *getDeclForTypeImpl(
const Ty *T) {
53const NamedDecl *getDeclForTypeImpl(
const void *T) {
return nullptr; }
54const NamedDecl *getDeclForType(
const Type *T) {
55 switch (
T->getTypeClass()) {
56#define ABSTRACT_TYPE(TY, BASE)
57#define TYPE(TY, BASE) \
59 return getDeclForTypeImpl(llvm::cast<TY##Type>(T));
60#include "clang/AST/TypeNodes.inc"
62 llvm_unreachable(
"Unknown TypeClass enum");
66llvm::StringRef getSimpleName(
const DeclarationName &DN) {
67 if (IdentifierInfo *Ident = DN.getAsIdentifierInfo())
68 return Ident->getName();
71llvm::StringRef getSimpleName(
const NamedDecl &D) {
72 return getSimpleName(D.getDeclName());
74llvm::StringRef getSimpleName(QualType T) {
75 if (
const auto *ET = llvm::dyn_cast<ElaboratedType>(T))
76 return getSimpleName(ET->getNamedType());
77 if (
const auto *BT = llvm::dyn_cast<BuiltinType>(T)) {
78 PrintingPolicy PP(LangOptions{});
79 PP.adjustForCPlusPlus();
80 return BT->getName(PP);
82 if (
const auto *D = getDeclForType(
T.getTypePtr()))
83 return getSimpleName(D->getDeclName());
90std::string summarizeExpr(
const Expr *
E) {
91 struct Namer : ConstStmtVisitor<Namer, std::string> {
92 std::string Visit(
const Expr *
E) {
95 return ConstStmtVisitor::Visit(
E->IgnoreImplicit());
99 std::string VisitMemberExpr(
const MemberExpr *
E) {
100 return getSimpleName(*
E->getMemberDecl()).str();
102 std::string VisitDeclRefExpr(
const DeclRefExpr *
E) {
103 return getSimpleName(*
E->getFoundDecl()).str();
105 std::string VisitCallExpr(
const CallExpr *
E) {
106 return Visit(
E->getCallee());
109 VisitCXXDependentScopeMemberExpr(
const CXXDependentScopeMemberExpr *
E) {
110 return getSimpleName(
E->getMember()).str();
113 VisitDependentScopeDeclRefExpr(
const DependentScopeDeclRefExpr *
E) {
114 return getSimpleName(
E->getDeclName()).str();
116 std::string VisitCXXFunctionalCastExpr(
const CXXFunctionalCastExpr *
E) {
117 return getSimpleName(
E->getType()).str();
119 std::string VisitCXXTemporaryObjectExpr(
const CXXTemporaryObjectExpr *
E) {
120 return getSimpleName(
E->getType()).str();
124 std::string VisitCXXMemberCallExpr(
const CXXMemberCallExpr *
E) {
126 if (
E->getNumArgs() == 0 &&
E->getMethodDecl() &&
127 E->getMethodDecl()->getDeclName().getNameKind() ==
128 DeclarationName::CXXConversionFunctionName &&
129 E->getSourceRange() ==
130 E->getImplicitObjectArgument()->getSourceRange())
131 return Visit(
E->getImplicitObjectArgument());
132 return ConstStmtVisitor::VisitCXXMemberCallExpr(
E);
134 std::string VisitCXXConstructExpr(
const CXXConstructExpr *
E) {
135 if (
E->getNumArgs() == 1)
136 return Visit(
E->getArg(0));
141 std::string VisitCXXBoolLiteralExpr(
const CXXBoolLiteralExpr *
E) {
142 return E->getValue() ?
"true" :
"false";
144 std::string VisitIntegerLiteral(
const IntegerLiteral *
E) {
145 return llvm::to_string(
E->getValue());
147 std::string VisitFloatingLiteral(
const FloatingLiteral *
E) {
149 llvm::raw_string_ostream
OS(Result);
150 E->getValue().print(
OS);
152 Result.resize(llvm::StringRef(Result).rtrim().size());
155 std::string VisitStringLiteral(
const StringLiteral *
E) {
156 std::string Result =
"\"";
157 if (
E->containsNonAscii()) {
159 }
else if (
E->getLength() > 10) {
160 Result +=
E->getString().take_front(7);
163 llvm::raw_string_ostream
OS(Result);
164 llvm::printEscapedString(
E->getString(),
OS);
166 Result.push_back(
'"');
171 std::string printUnary(llvm::StringRef Spelling,
const Expr *Operand,
173 std::string Sub = Visit(Operand);
177 return (Spelling + Sub).str();
181 bool InsideBinary =
false;
182 std::string printBinary(llvm::StringRef Spelling,
const Expr *LHSOp,
186 llvm::SaveAndRestore InBinary(InsideBinary,
true);
188 std::string LHS = Visit(LHSOp);
189 std::string RHS = Visit(RHSOp);
190 if (LHS.empty() && RHS.empty())
204 std::string VisitUnaryOperator(
const UnaryOperator *
E) {
205 return printUnary(
E->getOpcodeStr(
E->getOpcode()),
E->getSubExpr(),
208 std::string VisitBinaryOperator(
const BinaryOperator *
E) {
209 return printBinary(
E->getOpcodeStr(
E->getOpcode()),
E->getLHS(),
212 std::string VisitCXXOperatorCallExpr(
const CXXOperatorCallExpr *
E) {
213 const char *Spelling = getOperatorSpelling(
E->getOperator());
215 if ((
E->getOperator() == OO_PlusPlus ||
216 E->getOperator() == OO_MinusMinus) &&
217 E->getNumArgs() == 2)
218 return printUnary(Spelling,
E->getArg(0),
false);
219 if (
E->isInfixBinaryOp())
220 return printBinary(Spelling,
E->getArg(0),
E->getArg(1));
221 if (
E->getNumArgs() == 1) {
222 switch (
E->getOperator()) {
231 return printUnary(Spelling,
E->getArg(0),
true);
239 return Namer{}.Visit(
E);
244bool isSugaredTemplateParameter(QualType QT) {
245 static auto PeelWrapper = [](QualType QT) {
248 QualType Peeled = QT->getPointeeType();
249 return Peeled.isNull() ? QT : Peeled;
277 if (QT->getAs<SubstTemplateTypeParmType>())
279 QualType Desugared = QT->getLocallyUnqualifiedSingleStepDesugaredType();
282 else if (
auto Peeled = PeelWrapper(Desugared); Peeled != QT)
292std::optional<QualType> desugar(ASTContext &
AST, QualType QT) {
293 bool ShouldAKA =
false;
294 auto Desugared = clang::desugarForDiagnostic(
AST, QT, ShouldAKA);
307QualType maybeDesugar(ASTContext &
AST, QualType QT) {
311 if (isSugaredTemplateParameter(QT))
312 return desugar(
AST, QT).value_or(QT);
315 if (QT->isDecltypeType())
316 return QT.getCanonicalType();
317 if (
const AutoType *AT = QT->getContainedAutoType())
318 if (!AT->getDeducedType().isNull() &&
319 AT->getDeducedType()->isDecltypeType())
320 return QT.getCanonicalType();
329static FunctionProtoTypeLoc getPrototypeLoc(Expr *Fn) {
331 Expr *NakedFn = Fn->IgnoreParenCasts();
332 if (
const auto *T = NakedFn->getType().getTypePtr()->getAs<TypedefType>()) {
333 Target =
T->getDecl()->getTypeSourceInfo()->getTypeLoc();
334 }
else if (
const auto *DR = dyn_cast<DeclRefExpr>(NakedFn)) {
335 const auto *D = DR->getDecl();
336 if (
const auto *
const VD = dyn_cast<VarDecl>(D)) {
337 Target = VD->getTypeSourceInfo()->getTypeLoc();
346 if (
auto P = Target.getAs<PointerTypeLoc>()) {
347 Target = P.getPointeeLoc();
350 if (
auto A = Target.getAs<AttributedTypeLoc>()) {
351 Target =
A.getModifiedLoc();
354 if (
auto P = Target.getAs<ParenTypeLoc>()) {
355 Target = P.getInnerLoc();
361 if (
auto F = Target.getAs<FunctionProtoTypeLoc>()) {
368ArrayRef<const ParmVarDecl *>
369maybeDropCxxExplicitObjectParameters(ArrayRef<const ParmVarDecl *> Params) {
370 if (!Params.empty() && Params.front()->isExplicitObjectParameter())
371 Params = Params.drop_front(1);
378 const FunctionDecl *
Decl =
nullptr;
384 InlayHintVisitor(std::vector<InlayHint> &
Results, ParsedAST &
AST,
385 const Config &Cfg, std::optional<Range> RestrictRange)
387 Cfg(Cfg), RestrictRange(std::move(RestrictRange)),
388 MainFileID(
AST.getSourceManager().getMainFileID()),
389 Resolver(
AST.getHeuristicResolver()),
390 TypeHintPolicy(this->AST.getPrintingPolicy()) {
392 llvm::StringRef Buf =
393 AST.getSourceManager().getBufferData(MainFileID, &
Invalid);
394 MainFileBuf =
Invalid ? StringRef{} : Buf;
396 TypeHintPolicy.SuppressScope =
true;
397 TypeHintPolicy.AnonymousTagLocations =
404 bool VisitTypeLoc(TypeLoc TL) {
405 if (
const auto *DT = llvm::dyn_cast<DecltypeType>(TL.getType()))
406 if (QualType UT = DT->getUnderlyingType(); !UT->isDependentType())
407 addTypeHint(TL.getSourceRange(), UT,
": ");
411 bool VisitCXXConstructExpr(CXXConstructExpr *
E) {
416 if (!
E->getParenOrBraceRange().isValid() ||
417 E->isStdInitListInitialization()) {
422 Callee.Decl =
E->getConstructor();
425 processCall(Callee, {
E->getArgs(),
E->getNumArgs()});
431 bool TraversePseudoObjectExpr(PseudoObjectExpr *
E) {
432 Expr *SyntacticExpr =
E->getSyntacticForm();
433 if (isa<CallExpr>(SyntacticExpr))
448 if (isa<BinaryOperator>(SyntacticExpr))
454 bool VisitCallExpr(CallExpr *
E) {
458 bool IsFunctor = isFunctionObjectCallExpr(
E);
463 if ((isa<CXXOperatorCallExpr>(
E) && !IsFunctor) ||
464 isa<UserDefinedLiteral>(
E))
468 if (CalleeDecls.size() != 1)
472 if (
const auto *FD = dyn_cast<FunctionDecl>(CalleeDecls[0]))
474 else if (
const auto *FTD = dyn_cast<FunctionTemplateDecl>(CalleeDecls[0]))
475 Callee.Decl = FTD->getTemplatedDecl();
476 else if (FunctionProtoTypeLoc
Loc = getPrototypeLoc(
E->getCallee()))
491 llvm::ArrayRef<const Expr *>
Args = {
E->getArgs(),
E->getNumArgs()};
494 if (
const CXXMethodDecl *
Method =
495 dyn_cast_or_null<CXXMethodDecl>(Callee.Decl))
496 if (IsFunctor ||
Method->hasCXXExplicitFunctionObjectParameter())
498 processCall(Callee,
Args);
502 bool VisitFunctionDecl(FunctionDecl *D) {
504 llvm::dyn_cast<FunctionProtoType>(D->getType().getTypePtr())) {
505 if (!FPT->hasTrailingReturn()) {
506 if (
auto FTL = D->getFunctionTypeLoc())
507 addReturnTypeHint(D, FTL.getRParenLoc());
513 if (
const Stmt *Body = D->getBody())
514 addBlockEndHint(Body->getSourceRange(),
"",
printName(
AST, *D),
"");
519 bool VisitForStmt(ForStmt *S) {
523 if (
auto *DS = llvm::dyn_cast_or_null<DeclStmt>(S->getInit());
524 DS && DS->isSingleDecl())
525 Name = getSimpleName(llvm::cast<NamedDecl>(*DS->getSingleDecl()));
527 Name = summarizeExpr(S->getCond());
528 markBlockEnd(S->getBody(),
"for",
Name);
533 bool VisitCXXForRangeStmt(CXXForRangeStmt *S) {
535 markBlockEnd(S->getBody(),
"for", getSimpleName(*S->getLoopVariable()));
539 bool VisitWhileStmt(WhileStmt *S) {
541 markBlockEnd(S->getBody(),
"while", summarizeExpr(S->getCond()));
545 bool VisitSwitchStmt(SwitchStmt *S) {
547 markBlockEnd(S->getBody(),
"switch", summarizeExpr(S->getCond()));
558 bool VisitIfStmt(IfStmt *S) {
560 if (
const auto *ElseIf = llvm::dyn_cast_or_null<IfStmt>(S->getElse()))
563 if (
const auto *EndCS = llvm::dyn_cast<CompoundStmt>(
564 S->getElse() ? S->getElse() : S->getThen())) {
566 {S->getThen()->getBeginLoc(), EndCS->getRBracLoc()},
"if",
567 ElseIfs.contains(S) ?
"" : summarizeExpr(S->getCond()),
"");
573 void markBlockEnd(
const Stmt *Body, llvm::StringRef
Label,
574 llvm::StringRef
Name =
"") {
575 if (
const auto *CS = llvm::dyn_cast_or_null<CompoundStmt>(Body))
576 addBlockEndHint(CS->getSourceRange(),
Label,
Name,
"");
579 bool VisitTagDecl(TagDecl *D) {
581 std::string DeclPrefix = D->getKindName().str();
582 if (
const auto *ED = dyn_cast<EnumDecl>(D)) {
584 DeclPrefix += ED->isScopedUsingClassTag() ?
" class" :
" struct";
586 addBlockEndHint(D->getBraceRange(), DeclPrefix, getSimpleName(*D),
";");
591 bool VisitNamespaceDecl(NamespaceDecl *D) {
595 addBlockEndHint(D->getSourceRange(),
"namespace", getSimpleName(*D),
"");
600 bool VisitLambdaExpr(LambdaExpr *
E) {
601 FunctionDecl *D =
E->getCallOperator();
602 if (!
E->hasExplicitResultType())
603 addReturnTypeHint(D,
E->hasExplicitParameters()
604 ? D->getFunctionTypeLoc().getRParenLoc()
605 :
E->getIntroducerRange().getEnd());
609 void addReturnTypeHint(FunctionDecl *D, SourceRange Range) {
610 auto *AT = D->getReturnType()->getContainedAutoType();
611 if (!AT || AT->getDeducedType().isNull())
613 addTypeHint(Range, D->getReturnType(),
"-> ");
616 bool VisitVarDecl(VarDecl *D) {
619 if (
auto *DD = dyn_cast<DecompositionDecl>(D)) {
620 for (
auto *Binding : DD->bindings()) {
624 if (
auto Type = Binding->getType();
625 !
Type.isNull() && !
Type->isDependentType())
626 addTypeHint(Binding->getLocation(),
Type.getCanonicalType(),
632 if (
auto *AT = D->getType()->getContainedAutoType()) {
633 if (AT->isDeduced() && !D->getType()->isDependentType()) {
639 addTypeHint(D->getLocation(), D->getType(),
": ");
644 if (
auto *PVD = llvm::dyn_cast<ParmVarDecl>(D)) {
645 if (D->getIdentifier() && PVD->getType()->isDependentType() &&
648 if (
auto *IPVD = getOnlyParamInstantiation(PVD))
649 addTypeHint(D->getLocation(), IPVD->getType(),
": ");
656 ParmVarDecl *getOnlyParamInstantiation(ParmVarDecl *D) {
657 auto *TemplateFunction = llvm::dyn_cast<FunctionDecl>(D->getDeclContext());
658 if (!TemplateFunction)
660 auto *InstantiatedFunction = llvm::dyn_cast_or_null<FunctionDecl>(
662 if (!InstantiatedFunction)
665 unsigned ParamIdx = 0;
666 for (
auto *Param : TemplateFunction->parameters()) {
669 if (Param->isParameterPack())
675 assert(ParamIdx < TemplateFunction->getNumParams() &&
676 "Couldn't find param in list?");
677 assert(ParamIdx < InstantiatedFunction->getNumParams() &&
678 "Instantiated function has fewer (non-pack) parameters?");
679 return InstantiatedFunction->getParamDecl(ParamIdx);
682 bool VisitInitListExpr(InitListExpr *Syn) {
689 assert(Syn->isSyntacticForm() &&
"RAV should not visit implicit code!");
692 if (Syn->isIdiomaticZeroInitializer(
AST.getLangOpts()))
694 llvm::DenseMap<SourceLocation, std::string> Designators =
696 for (
const Expr *Init : Syn->inits()) {
697 if (llvm::isa<DesignatedInitExpr>(Init))
699 auto It = Designators.find(Init->getBeginLoc());
700 if (It != Designators.end() &&
701 !isPrecededByParamNameComment(Init, It->second))
702 addDesignatorHint(Init->getSourceRange(), It->second);
710 using NameVec = SmallVector<StringRef, 8>;
712 void processCall(Callee Callee, llvm::ArrayRef<const Expr *>
Args) {
713 assert(Callee.Decl || Callee.Loc);
720 if (
auto *Ctor = dyn_cast<CXXConstructorDecl>(Callee.Decl))
721 if (Ctor->isCopyOrMoveConstructor())
724 ArrayRef<const ParmVarDecl *> Params, ForwardedParams;
726 SmallVector<const ParmVarDecl *> ForwardedParamsStorage;
728 Params = maybeDropCxxExplicitObjectParameters(Callee.Decl->parameters());
731 maybeDropCxxExplicitObjectParameters(ForwardedParamsStorage);
733 Params = maybeDropCxxExplicitObjectParameters(Callee.Loc.getParams());
734 ForwardedParams = {Params.begin(), Params.end()};
737 NameVec ParameterNames = chooseParameterNames(ForwardedParams);
743 (isSetter(Callee.Decl, ParameterNames) || isSimpleBuiltin(Callee.Decl)))
746 for (
size_t I = 0; I < ParameterNames.size() && I <
Args.size(); ++I) {
750 if (isa<PackExpansionExpr>(
Args[I])) {
754 StringRef
Name = ParameterNames[I];
755 bool NameHint = shouldHintName(
Args[I],
Name);
756 bool ReferenceHint = shouldHintReference(Params[I], ForwardedParams[I]);
758 if (NameHint || ReferenceHint) {
759 addInlayHint(
Args[I]->getSourceRange(), HintSide::Left,
761 NameHint ?
Name :
"",
": ");
766 static bool isSetter(
const FunctionDecl *Callee,
const NameVec &ParamNames) {
767 if (ParamNames.size() != 1)
770 StringRef
Name = getSimpleName(*Callee);
771 if (!
Name.starts_with_insensitive(
"set"))
785 StringRef WhatItIsSetting =
Name.substr(3).ltrim(
"_");
786 return WhatItIsSetting.equals_insensitive(ParamNames[0]);
791 static bool isSimpleBuiltin(
const FunctionDecl *Callee) {
792 switch (Callee->getBuiltinID()) {
793 case Builtin::BIaddressof:
794 case Builtin::BIas_const:
795 case Builtin::BIforward:
796 case Builtin::BImove:
797 case Builtin::BImove_if_noexcept:
804 bool shouldHintName(
const Expr *Arg, StringRef ParamName) {
805 if (ParamName.empty())
810 if (ParamName == getSpelledIdentifier(Arg))
814 if (isPrecededByParamNameComment(Arg, ParamName))
820 bool shouldHintReference(
const ParmVarDecl *Param,
821 const ParmVarDecl *ForwardedParam) {
844 auto Type = Param->getType();
845 auto ForwardedType = ForwardedParam->getType();
846 return Type->isLValueReferenceType() &&
847 ForwardedType->isLValueReferenceType() &&
848 !ForwardedType.getNonReferenceType().isConstQualified() &&
855 bool isPrecededByParamNameComment(
const Expr *
E, StringRef ParamName) {
856 auto &SM =
AST.getSourceManager();
857 auto FileLoc = SM.getFileLoc(
E->getBeginLoc());
858 auto Decomposed = SM.getDecomposedLoc(FileLoc);
859 if (Decomposed.first != MainFileID)
862 StringRef SourcePrefix = MainFileBuf.substr(0, Decomposed.second);
864 SourcePrefix = SourcePrefix.rtrim();
866 if (!SourcePrefix.consume_back(
"*/"))
870 llvm::StringLiteral IgnoreChars =
" =.";
871 SourcePrefix = SourcePrefix.rtrim(IgnoreChars);
872 ParamName = ParamName.trim(IgnoreChars);
874 if (!SourcePrefix.consume_back(ParamName))
876 SourcePrefix = SourcePrefix.rtrim(IgnoreChars);
877 return SourcePrefix.ends_with(
"/*");
882 static StringRef getSpelledIdentifier(
const Expr *
E) {
883 E =
E->IgnoreUnlessSpelledInSource();
885 if (
auto *DRE = dyn_cast<DeclRefExpr>(
E))
886 if (!DRE->getQualifier())
887 return getSimpleName(*DRE->getDecl());
889 if (
auto *ME = dyn_cast<MemberExpr>(
E))
890 if (!ME->getQualifier() && ME->isImplicitAccess())
891 return getSimpleName(*ME->getMemberDecl());
896 NameVec chooseParameterNames(ArrayRef<const ParmVarDecl *>
Parameters) {
897 NameVec ParameterNames;
903 ParameterNames.emplace_back();
905 auto SimpleName = getSimpleName(*P);
908 if (SimpleName.empty()) {
909 if (
const auto *PD = getParamDefinition(P)) {
910 SimpleName = getSimpleName(*PD);
913 ParameterNames.emplace_back(SimpleName);
919 for (
auto &
Name : ParameterNames)
920 stripLeadingUnderscores(
Name);
922 return ParameterNames;
927 static const ParmVarDecl *getParamDefinition(
const ParmVarDecl *P) {
928 if (
auto *Callee = dyn_cast<FunctionDecl>(P->getDeclContext())) {
929 if (
auto *Def = Callee->getDefinition()) {
930 auto I = std::distance(Callee->param_begin(),
931 llvm::find(Callee->parameters(), P));
932 if (I < (
int)Callee->getNumParams()) {
933 return Def->getParamDecl(I);
943 llvm::StringRef Prefix, llvm::StringRef
Label,
945 auto LSPRange = getHintRange(R);
953 llvm::StringRef Prefix, llvm::StringRef
Label,
960#define CHECK_KIND(Enumerator, ConfigProperty) \
961 case InlayHintKind::Enumerator: \
962 assert(Cfg.InlayHints.ConfigProperty && \
963 "Shouldn't get here if kind is disabled!"); \
964 if (!Cfg.InlayHints.ConfigProperty) \
974 Position LSPPos =
Side == HintSide::Left ? LSPRange.start : LSPRange.end;
976 (LSPPos < RestrictRange->start || !(LSPPos < RestrictRange->end)))
978 bool PadLeft = Prefix.consume_front(
" ");
979 bool PadRight =
Suffix.consume_back(
" ");
980 Results.push_back(InlayHint{LSPPos,
982 Kind, PadLeft, PadRight, LSPRange});
986 std::optional<Range> getHintRange(SourceRange R) {
987 const auto &SM =
AST.getSourceManager();
988 auto Spelled = Tokens.spelledForExpanded(Tokens.expandedTokens(R));
994 if (SM.getFileID(
Spelled->front().location()) != SM.getMainFileID() ||
995 SM.getFileID(
Spelled->back().location()) != SM.getMainFileID())
1001 void addTypeHint(SourceRange R, QualType T, llvm::StringRef Prefix) {
1007 auto Desugared = maybeDesugar(
AST, T);
1008 std::string TypeName = Desugared.getAsString(TypeHintPolicy);
1009 if (T != Desugared && !shouldPrintTypeHint(TypeName)) {
1012 TypeName =
T.getAsString(TypeHintPolicy);
1014 if (shouldPrintTypeHint(TypeName))
1019 void addDesignatorHint(SourceRange R, llvm::StringRef
Text) {
1024 bool shouldPrintTypeHint(llvm::StringRef TypeName)
const noexcept {
1029 void addBlockEndHint(SourceRange BraceRange, StringRef DeclPrefix,
1030 StringRef
Name, StringRef OptionalPunctuation) {
1031 auto HintRange = computeBlockEndHintRange(BraceRange, OptionalPunctuation);
1035 std::string
Label = DeclPrefix.str();
1040 constexpr unsigned HintMaxLengthLimit = 60;
1041 if (
Label.length() > HintMaxLengthLimit)
1054 std::optional<Range> computeBlockEndHintRange(SourceRange BraceRange,
1055 StringRef OptionalPunctuation) {
1056 constexpr unsigned HintMinLineLimit = 2;
1058 auto &SM =
AST.getSourceManager();
1059 auto [BlockBeginFileId, BlockBeginOffset] =
1060 SM.getDecomposedLoc(SM.getFileLoc(BraceRange.getBegin()));
1061 auto RBraceLoc = SM.getFileLoc(BraceRange.getEnd());
1062 auto [RBraceFileId, RBraceOffset] = SM.getDecomposedLoc(RBraceLoc);
1068 if (BlockBeginFileId != MainFileID || RBraceFileId != MainFileID)
1069 return std::nullopt;
1071 StringRef RestOfLine = MainFileBuf.substr(RBraceOffset).split(
'\n').first;
1072 if (!RestOfLine.starts_with(
"}"))
1073 return std::nullopt;
1075 StringRef TrimmedTrailingText = RestOfLine.drop_front().trim();
1076 if (!TrimmedTrailingText.empty() &&
1077 TrimmedTrailingText != OptionalPunctuation)
1078 return std::nullopt;
1080 auto BlockBeginLine = SM.getLineNumber(BlockBeginFileId, BlockBeginOffset);
1081 auto RBraceLine = SM.getLineNumber(RBraceFileId, RBraceOffset);
1084 if (BlockBeginLine + HintMinLineLimit - 1 > RBraceLine)
1085 return std::nullopt;
1088 StringRef HintRangeText = RestOfLine.take_front(
1089 TrimmedTrailingText.empty()
1091 : TrimmedTrailingText.bytes_end() - RestOfLine.bytes_begin());
1095 SM, RBraceLoc.getLocWithOffset(HintRangeText.size()));
1096 return Range{HintStart, HintEnd};
1099 static bool isFunctionObjectCallExpr(CallExpr *
E)
noexcept {
1100 if (
auto *CallExpr = dyn_cast<CXXOperatorCallExpr>(
E))
1101 return CallExpr->getOperator() == OverloadedOperatorKind::OO_Call;
1105 std::vector<InlayHint> &
Results;
1107 const syntax::TokenBuffer &Tokens;
1109 std::optional<Range> RestrictRange;
1111 StringRef MainFileBuf;
1112 const HeuristicResolver *Resolver;
1113 PrintingPolicy TypeHintPolicy;
1119 std::optional<Range> RestrictRange) {
1120 std::vector<InlayHint>
Results;
1124 InlayHintVisitor Visitor(
Results,
AST, Cfg, std::move(RestrictRange));
1125 Visitor.TraverseAST(
AST.getASTContext());
ArrayRef< const ParmVarDecl * > Parameters
const FunctionDecl * Decl
llvm::SmallString< 256U > Name
std::vector< CodeCompletionResult > Results
CharSourceRange Range
SourceRange for the file name.
llvm::DenseSet< const IfStmt * > ElseIfs
#define CHECK_KIND(Enumerator, ConfigProperty)
llvm::raw_string_ostream OS
std::vector< const NamedDecl * > resolveCalleeOfCallExpr(const CallExpr *CE) const
Stores and provides access to parsed AST.
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 printName(const ASTContext &Ctx, const NamedDecl &ND)
Prints unqualified name of the decl for the purpose of displaying it to the user.
NamedDecl * getOnlyInstantiation(NamedDecl *TemplatedDecl)
Position sourceLocToPosition(const SourceManager &SM, SourceLocation Loc)
Turn a SourceLocation into a [line, column] pair.
bool isExpandedFromParameterPack(const ParmVarDecl *D)
Checks whether D is instantiated from a function parameter pack whose type is a bare type parameter p...
InlayHintKind
Inlay hint kinds.
@ BlockEnd
A hint after function, type or namespace definition, indicating the defined symbol name of the defini...
@ Parameter
An inlay hint that is for a parameter.
@ Type
An inlay hint that for a type annotation.
@ Designator
A hint before an element of an aggregate braced initializer list, indicating what it is initializing.
std::vector< InlayHint > inlayHints(ParsedAST &AST, std::optional< Range > RestrictRange)
Compute and return inlay hints for a file.
TemplateTypeParmTypeLoc getContainedAutoParamType(TypeLoc TL)
@ Invalid
Sentinel bit pattern. DO NOT USE!
llvm::DenseMap< SourceLocation, std::string > getUnwrittenDesignators(const InitListExpr *Syn)
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
static const Config & current()
Returns the Config of the current Context, or an empty configuration.
bool Enabled
If false, inlay hints are completely disabled.
struct clang::clangd::Config::@8 InlayHints