blob: 8a37b1b68fa526e816c6c3bb0ceab8b6d4cc8280 [file] [log] [blame]
Matthias Gehref3331962015-10-26 21:56:02 +00001//===--- ProBoundsArrayToPointerDecayCheck.cpp - clang-tidy----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "ProBoundsArrayToPointerDecayCheck.h"
11#include "clang/AST/ASTContext.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13
14using namespace clang::ast_matchers;
15
16namespace clang {
17namespace tidy {
18
19AST_MATCHER_P(CXXForRangeStmt, hasRangeBeginEndStmt,
20 ast_matchers::internal::Matcher<DeclStmt>, InnerMatcher) {
Benjamin Kramer74e4d552016-03-20 14:24:49 +000021 for (const DeclStmt *Stmt : {Node.getBeginStmt(), Node.getEndStmt()})
22 if (Stmt != nullptr && InnerMatcher.matches(*Stmt, Finder, Builder))
23 return true;
24 return false;
Matthias Gehref3331962015-10-26 21:56:02 +000025}
26
27AST_MATCHER(Stmt, isInsideOfRangeBeginEndStmt) {
28 return stmt(hasAncestor(cxxForRangeStmt(
29 hasRangeBeginEndStmt(hasDescendant(equalsNode(&Node))))))
30 .matches(Node, Finder, Builder);
31}
32
Matthias Gehre4722f192015-11-17 23:35:39 +000033AST_MATCHER_P(Expr, hasParentIgnoringImpCasts,
34 ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
35 const Expr *E = &Node;
36 do {
37 ASTContext::DynTypedNodeList Parents =
38 Finder->getASTContext().getParents(*E);
39 if (Parents.size() != 1)
40 return false;
41 E = Parents[0].get<Expr>();
42 if (!E)
43 return false;
44 } while (isa<ImplicitCastExpr>(E));
45
46 return InnerMatcher.matches(*E, Finder, Builder);
47}
48
Matthias Gehref3331962015-10-26 21:56:02 +000049void ProBoundsArrayToPointerDecayCheck::registerMatchers(MatchFinder *Finder) {
50 if (!getLangOpts().CPlusPlus)
51 return;
52
53 // The only allowed array to pointer decay
54 // 1) just before array subscription
55 // 2) inside a range-for over an array
56 // 3) if it converts a string literal to a pointer
57 Finder->addMatcher(
58 implicitCastExpr(unless(hasParent(arraySubscriptExpr())),
Matthias Gehre4722f192015-11-17 23:35:39 +000059 unless(hasParentIgnoringImpCasts(explicitCastExpr())),
Matthias Gehref3331962015-10-26 21:56:02 +000060 unless(isInsideOfRangeBeginEndStmt()),
61 unless(hasSourceExpression(stringLiteral())))
62 .bind("cast"),
63 this);
64}
65
66void ProBoundsArrayToPointerDecayCheck::check(
67 const MatchFinder::MatchResult &Result) {
68 const auto *MatchedCast = Result.Nodes.getNodeAs<ImplicitCastExpr>("cast");
69 if (MatchedCast->getCastKind() != CK_ArrayToPointerDecay)
70 return;
71
72 diag(MatchedCast->getExprLoc(), "do not implicitly decay an array into a "
73 "pointer; consider using gsl::array_view or "
74 "an explicit cast instead");
75}
76
77} // namespace tidy
78} // namespace clang