1 //===--- StringFindStrContainsCheck.cc - clang-tidy------------------------===//
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 "StringFindStrContainsCheck.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/Tooling/Transformer/RewriteRule.h"
16 #include "clang/Tooling/Transformer/Stencil.h"
17 
18 // FixItHint - Hint to check documentation script to mark this check as
19 // providing a FixIt.
20 
21 using namespace clang::ast_matchers;
22 
23 namespace clang {
24 namespace tidy {
25 namespace abseil {
26 
27 using ::clang::transformer::applyFirst;
28 using ::clang::transformer::cat;
29 using ::clang::transformer::change;
30 using ::clang::transformer::makeRule;
31 using ::clang::transformer::node;
32 using ::clang::transformer::RewriteRule;
33 
AST_MATCHER(Type,isCharType)34 AST_MATCHER(Type, isCharType) { return Node.isCharType(); }
35 
36 static const char DefaultStringLikeClasses[] = "::std::basic_string;"
37                                                "::std::basic_string_view;"
38                                                "::absl::string_view";
39 static const char DefaultAbseilStringsMatchHeader[] = "absl/strings/match.h";
40 
41 static llvm::Optional<transformer::RewriteRule>
MakeRule(const LangOptions & LangOpts,const ClangTidyCheck::OptionsView & Options)42 MakeRule(const LangOptions &LangOpts,
43          const ClangTidyCheck::OptionsView &Options) {
44   // Parse options.
45   //
46   // FIXME(tdl-g): These options are being parsed redundantly with the
47   // constructor because TransformerClangTidyCheck forces us to provide MakeRule
48   // before "this" is fully constructed, but StoreOptions requires us to store
49   // the parsed options in "this".  We need to fix TransformerClangTidyCheck and
50   // then we can clean this up.
51   const std::vector<std::string> StringLikeClassNames =
52       utils::options::parseStringList(
53           Options.get("StringLikeClasses", DefaultStringLikeClasses));
54   const std::string AbseilStringsMatchHeader =
55       Options.get("AbseilStringsMatchHeader", DefaultAbseilStringsMatchHeader);
56 
57   auto StringLikeClass = cxxRecordDecl(hasAnyName(SmallVector<StringRef, 4>(
58       StringLikeClassNames.begin(), StringLikeClassNames.end())));
59   auto StringType =
60       hasUnqualifiedDesugaredType(recordType(hasDeclaration(StringLikeClass)));
61   auto CharStarType =
62       hasUnqualifiedDesugaredType(pointerType(pointee(isAnyCharacter())));
63   auto CharType = hasUnqualifiedDesugaredType(isCharType());
64   auto StringNpos = declRefExpr(
65       to(varDecl(hasName("npos"), hasDeclContext(StringLikeClass))));
66   auto StringFind = cxxMemberCallExpr(
67       callee(cxxMethodDecl(
68           hasName("find"),
69           hasParameter(
70               0, parmVarDecl(anyOf(hasType(StringType), hasType(CharStarType),
71                                    hasType(CharType)))))),
72       on(hasType(StringType)), hasArgument(0, expr().bind("parameter_to_find")),
73       anyOf(hasArgument(1, integerLiteral(equals(0))),
74             hasArgument(1, cxxDefaultArgExpr())),
75       onImplicitObjectArgument(expr().bind("string_being_searched")));
76 
77   RewriteRule rule = applyFirst(
78       {makeRule(binaryOperator(hasOperatorName("=="),
79                                hasOperands(ignoringParenImpCasts(StringNpos),
80                                            ignoringParenImpCasts(StringFind))),
81                 change(cat("!absl::StrContains(", node("string_being_searched"),
82                            ", ", node("parameter_to_find"), ")")),
83                 cat("use !absl::StrContains instead of find() == npos")),
84        makeRule(binaryOperator(hasOperatorName("!="),
85                                hasOperands(ignoringParenImpCasts(StringNpos),
86                                            ignoringParenImpCasts(StringFind))),
87                 change(cat("absl::StrContains(", node("string_being_searched"),
88                            ", ", node("parameter_to_find"), ")")),
89                 cat("use absl::StrContains instead of find() != npos"))});
90   addInclude(rule, AbseilStringsMatchHeader);
91   return rule;
92 }
93 
StringFindStrContainsCheck(StringRef Name,ClangTidyContext * Context)94 StringFindStrContainsCheck::StringFindStrContainsCheck(
95     StringRef Name, ClangTidyContext *Context)
96     : TransformerClangTidyCheck(&MakeRule, Name, Context),
97       StringLikeClassesOption(utils::options::parseStringList(
98           Options.get("StringLikeClasses", DefaultStringLikeClasses))),
99       AbseilStringsMatchHeaderOption(Options.get(
100           "AbseilStringsMatchHeader", DefaultAbseilStringsMatchHeader)) {}
101 
isLanguageVersionSupported(const LangOptions & LangOpts) const102 bool StringFindStrContainsCheck::isLanguageVersionSupported(
103     const LangOptions &LangOpts) const {
104   return LangOpts.CPlusPlus11;
105 }
106 
storeOptions(ClangTidyOptions::OptionMap & Opts)107 void StringFindStrContainsCheck::storeOptions(
108     ClangTidyOptions::OptionMap &Opts) {
109   TransformerClangTidyCheck::storeOptions(Opts);
110   Options.store(Opts, "StringLikeClasses",
111                 utils::options::serializeStringList(StringLikeClassesOption));
112   Options.store(Opts, "AbseilStringsMatchHeader",
113                 AbseilStringsMatchHeaderOption);
114 }
115 
116 } // namespace abseil
117 } // namespace tidy
118 } // namespace clang
119