blob: dfbb51bed12db0e54c173d4153b7ab80dcdd1efe [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
Jonas Tothad2524f2018-07-23 17:46:17 +000024 const auto AllPointerTypes = anyOf(
25 hasType(pointerType()), hasType(autoType(hasDeducedType(pointerType()))),
26 hasType(decltypeType(hasUnderlyingType(pointerType()))));
27
Matthias Gehredc484122015-10-12 21:53:19 +000028 // Flag all operators +, -, +=, -=, ++, -- that result in a pointer
29 Finder->addMatcher(
Matthias Gehre4241ced2015-11-26 22:32:11 +000030 binaryOperator(
31 anyOf(hasOperatorName("+"), hasOperatorName("-"),
32 hasOperatorName("+="), hasOperatorName("-=")),
Jonas Tothad2524f2018-07-23 17:46:17 +000033 AllPointerTypes,
Matthias Gehre4241ced2015-11-26 22:32:11 +000034 unless(hasLHS(ignoringImpCasts(declRefExpr(to(isImplicit()))))))
Matthias Gehredc484122015-10-12 21:53:19 +000035 .bind("expr"),
36 this);
37
38 Finder->addMatcher(
39 unaryOperator(anyOf(hasOperatorName("++"), hasOperatorName("--")),
40 hasType(pointerType()))
41 .bind("expr"),
42 this);
43
44 // Array subscript on a pointer (not an array) is also pointer arithmetic
45 Finder->addMatcher(
Matthias Gehre4241ced2015-11-26 22:32:11 +000046 arraySubscriptExpr(
47 hasBase(ignoringImpCasts(
Jonas Tothad2524f2018-07-23 17:46:17 +000048 anyOf(AllPointerTypes,
Matthias Gehre4241ced2015-11-26 22:32:11 +000049 hasType(decayedType(hasDecayedType(pointerType())))))))
Matthias Gehredc484122015-10-12 21:53:19 +000050 .bind("expr"),
51 this);
52}
53
Mandeep Singh Grang7c7ea7d2016-11-08 07:50:19 +000054void ProBoundsPointerArithmeticCheck::check(
55 const MatchFinder::MatchResult &Result) {
Matthias Gehredc484122015-10-12 21:53:19 +000056 const auto *MatchedExpr = Result.Nodes.getNodeAs<Expr>("expr");
57
58 diag(MatchedExpr->getExprLoc(), "do not use pointer arithmetic");
59}
60
Etienne Bergeron456177b2016-05-02 18:00:29 +000061} // namespace cppcoreguidelines
Matthias Gehredc484122015-10-12 21:53:19 +000062} // namespace tidy
63} // namespace clang