1 //===-- StringCompareCheck.cpp - clang-tidy--------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "StringCompareCheck.h"
10 #include "../utils/FixItHintUtils.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include "clang/Tooling/FixIt.h"
15 using namespace clang::ast_matchers
;
17 namespace clang::tidy::readability
{
19 static const StringRef CompareMessage
= "do not use 'compare' to test equality "
20 "of strings; use the string equality "
23 void StringCompareCheck::registerMatchers(MatchFinder
*Finder
) {
24 const auto StrCompare
= cxxMemberCallExpr(
25 callee(cxxMethodDecl(hasName("compare"),
26 ofClass(classTemplateSpecializationDecl(
27 hasName("::std::basic_string"))))),
28 hasArgument(0, expr().bind("str2")), argumentCountIs(1),
29 callee(memberExpr().bind("str1")));
31 // First and second case: cast str.compare(str) to boolean.
34 implicitCastExpr(hasImplicitDestinationType(booleanType()),
39 // Third and fourth case: str.compare(str) == 0 and str.compare(str) != 0.
41 binaryOperator(hasAnyOperatorName("==", "!="),
42 hasOperands(StrCompare
.bind("compare"),
43 integerLiteral(equals(0)).bind("zero")))
48 void StringCompareCheck::check(const MatchFinder::MatchResult
&Result
) {
49 if (const auto *Matched
= Result
.Nodes
.getNodeAs
<Stmt
>("match1")) {
50 diag(Matched
->getBeginLoc(), CompareMessage
);
54 if (const auto *Matched
= Result
.Nodes
.getNodeAs
<Stmt
>("match2")) {
55 const ASTContext
&Ctx
= *Result
.Context
;
57 if (const auto *Zero
= Result
.Nodes
.getNodeAs
<Stmt
>("zero")) {
58 const auto *Str1
= Result
.Nodes
.getNodeAs
<MemberExpr
>("str1");
59 const auto *Str2
= Result
.Nodes
.getNodeAs
<Stmt
>("str2");
60 const auto *Compare
= Result
.Nodes
.getNodeAs
<Stmt
>("compare");
62 auto Diag
= diag(Matched
->getBeginLoc(), CompareMessage
);
65 Diag
<< FixItHint::CreateInsertion(Str1
->getBeginLoc(), "*");
67 Diag
<< tooling::fixit::createReplacement(*Zero
, *Str2
, Ctx
)
68 << tooling::fixit::createReplacement(*Compare
, *Str1
->getBase(),
73 // FIXME: Add fixit to fix the code for case one and two (match1).
76 } // namespace clang::tidy::readability