1 //===--- StringFindStartswithCheck.cc - clang-tidy---------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "StringFindStartswithCheck.h"
11 #include "../utils/OptionsUtils.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/ASTMatchers/ASTMatchers.h"
14 #include "clang/Frontend/CompilerInstance.h"
15 #include "clang/Lex/Lexer.h"
16 #include "clang/Lex/Preprocessor.h"
18 using namespace clang::ast_matchers
;
20 namespace clang::tidy::abseil
{
22 const auto DefaultStringLikeClasses
=
23 "::std::basic_string;::std::basic_string_view";
25 StringFindStartswithCheck::StringFindStartswithCheck(StringRef Name
,
26 ClangTidyContext
*Context
)
27 : ClangTidyCheck(Name
, Context
),
28 StringLikeClasses(utils::options::parseStringList(
29 Options
.get("StringLikeClasses", DefaultStringLikeClasses
))),
30 IncludeInserter(Options
.getLocalOrGlobal("IncludeStyle",
31 utils::IncludeSorter::IS_LLVM
),
32 areDiagsSelfContained()),
33 AbseilStringsMatchHeader(
34 Options
.get("AbseilStringsMatchHeader", "absl/strings/match.h")) {}
36 void StringFindStartswithCheck::registerMatchers(MatchFinder
*Finder
) {
37 auto ZeroLiteral
= integerLiteral(equals(0));
38 auto StringClassMatcher
= cxxRecordDecl(hasAnyName(StringLikeClasses
));
39 auto StringType
= hasUnqualifiedDesugaredType(
40 recordType(hasDeclaration(StringClassMatcher
)));
42 auto StringFind
= cxxMemberCallExpr(
43 // .find()-call on a string...
44 callee(cxxMethodDecl(hasName("find")).bind("findfun")),
45 on(hasType(StringType
)),
46 // ... with some search expression ...
47 hasArgument(0, expr().bind("needle")),
48 // ... and either "0" as second argument or the default argument (also 0).
49 anyOf(hasArgument(1, ZeroLiteral
), hasArgument(1, cxxDefaultArgExpr())));
52 // Match [=!]= with a zero on one side and a string.find on the other.
54 hasAnyOperatorName("==", "!="),
55 hasOperands(ignoringParenImpCasts(ZeroLiteral
),
56 ignoringParenImpCasts(StringFind
.bind("findexpr"))))
60 auto StringRFind
= cxxMemberCallExpr(
61 // .rfind()-call on a string...
62 callee(cxxMethodDecl(hasName("rfind")).bind("findfun")),
63 on(hasType(StringType
)),
64 // ... with some search expression ...
65 hasArgument(0, expr().bind("needle")),
66 // ... and "0" as second argument.
67 hasArgument(1, ZeroLiteral
));
70 // Match [=!]= with either a zero or npos on one side and a string.rfind
73 hasAnyOperatorName("==", "!="),
74 hasOperands(ignoringParenImpCasts(ZeroLiteral
),
75 ignoringParenImpCasts(StringRFind
.bind("findexpr"))))
80 void StringFindStartswithCheck::check(const MatchFinder::MatchResult
&Result
) {
81 const ASTContext
&Context
= *Result
.Context
;
82 const SourceManager
&Source
= Context
.getSourceManager();
84 // Extract matching (sub)expressions
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())
100 // Get the source code blocks (as characters) for both the string object
101 // and the search expression
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());
109 // Create the StartsWith string, negating if comparison was "!=".
110 bool Neg
= ComparisonExpr
->getOpcode() == BO_NE
;
112 // Create the warning message and a FixIt hint replacing the original expr.
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
+ ")")
125 // Create a preprocessor #include FixIt hint (createIncludeInsertion checks
126 // whether this already exists).
127 Diagnostic
<< IncludeInserter
.createIncludeInsertion(
128 Source
.getFileID(ComparisonExpr
->getBeginLoc()),
129 AbseilStringsMatchHeader
);
132 void StringFindStartswithCheck::registerPPCallbacks(
133 const SourceManager
&SM
, Preprocessor
*PP
, Preprocessor
*ModuleExpanderPP
) {
134 IncludeInserter
.registerPreprocessor(PP
);
137 void StringFindStartswithCheck::storeOptions(
138 ClangTidyOptions::OptionMap
&Opts
) {
139 Options
.store(Opts
, "StringLikeClasses",
140 utils::options::serializeStringList(StringLikeClasses
));
141 Options
.store(Opts
, "IncludeStyle", IncludeInserter
.getStyle());
142 Options
.store(Opts
, "AbseilStringsMatchHeader", AbseilStringsMatchHeader
);
145 } // namespace clang::tidy::abseil