Skip to content

Commit abece58

Browse files
authored
[clang-tidy] Fix a false positive when converting a bool to a signed integer type (llvm#191696)
Fix llvm#191337
1 parent 6073fde commit abece58

File tree

3 files changed

+23
-1
lines changed

3 files changed

+23
-1
lines changed

clang-tools-extra/clang-tidy/bugprone/NarrowingConversionsCheck.cpp

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -593,9 +593,17 @@ void NarrowingConversionsCheck::handleImplicitCast(
593593
case CK_IntegralToFloating:
594594
handleIntegralToFloating(Context, SourceLoc, Lhs, Rhs);
595595
return;
596-
case CK_IntegralCast:
596+
case CK_IntegralCast: {
597+
const BuiltinType *ToType = getBuiltinType(Lhs);
598+
const BuiltinType *FromType = getBuiltinType(Rhs);
599+
if (ToType && FromType && FromType->getKind() == BuiltinType::Bool &&
600+
ToType->isSignedInteger()) {
601+
handleBooleanToSignedIntegral(Context, SourceLoc, Lhs, Rhs);
602+
return;
603+
}
597604
handleIntegralCast(Context, SourceLoc, Lhs, Rhs);
598605
return;
606+
}
599607
case CK_FloatingToBoolean:
600608
handleFloatingToBoolean(Context, SourceLoc, Lhs, Rhs);
601609
return;

clang-tools-extra/docs/ReleaseNotes.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,10 @@ Changes in existing checks
262262
<clang-tidy/checks/bugprone/macro-parentheses>` check by printing the macro
263263
definition in the warning message if the macro is defined on command line.
264264

265+
- Improved :doc:`bugprone-narrowing-conversions
266+
<clang-tidy/checks/bugprone/narrowing-conversions>` check by fixing a false
267+
positive when converting a ``bool`` to a signed integer type.
268+
265269
- Improved :doc:`bugprone-pointer-arithmetic-on-polymorphic-object
266270
<clang-tidy/checks/bugprone/pointer-arithmetic-on-polymorphic-object>` check
267271
by fixing a false positive when ``operator[]`` is used in a dependent context.

clang-tools-extra/test/clang-tidy/checkers/bugprone/narrowing-conversions.cpp

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -355,4 +355,14 @@ void typedef_context() {
355355
// CHECK-MESSAGES: :[[@LINE-1]]:7: warning: narrowing conversion from 'myint64_t' (aka 'long long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
356356
}
357357

358+
void testBoolToSignedType() {
359+
bool b = true;
360+
auto c = char{b};
361+
auto sc = (signed char){b};
362+
auto s = short{b};
363+
auto i = int{b};
364+
auto c1 = static_cast<char>(b);
365+
auto c2 = (char)b;
366+
}
367+
358368
} // namespace floats

0 commit comments

Comments
 (0)