clang-tools 20.0.0git
StringCompareCheck.cpp
Go to the documentation of this file.
1//===-- StringCompareCheck.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 "clang/ASTMatchers/ASTMatchers.h"
14#include "clang/Tooling/FixIt.h"
15#include "llvm/ADT/StringRef.h"
16
17using namespace clang::ast_matchers;
19
21
22static const StringRef CompareMessage = "do not use 'compare' to test equality "
23 "of strings; use the string equality "
24 "operator instead";
25
26static const StringRef DefaultStringLikeClasses = "::std::basic_string;"
27 "::std::basic_string_view";
28
30 ClangTidyContext *Context)
31 : ClangTidyCheck(Name, Context),
32 StringLikeClasses(optutils::parseStringList(
33 Options.get("StringLikeClasses", DefaultStringLikeClasses))) {}
34
36 Options.store(Opts, "StringLikeClasses",
37 optutils::serializeStringList(StringLikeClasses));
38}
39
40void StringCompareCheck::registerMatchers(MatchFinder *Finder) {
41 if (StringLikeClasses.empty()) {
42 return;
43 }
44 const auto StrCompare = cxxMemberCallExpr(
45 callee(cxxMethodDecl(hasName("compare"), ofClass(cxxRecordDecl(hasAnyName(
46 StringLikeClasses))))),
47 hasArgument(0, expr().bind("str2")), argumentCountIs(1),
48 callee(memberExpr().bind("str1")));
49
50 // First and second case: cast str.compare(str) to boolean.
51 Finder->addMatcher(
52 traverse(TK_AsIs,
53 implicitCastExpr(hasImplicitDestinationType(booleanType()),
54 has(StrCompare))
55 .bind("match1")),
56 this);
57
58 // Third and fourth case: str.compare(str) == 0 and str.compare(str) != 0.
59 Finder->addMatcher(
60 binaryOperator(hasAnyOperatorName("==", "!="),
61 hasOperands(StrCompare.bind("compare"),
62 integerLiteral(equals(0)).bind("zero")))
63 .bind("match2"),
64 this);
65}
66
67void StringCompareCheck::check(const MatchFinder::MatchResult &Result) {
68 if (const auto *Matched = Result.Nodes.getNodeAs<Stmt>("match1")) {
69 diag(Matched->getBeginLoc(), CompareMessage);
70 return;
71 }
72
73 if (const auto *Matched = Result.Nodes.getNodeAs<Stmt>("match2")) {
74 const ASTContext &Ctx = *Result.Context;
75
76 if (const auto *Zero = Result.Nodes.getNodeAs<Stmt>("zero")) {
77 const auto *Str1 = Result.Nodes.getNodeAs<MemberExpr>("str1");
78 const auto *Str2 = Result.Nodes.getNodeAs<Stmt>("str2");
79 const auto *Compare = Result.Nodes.getNodeAs<Stmt>("compare");
80
81 auto Diag = diag(Matched->getBeginLoc(), CompareMessage);
82
83 if (Str1->isArrow())
84 Diag << FixItHint::CreateInsertion(Str1->getBeginLoc(), "*");
85
86 Diag << tooling::fixit::createReplacement(*Zero, *Str2, Ctx)
87 << tooling::fixit::createReplacement(*Compare, *Str1->getBase(),
88 Ctx);
89 }
90 }
91
92 // FIXME: Add fixit to fix the code for case one and two (match1).
93}
94
95} // namespace clang::tidy::readability
llvm::SmallString< 256U > Name
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 registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
StringCompareCheck(StringRef Name, ClangTidyContext *Context)
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
Should store all options supported by this check with their current values or default values for opti...
static const StringRef DefaultStringLikeClasses
static const StringRef CompareMessage
std::string serializeStringList(ArrayRef< StringRef > Strings)
Serialize a sequence of names that can be parsed by parseStringList.
llvm::StringMap< ClangTidyValue > OptionMap