1 //===--- FasterStringFindCheck.cpp - 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 "FasterStringFindCheck.h"
10 #include "../utils/OptionsUtils.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include "llvm/ADT/Optional.h"
14 #include "llvm/Support/raw_ostream.h"
15 
16 using namespace clang::ast_matchers;
17 
18 namespace clang {
19 namespace tidy {
20 namespace performance {
21 
22 namespace {
23 
MakeCharacterLiteral(const StringLiteral * Literal)24 llvm::Optional<std::string> MakeCharacterLiteral(const StringLiteral *Literal) {
25   std::string Result;
26   {
27     llvm::raw_string_ostream OS(Result);
28     Literal->outputString(OS);
29   }
30   // Now replace the " with '.
31   auto pos = Result.find_first_of('"');
32   if (pos == Result.npos)
33     return llvm::None;
34   Result[pos] = '\'';
35   pos = Result.find_last_of('"');
36   if (pos == Result.npos)
37     return llvm::None;
38   Result[pos] = '\'';
39   return Result;
40 }
41 
AST_MATCHER_FUNCTION(ast_matchers::internal::Matcher<Expr>,hasSubstitutedType)42 AST_MATCHER_FUNCTION(ast_matchers::internal::Matcher<Expr>,
43                      hasSubstitutedType) {
44   return hasType(qualType(anyOf(substTemplateTypeParmType(),
45                                 hasDescendant(substTemplateTypeParmType()))));
46 }
47 
48 } // namespace
49 
FasterStringFindCheck(StringRef Name,ClangTidyContext * Context)50 FasterStringFindCheck::FasterStringFindCheck(StringRef Name,
51                                              ClangTidyContext *Context)
52     : ClangTidyCheck(Name, Context),
53       StringLikeClasses(utils::options::parseStringList(
54           Options.get("StringLikeClasses",
55                       "::std::basic_string;::std::basic_string_view"))) {}
56 
storeOptions(ClangTidyOptions::OptionMap & Opts)57 void FasterStringFindCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
58   Options.store(Opts, "StringLikeClasses",
59                 utils::options::serializeStringList(StringLikeClasses));
60 }
61 
registerMatchers(MatchFinder * Finder)62 void FasterStringFindCheck::registerMatchers(MatchFinder *Finder) {
63   const auto SingleChar =
64       expr(ignoringParenCasts(stringLiteral(hasSize(1)).bind("literal")));
65   const auto StringFindFunctions =
66       hasAnyName("find", "rfind", "find_first_of", "find_first_not_of",
67                  "find_last_of", "find_last_not_of");
68 
69   Finder->addMatcher(
70       cxxMemberCallExpr(
71           callee(functionDecl(StringFindFunctions).bind("func")),
72           anyOf(argumentCountIs(1), argumentCountIs(2)),
73           hasArgument(0, SingleChar),
74           on(expr(
75               hasType(hasUnqualifiedDesugaredType(recordType(hasDeclaration(
76                   recordDecl(hasAnyName(SmallVector<StringRef, 4>(
77                       StringLikeClasses.begin(), StringLikeClasses.end()))))))),
78               unless(hasSubstitutedType())))),
79       this);
80 }
81 
check(const MatchFinder::MatchResult & Result)82 void FasterStringFindCheck::check(const MatchFinder::MatchResult &Result) {
83   const auto *Literal = Result.Nodes.getNodeAs<StringLiteral>("literal");
84   const auto *FindFunc = Result.Nodes.getNodeAs<FunctionDecl>("func");
85 
86   auto Replacement = MakeCharacterLiteral(Literal);
87   if (!Replacement)
88     return;
89 
90   diag(Literal->getBeginLoc(), "%0 called with a string literal consisting of "
91                                "a single character; consider using the more "
92                                "effective overload accepting a character")
93       << FindFunc
94       << FixItHint::CreateReplacement(
95              CharSourceRange::getTokenRange(Literal->getBeginLoc(),
96                                             Literal->getEndLoc()),
97              *Replacement);
98 }
99 
100 } // namespace performance
101 } // namespace tidy
102 } // namespace clang
103