[clang] [Clang][Sema]: Diagnose lambda to bool implicit casts (PR #83152)

Vinayak Dev via cfe-commits cfe-commits at lists.llvm.org
Tue Feb 27 08:47:19 PST 2024


https://github.com/vinayakdsci created https://github.com/llvm/llvm-project/pull/83152

Fixes #82512 

Adds diagnostics for lambda expressions being cast to boolean values, which results in the expression always evaluating to true.
Earlier, Clang allowed compilation of such erroneous programs, but now emits a warning through `-Wpointer-bool-conversion`.

>From 859ce0b2acbeb65543e891e5e5a9b519c0c504b5 Mon Sep 17 00:00:00 2001
From: Vinayak Dev <vinayakdev.sci at gmail.com>
Date: Tue, 27 Feb 2024 18:05:29 +0530
Subject: [PATCH] [Clang][Sema]: Diagnose lambda to bool implicit casts

---
 clang/lib/Sema/SemaChecking.cpp | 21 +++++++++++++++++++++
 1 file changed, 21 insertions(+)

diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 0de76ee119cf81..3b03036587baeb 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -16538,6 +16538,27 @@ void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
     }
   }
 
+  // Complain if we are converting a lambda expression to a boolean value
+  if (auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
+    if (MCallExpr->getObjectType()->isRecordType()) {
+      if (auto *MRecordDecl = MCallExpr->getRecordDecl()) {
+        if (MRecordDecl->isLambda()) {
+          std::string Str;
+          llvm::raw_string_ostream S(Str);
+          const unsigned DiagID = diag::warn_impcast_pointer_to_bool;
+          // For lambdas, the pointer type is function, which corresponds to 1.
+          const unsigned FunctionPointerType = 1;
+          // Pretty print the diagnostic for the warning
+          E->printPretty(S, nullptr, getPrintingPolicy());
+          Diag(E->getExprLoc(), DiagID)
+              << FunctionPointerType << S.str() << E->getSourceRange() << Range
+              << IsEqual;
+          return;
+        }
+      }
+    }
+  }
+
   // Expect to find a single Decl.  Skip anything more complicated.
   ValueDecl *D = nullptr;
   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {



More information about the cfe-commits mailing list