blob: 9e56ee66a064fb199747c0dc40b5f24705c15953 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
//===--- AssignmentInIfConditionCheck.cpp - clang-tidy --------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "AssignmentInIfConditionCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
using namespace clang::ast_matchers;
namespace clang::tidy::bugprone {
void AssignmentInIfConditionCheck::registerMatchers(MatchFinder *Finder) {
Finder->addMatcher(translationUnitDecl(), this);
}
void AssignmentInIfConditionCheck::check(
const ast_matchers::MatchFinder::MatchResult &Result) {
class Visitor : public RecursiveASTVisitor<Visitor> {
AssignmentInIfConditionCheck &Check;
public:
explicit Visitor(AssignmentInIfConditionCheck &Check) : Check(Check) {}
bool VisitIfStmt(IfStmt *If) {
class ConditionVisitor : public RecursiveASTVisitor<ConditionVisitor> {
AssignmentInIfConditionCheck &Check;
public:
explicit ConditionVisitor(AssignmentInIfConditionCheck &Check)
: Check(Check) {}
// Dont traverse into any lambda expressions.
bool TraverseLambdaExpr(LambdaExpr *, DataRecursionQueue * = nullptr) {
return true;
}
bool VisitBinaryOperator(BinaryOperator *BO) {
if (BO->isAssignmentOp())
Check.report(BO);
return true;
}
bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *OCE) {
if (OCE->isAssignmentOp())
Check.report(OCE);
return true;
}
};
ConditionVisitor(Check).TraverseStmt(If->getCond());
return true;
}
};
Visitor(*this).TraverseAST(*Result.Context);
}
void AssignmentInIfConditionCheck::report(const Expr *AssignmentExpr) {
SourceLocation OpLoc =
isa<BinaryOperator>(AssignmentExpr)
? cast<BinaryOperator>(AssignmentExpr)->getOperatorLoc()
: cast<CXXOperatorCallExpr>(AssignmentExpr)->getOperatorLoc();
diag(OpLoc, "an assignment within an 'if' condition is bug-prone")
<< AssignmentExpr->getSourceRange();
diag(OpLoc,
"if it should be an assignment, move it out of the 'if' condition",
DiagnosticIDs::Note);
diag(OpLoc, "if it is meant to be an equality check, change '=' to '=='",
DiagnosticIDs::Note);
}
} // namespace clang::tidy::bugprone
|