xref: /llvm-project/clang-tools-extra/clang-tidy/readability/StringCompareCheck.cpp (revision febd89cafea11e6603f593e41be1a21ca9d009ac)
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 
9 #include "StringCompareCheck.h"
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 
17 using namespace clang::ast_matchers;
18 namespace optutils = clang::tidy::utils::options;
19 
20 namespace clang::tidy::readability {
21 
22 static const StringRef CompareMessage = "do not use 'compare' to test equality "
23                                         "of strings; use the string equality "
24                                         "operator instead";
25 
26 static const StringRef DefaultStringLikeClasses = "::std::basic_string;"
27                                                   "::std::basic_string_view";
28 
StringCompareCheck(StringRef Name,ClangTidyContext * Context)29 StringCompareCheck::StringCompareCheck(StringRef Name,
30                                        ClangTidyContext *Context)
31     : ClangTidyCheck(Name, Context),
32       StringLikeClasses(optutils::parseStringList(
33           Options.get("StringLikeClasses", DefaultStringLikeClasses))) {}
34 
storeOptions(ClangTidyOptions::OptionMap & Opts)35 void StringCompareCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
36   Options.store(Opts, "StringLikeClasses",
37                 optutils::serializeStringList(StringLikeClasses));
38 }
39 
registerMatchers(MatchFinder * Finder)40 void 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 
check(const MatchFinder::MatchResult & Result)67 void 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
96