MisplacedArrayIndexCheck.cpp 2.0 KB

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