1 //===--- ProBoundsPointerArithmeticCheck.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 "ProBoundsPointerArithmeticCheck.h" 11 #include "clang/AST/ASTContext.h" 12 #include "clang/ASTMatchers/ASTMatchFinder.h" 13 14 using namespace clang::ast_matchers; 15 16 namespace clang { 17 namespace tidy { 18 19 void ProBoundsPointerArithmeticCheck::registerMatchers(MatchFinder *Finder) { 20 if (!getLangOpts().CPlusPlus) 21 return; 22 23 // Flag all operators +, -, +=, -=, ++, -- that result in a pointer 24 Finder->addMatcher( 25 binaryOperator(anyOf(hasOperatorName("+"), hasOperatorName("-"), 26 hasOperatorName("+="), hasOperatorName("-=")), 27 hasType(pointerType())) 28 .bind("expr"), 29 this); 30 31 Finder->addMatcher( 32 unaryOperator(anyOf(hasOperatorName("++"), hasOperatorName("--")), 33 hasType(pointerType())) 34 .bind("expr"), 35 this); 36 37 // Array subscript on a pointer (not an array) is also pointer arithmetic 38 Finder->addMatcher( 39 arraySubscriptExpr(hasBase(ignoringImpCasts(anyOf(hasType(pointerType()), 40 hasType(decayedType(hasDecayedType(pointerType()))))))) 41 .bind("expr"), 42 this); 43 } 44 45 void 46 ProBoundsPointerArithmeticCheck::check(const MatchFinder::MatchResult &Result) { 47 const auto *MatchedExpr = Result.Nodes.getNodeAs<Expr>("expr"); 48 49 diag(MatchedExpr->getExprLoc(), "do not use pointer arithmetic"); 50 } 51 52 } // namespace tidy 53 } // namespace clang 54