[clang-tidy] Fix init-list handling in readability-implicit-bool-conversion

Adds support for explicit casts using initListExpr,
for example: int{boolValue} constructions.

Fixes: #47000

Reviewed By: ccotter

Differential Revision: https://reviews.llvm.org/D147551
This commit is contained in:
Piotr Zegar
2023-04-05 09:44:36 +00:00
parent adeb1fa7a3
commit dfa8f5b13e
3 changed files with 16 additions and 2 deletions

View File

@@ -262,7 +262,10 @@ void ImplicitBoolConversionCheck::registerMatchers(MatchFinder *Finder) {
expr(anyOf(allOf(isMacroExpansion(), unless(isNULLMacroExpansion())),
has(ignoringImplicit(
memberExpr(hasDeclaration(fieldDecl(hasBitWidth(1)))))),
hasParent(explicitCastExpr())));
hasParent(explicitCastExpr()),
expr(hasType(qualType().bind("type")),
hasParent(initListExpr(hasParent(explicitCastExpr(
hasType(qualType(equalsBoundNode("type"))))))))));
auto ImplicitCastFromBool = implicitCastExpr(
anyOf(hasCastKind(CK_IntegralCast), hasCastKind(CK_IntegralToFloating),
// Prior to C++11 cast from bool literal to pointer was allowed.
@@ -290,7 +293,7 @@ void ImplicitBoolConversionCheck::registerMatchers(MatchFinder *Finder) {
unless(ExceptionCases), unless(has(BoolXor)),
// Retrieve also parent statement, to check if we need
// additional parens in replacement.
anyOf(hasParent(stmt().bind("parentStmt")), anything()),
optionally(hasParent(stmt().bind("parentStmt"))),
unless(isInTemplateInstantiation()),
unless(hasAncestor(functionTemplateDecl())))
.bind("implicitCastToBool")),

View File

@@ -240,6 +240,10 @@ Changes in existing checks
behavior of using `i` as the prefix for enum tags, set the `EnumConstantPrefix`
option to `i` instead of using `EnumConstantHungarianPrefix`.
- Fixed a false positive in :doc:`readability-implicit-bool-conversion
<clang-tidy/checks/readability/implicit-bool-conversion>` check warning would
be unnecessarily emitted for explicit cast using direct list initialization.
- Added support to optionally ignore user-defined literals in
:doc:`readability-magic-numbers<clang-tidy/checks/readability/magic-numbers>`.

View File

@@ -471,3 +471,10 @@ bool f(S& s) {
}
} // namespace ignore_1bit_bitfields
namespace PR47000 {
int to_int(bool x) { return int{x}; }
using IntType = int;
int to_int2(bool x) { return IntType{x}; }
}