clang-tools 22.0.0git
ProBoundsArrayToPointerDecayCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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/AST/ParentMapContext.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/ASTMatchers/ASTMatchers.h"
14
15using namespace clang::ast_matchers;
16
18
19namespace {
20AST_MATCHER_P(CXXForRangeStmt, hasRangeBeginEndStmt,
21 ast_matchers::internal::Matcher<DeclStmt>, InnerMatcher) {
22 return llvm::any_of(llvm::ArrayRef{Node.getBeginStmt(), Node.getEndStmt()},
23 [&](const DeclStmt *Stmt) {
24 return Stmt &&
25 InnerMatcher.matches(*Stmt, Finder, Builder);
26 });
27}
28
29AST_MATCHER(Stmt, isInsideOfRangeBeginEndStmt) {
30 return stmt(hasAncestor(cxxForRangeStmt(
31 hasRangeBeginEndStmt(hasDescendant(equalsNode(&Node))))))
32 .matches(Node, Finder, Builder);
33}
34
35AST_MATCHER_P(Expr, hasParentIgnoringImpCasts,
36 ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
37 const Expr *E = &Node;
38 do {
39 const DynTypedNodeList Parents = Finder->getASTContext().getParents(*E);
40 if (Parents.size() != 1)
41 return false;
42 E = Parents[0].get<Expr>();
43 if (!E)
44 return false;
45 } while (isa<ImplicitCastExpr>(E));
46
47 return InnerMatcher.matches(*E, Finder, Builder);
48}
49} // namespace
50
52 // The only allowed array to pointer decay
53 // 1) just before array subscription
54 // 2) inside a range-for over an array
55 // 3) if it converts a string literal to a pointer
56 Finder->addMatcher(
57 traverse(
58 TK_AsIs,
59 implicitCastExpr(
60 unless(hasParent(arraySubscriptExpr())),
61 unless(hasSourceExpression(predefinedExpr())),
62 unless(hasParentIgnoringImpCasts(explicitCastExpr())),
63 unless(isInsideOfRangeBeginEndStmt()),
64 unless(hasSourceExpression(ignoringParens(stringLiteral()))),
65 unless(hasSourceExpression(ignoringParens(
66 conditionalOperator(hasTrueExpression(stringLiteral()),
67 hasFalseExpression(stringLiteral()))))))
68 .bind("cast")),
69 this);
70}
71
73 const MatchFinder::MatchResult &Result) {
74 const auto *MatchedCast = Result.Nodes.getNodeAs<ImplicitCastExpr>("cast");
75 if (MatchedCast->getCastKind() != CK_ArrayToPointerDecay)
76 return;
77
78 diag(MatchedCast->getExprLoc(), "do not implicitly decay an array into a "
79 "pointer; consider using gsl::array_view or "
80 "an explicit cast instead");
81}
82
83} // namespace clang::tidy::cppcoreguidelines
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
AST_MATCHER_P(Stmt, isStatementIdenticalToBoundNode, std::string, ID)
AST_MATCHER(BinaryOperator, isRelationalOperator)