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