1 //===--- ProBoundsPointerArithmeticCheck.cpp - clang-tidy------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "ProBoundsPointerArithmeticCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 using namespace clang::ast_matchers
;
15 namespace clang::tidy::cppcoreguidelines
{
17 void ProBoundsPointerArithmeticCheck::registerMatchers(MatchFinder
*Finder
) {
18 if (!getLangOpts().CPlusPlus
)
21 const auto AllPointerTypes
=
22 anyOf(hasType(pointerType()),
24 hasDeducedType(hasUnqualifiedDesugaredType(pointerType())))),
25 hasType(decltypeType(hasUnderlyingType(pointerType()))));
27 // Flag all operators +, -, +=, -=, ++, -- that result in a pointer
30 hasAnyOperatorName("+", "-", "+=", "-="), AllPointerTypes
,
31 unless(hasLHS(ignoringImpCasts(declRefExpr(to(isImplicit()))))))
36 unaryOperator(hasAnyOperatorName("++", "--"), hasType(pointerType()))
40 // Array subscript on a pointer (not an array) is also pointer arithmetic
43 hasBase(ignoringImpCasts(
44 anyOf(AllPointerTypes
,
45 hasType(decayedType(hasDecayedType(pointerType())))))))
50 void ProBoundsPointerArithmeticCheck::check(
51 const MatchFinder::MatchResult
&Result
) {
52 const auto *MatchedExpr
= Result
.Nodes
.getNodeAs
<Expr
>("expr");
54 diag(MatchedExpr
->getExprLoc(), "do not use pointer arithmetic");
57 } // namespace clang::tidy::cppcoreguidelines