Debian Codegraph @

llvm-project/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp

raw
1 //===--- ImplicitBoolConversionCheck.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 "ImplicitBoolConversionCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 #include "clang/Lex/Lexer.h"
13 #include "clang/Tooling/FixIt.h"
14 #include <queue>
15
16 using namespace clang::ast_matchers;
17
18 namespace clang::tidy::readability {
19
20 namespace {
21
22 AST_MATCHER(Stmt, isMacroExpansion) {
23 SourceManager &SM = Finder->getASTContext().getSourceManager();
24 SourceLocation Loc = Node.getBeginLoc();
25 return SM.isMacroBodyExpansion(Loc) || SM.isMacroArgExpansion(Loc);
26 }
27
28 bool isNULLMacroExpansion(const Stmt *Statement, ASTContext &Context) {
29 SourceManager &SM = Context.getSourceManager();
30 const LangOptions &LO = Context.getLangOpts();
31 SourceLocation Loc = Statement->getBeginLoc();
32 return SM.isMacroBodyExpansion(Loc) &&
33 Lexer::getImmediateMacroName(Loc, SM, LO) == "NULL";
34 }
35
36 AST_MATCHER(Stmt, isNULLMacroExpansion) {
37 return isNULLMacroExpansion(&Node, Finder->getASTContext());
38 }
39
40 StringRef getZeroLiteralToCompareWithForType(CastKind CastExprKind,
41 QualType Type,
42 ASTContext &Context) {
43 switch (CastExprKind) {
44 case CK_IntegralToBoolean:
45 return Type->isUnsignedIntegerType() ? "0u" : "0";
46
47 case CK_FloatingToBoolean:
48 return Context.hasSameType(Type, Context.FloatTy) ? "0.0f" : "0.0";
49
50 case CK_PointerToBoolean:
51 case CK_MemberPointerToBoolean: // Fall-through on purpose.
52 return Context.getLangOpts().CPlusPlus11 ? "nullptr" : "0";
53
54 default:
55 llvm_unreachable("Unexpected cast kind");
56 }
57 }
58
59 bool isUnaryLogicalNotOperator(const Stmt *Statement) {
60 const auto *UnaryOperatorExpr = dyn_cast<UnaryOperator>(Statement);
61 return UnaryOperatorExpr && UnaryOperatorExpr->getOpcode() == UO_LNot;
62 }
63
64 bool areParensNeededForOverloadedOperator(OverloadedOperatorKind OperatorKind) {
65 switch (OperatorKind) {
66 case OO_New:
67 case OO_Delete: // Fall-through on purpose.
68 case OO_Array_New:
69 case OO_Array_Delete:
70 case OO_ArrowStar:
71 case OO_Arrow:
72 case OO_Call:
73 case OO_Subscript:
74 return false;
75
76 default:
77 return true;
78 }
79 }
80
81 bool areParensNeededForStatement(const Stmt *Statement) {
82 if (const auto *OperatorCall = dyn_cast<CXXOperatorCallExpr>(Statement)) {
83 return areParensNeededForOverloadedOperator(OperatorCall->getOperator());
84 }
85
86 return isa<BinaryOperator>(Statement) || isa<UnaryOperator>(Statement);
87 }
88
89 void fixGenericExprCastToBool(DiagnosticBuilder &Diag,
90 const ImplicitCastExpr *Cast, const Stmt *Parent,
91 ASTContext &Context) {
92 // In case of expressions like (! integer), we should remove the redundant not
93 // operator and use inverted comparison (integer == 0).
94 bool InvertComparison =
95 Parent != nullptr && isUnaryLogicalNotOperator(Parent);
96 if (InvertComparison) {
97 SourceLocation ParentStartLoc = Parent->getBeginLoc();
98 SourceLocation ParentEndLoc =
99 cast<UnaryOperator>(Parent)->getSubExpr()->getBeginLoc();
100 Diag << FixItHint::CreateRemoval(
101 CharSourceRange::getCharRange(ParentStartLoc, ParentEndLoc));
102
103 Parent = Context.getParents(*Parent)[0].get<Stmt>();
104 }
105
106 const Expr *SubExpr = Cast->getSubExpr();
107
108 bool NeedInnerParens = areParensNeededForStatement(SubExpr);
109 bool NeedOuterParens =
110 Parent != nullptr && areParensNeededForStatement(Parent);
111
112 std::string StartLocInsertion;
113
114 if (NeedOuterParens) {
115 StartLocInsertion += "(";
116 }
117 if (NeedInnerParens) {
118 StartLocInsertion += "(";
119 }
120
121 if (!StartLocInsertion.empty()) {
122 Diag << FixItHint::CreateInsertion(Cast->getBeginLoc(), StartLocInsertion);
123 }
124
125 std::string EndLocInsertion;
126
127 if (NeedInnerParens) {
128 EndLocInsertion += ")";
129 }
130
131 if (InvertComparison) {
132 EndLocInsertion += " == ";
133 } else {
134 EndLocInsertion += " != ";
135 }
136
137 EndLocInsertion += getZeroLiteralToCompareWithForType(
138 Cast->getCastKind(), SubExpr->getType(), Context);
139
140 if (NeedOuterParens) {
141 EndLocInsertion += ")";
142 }
143
144 SourceLocation EndLoc = Lexer::getLocForEndOfToken(
145 Cast->getEndLoc(), 0, Context.getSourceManager(), Context.getLangOpts());
146 Diag << FixItHint::CreateInsertion(EndLoc, EndLocInsertion);
147 }
148
149 StringRef getEquivalentBoolLiteralForExpr(const Expr *Expression,
150 ASTContext &Context) {
151 if (isNULLMacroExpansion(Expression, Context)) {
152 return "false";
153 }
154
155 if (const auto *IntLit = dyn_cast<IntegerLiteral>(Expression)) {
156 return (IntLit->getValue() == 0) ? "false" : "true";
157 }
158
159 if (const auto *FloatLit = dyn_cast<FloatingLiteral>(Expression)) {
160 llvm::APFloat FloatLitAbsValue = FloatLit->getValue();
161 FloatLitAbsValue.clearSign();
162 return (FloatLitAbsValue.bitcastToAPInt() == 0) ? "false" : "true";
163 }
164
165 if (const auto *CharLit = dyn_cast<CharacterLiteral>(Expression)) {
166 return (CharLit->getValue() == 0) ? "false" : "true";
167 }
168
169 if (isa<StringLiteral>(Expression->IgnoreCasts())) {
170 return "true";
171 }
172
173 return StringRef();
174 }
175
176 void fixGenericExprCastFromBool(DiagnosticBuilder &Diag,
177 const ImplicitCastExpr *Cast,
178 ASTContext &Context, StringRef OtherType) {
179 const Expr *SubExpr = Cast->getSubExpr();
180 bool NeedParens = !isa<ParenExpr>(SubExpr);
181
182 Diag << FixItHint::CreateInsertion(
183 Cast->getBeginLoc(),
184 (Twine("static_cast<") + OtherType + ">" + (NeedParens ? "(" : ""))
185 .str());
186
187 if (NeedParens) {
188 SourceLocation EndLoc = Lexer::getLocForEndOfToken(
189 Cast->getEndLoc(), 0, Context.getSourceManager(),
190 Context.getLangOpts());
191
192 Diag << FixItHint::CreateInsertion(EndLoc, ")");
193 }
194 }
195
196 StringRef getEquivalentForBoolLiteral(const CXXBoolLiteralExpr *BoolLiteral,
197 QualType DestType, ASTContext &Context) {
198 // Prior to C++11, false literal could be implicitly converted to pointer.
199 if (!Context.getLangOpts().CPlusPlus11 &&
200 (DestType->isPointerType() || DestType->isMemberPointerType()) &&
201 BoolLiteral->getValue() == false) {
202 return "0";
203 }
204
205 if (DestType->isFloatingType()) {
206 if (Context.hasSameType(DestType, Context.FloatTy)) {
207 return BoolLiteral->getValue() ? "1.0f" : "0.0f";
208 }
209 return BoolLiteral->getValue() ? "1.0" : "0.0";
210 }
211
212 if (DestType->isUnsignedIntegerType()) {
213 return BoolLiteral->getValue() ? "1u" : "0u";
214 }
215 return BoolLiteral->getValue() ? "1" : "0";
216 }
217
218 bool isCastAllowedInCondition(const ImplicitCastExpr *Cast,
219 ASTContext &Context) {
220 std::queue<const Stmt *> Q;
221 Q.push(Cast);
222
223 TraversalKindScope RAII(Context, TK_AsIs);
224
225 while (!Q.empty()) {
226 for (const auto &N : Context.getParents(*Q.front())) {
227 const Stmt *S = N.get<Stmt>();
228 if (!S)
229 return false;
230 if (isa<IfStmt>(S) || isa<ConditionalOperator>(S) || isa<ForStmt>(S) ||
231 isa<WhileStmt>(S) || isa<BinaryConditionalOperator>(S))
232 return true;
233 if (isa<ParenExpr>(S) || isa<ImplicitCastExpr>(S) ||
234 isUnaryLogicalNotOperator(S) ||
235 (isa<BinaryOperator>(S) && cast<BinaryOperator>(S)->isLogicalOp())) {
236 Q.push(S);
237 } else {
238 return false;
239 }
240 }
241 Q.pop();
242 }
243 return false;
244 }
245
246 } // anonymous namespace
247
248 ImplicitBoolConversionCheck::ImplicitBoolConversionCheck(
249 StringRef Name, ClangTidyContext *Context)
250 : ClangTidyCheck(Name, Context),
251 AllowIntegerConditions(Options.get("AllowIntegerConditions", false)),
252 AllowPointerConditions(Options.get("AllowPointerConditions", false)) {}
253
254 void ImplicitBoolConversionCheck::storeOptions(
255 ClangTidyOptions::OptionMap &Opts) {
256 Options.store(Opts, "AllowIntegerConditions", AllowIntegerConditions);
257 Options.store(Opts, "AllowPointerConditions", AllowPointerConditions);
258 }
259
260 void ImplicitBoolConversionCheck::registerMatchers(MatchFinder *Finder) {
261 auto ExceptionCases =
262 expr(anyOf(allOf(isMacroExpansion(), unless(isNULLMacroExpansion())),
263 has(ignoringImplicit(
264 memberExpr(hasDeclaration(fieldDecl(hasBitWidth(1)))))),
265 hasParent(explicitCastExpr())));
266 auto ImplicitCastFromBool = implicitCastExpr(
267 anyOf(hasCastKind(CK_IntegralCast), hasCastKind(CK_IntegralToFloating),
268 // Prior to C++11 cast from bool literal to pointer was allowed.
269 allOf(anyOf(hasCastKind(CK_NullToPointer),
270 hasCastKind(CK_NullToMemberPointer)),
271 hasSourceExpression(cxxBoolLiteral()))),
272 hasSourceExpression(expr(hasType(booleanType()))),
273 unless(ExceptionCases));
274 auto BoolXor =
275 binaryOperator(hasOperatorName("^"), hasLHS(ImplicitCastFromBool),
276 hasRHS(ImplicitCastFromBool));
277 Finder->addMatcher(
278 traverse(TK_AsIs,
279 implicitCastExpr(
280 anyOf(hasCastKind(CK_IntegralToBoolean),
281 hasCastKind(CK_FloatingToBoolean),
282 hasCastKind(CK_PointerToBoolean),
283 hasCastKind(CK_MemberPointerToBoolean)),
284 // Exclude case of using if or while statements with variable
285 // declaration, e.g.:
286 // if (int var = functionCall()) {}
287 unless(hasParent(
288 stmt(anyOf(ifStmt(), whileStmt()), has(declStmt())))),
289 // Exclude cases common to implicit cast to and from bool.
290 unless(ExceptionCases), unless(has(BoolXor)),
291 // Retrieve also parent statement, to check if we need
292 // additional parens in replacement.
293 anyOf(hasParent(stmt().bind("parentStmt")), anything()),
294 unless(isInTemplateInstantiation()),
295 unless(hasAncestor(functionTemplateDecl())))
296 .bind("implicitCastToBool")),
297 this);
298
299 auto BoolComparison = binaryOperator(hasAnyOperatorName("==", "!="),
300 hasLHS(ImplicitCastFromBool),
301 hasRHS(ImplicitCastFromBool));
302 auto BoolOpAssignment = binaryOperator(hasAnyOperatorName("|=", "&="),
303 hasLHS(expr(hasType(booleanType()))));
304 auto BitfieldAssignment = binaryOperator(
305 hasLHS(memberExpr(hasDeclaration(fieldDecl(hasBitWidth(1))))));
306 auto BitfieldConstruct = cxxConstructorDecl(hasDescendant(cxxCtorInitializer(
307 withInitializer(equalsBoundNode("implicitCastFromBool")),
308 forField(hasBitWidth(1)))));
309 Finder->addMatcher(
310 traverse(
311 TK_AsIs,
312 implicitCastExpr(
313 ImplicitCastFromBool,
314 // Exclude comparisons of bools, as they are always cast to
315 // integers in such context:
316 // bool_expr_a == bool_expr_b
317 // bool_expr_a != bool_expr_b
318 unless(hasParent(
319 binaryOperator(anyOf(BoolComparison, BoolXor,
320 BoolOpAssignment, BitfieldAssignment)))),
321 implicitCastExpr().bind("implicitCastFromBool"),
322 unless(hasParent(BitfieldConstruct)),
323 // Check also for nested casts, for example: bool -> int -> float.
324 anyOf(hasParent(implicitCastExpr().bind("furtherImplicitCast")),
325 anything()),
326 unless(isInTemplateInstantiation()),
327 unless(hasAncestor(functionTemplateDecl())))),
328 this);
329 }
330
331 void ImplicitBoolConversionCheck::check(
332 const MatchFinder::MatchResult &Result) {
333
334 if (const auto *CastToBool =
335 Result.Nodes.getNodeAs<ImplicitCastExpr>("implicitCastToBool")) {
336 const auto *Parent = Result.Nodes.getNodeAs<Stmt>("parentStmt");
337 return handleCastToBool(CastToBool, Parent, *Result.Context);
338 }
339
340 if (const auto *CastFromBool =
341 Result.Nodes.getNodeAs<ImplicitCastExpr>("implicitCastFromBool")) {
342 const auto *NextImplicitCast =
343 Result.Nodes.getNodeAs<ImplicitCastExpr>("furtherImplicitCast");
344 return handleCastFromBool(CastFromBool, NextImplicitCast, *Result.Context);
345 }
346 }
347
348 void ImplicitBoolConversionCheck::handleCastToBool(const ImplicitCastExpr *Cast,
349 const Stmt *Parent,
350 ASTContext &Context) {
351 if (AllowPointerConditions &&
352 (Cast->getCastKind() == CK_PointerToBoolean ||
353 Cast->getCastKind() == CK_MemberPointerToBoolean) &&
354 isCastAllowedInCondition(Cast, Context)) {
355 return;
356 }
357
358 if (AllowIntegerConditions && Cast->getCastKind() == CK_IntegralToBoolean &&
359 isCastAllowedInCondition(Cast, Context)) {
360 return;
361 }
362
363 auto Diag = diag(Cast->getBeginLoc(), "implicit conversion %0 -> bool")
364 << Cast->getSubExpr()->getType();
365
366 StringRef EquivalentLiteral =
367 getEquivalentBoolLiteralForExpr(Cast->getSubExpr(), Context);
368 if (!EquivalentLiteral.empty()) {
369 Diag << tooling::fixit::createReplacement(*Cast, EquivalentLiteral);
370 } else {
371 fixGenericExprCastToBool(Diag, Cast, Parent, Context);
372 }
373 }
374
375 void ImplicitBoolConversionCheck::handleCastFromBool(
376 const ImplicitCastExpr *Cast, const ImplicitCastExpr *NextImplicitCast,
377 ASTContext &Context) {
378 QualType DestType =
379 NextImplicitCast ? NextImplicitCast->getType() : Cast->getType();
380 auto Diag = diag(Cast->getBeginLoc(), "implicit conversion bool -> %0")
381 << DestType;
382
383 if (const auto *BoolLiteral =
384 dyn_cast<CXXBoolLiteralExpr>(Cast->getSubExpr())) {
385 Diag << tooling::fixit::createReplacement(
386 *Cast, getEquivalentForBoolLiteral(BoolLiteral, DestType, Context));
387 } else {
388 fixGenericExprCastFromBool(Diag, Cast, Context, DestType.getAsString());
389 }
390 }
391
392 } // namespace clang::tidy::readability