blob: 3d1971bedc5f3f48d4c61718f1e66b728773f918 [file] [log] [blame]
Daniel Marjamaki03ea4682016-09-12 12:04:13 +00001//===--- 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
10#include "MisplacedArrayIndexCheck.h"
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
16using namespace clang::ast_matchers;
17
18namespace clang {
19namespace tidy {
20namespace readability {
21
22void MisplacedArrayIndexCheck::registerMatchers(MatchFinder *Finder) {
23 Finder->addMatcher(arraySubscriptExpr(hasLHS(hasType(isInteger())),
24 hasRHS(hasType(isAnyPointer())))
25 .bind("expr"),
26 this);
27}
28
29void MisplacedArrayIndexCheck::check(const MatchFinder::MatchResult &Result) {
30 const auto *ArraySubscriptE =
31 Result.Nodes.getNodeAs<ArraySubscriptExpr>("expr");
32
Stephen Kelly43465bf2018-08-09 22:42:26 +000033 auto Diag = diag(ArraySubscriptE->getBeginLoc(), "confusing array subscript "
Daniel Marjamaki03ea4682016-09-12 12:04:13 +000034 "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