blob: 15ea27a4462d0ebfbfce2fce25bc760af3567f38 [file] [log] [blame]
Matthias Gehredc484122015-10-12 21:53:19 +00001//===--- 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
14using namespace clang::ast_matchers;
15
16namespace clang {
17namespace tidy {
18
19void 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
45void
46ProBoundsPointerArithmeticCheck::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