2015-10-13 05:53:19 +08:00
|
|
|
//===--- ProBoundsPointerArithmeticCheck.cpp - clang-tidy------------------===//
|
|
|
|
//
|
2019-01-19 16:50:56 +08:00
|
|
|
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
|
|
|
|
// See https://llvm.org/LICENSE.txt for license information.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
2015-10-13 05:53:19 +08:00
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
#include "ProBoundsPointerArithmeticCheck.h"
|
|
|
|
#include "clang/AST/ASTContext.h"
|
|
|
|
#include "clang/ASTMatchers/ASTMatchFinder.h"
|
|
|
|
|
|
|
|
using namespace clang::ast_matchers;
|
|
|
|
|
|
|
|
namespace clang {
|
|
|
|
namespace tidy {
|
2016-05-03 02:00:29 +08:00
|
|
|
namespace cppcoreguidelines {
|
2015-10-13 05:53:19 +08:00
|
|
|
|
|
|
|
void ProBoundsPointerArithmeticCheck::registerMatchers(MatchFinder *Finder) {
|
|
|
|
if (!getLangOpts().CPlusPlus)
|
|
|
|
return;
|
|
|
|
|
2018-07-24 01:46:17 +08:00
|
|
|
const auto AllPointerTypes = anyOf(
|
|
|
|
hasType(pointerType()), hasType(autoType(hasDeducedType(pointerType()))),
|
|
|
|
hasType(decltypeType(hasUnderlyingType(pointerType()))));
|
|
|
|
|
2015-10-13 05:53:19 +08:00
|
|
|
// Flag all operators +, -, +=, -=, ++, -- that result in a pointer
|
|
|
|
Finder->addMatcher(
|
2015-11-27 06:32:11 +08:00
|
|
|
binaryOperator(
|
|
|
|
anyOf(hasOperatorName("+"), hasOperatorName("-"),
|
|
|
|
hasOperatorName("+="), hasOperatorName("-=")),
|
2018-07-24 01:46:17 +08:00
|
|
|
AllPointerTypes,
|
2015-11-27 06:32:11 +08:00
|
|
|
unless(hasLHS(ignoringImpCasts(declRefExpr(to(isImplicit()))))))
|
2015-10-13 05:53:19 +08:00
|
|
|
.bind("expr"),
|
|
|
|
this);
|
|
|
|
|
|
|
|
Finder->addMatcher(
|
|
|
|
unaryOperator(anyOf(hasOperatorName("++"), hasOperatorName("--")),
|
|
|
|
hasType(pointerType()))
|
|
|
|
.bind("expr"),
|
|
|
|
this);
|
|
|
|
|
|
|
|
// Array subscript on a pointer (not an array) is also pointer arithmetic
|
|
|
|
Finder->addMatcher(
|
2015-11-27 06:32:11 +08:00
|
|
|
arraySubscriptExpr(
|
|
|
|
hasBase(ignoringImpCasts(
|
2018-07-24 01:46:17 +08:00
|
|
|
anyOf(AllPointerTypes,
|
2015-11-27 06:32:11 +08:00
|
|
|
hasType(decayedType(hasDecayedType(pointerType())))))))
|
2015-10-13 05:53:19 +08:00
|
|
|
.bind("expr"),
|
|
|
|
this);
|
|
|
|
}
|
|
|
|
|
2016-11-08 15:50:19 +08:00
|
|
|
void ProBoundsPointerArithmeticCheck::check(
|
|
|
|
const MatchFinder::MatchResult &Result) {
|
2015-10-13 05:53:19 +08:00
|
|
|
const auto *MatchedExpr = Result.Nodes.getNodeAs<Expr>("expr");
|
|
|
|
|
|
|
|
diag(MatchedExpr->getExprLoc(), "do not use pointer arithmetic");
|
|
|
|
}
|
|
|
|
|
2016-05-03 02:00:29 +08:00
|
|
|
} // namespace cppcoreguidelines
|
2015-10-13 05:53:19 +08:00
|
|
|
} // namespace tidy
|
|
|
|
} // namespace clang
|