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