clang-tools  11.0.0
MisplacedArrayIndexCheck.cpp
Go to the documentation of this file.
1 //===--- MisplacedArrayIndexCheck.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 
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 #include "clang/Lex/Lexer.h"
13 #include "clang/Tooling/FixIt.h"
14 
15 using namespace clang::ast_matchers;
16 
17 namespace clang {
18 namespace tidy {
19 namespace readability {
20 
21 void MisplacedArrayIndexCheck::registerMatchers(MatchFinder *Finder) {
22  Finder->addMatcher(
23  traverse(ast_type_traits::TK_AsIs,
24  arraySubscriptExpr(hasLHS(hasType(isInteger())),
25  hasRHS(hasType(isAnyPointer())))
26  .bind("expr")),
27  this);
28 }
29 
30 void MisplacedArrayIndexCheck::check(const MatchFinder::MatchResult &Result) {
31  const auto *ArraySubscriptE =
32  Result.Nodes.getNodeAs<ArraySubscriptExpr>("expr");
33 
34  auto Diag = diag(ArraySubscriptE->getBeginLoc(), "confusing array subscript "
35  "expression, usually the "
36  "index is inside the []");
37 
38  // Only try to fixit when LHS and RHS can be swapped directly without changing
39  // the logic.
40  const Expr *RHSE = ArraySubscriptE->getRHS()->IgnoreParenImpCasts();
41  if (!isa<StringLiteral>(RHSE) && !isa<DeclRefExpr>(RHSE) &&
42  !isa<MemberExpr>(RHSE))
43  return;
44 
45  const StringRef LText = tooling::fixit::getText(
46  ArraySubscriptE->getLHS()->getSourceRange(), *Result.Context);
47  const StringRef RText = tooling::fixit::getText(
48  ArraySubscriptE->getRHS()->getSourceRange(), *Result.Context);
49 
50  Diag << FixItHint::CreateReplacement(
51  ArraySubscriptE->getLHS()->getSourceRange(), RText);
52  Diag << FixItHint::CreateReplacement(
53  ArraySubscriptE->getRHS()->getSourceRange(), LText);
54 }
55 
56 } // namespace readability
57 } // namespace tidy
58 } // namespace clang
clang::ast_matchers
Definition: AbseilMatcher.h:14
MisplacedArrayIndexCheck.h
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27