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 9 #include "MisplacedArrayIndexCheck.h" 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(TK_AsIs, 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 58