blob: d664b6401ae195ddb1c366310adc7d27cf72ac66 [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 {
Etienne Bergeron456177b2016-05-02 18:00:29 +000018namespace cppcoreguidelines {
Matthias Gehredc484122015-10-12 21:53:19 +000019
20void ProBoundsPointerArithmeticCheck::registerMatchers(MatchFinder *Finder) {
21 if (!getLangOpts().CPlusPlus)
22 return;
23
24 // Flag all operators +, -, +=, -=, ++, -- that result in a pointer
25 Finder->addMatcher(
Matthias Gehre4241ced2015-11-26 22:32:11 +000026 binaryOperator(
27 anyOf(hasOperatorName("+"), hasOperatorName("-"),
28 hasOperatorName("+="), hasOperatorName("-=")),
29 hasType(pointerType()),
30 unless(hasLHS(ignoringImpCasts(declRefExpr(to(isImplicit()))))))
Matthias Gehredc484122015-10-12 21:53:19 +000031 .bind("expr"),
32 this);
33
34 Finder->addMatcher(
35 unaryOperator(anyOf(hasOperatorName("++"), hasOperatorName("--")),
36 hasType(pointerType()))
37 .bind("expr"),
38 this);
39
40 // Array subscript on a pointer (not an array) is also pointer arithmetic
41 Finder->addMatcher(
Matthias Gehre4241ced2015-11-26 22:32:11 +000042 arraySubscriptExpr(
43 hasBase(ignoringImpCasts(
44 anyOf(hasType(pointerType()),
45 hasType(decayedType(hasDecayedType(pointerType())))))))
Matthias Gehredc484122015-10-12 21:53:19 +000046 .bind("expr"),
47 this);
48}
49
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000050void ProBoundsPointerArithmeticCheck::check(
51 const MatchFinder::MatchResult &Result) {
Matthias Gehredc484122015-10-12 21:53:19 +000052 const auto *MatchedExpr = Result.Nodes.getNodeAs<Expr>("expr");
53
54 diag(MatchedExpr->getExprLoc(), "do not use pointer arithmetic");
55}
56
Etienne Bergeron456177b2016-05-02 18:00:29 +000057} // namespace cppcoreguidelines
Matthias Gehredc484122015-10-12 21:53:19 +000058} // namespace tidy
59} // namespace clang