clang-tools 19.0.0git
StringFindStartswithCheck.cpp
Go to the documentation of this file.
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
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
18using namespace clang::ast_matchers;
19
20namespace clang::tidy::abseil {
21
23 "::std::basic_string;::std::basic_string_view";
24
26 ClangTidyContext *Context)
27 : ClangTidyCheck(Name, Context),
28 StringLikeClasses(utils::options::parseStringList(
29 Options.get("StringLikeClasses", DefaultStringLikeClasses))),
30 IncludeInserter(Options.getLocalOrGlobal("IncludeStyle",
31 utils::IncludeSorter::IS_LLVM),
32 areDiagsSelfContained()),
33 AbseilStringsMatchHeader(
34 Options.get("AbseilStringsMatchHeader", "absl/strings/match.h")) {}
35
37 auto ZeroLiteral = integerLiteral(equals(0));
38 auto StringClassMatcher = cxxRecordDecl(hasAnyName(StringLikeClasses));
39 auto StringType = hasUnqualifiedDesugaredType(
40 recordType(hasDeclaration(StringClassMatcher)));
41
42 auto StringFind = cxxMemberCallExpr(
43 // .find()-call on a string...
44 callee(cxxMethodDecl(hasName("find")).bind("findfun")),
45 on(hasType(StringType)),
46 // ... with some search expression ...
47 hasArgument(0, expr().bind("needle")),
48 // ... and either "0" as second argument or the default argument (also 0).
49 anyOf(hasArgument(1, ZeroLiteral), hasArgument(1, cxxDefaultArgExpr())));
50
51 Finder->addMatcher(
52 // Match [=!]= with a zero on one side and a string.find on the other.
53 binaryOperator(
54 hasAnyOperatorName("==", "!="),
55 hasOperands(ignoringParenImpCasts(ZeroLiteral),
56 ignoringParenImpCasts(StringFind.bind("findexpr"))))
57 .bind("expr"),
58 this);
59
60 auto StringRFind = cxxMemberCallExpr(
61 // .rfind()-call on a string...
62 callee(cxxMethodDecl(hasName("rfind")).bind("findfun")),
63 on(hasType(StringType)),
64 // ... with some search expression ...
65 hasArgument(0, expr().bind("needle")),
66 // ... and "0" as second argument.
67 hasArgument(1, ZeroLiteral));
68
69 Finder->addMatcher(
70 // Match [=!]= with either a zero or npos on one side and a string.rfind
71 // on the other.
72 binaryOperator(
73 hasAnyOperatorName("==", "!="),
74 hasOperands(ignoringParenImpCasts(ZeroLiteral),
75 ignoringParenImpCasts(StringRFind.bind("findexpr"))))
76 .bind("expr"),
77 this);
78}
79
80void StringFindStartswithCheck::check(const MatchFinder::MatchResult &Result) {
81 const ASTContext &Context = *Result.Context;
82 const SourceManager &Source = Context.getSourceManager();
83
84 // Extract matching (sub)expressions
85 const auto *ComparisonExpr = Result.Nodes.getNodeAs<BinaryOperator>("expr");
86 assert(ComparisonExpr != nullptr);
87 const auto *Needle = Result.Nodes.getNodeAs<Expr>("needle");
88 assert(Needle != nullptr);
89 const Expr *Haystack = Result.Nodes.getNodeAs<CXXMemberCallExpr>("findexpr")
90 ->getImplicitObjectArgument();
91 assert(Haystack != nullptr);
92 const auto *FindFun = 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
133 const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) {
134 IncludeInserter.registerPreprocessor(PP);
135}
136
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 clang::tidy::abseil
llvm::SmallString< 256U > Name
DiagnosticCallback Diagnostic
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.
Base class for all clang-tidy checks.
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
StringFindStartswithCheck(StringRef Name, ClangTidyContext *Context)
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
Override this to register PPCallbacks in the preprocessor.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
void registerPreprocessor(Preprocessor *PP)
Registers this with the Preprocessor PP, must be called before this class is used.
std::optional< FixItHint > createIncludeInsertion(FileID FileID, llvm::StringRef Header)
Creates a Header inclusion directive fixit in the File FileID.
IncludeSorter::IncludeStyle getStyle() const
std::string serializeStringList(ArrayRef< StringRef > Strings)
Serialize a sequence of names that can be parsed by parseStringList.
llvm::StringMap< ClangTidyValue > OptionMap