clang-tools 20.0.0git
ProBoundsPointerArithmeticCheck.cpp
Go to the documentation of this file.
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
10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12
13using namespace clang::ast_matchers;
14
16
18 if (!getLangOpts().CPlusPlus)
19 return;
20
21 const auto AllPointerTypes =
22 anyOf(hasType(pointerType()),
23 hasType(autoType(
24 hasDeducedType(hasUnqualifiedDesugaredType(pointerType())))),
25 hasType(decltypeType(hasUnderlyingType(pointerType()))));
26
27 // Flag all operators +, -, +=, -=, ++, -- that result in a pointer
28 Finder->addMatcher(
29 binaryOperator(
30 hasAnyOperatorName("+", "-", "+=", "-="), AllPointerTypes,
31 unless(hasLHS(ignoringImpCasts(declRefExpr(to(isImplicit()))))))
32 .bind("expr"),
33 this);
34
35 Finder->addMatcher(
36 unaryOperator(hasAnyOperatorName("++", "--"), hasType(pointerType()))
37 .bind("expr"),
38 this);
39
40 // Array subscript on a pointer (not an array) is also pointer arithmetic
41 Finder->addMatcher(
42 arraySubscriptExpr(
43 hasBase(ignoringImpCasts(
44 anyOf(AllPointerTypes,
45 hasType(decayedType(hasDecayedType(pointerType())))))))
46 .bind("expr"),
47 this);
48}
49
51 const MatchFinder::MatchResult &Result) {
52 const auto *MatchedExpr = Result.Nodes.getNodeAs<Expr>("expr");
53
54 diag(MatchedExpr->getExprLoc(), "do not use pointer arithmetic");
55}
56
57} // namespace clang::tidy::cppcoreguidelines
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
const LangOptions & getLangOpts() const
Returns the language options from the context.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.