aboutsummaryrefslogtreecommitdiff
path: root/clang-tools-extra/clang-tidy/readability/OperatorsRepresentationCheck.cpp
blob: ccaa686f853234de7d9d655ba11dff953fb318ed (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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
//===--- OperatorsRepresentationCheck.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 "OperatorsRepresentationCheck.h"
#include "../utils/OptionsUtils.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Lex/Lexer.h"
#include "llvm/ADT/STLExtras.h"
#include <array>
#include <utility>

using namespace clang::ast_matchers;

namespace clang::tidy::readability {

static StringRef getOperatorSpelling(SourceLocation Loc, ASTContext &Context) {
  if (Loc.isInvalid())
    return {};

  SourceManager &SM = Context.getSourceManager();

  Loc = SM.getSpellingLoc(Loc);
  if (Loc.isInvalid())
    return {};

  const CharSourceRange TokenRange = CharSourceRange::getTokenRange(Loc);
  return Lexer::getSourceText(TokenRange, SM, Context.getLangOpts());
}

namespace {

AST_MATCHER_P2(BinaryOperator, hasInvalidBinaryOperatorRepresentation,
               BinaryOperatorKind, Kind, llvm::StringRef,
               ExpectedRepresentation) {
  if (Node.getOpcode() != Kind || ExpectedRepresentation.empty())
    return false;

  StringRef Spelling =
      getOperatorSpelling(Node.getOperatorLoc(), Finder->getASTContext());
  return !Spelling.empty() && Spelling != ExpectedRepresentation;
}

AST_MATCHER_P2(UnaryOperator, hasInvalidUnaryOperatorRepresentation,
               UnaryOperatorKind, Kind, llvm::StringRef,
               ExpectedRepresentation) {
  if (Node.getOpcode() != Kind || ExpectedRepresentation.empty())
    return false;

  StringRef Spelling =
      getOperatorSpelling(Node.getOperatorLoc(), Finder->getASTContext());
  return !Spelling.empty() && Spelling != ExpectedRepresentation;
}

AST_MATCHER_P2(CXXOperatorCallExpr, hasInvalidOverloadedOperatorRepresentation,
               OverloadedOperatorKind, Kind, llvm::StringRef,
               ExpectedRepresentation) {
  if (Node.getOperator() != Kind || ExpectedRepresentation.empty())
    return false;

  StringRef Spelling =
      getOperatorSpelling(Node.getOperatorLoc(), Finder->getASTContext());
  return !Spelling.empty() && Spelling != ExpectedRepresentation;
}

} // namespace

constexpr std::array<std::pair<llvm::StringRef, llvm::StringRef>, 2U>
    UnaryRepresentation{{{"!", "not"}, {"~", "compl"}}};

constexpr std::array<std::pair<llvm::StringRef, llvm::StringRef>, 9U>
    OperatorsRepresentation{{{"&&", "and"},
                             {"||", "or"},
                             {"^", "xor"},
                             {"&", "bitand"},
                             {"|", "bitor"},
                             {"&=", "and_eq"},
                             {"|=", "or_eq"},
                             {"!=", "not_eq"},
                             {"^=", "xor_eq"}}};

static llvm::StringRef translate(llvm::StringRef Value) {
  for (const auto &[Traditional, Alternative] : UnaryRepresentation) {
    if (Value == Traditional)
      return Alternative;
    if (Value == Alternative)
      return Traditional;
  }

  for (const auto &[Traditional, Alternative] : OperatorsRepresentation) {
    if (Value == Traditional)
      return Alternative;
    if (Value == Alternative)
      return Traditional;
  }
  return {};
}

static bool isNotOperatorStr(llvm::StringRef Value) {
  return translate(Value).empty();
}

static bool isSeparator(char C) noexcept {
  constexpr llvm::StringRef Separators(" \t\r\n\0()<>{};,");
  return Separators.contains(C);
}

static bool needEscaping(llvm::StringRef Operator) {
  switch (Operator[0]) {
  case '&':
  case '|':
  case '!':
  case '^':
  case '~':
    return false;
  default:
    return true;
  }
}

static llvm::StringRef
getRepresentation(const std::vector<llvm::StringRef> &Config,
                  llvm::StringRef Traditional, llvm::StringRef Alternative) {
  if (llvm::is_contained(Config, Traditional))
    return Traditional;
  if (llvm::is_contained(Config, Alternative))
    return Alternative;
  return {};
}

template <typename T>
static bool isAnyOperatorEnabled(const std::vector<llvm::StringRef> &Config,
                                 const T &Operators) {
  for (const auto &[traditional, alternative] : Operators) {
    if (!getRepresentation(Config, traditional, alternative).empty())
      return true;
  }
  return false;
}

OperatorsRepresentationCheck::OperatorsRepresentationCheck(
    StringRef Name, ClangTidyContext *Context)
    : ClangTidyCheck(Name, Context),
      BinaryOperators(
          utils::options::parseStringList(Options.get("BinaryOperators", ""))),
      OverloadedOperators(utils::options::parseStringList(
          Options.get("OverloadedOperators", ""))) {
  llvm::erase_if(BinaryOperators, isNotOperatorStr);
  llvm::erase_if(OverloadedOperators, isNotOperatorStr);
}

void OperatorsRepresentationCheck::storeOptions(
    ClangTidyOptions::OptionMap &Opts) {
  Options.store(Opts, "BinaryOperators",
                utils::options::serializeStringList(BinaryOperators));
  Options.store(Opts, "OverloadedOperators",
                utils::options::serializeStringList(OverloadedOperators));
}

std::optional<TraversalKind>
OperatorsRepresentationCheck::getCheckTraversalKind() const {
  return TK_IgnoreUnlessSpelledInSource;
}

bool OperatorsRepresentationCheck::isLanguageVersionSupported(
    const LangOptions &LangOpts) const {
  return LangOpts.CPlusPlus;
}

void OperatorsRepresentationCheck::registerBinaryOperatorMatcher(
    MatchFinder *Finder) {
  if (!isAnyOperatorEnabled(BinaryOperators, OperatorsRepresentation))
    return;

  Finder->addMatcher(
      binaryOperator(
          unless(isExpansionInSystemHeader()),
          anyOf(hasInvalidBinaryOperatorRepresentation(
                    BO_LAnd, getRepresentation(BinaryOperators, "&&", "and")),
                hasInvalidBinaryOperatorRepresentation(
                    BO_LOr, getRepresentation(BinaryOperators, "||", "or")),
                hasInvalidBinaryOperatorRepresentation(
                    BO_NE, getRepresentation(BinaryOperators, "!=", "not_eq")),
                hasInvalidBinaryOperatorRepresentation(
                    BO_Xor, getRepresentation(BinaryOperators, "^", "xor")),
                hasInvalidBinaryOperatorRepresentation(
                    BO_And, getRepresentation(BinaryOperators, "&", "bitand")),
                hasInvalidBinaryOperatorRepresentation(
                    BO_Or, getRepresentation(BinaryOperators, "|", "bitor")),
                hasInvalidBinaryOperatorRepresentation(
                    BO_AndAssign,
                    getRepresentation(BinaryOperators, "&=", "and_eq")),
                hasInvalidBinaryOperatorRepresentation(
                    BO_OrAssign,
                    getRepresentation(BinaryOperators, "|=", "or_eq")),
                hasInvalidBinaryOperatorRepresentation(
                    BO_XorAssign,
                    getRepresentation(BinaryOperators, "^=", "xor_eq"))))
          .bind("binary_op"),
      this);
}

void OperatorsRepresentationCheck::registerUnaryOperatorMatcher(
    MatchFinder *Finder) {
  if (!isAnyOperatorEnabled(BinaryOperators, UnaryRepresentation))
    return;

  Finder->addMatcher(
      unaryOperator(
          unless(isExpansionInSystemHeader()),
          anyOf(hasInvalidUnaryOperatorRepresentation(
                    UO_LNot, getRepresentation(BinaryOperators, "!", "not")),
                hasInvalidUnaryOperatorRepresentation(
                    UO_Not, getRepresentation(BinaryOperators, "~", "compl"))))
          .bind("unary_op"),
      this);
}

void OperatorsRepresentationCheck::registerOverloadedOperatorMatcher(
    MatchFinder *Finder) {
  if (!isAnyOperatorEnabled(OverloadedOperators, OperatorsRepresentation) &&
      !isAnyOperatorEnabled(OverloadedOperators, UnaryRepresentation))
    return;

  Finder->addMatcher(
      cxxOperatorCallExpr(
          unless(isExpansionInSystemHeader()),
          anyOf(
              hasInvalidOverloadedOperatorRepresentation(
                  OO_AmpAmp,
                  getRepresentation(OverloadedOperators, "&&", "and")),
              hasInvalidOverloadedOperatorRepresentation(
                  OO_PipePipe,
                  getRepresentation(OverloadedOperators, "||", "or")),
              hasInvalidOverloadedOperatorRepresentation(
                  OO_Exclaim,
                  getRepresentation(OverloadedOperators, "!", "not")),
              hasInvalidOverloadedOperatorRepresentation(
                  OO_ExclaimEqual,
                  getRepresentation(OverloadedOperators, "!=", "not_eq")),
              hasInvalidOverloadedOperatorRepresentation(
                  OO_Caret, getRepresentation(OverloadedOperators, "^", "xor")),
              hasInvalidOverloadedOperatorRepresentation(
                  OO_Amp,
                  getRepresentation(OverloadedOperators, "&", "bitand")),
              hasInvalidOverloadedOperatorRepresentation(
                  OO_Pipe,
                  getRepresentation(OverloadedOperators, "|", "bitor")),
              hasInvalidOverloadedOperatorRepresentation(
                  OO_AmpEqual,
                  getRepresentation(OverloadedOperators, "&=", "and_eq")),
              hasInvalidOverloadedOperatorRepresentation(
                  OO_PipeEqual,
                  getRepresentation(OverloadedOperators, "|=", "or_eq")),
              hasInvalidOverloadedOperatorRepresentation(
                  OO_CaretEqual,
                  getRepresentation(OverloadedOperators, "^=", "xor_eq")),
              hasInvalidOverloadedOperatorRepresentation(
                  OO_Tilde,
                  getRepresentation(OverloadedOperators, "~", "compl"))))
          .bind("overloaded_op"),
      this);
}

void OperatorsRepresentationCheck::registerMatchers(MatchFinder *Finder) {
  registerBinaryOperatorMatcher(Finder);
  registerUnaryOperatorMatcher(Finder);
  registerOverloadedOperatorMatcher(Finder);
}

void OperatorsRepresentationCheck::check(
    const MatchFinder::MatchResult &Result) {

  SourceLocation Loc;

  if (const auto *Op = Result.Nodes.getNodeAs<BinaryOperator>("binary_op"))
    Loc = Op->getOperatorLoc();
  else if (const auto *Op = Result.Nodes.getNodeAs<UnaryOperator>("unary_op"))
    Loc = Op->getOperatorLoc();
  else if (const auto *Op =
               Result.Nodes.getNodeAs<CXXOperatorCallExpr>("overloaded_op"))
    Loc = Op->getOperatorLoc();

  if (Loc.isInvalid())
    return;

  Loc = Result.SourceManager->getSpellingLoc(Loc);
  if (Loc.isInvalid() || Loc.isMacroID())
    return;

  const CharSourceRange TokenRange = CharSourceRange::getTokenRange(Loc);
  if (TokenRange.isInvalid())
    return;

  StringRef Spelling = Lexer::getSourceText(TokenRange, *Result.SourceManager,
                                            Result.Context->getLangOpts());
  StringRef TranslatedSpelling = translate(Spelling);

  if (TranslatedSpelling.empty())
    return;

  std::string FixSpelling = TranslatedSpelling.str();

  StringRef SourceRepresentation = "an alternative";
  StringRef TargetRepresentation = "a traditional";
  if (needEscaping(TranslatedSpelling)) {
    SourceRepresentation = "a traditional";
    TargetRepresentation = "an alternative";

    StringRef SpellingEx = Lexer::getSourceText(
        CharSourceRange::getCharRange(
            TokenRange.getBegin().getLocWithOffset(-1),
            TokenRange.getBegin().getLocWithOffset(Spelling.size() + 1U)),
        *Result.SourceManager, Result.Context->getLangOpts());
    if (SpellingEx.empty() || !isSeparator(SpellingEx.front()))
      FixSpelling.insert(FixSpelling.begin(), ' ');
    if (SpellingEx.empty() || !isSeparator(SpellingEx.back()))
      FixSpelling.push_back(' ');
  }

  diag(
      Loc,
      "'%0' is %1 token spelling, consider using %2 token '%3' for consistency")
      << Spelling << SourceRepresentation << TargetRepresentation
      << TranslatedSpelling
      << FixItHint::CreateReplacement(TokenRange, FixSpelling);
}

} // namespace clang::tidy::readability