clang-tools  16.0.0git
FasterStringFindCheck.cpp
Go to the documentation of this file.
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 
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 
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 
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 
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 
58  Options.store(Opts, "StringLikeClasses",
59  utils::options::serializeStringList(StringLikeClasses));
60 }
61 
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(hasType(hasUnqualifiedDesugaredType(recordType(hasDeclaration(
75  recordDecl(hasAnyName(StringLikeClasses)))))),
76  unless(hasSubstitutedType())))),
77  this);
78 }
79 
80 void FasterStringFindCheck::check(const MatchFinder::MatchResult &Result) {
81  const auto *Literal = Result.Nodes.getNodeAs<StringLiteral>("literal");
82  const auto *FindFunc = Result.Nodes.getNodeAs<FunctionDecl>("func");
83 
84  auto Replacement = makeCharacterLiteral(Literal);
85  if (!Replacement)
86  return;
87 
88  diag(Literal->getBeginLoc(), "%0 called with a string literal consisting of "
89  "a single character; consider using the more "
90  "effective overload accepting a character")
91  << FindFunc
92  << FixItHint::CreateReplacement(
93  CharSourceRange::getTokenRange(Literal->getBeginLoc(),
94  Literal->getEndLoc()),
95  *Replacement);
96 }
97 
98 } // namespace performance
99 } // namespace tidy
100 } // namespace clang
clang::tidy::performance::FasterStringFindCheck::storeOptions
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
Definition: FasterStringFindCheck.cpp:57
clang::tidy::ClangTidyOptions::OptionMap
llvm::StringMap< ClangTidyValue > OptionMap
Definition: ClangTidyOptions.h:115
clang::tidy::abseil::AST_MATCHER_FUNCTION
AST_MATCHER_FUNCTION(ast_matchers::internal::Matcher< FunctionDecl >, DurationConversionFunction)
Definition: DurationRewriter.h:99
clang::tidy::ClangTidyCheck
Base class for all clang-tidy checks.
Definition: ClangTidyCheck.h:53
FasterStringFindCheck.h
clang::tidy::performance::FasterStringFindCheck::check
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
Definition: FasterStringFindCheck.cpp:80
clang::ast_matchers
Definition: AbseilMatcher.h:14
Pos
size_t Pos
Definition: NoLintDirectiveHandler.cpp:97
clang::tidy::ClangTidyCheck::Options
OptionsView Options
Definition: ClangTidyCheck.h:415
clang::tidy::ClangTidyContext
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
Definition: ClangTidyDiagnosticConsumer.h:67
clang::tidy::ClangTidyCheck::diag
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
Definition: ClangTidyCheck.cpp:25
Name
Token Name
Definition: MacroToEnumCheck.cpp:89
clang::tidy::performance::FasterStringFindCheck::registerMatchers
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
Definition: FasterStringFindCheck.cpp:62
clang::tidy::utils::options::serializeStringList
std::string serializeStringList(ArrayRef< StringRef > Strings)
Serialize a sequence of names that can be parsed by parseStringList.
Definition: OptionsUtils.cpp:62
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27
clang::tidy::utils::options::parseStringList
std::vector< StringRef > parseStringList(StringRef Option)
Parse a semicolon separated list of strings.
Definition: OptionsUtils.cpp:19
OS
llvm::raw_string_ostream OS
Definition: TraceTests.cpp:160
clang::tidy::ClangTidyCheck::OptionsView::store
void store(ClangTidyOptions::OptionMap &Options, StringRef LocalName, StringRef Value) const
Stores an option with the check-local name LocalName with string value Value to Options.
Definition: ClangTidyCheck.cpp:129