blob: 7b39012b7693aad4b4a65e3e3f4a21cb93632b47 [file] [log] [blame]
Daniel Marjamaki03ea4682016-09-12 12:04:13 +00001//===--- MisplacedArrayIndexCheck.cpp - clang-tidy-------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Daniel Marjamaki03ea4682016-09-12 12:04:13 +00006//
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
15using namespace clang::ast_matchers;
16
17namespace clang {
18namespace tidy {
19namespace readability {
20
21void MisplacedArrayIndexCheck::registerMatchers(MatchFinder *Finder) {
22 Finder->addMatcher(arraySubscriptExpr(hasLHS(hasType(isInteger())),
23 hasRHS(hasType(isAnyPointer())))
24 .bind("expr"),
25 this);
26}
27
28void MisplacedArrayIndexCheck::check(const MatchFinder::MatchResult &Result) {
29 const auto *ArraySubscriptE =
30 Result.Nodes.getNodeAs<ArraySubscriptExpr>("expr");
31
Stephen Kelly43465bf2018-08-09 22:42:26 +000032 auto Diag = diag(ArraySubscriptE->getBeginLoc(), "confusing array subscript "
Daniel Marjamaki03ea4682016-09-12 12:04:13 +000033 "expression, usually the "
34 "index is inside the []");
35
36 // Only try to fixit when LHS and RHS can be swapped directly without changing
37 // the logic.
38 const Expr *RHSE = ArraySubscriptE->getRHS()->IgnoreParenImpCasts();
39 if (!isa<StringLiteral>(RHSE) && !isa<DeclRefExpr>(RHSE) &&
40 !isa<MemberExpr>(RHSE))
41 return;
42
43 const StringRef LText = tooling::fixit::getText(
44 ArraySubscriptE->getLHS()->getSourceRange(), *Result.Context);
45 const StringRef RText = tooling::fixit::getText(
46 ArraySubscriptE->getRHS()->getSourceRange(), *Result.Context);
47
48 Diag << FixItHint::CreateReplacement(
49 ArraySubscriptE->getLHS()->getSourceRange(), RText);
50 Diag << FixItHint::CreateReplacement(
51 ArraySubscriptE->getRHS()->getSourceRange(), LText);
52}
53
54} // namespace readability
55} // namespace tidy
56} // namespace clang