37 auto ZeroLiteral = integerLiteral(equals(0));
38 auto StringClassMatcher = cxxRecordDecl(hasAnyName(StringLikeClasses));
39 auto StringType = hasUnqualifiedDesugaredType(
40 recordType(hasDeclaration(StringClassMatcher)));
42 auto StringFind = cxxMemberCallExpr(
44 callee(cxxMethodDecl(hasName(
"find")).bind(
"findfun")),
45 on(hasType(StringType)),
47 hasArgument(0, expr().bind(
"needle")),
49 anyOf(hasArgument(1, ZeroLiteral), hasArgument(1, cxxDefaultArgExpr())));
54 hasAnyOperatorName(
"==",
"!="),
55 hasOperands(ignoringParenImpCasts(ZeroLiteral),
56 ignoringParenImpCasts(StringFind.bind(
"findexpr"))))
60 auto StringRFind = cxxMemberCallExpr(
62 callee(cxxMethodDecl(hasName(
"rfind")).bind(
"findfun")),
63 on(hasType(StringType)),
65 hasArgument(0, expr().bind(
"needle")),
67 hasArgument(1, ZeroLiteral));
73 hasAnyOperatorName(
"==",
"!="),
74 hasOperands(ignoringParenImpCasts(ZeroLiteral),
75 ignoringParenImpCasts(StringRFind.bind(
"findexpr"))))
81 const ASTContext &Context = *Result.Context;
82 const SourceManager &Source = Context.getSourceManager();
85 const auto *ComparisonExpr = Result.Nodes.getNodeAs<BinaryOperator>(
"expr");
86 assert(ComparisonExpr !=
nullptr);
87 const auto *Needle = Result.Nodes.getNodeAs<Expr>(
"needle");
88 assert(Needle !=
nullptr);
89 const Expr *Haystack = Result.Nodes.getNodeAs<CXXMemberCallExpr>(
"findexpr")
90 ->getImplicitObjectArgument();
91 assert(Haystack !=
nullptr);
92 const auto *FindFun = Result.Nodes.getNodeAs<CXXMethodDecl>(
"findfun");
93 assert(FindFun !=
nullptr);
95 bool Rev = FindFun->getName().contains(
"rfind");
97 if (ComparisonExpr->getBeginLoc().isMacroID())
102 const StringRef NeedleExprCode = Lexer::getSourceText(
103 CharSourceRange::getTokenRange(Needle->getSourceRange()), Source,
104 Context.getLangOpts());
105 const StringRef HaystackExprCode = Lexer::getSourceText(
106 CharSourceRange::getTokenRange(Haystack->getSourceRange()), Source,
107 Context.getLangOpts());
110 bool Neg = ComparisonExpr->getOpcode() == BO_NE;
114 diag(ComparisonExpr->getBeginLoc(),
115 "use %select{absl::StartsWith|!absl::StartsWith}0 "
116 "instead of %select{find()|rfind()}1 %select{==|!=}0 0")
119 Diagnostic << FixItHint::CreateReplacement(
120 ComparisonExpr->getSourceRange(),
121 ((Neg ?
"!absl::StartsWith(" :
"absl::StartsWith(") + HaystackExprCode +
122 ", " + NeedleExprCode +
")")
127 Diagnostic << IncludeInserter.createIncludeInsertion(
128 Source.getFileID(ComparisonExpr->getBeginLoc()),
129 AbseilStringsMatchHeader);
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.