xref: /llvm-project/clang-tools-extra/clang-tidy/abseil/StringFindStartswithCheck.cpp (revision b859c39c40a79ff74033f67d807a18130b9afe30)
1 //===--- StringFindStartswithCheck.cc - clang-tidy---------------*- C++ -*-===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "StringFindStartswithCheck.h"
10 
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"
17 
18 using namespace clang::ast_matchers;
19 
20 namespace clang {
21 namespace tidy {
22 namespace abseil {
23 
24 StringFindStartswithCheck::StringFindStartswithCheck(StringRef Name,
25                                                      ClangTidyContext *Context)
26     : ClangTidyCheck(Name, Context),
27       StringLikeClasses(utils::options::parseStringList(
28           Options.get("StringLikeClasses", "::std::basic_string"))),
29       IncludeInserter(Options.getLocalOrGlobal("IncludeStyle",
30                                                utils::IncludeSorter::IS_LLVM),
31                       areDiagsSelfContained()),
32       AbseilStringsMatchHeader(
33           Options.get("AbseilStringsMatchHeader", "absl/strings/match.h")) {}
34 
35 void StringFindStartswithCheck::registerMatchers(MatchFinder *Finder) {
36   auto ZeroLiteral = integerLiteral(equals(0));
37   auto StringClassMatcher = cxxRecordDecl(hasAnyName(SmallVector<StringRef, 4>(
38       StringLikeClasses.begin(), StringLikeClasses.end())));
39   auto StringType = hasUnqualifiedDesugaredType(
40       recordType(hasDeclaration(StringClassMatcher)));
41 
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())));
50 
51   Finder->addMatcher(
52       // Match [=!]= with a zero on one side and a string.find on the other.
53       binaryOperator(
54           hasAnyOperatorName("==", "!="),
55           hasOperands(ignoringParenImpCasts(ZeroLiteral),
56                       ignoringParenImpCasts(StringFind.bind("findexpr"))))
57           .bind("expr"),
58       this);
59 
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));
68 
69   Finder->addMatcher(
70       // Match [=!]= with either a zero or npos on one side and a string.rfind
71       // on the other.
72       binaryOperator(
73           hasAnyOperatorName("==", "!="),
74           hasOperands(ignoringParenImpCasts(ZeroLiteral),
75                       ignoringParenImpCasts(StringRFind.bind("findexpr"))))
76           .bind("expr"),
77       this);
78 }
79 
80 void StringFindStartswithCheck::check(const MatchFinder::MatchResult &Result) {
81   const ASTContext &Context = *Result.Context;
82   const SourceManager &Source = Context.getSourceManager();
83 
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 CXXMethodDecl *FindFun =
93       Result.Nodes.getNodeAs<CXXMethodDecl>("findfun");
94   assert(FindFun != nullptr);
95 
96   bool Rev = FindFun->getName().contains("rfind");
97 
98   if (ComparisonExpr->getBeginLoc().isMacroID())
99     return;
100 
101   // Get the source code blocks (as characters) for both the string object
102   // and the search expression
103   const StringRef NeedleExprCode = Lexer::getSourceText(
104       CharSourceRange::getTokenRange(Needle->getSourceRange()), Source,
105       Context.getLangOpts());
106   const StringRef HaystackExprCode = Lexer::getSourceText(
107       CharSourceRange::getTokenRange(Haystack->getSourceRange()), Source,
108       Context.getLangOpts());
109 
110   // Create the StartsWith string, negating if comparison was "!=".
111   bool Neg = ComparisonExpr->getOpcode() == BO_NE;
112 
113   // Create the warning message and a FixIt hint replacing the original expr.
114   auto Diagnostic =
115       diag(ComparisonExpr->getBeginLoc(),
116            "use %select{absl::StartsWith|!absl::StartsWith}0 "
117            "instead of %select{find()|rfind()}1 %select{==|!=}0 0")
118       << Neg << Rev;
119 
120   Diagnostic << FixItHint::CreateReplacement(
121       ComparisonExpr->getSourceRange(),
122       ((Neg ? "!absl::StartsWith(" : "absl::StartsWith(") + HaystackExprCode +
123        ", " + NeedleExprCode + ")")
124           .str());
125 
126   // Create a preprocessor #include FixIt hint (createIncludeInsertion checks
127   // whether this already exists).
128   Diagnostic << IncludeInserter.createIncludeInsertion(
129       Source.getFileID(ComparisonExpr->getBeginLoc()),
130       AbseilStringsMatchHeader);
131 }
132 
133 void StringFindStartswithCheck::registerPPCallbacks(
134     const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) {
135   IncludeInserter.registerPreprocessor(PP);
136 }
137 
138 void StringFindStartswithCheck::storeOptions(
139     ClangTidyOptions::OptionMap &Opts) {
140   Options.store(Opts, "StringLikeClasses",
141                 utils::options::serializeStringList(StringLikeClasses));
142   Options.store(Opts, "IncludeStyle", IncludeInserter.getStyle());
143   Options.store(Opts, "AbseilStringsMatchHeader", AbseilStringsMatchHeader);
144 }
145 
146 } // namespace abseil
147 } // namespace tidy
148 } // namespace clang
149