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.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 VisitCXXParenListInitExpr(CXXParenListInitExpr *E) {
703 if (!Cfg.InlayHints.Designators)
706 if (
const auto *CXXRecord = E->getType()->getAsCXXRecordDecl()) {
707 const auto &InitExprs = E->getUserSpecifiedInitExprs();
709 if (InitExprs.size() <= CXXRecord->getNumBases())
714 const auto &MemberInitExprs =
715 InitExprs.drop_front(CXXRecord->getNumBases());
718 for (
const auto &[InitExpr,
Field] :
719 llvm::zip(MemberInitExprs, CXXRecord->fields())) {
720 addDesignatorHint(InitExpr->getSourceRange(),
721 "." +
Field->getName().str());
728 bool VisitInitListExpr(InitListExpr *Syn) {
735 assert(Syn->isSyntacticForm() &&
"RAV should not visit implicit code!");
736 if (!Cfg.InlayHints.Designators)
738 if (Syn->isIdiomaticZeroInitializer(AST.getLangOpts()))
740 llvm::DenseMap<SourceLocation, std::string> Designators =
742 for (
const Expr *Init : Syn->inits()) {
743 if (llvm::isa<DesignatedInitExpr>(Init))
745 auto It = Designators.find(Init->getBeginLoc());
746 if (It != Designators.end() &&
747 !isPrecededByParamNameComment(Init, It->second))
748 addDesignatorHint(Init->getSourceRange(), It->second);
756 using NameVec = SmallVector<StringRef, 8>;
758 void processCall(Callee Callee, SourceLocation RParenOrBraceLoc,
759 llvm::ArrayRef<const Expr *> Args) {
760 assert(Callee.Decl || Callee.Loc);
762 if ((!Cfg.InlayHints.Parameters && !Cfg.InlayHints.DefaultArguments) ||
768 if (
auto *Ctor = dyn_cast<CXXConstructorDecl>(Callee.Decl))
769 if (Ctor->isCopyOrMoveConstructor())
772 SmallVector<std::string> FormattedDefaultArgs;
773 bool HasNonDefaultArgs =
false;
775 ArrayRef<const ParmVarDecl *> Params, ForwardedParams;
777 SmallVector<const ParmVarDecl *> ForwardedParamsStorage;
779 Params = maybeDropCxxExplicitObjectParameters(Callee.Decl->parameters());
782 maybeDropCxxExplicitObjectParameters(ForwardedParamsStorage);
784 Params = maybeDropCxxExplicitObjectParameters(Callee.Loc.getParams());
785 ForwardedParams = {Params.begin(), Params.end()};
788 NameVec ParameterNames = chooseParameterNames(ForwardedParams);
794 (isSetter(Callee.Decl, ParameterNames) || isSimpleBuiltin(Callee.Decl)))
797 for (
size_t I = 0; I < ParameterNames.size() && I < Args.size(); ++I) {
801 if (isa<PackExpansionExpr>(Args[I])) {
805 StringRef Name = ParameterNames[I];
806 const bool NameHint =
807 shouldHintName(Args[I], Name) && Cfg.InlayHints.Parameters;
808 const bool ReferenceHint =
809 shouldHintReference(Params[I], ForwardedParams[I]) &&
810 Cfg.InlayHints.Parameters;
812 const bool IsDefault = isa<CXXDefaultArgExpr>(Args[I]);
813 HasNonDefaultArgs |= !IsDefault;
815 if (Cfg.InlayHints.DefaultArguments) {
816 const auto SourceText = Lexer::getSourceText(
817 CharSourceRange::getTokenRange(Params[I]->getDefaultArgRange()),
818 AST.getSourceManager(), AST.getLangOpts());
820 (SourceText.size() > Cfg.InlayHints.TypeNameLimit ||
821 SourceText.contains(
"\n"))
825 FormattedDefaultArgs.emplace_back(
826 llvm::formatv(
"{0}: {1}", Name, Abbrev));
828 FormattedDefaultArgs.emplace_back(llvm::formatv(
"{0}", Abbrev));
830 }
else if (NameHint || ReferenceHint) {
831 addInlayHint(Args[I]->getSourceRange(), HintSide::Left,
833 NameHint ? Name :
"",
": ");
837 if (!FormattedDefaultArgs.empty()) {
839 joinAndTruncate(FormattedDefaultArgs, Cfg.InlayHints.TypeNameLimit);
840 addInlayHint(SourceRange{RParenOrBraceLoc}, HintSide::Left,
842 HasNonDefaultArgs ?
", " :
"", Hint,
"");
846 static bool isSetter(
const FunctionDecl *Callee,
const NameVec &ParamNames) {
847 if (ParamNames.size() != 1)
850 StringRef Name = getSimpleName(*Callee);
851 if (!Name.starts_with_insensitive(
"set"))
865 StringRef WhatItIsSetting = Name.substr(3).ltrim(
"_");
866 return WhatItIsSetting.equals_insensitive(ParamNames[0]);
871 static bool isSimpleBuiltin(
const FunctionDecl *Callee) {
872 switch (Callee->getBuiltinID()) {
873 case Builtin::BIaddressof:
874 case Builtin::BIas_const:
875 case Builtin::BIforward:
876 case Builtin::BImove:
877 case Builtin::BImove_if_noexcept:
884 bool shouldHintName(
const Expr *Arg, StringRef ParamName) {
885 if (ParamName.empty())
890 if (ParamName == getSpelledIdentifier(Arg))
894 if (isPrecededByParamNameComment(Arg, ParamName))
900 bool shouldHintReference(
const ParmVarDecl *Param,
901 const ParmVarDecl *ForwardedParam) {
924 auto Type = Param->getType();
925 auto ForwardedType = ForwardedParam->getType();
926 return Type->isLValueReferenceType() &&
927 ForwardedType->isLValueReferenceType() &&
928 !ForwardedType.getNonReferenceType().isConstQualified() &&
935 bool isPrecededByParamNameComment(
const Expr *E, StringRef ParamName) {
936 auto &SM = AST.getSourceManager();
937 auto FileLoc = SM.getFileLoc(E->getBeginLoc());
938 auto Decomposed = SM.getDecomposedLoc(FileLoc);
939 if (Decomposed.first != MainFileID)
942 StringRef SourcePrefix = MainFileBuf.substr(0, Decomposed.second);
944 SourcePrefix = SourcePrefix.rtrim();
946 if (!SourcePrefix.consume_back(
"*/"))
950 llvm::StringLiteral IgnoreChars =
" =.";
951 SourcePrefix = SourcePrefix.rtrim(IgnoreChars);
952 ParamName = ParamName.trim(IgnoreChars);
954 if (!SourcePrefix.consume_back(ParamName))
956 SourcePrefix = SourcePrefix.rtrim(IgnoreChars);
957 return SourcePrefix.ends_with(
"/*");
962 static StringRef getSpelledIdentifier(
const Expr *E) {
963 E = E->IgnoreUnlessSpelledInSource();
965 if (
auto *DRE = dyn_cast<DeclRefExpr>(E))
966 if (!DRE->getQualifier())
967 return getSimpleName(*DRE->getDecl());
969 if (
auto *ME = dyn_cast<MemberExpr>(E))
970 if (!ME->getQualifier() && ME->isImplicitAccess())
971 return getSimpleName(*ME->getMemberDecl());
976 NameVec chooseParameterNames(ArrayRef<const ParmVarDecl *> Parameters) {
977 NameVec ParameterNames;
978 for (
const auto *P : Parameters) {
983 ParameterNames.emplace_back();
985 auto SimpleName = getSimpleName(*P);
988 if (SimpleName.empty()) {
989 if (
const auto *PD = getParamDefinition(P)) {
990 SimpleName = getSimpleName(*PD);
993 ParameterNames.emplace_back(SimpleName);
999 for (
auto &Name : ParameterNames)
1000 stripLeadingUnderscores(Name);
1002 return ParameterNames;
1007 static const ParmVarDecl *getParamDefinition(
const ParmVarDecl *P) {
1008 if (
auto *Callee = dyn_cast<FunctionDecl>(
P->getDeclContext())) {
1009 if (
auto *Def = Callee->getDefinition()) {
1010 auto I = std::distance(Callee->param_begin(),
1011 llvm::find(Callee->parameters(), P));
1012 if (I < (
int)Callee->getNumParams()) {
1013 return Def->getParamDecl(I);
1022 void addInlayHint(SourceRange R, HintSide Side,
InlayHintKind Kind,
1023 llvm::StringRef Prefix, llvm::StringRef
Label,
1024 llvm::StringRef Suffix) {
1025 auto LSPRange = getHintRange(R);
1029 addInlayHint(*LSPRange, Side, Kind, Prefix,
Label, Suffix);
1032 void addInlayHint(Range LSPRange, HintSide Side,
InlayHintKind Kind,
1033 llvm::StringRef Prefix, llvm::StringRef
Label,
1034 llvm::StringRef Suffix) {
1038 assert(Cfg.InlayHints.Enabled &&
"Shouldn't get here if disabled!");
1040#define CHECK_KIND(Enumerator, ConfigProperty) \
1041 case InlayHintKind::Enumerator: \
1042 assert(Cfg.InlayHints.ConfigProperty && \
1043 "Shouldn't get here if kind is disabled!"); \
1044 if (!Cfg.InlayHints.ConfigProperty) \
1055 Position LSPPos = Side == HintSide::Left ? LSPRange.start : LSPRange.end;
1056 if (RestrictRange &&
1057 (LSPPos < RestrictRange->start || !(LSPPos < RestrictRange->end)))
1059 bool PadLeft = Prefix.consume_front(
" ");
1060 bool PadRight = Suffix.consume_back(
" ");
1061 Results.push_back(InlayHint{LSPPos,
1062 {(Prefix +
Label + Suffix).str()},
1063 Kind, PadLeft, PadRight, LSPRange});
1067 std::optional<Range> getHintRange(SourceRange R) {
1068 const auto &SM = AST.getSourceManager();
1069 auto Spelled = Tokens.spelledForExpanded(Tokens.expandedTokens(R));
1073 return std::nullopt;
1075 if (SM.getFileID(
Spelled->front().location()) != SM.getMainFileID() ||
1076 SM.getFileID(
Spelled->back().location()) != SM.getMainFileID())
1077 return std::nullopt;
1082 void addTypeHint(SourceRange R, QualType T, llvm::StringRef Prefix) {
1083 if (!Cfg.InlayHints.DeducedTypes ||
T.isNull())
1088 auto Desugared = maybeDesugar(AST, T);
1089 std::string TypeName = Desugared.getAsString(TypeHintPolicy);
1090 if (T != Desugared && !shouldPrintTypeHint(TypeName)) {
1093 TypeName =
T.getAsString(TypeHintPolicy);
1095 if (shouldPrintTypeHint(TypeName))
1100 void addDesignatorHint(SourceRange R, llvm::StringRef
Text) {
1105 bool shouldPrintTypeHint(llvm::StringRef TypeName)
const noexcept {
1106 return Cfg.InlayHints.TypeNameLimit == 0 ||
1107 TypeName.size() < Cfg.InlayHints.TypeNameLimit;
1110 void addBlockEndHint(SourceRange BraceRange, StringRef DeclPrefix,
1111 StringRef Name, StringRef OptionalPunctuation) {
1112 auto HintRange = computeBlockEndHintRange(BraceRange, OptionalPunctuation);
1116 std::string
Label = DeclPrefix.str();
1117 if (!
Label.empty() && !Name.empty())
1121 constexpr unsigned HintMaxLengthLimit = 60;
1122 if (
Label.length() > HintMaxLengthLimit)
1135 std::optional<Range> computeBlockEndHintRange(SourceRange BraceRange,
1136 StringRef OptionalPunctuation) {
1138 auto &SM = AST.getSourceManager();
1139 auto [BlockBeginFileId, BlockBeginOffset] =
1140 SM.getDecomposedLoc(SM.getFileLoc(BraceRange.getBegin()));
1141 auto RBraceLoc = SM.getFileLoc(BraceRange.getEnd());
1142 auto [RBraceFileId, RBraceOffset] = SM.getDecomposedLoc(RBraceLoc);
1148 if (BlockBeginFileId != MainFileID || RBraceFileId != MainFileID)
1149 return std::nullopt;
1151 StringRef RestOfLine = MainFileBuf.substr(RBraceOffset).split(
'\n').first;
1152 if (!RestOfLine.starts_with(
"}"))
1153 return std::nullopt;
1155 StringRef TrimmedTrailingText = RestOfLine.drop_front().trim();
1156 if (!TrimmedTrailingText.empty() &&
1157 TrimmedTrailingText != OptionalPunctuation)
1158 return std::nullopt;
1160 auto BlockBeginLine = SM.getLineNumber(BlockBeginFileId, BlockBeginOffset);
1161 auto RBraceLine = SM.getLineNumber(RBraceFileId, RBraceOffset);
1164 if (BlockBeginLine + HintOptions.HintMinLineLimit - 1 > RBraceLine)
1165 return std::nullopt;
1168 StringRef HintRangeText = RestOfLine.take_front(
1169 TrimmedTrailingText.empty()
1171 : TrimmedTrailingText.bytes_end() - RestOfLine.bytes_begin());
1175 SM, RBraceLoc.getLocWithOffset(HintRangeText.size()));
1176 return Range{HintStart, HintEnd};
1179 static bool isFunctionObjectCallExpr(CallExpr *E)
noexcept {
1180 if (
auto *CallExpr = dyn_cast<CXXOperatorCallExpr>(E))
1181 return CallExpr->getOperator() == OverloadedOperatorKind::OO_Call;
1185 std::vector<InlayHint> &Results;
1187 const syntax::TokenBuffer &Tokens;
1189 std::optional<Range> RestrictRange;
1191 StringRef MainFileBuf;
1192 const HeuristicResolver *Resolver;
1193 PrintingPolicy TypeHintPolicy;
1194 InlayHintOptions HintOptions;
1200 std::optional<Range> RestrictRange,
1202 std::vector<InlayHint> Results;
1204 if (!Cfg.InlayHints.Enabled)
1206 InlayHintVisitor Visitor(Results,
AST, Cfg, std::move(RestrictRange),
1208 Visitor.TraverseAST(
AST.getASTContext());
1212 llvm::sort(Results);
1213 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.