1//===--- ProBoundsPointerArithmeticCheck.cpp - clang-tidy------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8
9#include "ProBoundsPointerArithmeticCheck.h"
10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12
13using namespace clang::ast_matchers;
14
15namespace clang::tidy::cppcoreguidelines {
16
17void ProBoundsPointerArithmeticCheck::registerMatchers(MatchFinder *Finder) {
18 if (!getLangOpts().CPlusPlus)
19 return;
20
21 const auto AllPointerTypes =
22 anyOf(hasType(InnerMatcher: pointerType()),
23 hasType(InnerMatcher: autoType(
24 hasDeducedType(hasUnqualifiedDesugaredType(InnerMatcher: pointerType())))),
25 hasType(InnerMatcher: decltypeType(hasUnderlyingType(pointerType()))));
26
27 // Flag all operators +, -, +=, -=, ++, -- that result in a pointer
28 Finder->addMatcher(
29 NodeMatch: binaryOperator(
30 hasAnyOperatorName("+", "-", "+=", "-="), AllPointerTypes,
31 unless(hasLHS(InnerMatcher: ignoringImpCasts(InnerMatcher: declRefExpr(to(InnerMatcher: isImplicit()))))))
32 .bind(ID: "expr"),
33 Action: this);
34
35 Finder->addMatcher(
36 NodeMatch: unaryOperator(hasAnyOperatorName("++", "--"), hasType(InnerMatcher: pointerType()))
37 .bind(ID: "expr"),
38 Action: this);
39
40 // Array subscript on a pointer (not an array) is also pointer arithmetic
41 Finder->addMatcher(
42 NodeMatch: arraySubscriptExpr(
43 hasBase(InnerMatcher: ignoringImpCasts(
44 InnerMatcher: anyOf(AllPointerTypes,
45 hasType(InnerMatcher: decayedType(hasDecayedType(InnerType: pointerType())))))))
46 .bind(ID: "expr"),
47 Action: this);
48}
49
50void ProBoundsPointerArithmeticCheck::check(
51 const MatchFinder::MatchResult &Result) {
52 const auto *MatchedExpr = Result.Nodes.getNodeAs<Expr>(ID: "expr");
53
54 diag(Loc: MatchedExpr->getExprLoc(), Description: "do not use pointer arithmetic");
55}
56
57} // namespace clang::tidy::cppcoreguidelines
58

source code of clang-tools-extra/clang-tidy/cppcoreguidelines/ProBoundsPointerArithmeticCheck.cpp