1 //===--- AssignmentInIfConditionCheck.cpp - clang-tidy --------------------===//
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 
9 #include "AssignmentInIfConditionCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 
13 using namespace clang::ast_matchers;
14 
15 namespace clang {
16 namespace tidy {
17 namespace bugprone {
18 
19 void AssignmentInIfConditionCheck::registerMatchers(MatchFinder *Finder) {
20   Finder->addMatcher(ifStmt(hasCondition(forEachDescendant(
21                          binaryOperator(isAssignmentOperator())
22                              .bind("assignment_in_if_statement")))),
23                      this);
24   Finder->addMatcher(ifStmt(hasCondition(forEachDescendant(
25                          cxxOperatorCallExpr(isAssignmentOperator())
26                              .bind("assignment_in_if_statement")))),
27                      this);
28 }
29 
30 void AssignmentInIfConditionCheck::check(
31     const MatchFinder::MatchResult &Result) {
32   const auto *MatchedDecl =
33       Result.Nodes.getNodeAs<clang::Stmt>("assignment_in_if_statement");
34   if (!MatchedDecl) {
35     return;
36   }
37   diag(MatchedDecl->getBeginLoc(),
38        "an assignment within an 'if' condition is bug-prone");
39   diag(MatchedDecl->getBeginLoc(),
40        "if it should be an assignment, move it out of the 'if' condition",
41        DiagnosticIDs::Note);
42   diag(MatchedDecl->getBeginLoc(),
43        "if it is meant to be an equality check, change '=' to '=='",
44        DiagnosticIDs::Note);
45 }
46 
47 } // namespace bugprone
48 } // namespace tidy
49 } // namespace clang
50