blob: 9dcd7c4a3707cc57552c487a122eede046b103e7 [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(
Matthias Gehre4241ced2015-11-26 22:32:11 +000025 binaryOperator(
26 anyOf(hasOperatorName("+"), hasOperatorName("-"),
27 hasOperatorName("+="), hasOperatorName("-=")),
28 hasType(pointerType()),
29 unless(hasLHS(ignoringImpCasts(declRefExpr(to(isImplicit()))))))
Matthias Gehredc484122015-10-12 21:53:19 +000030 .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(
Matthias Gehre4241ced2015-11-26 22:32:11 +000041 arraySubscriptExpr(
42 hasBase(ignoringImpCasts(
43 anyOf(hasType(pointerType()),
44 hasType(decayedType(hasDecayedType(pointerType())))))))
Matthias Gehredc484122015-10-12 21:53:19 +000045 .bind("expr"),
46 this);
47}
48
49void
50ProBoundsPointerArithmeticCheck::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