aboutsummaryrefslogtreecommitdiff
path: root/clang-tools-extra/clang-tidy/modernize/UseStartsEndsWithCheck.cpp
blob: 89ee45faecd7f33e8f80189ee59fad02849695aa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
//===--- UseStartsEndsWithCheck.cpp - clang-tidy --------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "UseStartsEndsWithCheck.h"

#include "../utils/OptionsUtils.h"
#include "clang/Lex/Lexer.h"

#include <string>

using namespace clang::ast_matchers;

namespace clang::tidy::modernize {

UseStartsEndsWithCheck::UseStartsEndsWithCheck(StringRef Name,
                                               ClangTidyContext *Context)
    : ClangTidyCheck(Name, Context) {}

void UseStartsEndsWithCheck::registerMatchers(MatchFinder *Finder) {
  const auto ZeroLiteral = integerLiteral(equals(0));
  const auto HasStartsWithMethodWithName = [](const std::string &Name) {
    return hasMethod(
        cxxMethodDecl(hasName(Name), isConst(), parameterCountIs(1))
            .bind("starts_with_fun"));
  };
  const auto HasStartsWithMethod =
      anyOf(HasStartsWithMethodWithName("starts_with"),
            HasStartsWithMethodWithName("startsWith"),
            HasStartsWithMethodWithName("startswith"));
  const auto ClassWithStartsWithFunction = cxxRecordDecl(anyOf(
      HasStartsWithMethod, hasAnyBase(hasType(hasCanonicalType(hasDeclaration(
                               cxxRecordDecl(HasStartsWithMethod)))))));

  const auto FindExpr = cxxMemberCallExpr(
      // A method call with no second argument or the second argument is zero...
      anyOf(argumentCountIs(1), hasArgument(1, ZeroLiteral)),
      // ... named find...
      callee(cxxMethodDecl(hasName("find")).bind("find_fun")),
      // ... on a class with a starts_with function.
      on(hasType(
          hasCanonicalType(hasDeclaration(ClassWithStartsWithFunction)))),
      // Bind search expression.
      hasArgument(0, expr().bind("search_expr")));

  const auto RFindExpr = cxxMemberCallExpr(
      // A method call with a second argument of zero...
      hasArgument(1, ZeroLiteral),
      // ... named rfind...
      callee(cxxMethodDecl(hasName("rfind")).bind("find_fun")),
      // ... on a class with a starts_with function.
      on(hasType(
          hasCanonicalType(hasDeclaration(ClassWithStartsWithFunction)))),
      // Bind search expression.
      hasArgument(0, expr().bind("search_expr")));

  // Match a string literal and an integer or strlen() call matching the length.
  const auto HasStringLiteralAndLengthArgs = [](const auto StringArgIndex,
                                                const auto LengthArgIndex) {
    return allOf(
        hasArgument(StringArgIndex, stringLiteral().bind("string_literal_arg")),
        hasArgument(LengthArgIndex,
                    anyOf(integerLiteral().bind("integer_literal_size_arg"),
                          callExpr(callee(functionDecl(parameterCountIs(1),
                                                       hasName("strlen"))),
                                   hasArgument(0, stringLiteral().bind(
                                                      "strlen_arg"))))));
  };

  // Match a string variable and a call to length() or size().
  const auto HasStringVariableAndSizeCallArgs = [](const auto StringArgIndex,
                                                   const auto LengthArgIndex) {
    return allOf(
        hasArgument(StringArgIndex, declRefExpr(hasDeclaration(
                                        decl().bind("string_var_decl")))),
        hasArgument(LengthArgIndex,
                    cxxMemberCallExpr(
                        callee(cxxMethodDecl(isConst(), parameterCountIs(0),
                                             hasAnyName("size", "length"))),
                        on(declRefExpr(
                            to(decl(equalsBoundNode("string_var_decl"))))))));
  };

  // Match either one of the two cases above.
  const auto HasStringAndLengthArgs =
      [HasStringLiteralAndLengthArgs, HasStringVariableAndSizeCallArgs](
          const auto StringArgIndex, const auto LengthArgIndex) {
        return anyOf(
            HasStringLiteralAndLengthArgs(StringArgIndex, LengthArgIndex),
            HasStringVariableAndSizeCallArgs(StringArgIndex, LengthArgIndex));
      };

  const auto CompareExpr = cxxMemberCallExpr(
      // A method call with three arguments...
      argumentCountIs(3),
      // ... where the first argument is zero...
      hasArgument(0, ZeroLiteral),
      // ... named compare...
      callee(cxxMethodDecl(hasName("compare")).bind("find_fun")),
      // ... on a class with a starts_with function...
      on(hasType(
          hasCanonicalType(hasDeclaration(ClassWithStartsWithFunction)))),
      // ... where the third argument is some string and the second a length.
      HasStringAndLengthArgs(2, 1),
      // Bind search expression.
      hasArgument(2, expr().bind("search_expr")));

  Finder->addMatcher(
      // Match [=!]= with a zero on one side and (r?)find|compare on the other.
      binaryOperator(
          hasAnyOperatorName("==", "!="),
          hasOperands(cxxMemberCallExpr(anyOf(FindExpr, RFindExpr, CompareExpr))
                          .bind("find_expr"),
                      ZeroLiteral))
          .bind("expr"),
      this);
}

void UseStartsEndsWithCheck::check(const MatchFinder::MatchResult &Result) {
  const auto *ComparisonExpr = Result.Nodes.getNodeAs<BinaryOperator>("expr");
  const auto *FindExpr = Result.Nodes.getNodeAs<CXXMemberCallExpr>("find_expr");
  const auto *FindFun = Result.Nodes.getNodeAs<CXXMethodDecl>("find_fun");
  const auto *SearchExpr = Result.Nodes.getNodeAs<Expr>("search_expr");
  const auto *StartsWithFunction =
      Result.Nodes.getNodeAs<CXXMethodDecl>("starts_with_fun");

  const auto *StringLiteralArg =
      Result.Nodes.getNodeAs<StringLiteral>("string_literal_arg");
  const auto *IntegerLiteralSizeArg =
      Result.Nodes.getNodeAs<IntegerLiteral>("integer_literal_size_arg");
  const auto *StrlenArg = Result.Nodes.getNodeAs<StringLiteral>("strlen_arg");

  // Filter out compare cases where the length does not match string literal.
  if (StringLiteralArg && IntegerLiteralSizeArg &&
      StringLiteralArg->getLength() !=
          IntegerLiteralSizeArg->getValue().getZExtValue()) {
    return;
  }

  if (StringLiteralArg && StrlenArg &&
      StringLiteralArg->getLength() != StrlenArg->getLength()) {
    return;
  }

  if (ComparisonExpr->getBeginLoc().isMacroID()) {
    return;
  }

  const bool Neg = ComparisonExpr->getOpcode() == BO_NE;

  auto Diagnostic =
      diag(FindExpr->getExprLoc(), "use %0 instead of %1() %select{==|!=}2 0")
      << StartsWithFunction->getName() << FindFun->getName() << Neg;

  // Remove possible arguments after search expression and ' [!=]= 0' suffix.
  Diagnostic << FixItHint::CreateReplacement(
      CharSourceRange::getTokenRange(
          Lexer::getLocForEndOfToken(SearchExpr->getEndLoc(), 0,
                                     *Result.SourceManager, getLangOpts()),
          ComparisonExpr->getEndLoc()),
      ")");

  // Remove possible '0 [!=]= ' prefix.
  Diagnostic << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
      ComparisonExpr->getBeginLoc(), FindExpr->getBeginLoc()));

  // Replace method name by 'starts_with'.
  // Remove possible arguments before search expression.
  Diagnostic << FixItHint::CreateReplacement(
      CharSourceRange::getCharRange(FindExpr->getExprLoc(),
                                    SearchExpr->getBeginLoc()),
      (StartsWithFunction->getName() + "(").str());

  // Add possible negation '!'.
  if (Neg) {
    Diagnostic << FixItHint::CreateInsertion(FindExpr->getBeginLoc(), "!");
  }
}

} // namespace clang::tidy::modernize