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)->getDecl();
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) {
387 bool Invalid =
false;
388 llvm::StringRef Buf =
389 AST.getSourceManager().getBufferData(MainFileID, &Invalid);
390 MainFileBuf = Invalid ? StringRef{} : Buf;
392 TypeHintPolicy.SuppressScope =
true;
393 TypeHintPolicy.AnonymousTagNameStyle = llvm::to_underlying(
394 PrintingPolicy::AnonymousTagMode::Plain);
401 bool VisitTypeLoc(TypeLoc TL) {
402 if (
const auto *DT = llvm::dyn_cast<DecltypeType>(TL.getType()))
403 if (QualType UT = DT->getUnderlyingType(); !UT->isDependentType())
404 addTypeHint(TL.getSourceRange(), UT,
": ");
408 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
413 if (!E->getParenOrBraceRange().isValid() ||
414 E->isStdInitListInitialization()) {
419 Callee.Decl = E->getConstructor();
422 processCall(Callee, E->getParenOrBraceRange().getEnd(),
423 {E->getArgs(), E->getNumArgs()});
429 bool TraversePseudoObjectExpr(PseudoObjectExpr *E) {
430 Expr *SyntacticExpr = E->getSyntacticForm();
431 if (isa<CallExpr>(SyntacticExpr))
438 return RecursiveASTVisitor<InlayHintVisitor>::TraverseStmt(SyntacticExpr);
446 if (isa<BinaryOperator>(SyntacticExpr))
449 return RecursiveASTVisitor<InlayHintVisitor>::TraversePseudoObjectExpr(E);
452 bool VisitCallExpr(CallExpr *E) {
453 if (!Cfg.InlayHints.Parameters)
456 bool IsFunctor = isFunctionObjectCallExpr(E);
461 if ((isa<CXXOperatorCallExpr>(E) && !IsFunctor) ||
462 isa<UserDefinedLiteral>(E))
465 auto CalleeDecls = Resolver->resolveCalleeOfCallExpr(E);
466 if (CalleeDecls.size() != 1)
470 if (
const auto *FD = dyn_cast<FunctionDecl>(CalleeDecls[0]))
472 else if (
const auto *FTD = dyn_cast<FunctionTemplateDecl>(CalleeDecls[0]))
473 Callee.Decl = FTD->getTemplatedDecl();
474 else if (FunctionProtoTypeLoc Loc =
475 Resolver->getFunctionProtoTypeLoc(E->getCallee()))
490 llvm::ArrayRef<const Expr *> Args = {E->getArgs(), E->getNumArgs()};
493 if (
const CXXMethodDecl *
Method =
494 dyn_cast_or_null<CXXMethodDecl>(Callee.Decl))
495 if (IsFunctor ||
Method->hasCXXExplicitFunctionObjectParameter())
496 Args = Args.drop_front(1);
497 processCall(Callee, E->getRParenLoc(), Args);
501 bool VisitFunctionDecl(FunctionDecl *D) {
503 llvm::dyn_cast<FunctionProtoType>(
D->getType().getTypePtr())) {
504 if (!FPT->hasTrailingReturn()) {
505 if (
auto FTL =
D->getFunctionTypeLoc())
506 addReturnTypeHint(D, FTL.getRParenLoc());
509 if (Cfg.InlayHints.BlockEnd &&
D->isThisDeclarationADefinition()) {
512 if (
const Stmt *Body =
D->getBody())
513 addBlockEndHint(Body->getSourceRange(),
"",
printName(AST, *D),
"");
518 bool VisitForStmt(ForStmt *S) {
519 if (Cfg.InlayHints.BlockEnd) {
522 if (
auto *DS = llvm::dyn_cast_or_null<DeclStmt>(S->getInit());
523 DS && DS->isSingleDecl())
524 Name = getSimpleName(llvm::cast<NamedDecl>(*DS->getSingleDecl()));
526 Name = summarizeExpr(S->getCond());
527 markBlockEnd(S->getBody(),
"for", Name);
532 bool VisitCXXForRangeStmt(CXXForRangeStmt *S) {
533 if (Cfg.InlayHints.BlockEnd)
534 markBlockEnd(S->getBody(),
"for", getSimpleName(*S->getLoopVariable()));
538 bool VisitWhileStmt(WhileStmt *S) {
539 if (Cfg.InlayHints.BlockEnd)
540 markBlockEnd(S->getBody(),
"while", summarizeExpr(S->getCond()));
544 bool VisitSwitchStmt(SwitchStmt *S) {
545 if (Cfg.InlayHints.BlockEnd)
546 markBlockEnd(S->getBody(),
"switch", summarizeExpr(S->getCond()));
556 llvm::DenseSet<const IfStmt *> ElseIfs;
557 bool VisitIfStmt(IfStmt *S) {
558 if (Cfg.InlayHints.BlockEnd) {
559 if (
const auto *ElseIf = llvm::dyn_cast_or_null<IfStmt>(S->getElse()))
560 ElseIfs.insert(ElseIf);
562 if (
const auto *EndCS = llvm::dyn_cast<CompoundStmt>(
563 S->getElse() ? S->getElse() : S->getThen())) {
565 {S->getThen()->getBeginLoc(), EndCS->getRBracLoc()},
"if",
566 ElseIfs.contains(S) ?
"" : summarizeExpr(S->getCond()),
"");
572 void markBlockEnd(
const Stmt *Body, llvm::StringRef
Label,
573 llvm::StringRef Name =
"") {
574 if (
const auto *CS = llvm::dyn_cast_or_null<CompoundStmt>(Body))
575 addBlockEndHint(CS->getSourceRange(),
Label, Name,
"");
578 bool VisitTagDecl(TagDecl *D) {
579 if (Cfg.InlayHints.BlockEnd &&
D->isThisDeclarationADefinition()) {
580 std::string DeclPrefix =
D->getKindName().str();
581 if (
const auto *ED = dyn_cast<EnumDecl>(D)) {
583 DeclPrefix += ED->isScopedUsingClassTag() ?
" class" :
" struct";
585 addBlockEndHint(
D->getBraceRange(), DeclPrefix, getSimpleName(*D),
";");
590 bool VisitNamespaceDecl(NamespaceDecl *D) {
591 if (Cfg.InlayHints.BlockEnd) {
594 addBlockEndHint(
D->getSourceRange(),
"namespace", getSimpleName(*D),
"");
599 bool VisitLambdaExpr(LambdaExpr *E) {
600 FunctionDecl *
D = E->getCallOperator();
601 if (!E->hasExplicitResultType()) {
602 SourceLocation TypeHintLoc;
603 if (!E->hasExplicitParameters())
604 TypeHintLoc = E->getIntroducerRange().getEnd();
605 else if (
auto FTL =
D->getFunctionTypeLoc())
606 TypeHintLoc = FTL.getRParenLoc();
607 if (TypeHintLoc.isValid())
608 addReturnTypeHint(D, TypeHintLoc);
613 void addReturnTypeHint(FunctionDecl *D, SourceRange Range) {
614 auto *AT =
D->getReturnType()->getContainedAutoType();
615 if (!AT || AT->getDeducedType().isNull())
617 addTypeHint(Range,
D->getReturnType(),
"-> ");
620 bool VisitVarDecl(VarDecl *D) {
623 if (
auto *DD = dyn_cast<DecompositionDecl>(D)) {
624 for (
auto *Binding : DD->bindings()) {
628 if (
auto Type = Binding->getType();
629 !
Type.isNull() && !
Type->isDependentType())
630 addTypeHint(Binding->getLocation(),
Type.getCanonicalType(),
636 if (
auto *AT =
D->getType()->getContainedAutoType()) {
637 if (AT->isDeduced()) {
643 if (
D->getType()->isDependentType()) {
645 QualType Resolved = Resolver->resolveExprToType(
D->getInit());
646 if (Resolved != AST.DependentTy) {
659 addTypeHint(
D->getLocation(), T,
": ");
665 if (
auto *PVD = llvm::dyn_cast<ParmVarDecl>(D)) {
666 if (
D->getIdentifier() && PVD->getType()->isDependentType() &&
669 if (
auto *IPVD = getOnlyParamInstantiation(PVD))
670 addTypeHint(
D->getLocation(), IPVD->getType(),
": ");
677 ParmVarDecl *getOnlyParamInstantiation(ParmVarDecl *D) {
678 auto *TemplateFunction = llvm::dyn_cast<FunctionDecl>(
D->getDeclContext());
679 if (!TemplateFunction)
681 auto *InstantiatedFunction = llvm::dyn_cast_or_null<FunctionDecl>(
683 if (!InstantiatedFunction)
686 unsigned ParamIdx = 0;
687 for (
auto *Param : TemplateFunction->parameters()) {
690 if (Param->isParameterPack())
696 assert(ParamIdx < TemplateFunction->getNumParams() &&
697 "Couldn't find param in list?");
698 assert(ParamIdx < InstantiatedFunction->getNumParams() &&
699 "Instantiated function has fewer (non-pack) parameters?");
700 return InstantiatedFunction->getParamDecl(ParamIdx);
703 bool VisitCXXParenListInitExpr(CXXParenListInitExpr *E) {
704 if (!Cfg.InlayHints.Designators)
707 if (
const auto *CXXRecord = E->getType()->getAsCXXRecordDecl()) {
708 const auto &InitExprs = E->getUserSpecifiedInitExprs();
710 if (InitExprs.size() <= CXXRecord->getNumBases())
715 const auto &MemberInitExprs =
716 InitExprs.drop_front(CXXRecord->getNumBases());
719 for (
const auto &[InitExpr,
Field] :
720 llvm::zip(MemberInitExprs, CXXRecord->fields())) {
721 addDesignatorHint(InitExpr->getSourceRange(),
722 "." +
Field->getName().str());
729 bool VisitInitListExpr(InitListExpr *Syn) {
736 assert(Syn->isSyntacticForm() &&
"RAV should not visit implicit code!");
737 if (!Cfg.InlayHints.Designators)
739 if (Syn->isIdiomaticZeroInitializer(AST.getLangOpts()))
741 llvm::DenseMap<SourceLocation, std::string> Designators =
743 for (
const Expr *Init : Syn->inits()) {
744 if (llvm::isa<DesignatedInitExpr>(Init))
746 auto It = Designators.find(Init->getBeginLoc());
747 if (It != Designators.end() &&
748 !isPrecededByParamNameComment(Init, It->second))
749 addDesignatorHint(Init->getSourceRange(), It->second);
757 using NameVec = SmallVector<StringRef, 8>;
759 void processCall(Callee Callee, SourceLocation RParenOrBraceLoc,
760 llvm::ArrayRef<const Expr *> Args) {
761 assert(Callee.Decl || Callee.Loc);
763 if ((!Cfg.InlayHints.Parameters && !Cfg.InlayHints.DefaultArguments) ||
769 if (
auto *Ctor = dyn_cast<CXXConstructorDecl>(Callee.Decl))
770 if (Ctor->isCopyOrMoveConstructor())
773 SmallVector<std::string> FormattedDefaultArgs;
774 bool HasNonDefaultArgs =
false;
776 ArrayRef<const ParmVarDecl *> Params, ForwardedParams;
778 SmallVector<const ParmVarDecl *> ForwardedParamsStorage;
780 Params = maybeDropCxxExplicitObjectParameters(Callee.Decl->parameters());
783 maybeDropCxxExplicitObjectParameters(ForwardedParamsStorage);
785 Params = maybeDropCxxExplicitObjectParameters(Callee.Loc.getParams());
786 ForwardedParams = {Params.begin(), Params.end()};
789 NameVec ParameterNames = chooseParameterNames(ForwardedParams);
795 (isSetter(Callee.Decl, ParameterNames) || isSimpleBuiltin(Callee.Decl)))
798 for (
size_t I = 0; I < ParameterNames.size() && I < Args.size(); ++I) {
802 if (isa<PackExpansionExpr>(Args[I])) {
806 StringRef Name = ParameterNames[I];
807 const bool NameHint =
808 shouldHintName(Args[I], Name) && Cfg.InlayHints.Parameters;
809 const bool ReferenceHint =
810 shouldHintReference(Params[I], ForwardedParams[I]) &&
811 Cfg.InlayHints.Parameters;
813 const bool IsDefault = isa<CXXDefaultArgExpr>(Args[I]);
814 HasNonDefaultArgs |= !IsDefault;
816 if (Cfg.InlayHints.DefaultArguments) {
817 const auto SourceText = Lexer::getSourceText(
818 CharSourceRange::getTokenRange(Params[I]->getDefaultArgRange()),
819 AST.getSourceManager(), AST.getLangOpts());
821 (SourceText.size() > Cfg.InlayHints.TypeNameLimit ||
822 SourceText.contains(
"\n"))
826 FormattedDefaultArgs.emplace_back(
827 llvm::formatv(
"{0}: {1}", Name, Abbrev));
829 FormattedDefaultArgs.emplace_back(llvm::formatv(
"{0}", Abbrev));
831 }
else if (NameHint || ReferenceHint) {
832 addInlayHint(Args[I]->getSourceRange(), HintSide::Left,
834 NameHint ? Name :
"",
": ");
838 if (!FormattedDefaultArgs.empty()) {
840 joinAndTruncate(FormattedDefaultArgs, Cfg.InlayHints.TypeNameLimit);
841 addInlayHint(SourceRange{RParenOrBraceLoc}, HintSide::Left,
843 HasNonDefaultArgs ?
", " :
"", Hint,
"");
847 static bool isSetter(
const FunctionDecl *Callee,
const NameVec &ParamNames) {
848 if (ParamNames.size() != 1)
851 StringRef Name = getSimpleName(*Callee);
852 if (!Name.starts_with_insensitive(
"set"))
866 StringRef WhatItIsSetting = Name.substr(3).ltrim(
"_");
867 return WhatItIsSetting.equals_insensitive(ParamNames[0]);
872 static bool isSimpleBuiltin(
const FunctionDecl *Callee) {
873 switch (Callee->getBuiltinID()) {
874 case Builtin::BIaddressof:
875 case Builtin::BIas_const:
876 case Builtin::BIforward:
877 case Builtin::BImove:
878 case Builtin::BImove_if_noexcept:
885 bool shouldHintName(
const Expr *Arg, StringRef ParamName) {
886 if (ParamName.empty())
891 if (ParamName == getSpelledIdentifier(Arg))
895 if (isPrecededByParamNameComment(Arg, ParamName))
901 bool shouldHintReference(
const ParmVarDecl *Param,
902 const ParmVarDecl *ForwardedParam) {
925 auto Type = Param->getType();
926 auto ForwardedType = ForwardedParam->getType();
927 return Type->isLValueReferenceType() &&
928 ForwardedType->isLValueReferenceType() &&
929 !ForwardedType.getNonReferenceType().isConstQualified() &&
936 bool isPrecededByParamNameComment(
const Expr *E, StringRef ParamName) {
937 auto &SM = AST.getSourceManager();
938 auto FileLoc = SM.getFileLoc(E->getBeginLoc());
939 auto Decomposed = SM.getDecomposedLoc(FileLoc);
940 if (Decomposed.first != MainFileID)
943 StringRef SourcePrefix = MainFileBuf.substr(0, Decomposed.second);
945 SourcePrefix = SourcePrefix.rtrim();
947 if (!SourcePrefix.consume_back(
"*/"))
951 llvm::StringLiteral IgnoreChars =
" =.";
952 SourcePrefix = SourcePrefix.rtrim(IgnoreChars);
953 ParamName = ParamName.trim(IgnoreChars);
955 if (!SourcePrefix.consume_back(ParamName))
957 SourcePrefix = SourcePrefix.rtrim(IgnoreChars);
958 return SourcePrefix.ends_with(
"/*");
963 static StringRef getSpelledIdentifier(
const Expr *E) {
964 E = E->IgnoreUnlessSpelledInSource();
966 if (
auto *DRE = dyn_cast<DeclRefExpr>(E))
967 if (!DRE->getQualifier())
968 return getSimpleName(*DRE->getDecl());
970 if (
auto *ME = dyn_cast<MemberExpr>(E))
971 if (!ME->getQualifier() && ME->isImplicitAccess())
972 return getSimpleName(*ME->getMemberDecl());
977 NameVec chooseParameterNames(ArrayRef<const ParmVarDecl *> Parameters) {
978 NameVec ParameterNames;
979 for (
const auto *P : Parameters) {
984 ParameterNames.emplace_back();
986 auto SimpleName = getSimpleName(*P);
989 if (SimpleName.empty()) {
990 if (
const auto *PD = getParamDefinition(P)) {
991 SimpleName = getSimpleName(*PD);
994 ParameterNames.emplace_back(SimpleName);
1000 for (
auto &Name : ParameterNames)
1001 stripLeadingUnderscores(Name);
1003 return ParameterNames;
1008 static const ParmVarDecl *getParamDefinition(
const ParmVarDecl *P) {
1009 if (
auto *Callee = dyn_cast<FunctionDecl>(
P->getDeclContext())) {
1010 if (
auto *Def = Callee->getDefinition()) {
1011 auto I = std::distance(Callee->param_begin(),
1012 llvm::find(Callee->parameters(), P));
1013 if (I < (
int)Callee->getNumParams()) {
1014 return Def->getParamDecl(I);
1023 void addInlayHint(SourceRange R, HintSide Side,
InlayHintKind Kind,
1024 llvm::StringRef Prefix, llvm::StringRef
Label,
1025 llvm::StringRef Suffix) {
1026 auto LSPRange = getHintRange(R);
1030 addInlayHint(*LSPRange, Side, Kind, Prefix,
Label, Suffix);
1033 void addInlayHint(Range LSPRange, HintSide Side,
InlayHintKind Kind,
1034 llvm::StringRef Prefix, llvm::StringRef
Label,
1035 llvm::StringRef Suffix) {
1039 assert(Cfg.InlayHints.Enabled &&
"Shouldn't get here if disabled!");
1041#define CHECK_KIND(Enumerator, ConfigProperty) \
1042 case InlayHintKind::Enumerator: \
1043 assert(Cfg.InlayHints.ConfigProperty && \
1044 "Shouldn't get here if kind is disabled!"); \
1045 if (!Cfg.InlayHints.ConfigProperty) \
1056 Position LSPPos = Side == HintSide::Left ? LSPRange.start : LSPRange.end;
1057 if (RestrictRange &&
1058 (LSPPos < RestrictRange->start || !(LSPPos < RestrictRange->end)))
1060 bool PadLeft = Prefix.consume_front(
" ");
1061 bool PadRight = Suffix.consume_back(
" ");
1062 Results.push_back(InlayHint{LSPPos,
1063 {(Prefix +
Label + Suffix).str()},
1064 Kind, PadLeft, PadRight, LSPRange});
1068 std::optional<Range> getHintRange(SourceRange R) {
1069 const auto &SM = AST.getSourceManager();
1070 auto Spelled = Tokens.spelledForExpanded(Tokens.expandedTokens(R));
1074 return std::nullopt;
1076 if (SM.getFileID(
Spelled->front().location()) != SM.getMainFileID() ||
1077 SM.getFileID(
Spelled->back().location()) != SM.getMainFileID())
1078 return std::nullopt;
1083 void addTypeHint(SourceRange R, QualType T, llvm::StringRef Prefix) {
1084 if (!Cfg.InlayHints.DeducedTypes ||
T.isNull())
1089 auto Desugared = maybeDesugar(AST, T);
1090 std::string TypeName = Desugared.getAsString(TypeHintPolicy);
1091 if (T != Desugared && !shouldPrintTypeHint(TypeName)) {
1094 TypeName =
T.getAsString(TypeHintPolicy);
1096 if (shouldPrintTypeHint(TypeName))
1101 void addDesignatorHint(SourceRange R, llvm::StringRef
Text) {
1106 bool shouldPrintTypeHint(llvm::StringRef TypeName)
const noexcept {
1107 return Cfg.InlayHints.TypeNameLimit == 0 ||
1108 TypeName.size() < Cfg.InlayHints.TypeNameLimit;
1111 void addBlockEndHint(SourceRange BraceRange, StringRef DeclPrefix,
1112 StringRef Name, StringRef OptionalPunctuation) {
1113 auto HintRange = computeBlockEndHintRange(BraceRange, OptionalPunctuation);
1117 std::string
Label = DeclPrefix.str();
1118 if (!
Label.empty() && !Name.empty())
1122 constexpr unsigned HintMaxLengthLimit = 60;
1123 if (
Label.length() > HintMaxLengthLimit)
1136 std::optional<Range> computeBlockEndHintRange(SourceRange BraceRange,
1137 StringRef OptionalPunctuation) {
1139 auto &SM = AST.getSourceManager();
1140 auto [BlockBeginFileId, BlockBeginOffset] =
1141 SM.getDecomposedLoc(SM.getFileLoc(BraceRange.getBegin()));
1142 auto RBraceLoc = SM.getFileLoc(BraceRange.getEnd());
1143 auto [RBraceFileId, RBraceOffset] = SM.getDecomposedLoc(RBraceLoc);
1149 if (BlockBeginFileId != MainFileID || RBraceFileId != MainFileID)
1150 return std::nullopt;
1152 StringRef RestOfLine = MainFileBuf.substr(RBraceOffset).split(
'\n').first;
1153 if (!RestOfLine.starts_with(
"}"))
1154 return std::nullopt;
1156 StringRef TrimmedTrailingText = RestOfLine.drop_front().trim();
1157 if (!TrimmedTrailingText.empty() &&
1158 TrimmedTrailingText != OptionalPunctuation)
1159 return std::nullopt;
1161 auto BlockBeginLine = SM.getLineNumber(BlockBeginFileId, BlockBeginOffset);
1162 auto RBraceLine = SM.getLineNumber(RBraceFileId, RBraceOffset);
1165 if (BlockBeginLine + HintOptions.HintMinLineLimit - 1 > RBraceLine)
1166 return std::nullopt;
1169 StringRef HintRangeText = RestOfLine.take_front(
1170 TrimmedTrailingText.empty()
1172 : TrimmedTrailingText.bytes_end() - RestOfLine.bytes_begin());
1176 SM, RBraceLoc.getLocWithOffset(HintRangeText.size()));
1177 return Range{HintStart, HintEnd};
1180 static bool isFunctionObjectCallExpr(CallExpr *E)
noexcept {
1181 if (
auto *CallExpr = dyn_cast<CXXOperatorCallExpr>(E))
1182 return CallExpr->getOperator() == OverloadedOperatorKind::OO_Call;
1186 std::vector<InlayHint> &Results;
1188 const syntax::TokenBuffer &Tokens;
1190 std::optional<Range> RestrictRange;
1192 StringRef MainFileBuf;
1193 const HeuristicResolver *Resolver;
1194 PrintingPolicy TypeHintPolicy;
1195 InlayHintOptions HintOptions;
1201 std::optional<Range> RestrictRange,
1203 std::vector<InlayHint> Results;
1205 if (!Cfg.InlayHints.Enabled)
1207 InlayHintVisitor Visitor(Results,
AST, Cfg, std::move(RestrictRange),
1209 Visitor.TraverseAST(
AST.getASTContext());
1213 llvm::sort(Results);
1214 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.
llvm::DenseMap< SourceLocation, std::string > getUnwrittenDesignators(const InitListExpr *Syn)
cppcoreguidelines::ProBoundsAvoidUncheckedContainerAccessCheck P
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
static const Config & current()
Returns the Config of the current Context, or an empty configuration.