clang-tools 24.0.0git
PreferSingleCharOverloadsCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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/CheckUtils.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "llvm/Support/raw_ostream.h"
14#include <algorithm>
15#include <optional>
16
17using namespace clang::ast_matchers;
18
20
21namespace {
22
23constexpr llvm::StringLiteral DeprecatedCheckName =
24 "performance-faster-string-find";
25constexpr llvm::StringLiteral CanonicalCheckName =
26 "performance-prefer-single-char-overloads";
27
28} // namespace
29
30static std::optional<std::string>
31makeCharacterLiteral(const StringLiteral *Literal) {
32 std::string Result;
33 {
34 llvm::raw_string_ostream OS(Result);
35 Literal->outputString(OS);
36 }
37 // Now replace the " with '.
38 const auto OpenPos = Result.find_first_of('"');
39 if (OpenPos == std::string::npos)
40 return std::nullopt;
41 Result[OpenPos] = '\'';
42
43 const auto ClosePos = Result.find_last_of('"');
44 if (ClosePos == std::string::npos)
45 return std::nullopt;
46 Result[ClosePos] = '\'';
47
48 // "'" is OK, but ''' is not, so add a backslash
49 if ((ClosePos - OpenPos) == 2 && Result[OpenPos + 1] == '\'')
50 Result.replace(OpenPos + 1, 1, "\\'");
51
52 return Result;
53}
54
56 StringRef Name, ClangTidyContext *Context)
57 : ClangTidyCheck(Name, Context),
58 StringLikeClasses(utils::options::parseStringList(
59 Options.get("StringLikeClasses",
60 "::std::basic_string;::std::basic_string_view"))) {
61 if (Name == DeprecatedCheckName)
62 utils::diagDeprecatedCheckAlias(*this, *Context, DeprecatedCheckName,
63 CanonicalCheckName);
64}
65
68 Options.store(Opts, "StringLikeClasses",
69 utils::options::serializeStringList(StringLikeClasses));
70}
71
73 const auto SingleChar =
74 ignoringParenCasts(stringLiteral(hasSize(1)).bind("literal"));
75
76 const auto StringExpr = expr(hasType(hasUnqualifiedDesugaredType(
77 recordType(hasDeclaration(recordDecl(hasAnyName(StringLikeClasses)))))));
78
79 const auto InterestingStringFunction = hasAnyName(
80 "find", "rfind", "find_first_of", "find_first_not_of", "find_last_of",
81 "find_last_not_of", "starts_with", "ends_with", "contains", "operator+=");
82
83 Finder->addMatcher(
84 cxxMemberCallExpr(
85 callee(functionDecl(InterestingStringFunction).bind("func")),
86 anyOf(argumentCountIs(1), argumentCountIs(2)),
87 hasArgument(0, SingleChar), on(StringExpr)),
88 this);
89
90 Finder->addMatcher(cxxOperatorCallExpr(hasOperatorName("+="),
91 hasLHS(StringExpr), hasRHS(SingleChar),
92 callee(functionDecl().bind("func"))),
93 this);
94}
95
97 const MatchFinder::MatchResult &Result) {
98 const auto *Literal = Result.Nodes.getNodeAs<StringLiteral>("literal");
99 const auto *FindFunc = Result.Nodes.getNodeAs<FunctionDecl>("func");
100
101 auto Replacement = makeCharacterLiteral(Literal);
102 if (!Replacement)
103 return;
104
105 const auto Diag = diag(Literal->getBeginLoc(),
106 "%0 called with a string literal consisting of "
107 "a single character; consider using the more "
108 "efficient overload accepting a character")
109 << FindFunc;
110 if (std::none_of(Literal->tokloc_begin(), Literal->tokloc_end(),
111 [](SourceLocation Loc) { return Loc.isMacroID(); }))
112 Diag << FixItHint::CreateReplacement(Literal->getSourceRange(),
113 *Replacement);
114}
115
116} // namespace clang::tidy::performance
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
PreferSingleCharOverloadsCheck(StringRef Name, ClangTidyContext *Context)
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
static std::optional< std::string > makeCharacterLiteral(const StringLiteral *Literal)
std::string serializeStringList(ArrayRef< StringRef > Strings)
Serialize a sequence of names that can be parsed by parseStringList.
void diagDeprecatedCheckAlias(const ClangTidyCheck &Check, const ClangTidyContext &Context, StringRef DeprecatedName, StringRef CanonicalName)
Emits a configuration diagnostic when a deprecated check alias is enabled and the canonical check nam...
Definition CheckUtils.h:10
llvm::StringMap< ClangTidyValue > OptionMap