blob: 6565874a34061d59612c17c741385b58fbc3febd [file] [log] [blame]
Benjamin Kramer1c8b3172014-07-11 08:08:47 +00001//===--- BoolPointerImplicitConversion.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 "BoolPointerImplicitConversion.h"
11
12using namespace clang::ast_matchers;
13
14namespace clang {
15namespace ast_matchers {
16
17AST_MATCHER(CastExpr, isPointerToBoolean) {
18 return Node.getCastKind() == CK_PointerToBoolean;
19}
20AST_MATCHER(QualType, isBoolean) { return Node->isBooleanType(); }
21
22} // namespace ast_matchers
23
24namespace tidy {
25
26void BoolPointerImplicitConversion::registerMatchers(MatchFinder *Finder) {
27 // Look for ifs that have an implicit bool* to bool conversion in the
28 // condition. Filter negations.
29 Finder->addMatcher(
30 ifStmt(hasCondition(findAll(implicitCastExpr(
31 allOf(unless(hasParent(unaryOperator(hasOperatorName("!")))),
32 hasSourceExpression(expr(
33 hasType(pointerType(pointee(isBoolean()))),
34 ignoringParenImpCasts(declRefExpr().bind("expr")))),
35 isPointerToBoolean()))))).bind("if"),
36 this);
37}
38
39void
40BoolPointerImplicitConversion::check(const MatchFinder::MatchResult &Result) {
41 auto *If = Result.Nodes.getStmtAs<IfStmt>("if");
42 auto *Var = Result.Nodes.getStmtAs<DeclRefExpr>("expr");
43
44 // Only allow variable accesses for now, no function calls or member exprs.
45 // Check that we don't dereference the variable anywhere within the if. This
46 // avoids false positives for checks of the pointer for nullptr before it is
47 // dereferenced. If there is a dereferencing operator on this variable don't
48 // emit a diagnostic. Also ignore array subscripts.
49 const Decl *D = Var->getDecl();
50 auto DeclRef = ignoringParenImpCasts(declRefExpr(to(equalsNode(D))));
51 if (!match(findAll(
52 unaryOperator(hasOperatorName("*"), hasUnaryOperand(DeclRef))),
53 *If, *Result.Context).empty() ||
54 !match(findAll(arraySubscriptExpr(hasBase(DeclRef))), *If,
55 *Result.Context).empty() ||
56 // FIXME: We should still warn if the paremater is implicitly converted to
57 // bool.
58 !match(findAll(callExpr(hasAnyArgument(DeclRef))), *If, *Result.Context)
59 .empty() ||
60 !match(findAll(deleteExpr(has(expr(DeclRef)))), *If, *Result.Context)
61 .empty())
62 return;
63
64 diag(Var->getLocStart(), "dubious check of 'bool *' against 'nullptr', did "
65 "you mean to dereference it?")
66 << FixItHint::CreateInsertion(Var->getLocStart(), "*");
67}
68
69} // namespace tidy
70} // namespace clang