[clang] [clang] Added warn-assignment-bool-context (PR #115234)

Erich Keane via cfe-commits cfe-commits at lists.llvm.org
Fri Feb 21 08:56:17 PST 2025


================
@@ -687,6 +687,48 @@ void Sema::diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E) {
       << FixItHint::CreateReplacement(E->getSourceRange(), "nullptr");
 }
 
+void Sema::DiagnoseAssignmentBoolContext(Expr *E, QualType Ty) {
+  // Use copy to not alter original expression.
+  Expr *ECopy = E;
+
+  if (Ty->isBooleanType()) {
+    // `bool(x=0)` and if (x=0){} emit:
+    // - ImplicitCastExpr bool IntegralToBoolean
+    // -- ImplicitCastExpr int LValueToRValue
+    // --- Assignment ...
+    // But should still emit this warning (at least gcc does), even if bool-cast
----------------
erichkeane wrote:

>Basically just asking if ImplicitCastExpr is the only valid expression that can be in between the outer cast and the assignment expression or if there is another implicit expression that would need to be matched here.

None I can think of?  We might end up having a case where we don't properly warn if we miss anything here, which is perhaps acceptable.

>How can I check for that? Do you have a more robust approach?

Having this happen on the implicit cast makes this a little awkward since we can't record 'what is going on here' as we go.  That said, I think punting /not warning in the case of user-defined-operators is probably OK, that will prevent us from diagnosing in the cases of some DSLs or something, which is the behavior we probably want?

https://github.com/llvm/llvm-project/pull/115234


More information about the cfe-commits mailing list