[clang][modules] Don't prevent translation of FW_Private includes when explicitly...
[llvm-project.git] / clang-tools-extra / clang-tidy / readability / StringCompareCheck.cpp
blob3b5d89c8c647196ec57c779e7a93de23d3052994
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 //===----------------------------------------------------------------------===//
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 "
21 "operator instead";
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.
32 Finder->addMatcher(
33 traverse(TK_AsIs,
34 implicitCastExpr(hasImplicitDestinationType(booleanType()),
35 has(StrCompare))
36 .bind("match1")),
37 this);
39 // Third and fourth case: str.compare(str) == 0 and str.compare(str) != 0.
40 Finder->addMatcher(
41 binaryOperator(hasAnyOperatorName("==", "!="),
42 hasOperands(StrCompare.bind("compare"),
43 integerLiteral(equals(0)).bind("zero")))
44 .bind("match2"),
45 this);
48 void StringCompareCheck::check(const MatchFinder::MatchResult &Result) {
49 if (const auto *Matched = Result.Nodes.getNodeAs<Stmt>("match1")) {
50 diag(Matched->getBeginLoc(), CompareMessage);
51 return;
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);
64 if (Str1->isArrow())
65 Diag << FixItHint::CreateInsertion(Str1->getBeginLoc(), "*");
67 Diag << tooling::fixit::createReplacement(*Zero, *Str2, Ctx)
68 << tooling::fixit::createReplacement(*Compare, *Str1->getBase(),
69 Ctx);
73 // FIXME: Add fixit to fix the code for case one and two (match1).
76 } // namespace clang::tidy::readability