15#include "clang/AST/ASTDiagnostic.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclBase.h"
18#include "clang/AST/DeclarationName.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/RecursiveASTVisitor.h"
22#include "clang/AST/Stmt.h"
23#include "clang/AST/StmtVisitor.h"
24#include "clang/AST/Type.h"
25#include "clang/Basic/Builtins.h"
26#include "clang/Basic/OperatorKinds.h"
27#include "clang/Basic/SourceLocation.h"
28#include "clang/Basic/SourceManager.h"
29#include "clang/Sema/HeuristicResolver.h"
30#include "llvm/ADT/DenseSet.h"
31#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/SmallVector.h"
33#include "llvm/ADT/StringExtras.h"
34#include "llvm/ADT/StringRef.h"
35#include "llvm/ADT/Twine.h"
36#include "llvm/Support/Casting.h"
37#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/FormatVariadic.h"
39#include "llvm/Support/SaveAndRestore.h"
40#include "llvm/Support/ScopedPrinter.h"
41#include "llvm/Support/raw_ostream.h"
54void stripLeadingUnderscores(StringRef &Name) { Name = Name.ltrim(
'_'); }
58const NamedDecl *getDeclForType(
const Type *T) {
59 switch (
T->getTypeClass()) {
62 case Type::InjectedClassName:
63 return cast<TagType>(T)->getOriginalDecl();
64 case Type::TemplateSpecialization:
65 return cast<TemplateSpecializationType>(T)
67 .getAsTemplateDecl(
true);
69 return cast<TypedefType>(T)->getDecl();
70 case Type::UnresolvedUsing:
71 return cast<UnresolvedUsingType>(T)->getDecl();
73 return cast<UsingType>(T)->getDecl();
77 llvm_unreachable(
"Unknown TypeClass enum");
81llvm::StringRef getSimpleName(
const DeclarationName &DN) {
82 if (IdentifierInfo *Ident = DN.getAsIdentifierInfo())
83 return Ident->getName();
86llvm::StringRef getSimpleName(
const NamedDecl &D) {
87 return getSimpleName(
D.getDeclName());
89llvm::StringRef getSimpleName(QualType T) {
90 if (
const auto *BT = llvm::dyn_cast<BuiltinType>(T)) {
91 PrintingPolicy PP(LangOptions{});
92 PP.adjustForCPlusPlus();
93 return BT->getName(PP);
95 if (
const auto *D = getDeclForType(
T.getTypePtr()))
96 return getSimpleName(
D->getDeclName());
103std::string summarizeExpr(
const Expr *E) {
104 struct Namer : ConstStmtVisitor<Namer, std::string> {
105 std::string Visit(
const Expr *E) {
108 return ConstStmtVisitor::Visit(E->IgnoreImplicit());
112 std::string VisitMemberExpr(
const MemberExpr *E) {
113 return getSimpleName(*E->getMemberDecl()).str();
115 std::string VisitDeclRefExpr(
const DeclRefExpr *E) {
116 return getSimpleName(*E->getFoundDecl()).str();
118 std::string VisitCallExpr(
const CallExpr *E) {
119 std::string Result = Visit(E->getCallee());
120 Result += E->getNumArgs() == 0 ?
"()" :
"(...)";
124 VisitCXXDependentScopeMemberExpr(
const CXXDependentScopeMemberExpr *E) {
125 return getSimpleName(E->getMember()).str();
128 VisitDependentScopeDeclRefExpr(
const DependentScopeDeclRefExpr *E) {
129 return getSimpleName(E->getDeclName()).str();
131 std::string VisitCXXFunctionalCastExpr(
const CXXFunctionalCastExpr *E) {
132 return getSimpleName(E->getType()).str();
134 std::string VisitCXXTemporaryObjectExpr(
const CXXTemporaryObjectExpr *E) {
135 return getSimpleName(E->getType()).str();
139 std::string VisitCXXMemberCallExpr(
const CXXMemberCallExpr *E) {
141 if (E->getNumArgs() == 0 && E->getMethodDecl() &&
142 E->getMethodDecl()->getDeclName().getNameKind() ==
143 DeclarationName::CXXConversionFunctionName &&
144 E->getSourceRange() ==
145 E->getImplicitObjectArgument()->getSourceRange())
146 return Visit(E->getImplicitObjectArgument());
147 return ConstStmtVisitor::VisitCXXMemberCallExpr(E);
149 std::string VisitCXXConstructExpr(
const CXXConstructExpr *E) {
150 if (E->getNumArgs() == 1)
151 return Visit(E->getArg(0));
156 std::string VisitCXXNullPtrLiteralExpr(
const CXXNullPtrLiteralExpr *E) {
159 std::string VisitCXXBoolLiteralExpr(
const CXXBoolLiteralExpr *E) {
160 return E->getValue() ?
"true" :
"false";
162 std::string VisitIntegerLiteral(
const IntegerLiteral *E) {
163 return llvm::to_string(E->getValue());
165 std::string VisitFloatingLiteral(
const FloatingLiteral *E) {
167 llvm::raw_string_ostream OS(Result);
168 E->getValue().print(OS);
170 Result.resize(llvm::StringRef(Result).rtrim().size());
173 std::string VisitStringLiteral(
const StringLiteral *E) {
174 std::string Result =
"\"";
175 if (E->containsNonAscii()) {
178 llvm::raw_string_ostream OS(Result);
179 if (E->getLength() > 10) {
180 llvm::printEscapedString(E->getString().take_front(7), OS);
183 llvm::printEscapedString(E->getString(), OS);
186 Result.push_back(
'"');
191 std::string printUnary(llvm::StringRef Spelling,
const Expr *Operand,
193 std::string Sub = Visit(Operand);
197 return (Spelling + Sub).str();
201 bool InsideBinary =
false;
202 std::string printBinary(llvm::StringRef Spelling,
const Expr *LHSOp,
206 llvm::SaveAndRestore InBinary(InsideBinary,
true);
208 std::string LHS = Visit(LHSOp);
209 std::string RHS = Visit(RHSOp);
210 if (LHS.empty() && RHS.empty())
224 std::string VisitUnaryOperator(
const UnaryOperator *E) {
225 return printUnary(E->getOpcodeStr(E->getOpcode()), E->getSubExpr(),
228 std::string VisitBinaryOperator(
const BinaryOperator *E) {
229 return printBinary(E->getOpcodeStr(E->getOpcode()), E->getLHS(),
232 std::string VisitCXXOperatorCallExpr(
const CXXOperatorCallExpr *E) {
233 const char *Spelling = getOperatorSpelling(E->getOperator());
235 if ((E->getOperator() == OO_PlusPlus ||
236 E->getOperator() == OO_MinusMinus) &&
237 E->getNumArgs() == 2)
238 return printUnary(Spelling, E->getArg(0),
false);
239 if (E->isInfixBinaryOp())
240 return printBinary(Spelling, E->getArg(0), E->getArg(1));
241 if (E->getNumArgs() == 1) {
242 switch (E->getOperator()) {
251 return printUnary(Spelling, E->getArg(0),
true);
259 return Namer{}.Visit(E);
264bool isSugaredTemplateParameter(QualType QT) {
265 static auto PeelWrapper = [](QualType QT) {
268 QualType Peeled = QT->getPointeeType();
269 return Peeled.isNull() ? QT : Peeled;
297 if (QT->getAs<SubstTemplateTypeParmType>())
299 QualType Desugared = QT->getLocallyUnqualifiedSingleStepDesugaredType();
302 else if (
auto Peeled = PeelWrapper(Desugared); Peeled != QT)
312std::optional<QualType> desugar(ASTContext &
AST, QualType QT) {
313 bool ShouldAKA =
false;
314 auto Desugared = clang::desugarForDiagnostic(
AST, QT, ShouldAKA);
327QualType maybeDesugar(ASTContext &
AST, QualType QT) {
331 if (isSugaredTemplateParameter(QT))
332 return desugar(
AST, QT).value_or(QT);
335 if (QT->isDecltypeType())
336 return QT.getCanonicalType();
337 if (
const AutoType *AT = QT->getContainedAutoType())
338 if (!AT->getDeducedType().isNull() &&
339 AT->getDeducedType()->isDecltypeType())
340 return QT.getCanonicalType();
345ArrayRef<const ParmVarDecl *>
346maybeDropCxxExplicitObjectParameters(ArrayRef<const ParmVarDecl *> Params) {
347 if (!Params.empty() && Params.front()->isExplicitObjectParameter())
348 Params = Params.drop_front(1);
353std::string joinAndTruncate(
const R &
Range,
size_t MaxLength) {
355 llvm::raw_string_ostream OS(Out);
356 llvm::ListSeparator Sep(
", ");
357 for (
auto &&Element :
Range) {
359 if (Out.size() + Element.size() >= MaxLength) {
372 const FunctionDecl *Decl =
nullptr;
373 FunctionProtoTypeLoc Loc;
376class InlayHintVisitor :
public RecursiveASTVisitor<InlayHintVisitor> {
378 InlayHintVisitor(std::vector<InlayHint> &Results, ParsedAST &AST,
379 const Config &Cfg, std::optional<Range> RestrictRange,
380 InlayHintOptions HintOptions)
381 : Results(Results), AST(AST.getASTContext()), Tokens(AST.getTokens()),
382 Cfg(Cfg), RestrictRange(std::move(RestrictRange)),
383 MainFileID(AST.getSourceManager().getMainFileID()),
384 Resolver(AST.getHeuristicResolver()),
385 TypeHintPolicy(this->AST.getPrintingPolicy()),
386 HintOptions(HintOptions) {
388 llvm::StringRef Buf =
389 AST.getSourceManager().getBufferData(MainFileID, &Invalid);
390 MainFileBuf =
Invalid ? StringRef{} : Buf;
392 TypeHintPolicy.SuppressScope =
true;
393 TypeHintPolicy.AnonymousTagLocations =
400 bool VisitTypeLoc(TypeLoc TL) {
401 if (
const auto *DT = llvm::dyn_cast<DecltypeType>(TL.getType()))
402 if (QualType UT = DT->getUnderlyingType(); !UT->isDependentType())
403 addTypeHint(TL.getSourceRange(), UT,
": ");
407 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
412 if (!E->getParenOrBraceRange().isValid() ||
413 E->isStdInitListInitialization()) {
418 Callee.Decl = E->getConstructor();
421 processCall(Callee, E->getParenOrBraceRange().getEnd(),
422 {E->getArgs(), E->getNumArgs()});
428 bool TraversePseudoObjectExpr(PseudoObjectExpr *E) {
429 Expr *SyntacticExpr = E->getSyntacticForm();
430 if (isa<CallExpr>(SyntacticExpr))
437 return RecursiveASTVisitor<InlayHintVisitor>::TraverseStmt(SyntacticExpr);
445 if (isa<BinaryOperator>(SyntacticExpr))
448 return RecursiveASTVisitor<InlayHintVisitor>::TraversePseudoObjectExpr(E);
451 bool VisitCallExpr(CallExpr *E) {
452 if (!Cfg.InlayHints.Parameters)
455 bool IsFunctor = isFunctionObjectCallExpr(E);
460 if ((isa<CXXOperatorCallExpr>(E) && !IsFunctor) ||
461 isa<UserDefinedLiteral>(E))
464 auto CalleeDecls = Resolver->resolveCalleeOfCallExpr(E);
465 if (CalleeDecls.size() != 1)
469 if (
const auto *FD = dyn_cast<FunctionDecl>(CalleeDecls[0]))
471 else if (
const auto *FTD = dyn_cast<FunctionTemplateDecl>(CalleeDecls[0]))
472 Callee.Decl = FTD->getTemplatedDecl();
473 else if (FunctionProtoTypeLoc Loc =
474 Resolver->getFunctionProtoTypeLoc(E->getCallee()))
489 llvm::ArrayRef<const Expr *> Args = {E->getArgs(), E->getNumArgs()};
492 if (
const CXXMethodDecl *
Method =
493 dyn_cast_or_null<CXXMethodDecl>(Callee.Decl))
494 if (IsFunctor ||
Method->hasCXXExplicitFunctionObjectParameter())
495 Args = Args.drop_front(1);
496 processCall(Callee, E->getRParenLoc(), Args);
500 bool VisitFunctionDecl(FunctionDecl *D) {
502 llvm::dyn_cast<FunctionProtoType>(
D->getType().getTypePtr())) {
503 if (!FPT->hasTrailingReturn()) {
504 if (
auto FTL =
D->getFunctionTypeLoc())
505 addReturnTypeHint(D, FTL.getRParenLoc());
508 if (Cfg.InlayHints.BlockEnd &&
D->isThisDeclarationADefinition()) {
511 if (
const Stmt *Body =
D->getBody())
512 addBlockEndHint(Body->getSourceRange(),
"",
printName(AST, *D),
"");
517 bool VisitForStmt(ForStmt *S) {
518 if (Cfg.InlayHints.BlockEnd) {
521 if (
auto *DS = llvm::dyn_cast_or_null<DeclStmt>(S->getInit());
522 DS && DS->isSingleDecl())
523 Name = getSimpleName(llvm::cast<NamedDecl>(*DS->getSingleDecl()));
525 Name = summarizeExpr(S->getCond());
526 markBlockEnd(S->getBody(),
"for", Name);
531 bool VisitCXXForRangeStmt(CXXForRangeStmt *S) {
532 if (Cfg.InlayHints.BlockEnd)
533 markBlockEnd(S->getBody(),
"for", getSimpleName(*S->getLoopVariable()));
537 bool VisitWhileStmt(WhileStmt *S) {
538 if (Cfg.InlayHints.BlockEnd)
539 markBlockEnd(S->getBody(),
"while", summarizeExpr(S->getCond()));
543 bool VisitSwitchStmt(SwitchStmt *S) {
544 if (Cfg.InlayHints.BlockEnd)
545 markBlockEnd(S->getBody(),
"switch", summarizeExpr(S->getCond()));
555 llvm::DenseSet<const IfStmt *> ElseIfs;
556 bool VisitIfStmt(IfStmt *S) {
557 if (Cfg.InlayHints.BlockEnd) {
558 if (
const auto *ElseIf = llvm::dyn_cast_or_null<IfStmt>(S->getElse()))
559 ElseIfs.insert(ElseIf);
561 if (
const auto *EndCS = llvm::dyn_cast<CompoundStmt>(
562 S->getElse() ? S->getElse() : S->getThen())) {
564 {S->getThen()->getBeginLoc(), EndCS->getRBracLoc()},
"if",
565 ElseIfs.contains(S) ?
"" : summarizeExpr(S->getCond()),
"");
571 void markBlockEnd(
const Stmt *Body, llvm::StringRef
Label,
572 llvm::StringRef Name =
"") {
573 if (
const auto *CS = llvm::dyn_cast_or_null<CompoundStmt>(Body))
574 addBlockEndHint(CS->getSourceRange(),
Label, Name,
"");
577 bool VisitTagDecl(TagDecl *D) {
578 if (Cfg.InlayHints.BlockEnd &&
D->isThisDeclarationADefinition()) {
579 std::string DeclPrefix =
D->getKindName().str();
580 if (
const auto *ED = dyn_cast<EnumDecl>(D)) {
582 DeclPrefix += ED->isScopedUsingClassTag() ?
" class" :
" struct";
584 addBlockEndHint(
D->getBraceRange(), DeclPrefix, getSimpleName(*D),
";");
589 bool VisitNamespaceDecl(NamespaceDecl *D) {
590 if (Cfg.InlayHints.BlockEnd) {
593 addBlockEndHint(
D->getSourceRange(),
"namespace", getSimpleName(*D),
"");
598 bool VisitLambdaExpr(LambdaExpr *E) {
599 FunctionDecl *
D = E->getCallOperator();
600 if (!E->hasExplicitResultType()) {
601 SourceLocation TypeHintLoc;
602 if (!E->hasExplicitParameters())
603 TypeHintLoc = E->getIntroducerRange().getEnd();
604 else if (
auto FTL =
D->getFunctionTypeLoc())
605 TypeHintLoc = FTL.getRParenLoc();
606 if (TypeHintLoc.isValid())
607 addReturnTypeHint(D, TypeHintLoc);
612 void addReturnTypeHint(FunctionDecl *D, SourceRange Range) {
613 auto *AT =
D->getReturnType()->getContainedAutoType();
614 if (!AT || AT->getDeducedType().isNull())
616 addTypeHint(Range,
D->getReturnType(),
"-> ");
619 bool VisitVarDecl(VarDecl *D) {
622 if (
auto *DD = dyn_cast<DecompositionDecl>(D)) {
623 for (
auto *Binding : DD->bindings()) {
627 if (
auto Type = Binding->getType();
628 !
Type.isNull() && !
Type->isDependentType())
629 addTypeHint(Binding->getLocation(),
Type.getCanonicalType(),
635 if (
auto *AT =
D->getType()->getContainedAutoType()) {
636 if (AT->isDeduced()) {
642 if (
D->getType()->isDependentType()) {
644 QualType Resolved = Resolver->resolveExprToType(
D->getInit());
645 if (Resolved != AST.DependentTy) {
658 addTypeHint(
D->getLocation(), T,
": ");
664 if (
auto *PVD = llvm::dyn_cast<ParmVarDecl>(D)) {
665 if (
D->getIdentifier() && PVD->getType()->isDependentType() &&
668 if (
auto *IPVD = getOnlyParamInstantiation(PVD))
669 addTypeHint(
D->getLocation(), IPVD->getType(),
": ");
676 ParmVarDecl *getOnlyParamInstantiation(ParmVarDecl *D) {
677 auto *TemplateFunction = llvm::dyn_cast<FunctionDecl>(
D->getDeclContext());
678 if (!TemplateFunction)
680 auto *InstantiatedFunction = llvm::dyn_cast_or_null<FunctionDecl>(
682 if (!InstantiatedFunction)
685 unsigned ParamIdx = 0;
686 for (
auto *Param : TemplateFunction->parameters()) {
689 if (Param->isParameterPack())
695 assert(ParamIdx < TemplateFunction->getNumParams() &&
696 "Couldn't find param in list?");
697 assert(ParamIdx < InstantiatedFunction->getNumParams() &&
698 "Instantiated function has fewer (non-pack) parameters?");
699 return InstantiatedFunction->getParamDecl(ParamIdx);
702 bool VisitInitListExpr(InitListExpr *Syn) {
709 assert(Syn->isSyntacticForm() &&
"RAV should not visit implicit code!");
710 if (!Cfg.InlayHints.Designators)
712 if (Syn->isIdiomaticZeroInitializer(AST.getLangOpts()))
714 llvm::DenseMap<SourceLocation, std::string> Designators =
716 for (
const Expr *Init : Syn->inits()) {
717 if (llvm::isa<DesignatedInitExpr>(Init))
719 auto It = Designators.find(Init->getBeginLoc());
720 if (It != Designators.end() &&
721 !isPrecededByParamNameComment(Init, It->second))
722 addDesignatorHint(Init->getSourceRange(), It->second);
730 using NameVec = SmallVector<StringRef, 8>;
732 void processCall(Callee Callee, SourceLocation RParenOrBraceLoc,
733 llvm::ArrayRef<const Expr *> Args) {
734 assert(Callee.Decl || Callee.Loc);
736 if ((!Cfg.InlayHints.Parameters && !Cfg.InlayHints.DefaultArguments) ||
742 if (
auto *Ctor = dyn_cast<CXXConstructorDecl>(Callee.Decl))
743 if (Ctor->isCopyOrMoveConstructor())
746 SmallVector<std::string> FormattedDefaultArgs;
747 bool HasNonDefaultArgs =
false;
749 ArrayRef<const ParmVarDecl *> Params, ForwardedParams;
751 SmallVector<const ParmVarDecl *> ForwardedParamsStorage;
753 Params = maybeDropCxxExplicitObjectParameters(Callee.Decl->parameters());
756 maybeDropCxxExplicitObjectParameters(ForwardedParamsStorage);
758 Params = maybeDropCxxExplicitObjectParameters(Callee.Loc.getParams());
759 ForwardedParams = {Params.begin(), Params.end()};
762 NameVec ParameterNames = chooseParameterNames(ForwardedParams);
768 (isSetter(Callee.Decl, ParameterNames) || isSimpleBuiltin(Callee.Decl)))
771 for (
size_t I = 0; I < ParameterNames.size() && I < Args.size(); ++I) {
775 if (isa<PackExpansionExpr>(Args[I])) {
779 StringRef Name = ParameterNames[I];
780 const bool NameHint =
781 shouldHintName(Args[I], Name) && Cfg.InlayHints.Parameters;
782 const bool ReferenceHint =
783 shouldHintReference(Params[I], ForwardedParams[I]) &&
784 Cfg.InlayHints.Parameters;
786 const bool IsDefault = isa<CXXDefaultArgExpr>(Args[I]);
787 HasNonDefaultArgs |= !IsDefault;
789 if (Cfg.InlayHints.DefaultArguments) {
790 const auto SourceText = Lexer::getSourceText(
791 CharSourceRange::getTokenRange(Params[I]->getDefaultArgRange()),
792 AST.getSourceManager(), AST.getLangOpts());
794 (SourceText.size() > Cfg.InlayHints.TypeNameLimit ||
795 SourceText.contains(
"\n"))
799 FormattedDefaultArgs.emplace_back(
800 llvm::formatv(
"{0}: {1}", Name, Abbrev));
802 FormattedDefaultArgs.emplace_back(llvm::formatv(
"{0}", Abbrev));
804 }
else if (NameHint || ReferenceHint) {
805 addInlayHint(Args[I]->getSourceRange(), HintSide::Left,
807 NameHint ? Name :
"",
": ");
811 if (!FormattedDefaultArgs.empty()) {
813 joinAndTruncate(FormattedDefaultArgs, Cfg.InlayHints.TypeNameLimit);
814 addInlayHint(SourceRange{RParenOrBraceLoc}, HintSide::Left,
816 HasNonDefaultArgs ?
", " :
"", Hint,
"");
820 static bool isSetter(
const FunctionDecl *Callee,
const NameVec &ParamNames) {
821 if (ParamNames.size() != 1)
824 StringRef Name = getSimpleName(*Callee);
825 if (!Name.starts_with_insensitive(
"set"))
839 StringRef WhatItIsSetting = Name.substr(3).ltrim(
"_");
840 return WhatItIsSetting.equals_insensitive(ParamNames[0]);
845 static bool isSimpleBuiltin(
const FunctionDecl *Callee) {
846 switch (Callee->getBuiltinID()) {
847 case Builtin::BIaddressof:
848 case Builtin::BIas_const:
849 case Builtin::BIforward:
850 case Builtin::BImove:
851 case Builtin::BImove_if_noexcept:
858 bool shouldHintName(
const Expr *Arg, StringRef ParamName) {
859 if (ParamName.empty())
864 if (ParamName == getSpelledIdentifier(Arg))
868 if (isPrecededByParamNameComment(Arg, ParamName))
874 bool shouldHintReference(
const ParmVarDecl *Param,
875 const ParmVarDecl *ForwardedParam) {
898 auto Type = Param->getType();
899 auto ForwardedType = ForwardedParam->getType();
900 return Type->isLValueReferenceType() &&
901 ForwardedType->isLValueReferenceType() &&
902 !ForwardedType.getNonReferenceType().isConstQualified() &&
909 bool isPrecededByParamNameComment(
const Expr *E, StringRef ParamName) {
910 auto &SM = AST.getSourceManager();
911 auto FileLoc = SM.getFileLoc(E->getBeginLoc());
912 auto Decomposed = SM.getDecomposedLoc(FileLoc);
913 if (Decomposed.first != MainFileID)
916 StringRef SourcePrefix = MainFileBuf.substr(0, Decomposed.second);
918 SourcePrefix = SourcePrefix.rtrim();
920 if (!SourcePrefix.consume_back(
"*/"))
924 llvm::StringLiteral IgnoreChars =
" =.";
925 SourcePrefix = SourcePrefix.rtrim(IgnoreChars);
926 ParamName = ParamName.trim(IgnoreChars);
928 if (!SourcePrefix.consume_back(ParamName))
930 SourcePrefix = SourcePrefix.rtrim(IgnoreChars);
931 return SourcePrefix.ends_with(
"/*");
936 static StringRef getSpelledIdentifier(
const Expr *E) {
937 E = E->IgnoreUnlessSpelledInSource();
939 if (
auto *DRE = dyn_cast<DeclRefExpr>(E))
940 if (!DRE->getQualifier())
941 return getSimpleName(*DRE->getDecl());
943 if (
auto *ME = dyn_cast<MemberExpr>(E))
944 if (!ME->getQualifier() && ME->isImplicitAccess())
945 return getSimpleName(*ME->getMemberDecl());
950 NameVec chooseParameterNames(ArrayRef<const ParmVarDecl *> Parameters) {
951 NameVec ParameterNames;
952 for (
const auto *P : Parameters) {
957 ParameterNames.emplace_back();
959 auto SimpleName = getSimpleName(*P);
962 if (SimpleName.empty()) {
963 if (
const auto *PD = getParamDefinition(P)) {
964 SimpleName = getSimpleName(*PD);
967 ParameterNames.emplace_back(SimpleName);
973 for (
auto &Name : ParameterNames)
974 stripLeadingUnderscores(Name);
976 return ParameterNames;
981 static const ParmVarDecl *getParamDefinition(
const ParmVarDecl *P) {
982 if (
auto *Callee = dyn_cast<FunctionDecl>(
P->getDeclContext())) {
983 if (
auto *Def = Callee->getDefinition()) {
984 auto I = std::distance(Callee->param_begin(),
985 llvm::find(Callee->parameters(), P));
986 if (I < (
int)Callee->getNumParams()) {
987 return Def->getParamDecl(I);
996 void addInlayHint(SourceRange R, HintSide Side,
InlayHintKind Kind,
997 llvm::StringRef Prefix, llvm::StringRef
Label,
998 llvm::StringRef Suffix) {
999 auto LSPRange = getHintRange(R);
1003 addInlayHint(*LSPRange, Side, Kind, Prefix,
Label, Suffix);
1006 void addInlayHint(Range LSPRange, HintSide Side,
InlayHintKind Kind,
1007 llvm::StringRef Prefix, llvm::StringRef
Label,
1008 llvm::StringRef Suffix) {
1012 assert(Cfg.InlayHints.Enabled &&
"Shouldn't get here if disabled!");
1014#define CHECK_KIND(Enumerator, ConfigProperty) \
1015 case InlayHintKind::Enumerator: \
1016 assert(Cfg.InlayHints.ConfigProperty && \
1017 "Shouldn't get here if kind is disabled!"); \
1018 if (!Cfg.InlayHints.ConfigProperty) \
1029 Position LSPPos = Side == HintSide::Left ? LSPRange.start : LSPRange.end;
1030 if (RestrictRange &&
1031 (LSPPos < RestrictRange->start || !(LSPPos < RestrictRange->end)))
1033 bool PadLeft = Prefix.consume_front(
" ");
1034 bool PadRight = Suffix.consume_back(
" ");
1035 Results.push_back(InlayHint{LSPPos,
1036 {(Prefix +
Label + Suffix).str()},
1037 Kind, PadLeft, PadRight, LSPRange});
1041 std::optional<Range> getHintRange(SourceRange R) {
1042 const auto &SM = AST.getSourceManager();
1043 auto Spelled = Tokens.spelledForExpanded(Tokens.expandedTokens(R));
1047 return std::nullopt;
1049 if (SM.getFileID(
Spelled->front().location()) != SM.getMainFileID() ||
1050 SM.getFileID(
Spelled->back().location()) != SM.getMainFileID())
1051 return std::nullopt;
1056 void addTypeHint(SourceRange R, QualType T, llvm::StringRef Prefix) {
1057 if (!Cfg.InlayHints.DeducedTypes ||
T.isNull())
1062 auto Desugared = maybeDesugar(AST, T);
1063 std::string TypeName = Desugared.getAsString(TypeHintPolicy);
1064 if (T != Desugared && !shouldPrintTypeHint(TypeName)) {
1067 TypeName =
T.getAsString(TypeHintPolicy);
1069 if (shouldPrintTypeHint(TypeName))
1074 void addDesignatorHint(SourceRange R, llvm::StringRef
Text) {
1079 bool shouldPrintTypeHint(llvm::StringRef TypeName)
const noexcept {
1080 return Cfg.InlayHints.TypeNameLimit == 0 ||
1081 TypeName.size() < Cfg.InlayHints.TypeNameLimit;
1084 void addBlockEndHint(SourceRange BraceRange, StringRef DeclPrefix,
1085 StringRef Name, StringRef OptionalPunctuation) {
1086 auto HintRange = computeBlockEndHintRange(BraceRange, OptionalPunctuation);
1090 std::string
Label = DeclPrefix.str();
1091 if (!
Label.empty() && !Name.empty())
1095 constexpr unsigned HintMaxLengthLimit = 60;
1096 if (
Label.length() > HintMaxLengthLimit)
1109 std::optional<Range> computeBlockEndHintRange(SourceRange BraceRange,
1110 StringRef OptionalPunctuation) {
1112 auto &SM = AST.getSourceManager();
1113 auto [BlockBeginFileId, BlockBeginOffset] =
1114 SM.getDecomposedLoc(SM.getFileLoc(BraceRange.getBegin()));
1115 auto RBraceLoc = SM.getFileLoc(BraceRange.getEnd());
1116 auto [RBraceFileId, RBraceOffset] = SM.getDecomposedLoc(RBraceLoc);
1122 if (BlockBeginFileId != MainFileID || RBraceFileId != MainFileID)
1123 return std::nullopt;
1125 StringRef RestOfLine = MainFileBuf.substr(RBraceOffset).split(
'\n').first;
1126 if (!RestOfLine.starts_with(
"}"))
1127 return std::nullopt;
1129 StringRef TrimmedTrailingText = RestOfLine.drop_front().trim();
1130 if (!TrimmedTrailingText.empty() &&
1131 TrimmedTrailingText != OptionalPunctuation)
1132 return std::nullopt;
1134 auto BlockBeginLine = SM.getLineNumber(BlockBeginFileId, BlockBeginOffset);
1135 auto RBraceLine = SM.getLineNumber(RBraceFileId, RBraceOffset);
1138 if (BlockBeginLine + HintOptions.HintMinLineLimit - 1 > RBraceLine)
1139 return std::nullopt;
1142 StringRef HintRangeText = RestOfLine.take_front(
1143 TrimmedTrailingText.empty()
1145 : TrimmedTrailingText.bytes_end() - RestOfLine.bytes_begin());
1149 SM, RBraceLoc.getLocWithOffset(HintRangeText.size()));
1150 return Range{HintStart, HintEnd};
1153 static bool isFunctionObjectCallExpr(CallExpr *E)
noexcept {
1154 if (
auto *CallExpr = dyn_cast<CXXOperatorCallExpr>(E))
1155 return CallExpr->getOperator() == OverloadedOperatorKind::OO_Call;
1159 std::vector<InlayHint> &Results;
1161 const syntax::TokenBuffer &Tokens;
1163 std::optional<Range> RestrictRange;
1165 StringRef MainFileBuf;
1166 const HeuristicResolver *Resolver;
1167 PrintingPolicy TypeHintPolicy;
1168 InlayHintOptions HintOptions;
1174 std::optional<Range> RestrictRange,
1176 std::vector<InlayHint> Results;
1178 if (!Cfg.InlayHints.Enabled)
1180 InlayHintVisitor Visitor(Results,
AST, Cfg, std::move(RestrictRange),
1182 Visitor.TraverseAST(
AST.getASTContext());
1186 llvm::sort(Results);
1187 Results.erase(llvm::unique(Results), Results.end());
static cl::opt< std::string > Config("config", desc(R"(
Specifies a configuration in YAML/JSON format:
-config="{Checks:' *', CheckOptions:{x:y}}"
When the value is empty, clang-tidy will
attempt to find a file named .clang-tidy for
each source file in its parent directories.
)"), cl::init(""), cl::cat(ClangTidyCategory))
This file provides utilities for designated initializers.
#define CHECK_KIND(Enumerator, ConfigProperty)
Stores and provides access to parsed AST.
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 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...
@ DefaultArgument
An inlay hint that is for a default argument.
@ 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.
TemplateTypeParmTypeLoc getContainedAutoParamType(TypeLoc TL)
std::vector< InlayHint > inlayHints(ParsedAST &AST, std::optional< Range > RestrictRange, InlayHintOptions HintOptions)
Compute and return inlay hints for a file.
@ Invalid
Sentinel bit pattern. DO NOT USE!
llvm::DenseMap< SourceLocation, std::string > getUnwrittenDesignators(const InitListExpr *Syn)
cppcoreguidelines::ProBoundsAvoidUncheckedContainerAccess P
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
static const Config & current()
Returns the Config of the current Context, or an empty configuration.