[clang] Reject if constexpr in C (#112685)
authorMariya Podchishchaeva <mariya.podchishchaeva@intel.com>
Thu, 17 Oct 2024 11:42:35 +0000 (13:42 +0200)
committerTobias Hieta <tobias@hieta.se>
Tue, 29 Oct 2024 08:59:53 +0000 (09:59 +0100)
Fixes https://github.com/llvm/llvm-project/issues/112587

clang/lib/Parse/ParseStmt.cpp
clang/test/Sema/constexpr.c

index 22d38adc28ebe9f2e2a547cd55534f7f8c2e2391..3ac1f0fa27f83f221e70f50ec2a30f55edf995bb 100644 (file)
@@ -1508,10 +1508,13 @@ StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
   SourceLocation ConstevalLoc;
 
   if (Tok.is(tok::kw_constexpr)) {
-    Diag(Tok, getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_constexpr_if
-                                        : diag::ext_constexpr_if);
-    IsConstexpr = true;
-    ConsumeToken();
+    // C23 supports constexpr keyword, but only for object definitions.
+    if (getLangOpts().CPlusPlus) {
+      Diag(Tok, getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_constexpr_if
+                                          : diag::ext_constexpr_if);
+      IsConstexpr = true;
+      ConsumeToken();
+    }
   } else {
     if (Tok.is(tok::exclaim)) {
       NotLocation = ConsumeToken();
index 8286cd2107d2f2b842684c5daf7dff7d8b915142..a874fd64808404e92f3ae3791d86c466f6509553 100644 (file)
@@ -357,3 +357,10 @@ void infsNaNs() {
   constexpr double db5 = LD_SNAN; // expected-error {{constexpr initializer evaluates to nan which is not exactly representable in type 'const double'}}
   constexpr double db6 = INF;
 }
+
+void constexprif() {
+  if constexpr (300) {} //expected-error {{expected '(' after 'if'}}
+}
+void constevalif() {
+  if consteval (300) {} //expected-error {{expected '(' after 'if'}}
+}