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(
26           anyOf(hasOperatorName("+"), hasOperatorName("-"),
27                 hasOperatorName("+="), hasOperatorName("-=")),
28           hasType(pointerType()),
29           unless(hasLHS(ignoringImpCasts(declRefExpr(to(isImplicit()))))))
30           .bind("expr"),
31       this);
32 
33   Finder->addMatcher(
34       unaryOperator(anyOf(hasOperatorName("++"), hasOperatorName("--")),
35                     hasType(pointerType()))
36           .bind("expr"),
37       this);
38 
39   // Array subscript on a pointer (not an array) is also pointer arithmetic
40   Finder->addMatcher(
41       arraySubscriptExpr(
42           hasBase(ignoringImpCasts(
43               anyOf(hasType(pointerType()),
44                     hasType(decayedType(hasDecayedType(pointerType())))))))
45           .bind("expr"),
46       this);
47 }
48 
49 void
50 ProBoundsPointerArithmeticCheck::check(const MatchFinder::MatchResult &Result) {
51   const auto *MatchedExpr = Result.Nodes.getNodeAs<Expr>("expr");
52 
53   diag(MatchedExpr->getExprLoc(), "do not use pointer arithmetic");
54 }
55 
56 } // namespace tidy
57 } // namespace clang
58