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
StringFindStartswithCheck(StringRef Name,ClangTidyContext * Context)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
registerMatchers(MatchFinder * Finder)35 void StringFindStartswithCheck::registerMatchers(MatchFinder *Finder) {
36 auto ZeroLiteral = integerLiteral(equals(0));
37 auto StringClassMatcher = cxxRecordDecl(hasAnyName(StringLikeClasses));
38 auto StringType = hasUnqualifiedDesugaredType(
39 recordType(hasDeclaration(StringClassMatcher)));
40
41 auto StringFind = cxxMemberCallExpr(
42 // .find()-call on a string...
43 callee(cxxMethodDecl(hasName("find")).bind("findfun")),
44 on(hasType(StringType)),
45 // ... with some search expression ...
46 hasArgument(0, expr().bind("needle")),
47 // ... and either "0" as second argument or the default argument (also 0).
48 anyOf(hasArgument(1, ZeroLiteral), hasArgument(1, cxxDefaultArgExpr())));
49
50 Finder->addMatcher(
51 // Match [=!]= with a zero on one side and a string.find on the other.
52 binaryOperator(
53 hasAnyOperatorName("==", "!="),
54 hasOperands(ignoringParenImpCasts(ZeroLiteral),
55 ignoringParenImpCasts(StringFind.bind("findexpr"))))
56 .bind("expr"),
57 this);
58
59 auto StringRFind = cxxMemberCallExpr(
60 // .rfind()-call on a string...
61 callee(cxxMethodDecl(hasName("rfind")).bind("findfun")),
62 on(hasType(StringType)),
63 // ... with some search expression ...
64 hasArgument(0, expr().bind("needle")),
65 // ... and "0" as second argument.
66 hasArgument(1, ZeroLiteral));
67
68 Finder->addMatcher(
69 // Match [=!]= with either a zero or npos on one side and a string.rfind
70 // on the other.
71 binaryOperator(
72 hasAnyOperatorName("==", "!="),
73 hasOperands(ignoringParenImpCasts(ZeroLiteral),
74 ignoringParenImpCasts(StringRFind.bind("findexpr"))))
75 .bind("expr"),
76 this);
77 }
78
check(const MatchFinder::MatchResult & Result)79 void StringFindStartswithCheck::check(const MatchFinder::MatchResult &Result) {
80 const ASTContext &Context = *Result.Context;
81 const SourceManager &Source = Context.getSourceManager();
82
83 // Extract matching (sub)expressions
84 const auto *ComparisonExpr = Result.Nodes.getNodeAs<BinaryOperator>("expr");
85 assert(ComparisonExpr != nullptr);
86 const auto *Needle = Result.Nodes.getNodeAs<Expr>("needle");
87 assert(Needle != nullptr);
88 const Expr *Haystack = Result.Nodes.getNodeAs<CXXMemberCallExpr>("findexpr")
89 ->getImplicitObjectArgument();
90 assert(Haystack != nullptr);
91 const CXXMethodDecl *FindFun =
92 Result.Nodes.getNodeAs<CXXMethodDecl>("findfun");
93 assert(FindFun != nullptr);
94
95 bool Rev = FindFun->getName().contains("rfind");
96
97 if (ComparisonExpr->getBeginLoc().isMacroID())
98 return;
99
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());
108
109 // Create the StartsWith string, negating if comparison was "!=".
110 bool Neg = ComparisonExpr->getOpcode() == BO_NE;
111
112 // Create the warning message and a FixIt hint replacing the original expr.
113 auto Diagnostic =
114 diag(ComparisonExpr->getBeginLoc(),
115 "use %select{absl::StartsWith|!absl::StartsWith}0 "
116 "instead of %select{find()|rfind()}1 %select{==|!=}0 0")
117 << Neg << Rev;
118
119 Diagnostic << FixItHint::CreateReplacement(
120 ComparisonExpr->getSourceRange(),
121 ((Neg ? "!absl::StartsWith(" : "absl::StartsWith(") + HaystackExprCode +
122 ", " + NeedleExprCode + ")")
123 .str());
124
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);
130 }
131
registerPPCallbacks(const SourceManager & SM,Preprocessor * PP,Preprocessor * ModuleExpanderPP)132 void StringFindStartswithCheck::registerPPCallbacks(
133 const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) {
134 IncludeInserter.registerPreprocessor(PP);
135 }
136
storeOptions(ClangTidyOptions::OptionMap & Opts)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);
143 }
144
145 } // namespace abseil
146 } // namespace tidy
147 } // namespace clang
148