[clang] [clang] Improve diagnostics with incompatible VLA types (PR #101261)

Andrew Sukach via cfe-commits cfe-commits at lists.llvm.org
Sun Sep 8 17:26:23 PDT 2024


https://github.com/sookach updated https://github.com/llvm/llvm-project/pull/101261

>From 7c6109ea5133941baf32ec57e48c770ad015b883 Mon Sep 17 00:00:00 2001
From: Andrew Sukach <andrewsukach at gmail.com>
Date: Tue, 30 Jul 2024 19:31:41 -0400
Subject: [PATCH] [clang] Improve diagnostics with incompatible VLA types

---
 clang/lib/AST/ASTDiagnostic.cpp               | 22 +++++++++++++++++++
 .../test/Sema/incompatible-vla-assignment.cpp |  9 ++++++++
 2 files changed, 31 insertions(+)
 create mode 100644 clang/test/Sema/incompatible-vla-assignment.cpp

diff --git a/clang/lib/AST/ASTDiagnostic.cpp b/clang/lib/AST/ASTDiagnostic.cpp
index 0680ff5e3a3851..0f5e8ae600f235 100644
--- a/clang/lib/AST/ASTDiagnostic.cpp
+++ b/clang/lib/AST/ASTDiagnostic.cpp
@@ -422,8 +422,30 @@ void clang::FormatASTNodeDiagnosticArgument(
       // Attempting to do a template diff on non-templates.  Set the variables
       // and continue with regular type printing of the appropriate type.
       Val = TDT.PrintFromType ? TDT.FromType : TDT.ToType;
+
       Modifier = StringRef();
       Argument = StringRef();
+
+      if ((FromType->isVariableArrayType() || FromType->isPointerType()) &&
+          (ToType->isVariableArrayType() || ToType->isPointerType()) &&
+          ConvertTypeToDiagnosticString(Context, FromType, PrevArgs,
+                                        QualTypeVals) ==
+              ConvertTypeToDiagnosticString(Context, ToType, PrevArgs,
+                                            QualTypeVals)) {
+        assert(Modifier.empty() && Argument.empty() &&
+               "Invalid modifier for QualType argument");
+
+        QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void *>(Val)));
+        OS << ConvertTypeToDiagnosticString(Context, Ty, PrevArgs,
+                                            QualTypeVals);
+        NeedQuotes = false;
+
+        if (!TDT.PrintFromType)
+          OS << "; VLA types differ despite using the same array size "
+                "expression";
+
+        break;
+      }
       // Fall through
       [[fallthrough]];
     }
diff --git a/clang/test/Sema/incompatible-vla-assignment.cpp b/clang/test/Sema/incompatible-vla-assignment.cpp
new file mode 100644
index 00000000000000..9df97a1223150a
--- /dev/null
+++ b/clang/test/Sema/incompatible-vla-assignment.cpp
@@ -0,0 +1,9 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+void func(int n) {
+    int grp[n][n];
+    int (*ptr)[n];
+
+    for (int i = 0; i < n; i++)
+        ptr = &grp[i]; // expected-error {{incompatible pointer types assigning to 'int (*)[n]' from 'int (*)[n]'; VLA types differ despite using the same array size expression}}
+}



More information about the cfe-commits mailing list