[clang] [Clang] Diagnose classes defined in the type of a variable template (PR #248352)

via cfe-commits cfe-commits at lists.llvm.org
Wed Dec 2 22:57:35 PST 2026


https://github.com/YzK0741 created https://github.com/llvm/llvm-project/pull/248352

An unnamed class definition in a variable template declaration was treated as
the templated entity, so the parser passed the template parameters to the class
and Sema reported "cannot declare a class template with no name".

ParseClassSpecifier now looks past the class body to check whether a declarator
follows, and only hands the template parameters to the class when it does not.
Sema then rejects the type definition with the new "cannot be defined in the
type of a variable template" diagnostic.

As discussed with @zygoloid, cases where a parenthesized declarator is ambiguous
with a function declarator (`template <int> struct {} test(1);`,
`template <int> struct {} f();`) are left on the old path and will be handled
separately.

Tests are in clang/test/CXX/temp/p3.cpp.

Fixes #82499


>From 5df325a909ff78108068464def82b93fa1ab9025 Mon Sep 17 00:00:00 2001
From: YzK0741 <2353036486 at qq.com>
Date: Thu, 3 Dec 2026 08:19:48 +0800
Subject: [PATCH] [Clang] Diagnose classes defined in the type of a variable
 template

An unnamed class definition in a variable template declaration was treated
as the templated entity, so the parser passed the template parameters to the
class and Sema reported "cannot declare a class template with no name". Look
past the class body in ParseClassSpecifier to tell a variable declarator apart
from a missing semicolon, and diagnose the type definition instead.

Fixes #82499
---
 clang/docs/ReleaseNotes.md                    |  3 ++
 .../clang/Basic/DiagnosticSemaKinds.td        |  2 ++
 clang/lib/Parse/ParseDeclCXX.cpp              | 34 +++++++++++++++++--
 clang/lib/Sema/SemaDecl.cpp                   |  8 +++++
 clang/test/CXX/temp/p3.cpp                    | 17 ++++++++++
 5 files changed, 61 insertions(+), 3 deletions(-)

diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index 2c1e0b45e9daec..dca2986bb8bf0f 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -944,6 +944,9 @@ documentation](CIR/index.md) for more information regarding ClangIR's status and
   canonical unqualified type as `T` (ignoring top-level qualifiers, references,
   and array element qualifiers).
 
+- Clang now diagnoses a class defined in the type of a variable template, as in
+  `template <int> constexpr struct {} test;`. (#GH82499)
+
 ### Improvements to Clang's time-trace
 
 ### Improvements to Coverage Mapping
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index ff82dc0cb76c64..dd0a1bf83edef6 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -2032,6 +2032,8 @@ def err_type_defined_in_param_type : Error<
   "%0 cannot be defined in a parameter type">;
 def err_type_defined_in_alias_template : Error<
   "%0 cannot be defined in a type alias template">;
+def err_type_defined_in_variable_template : Error<
+  "%0 cannot be defined in the type of a variable template">;
 def err_type_defined_in_condition : Error<
   "%0 cannot be defined in a condition">;
 def err_type_defined_in_enum : Error<
diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp
index 2d799e8e9585e0..1fd1ff73bffda5 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -2005,6 +2005,32 @@ void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
   } else
     TUK = TagUseKind::Reference;
 
+  bool HasFollowingVariableDeclarator = false;
+  if (TUK == TagUseKind::Definition &&
+      TemplateInfo.Kind == ParsedTemplateKind::Template && !TemplateId &&
+      SS.isEmpty() && Tok.is(tok::l_brace)) {
+    // Check whether the template-head belongs to a variable declarator before
+    // passing the template parameters to ActOnTag.
+    llvm::SaveAndRestore SavedPrevTokLocation(PrevTokLocation);
+    RevertingTentativeParsingAction PA(*this, /*Unannotated=*/true);
+    ConsumeBrace();
+    if (SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
+      while (Tok.isOneOf(tok::kw_const, tok::kw_volatile, tok::kw_restrict))
+        ConsumeToken();
+      // Keep the usual class-template recovery for function declarators and
+      // tokens that may instead start a new declaration, such as 'Type name'.
+      bool ParsedPrefix = !Tok.isOneOf(tok::star, tok::amp, tok::ampamp) ||
+                          TryParsePtrOperatorSeq() != TPResult::Error;
+      if (ParsedPrefix && Tok.is(tok::identifier)) {
+        const Token &Next = NextToken();
+        HasFollowingVariableDeclarator =
+            Next.isOneOf(tok::semi, tok::comma, tok::equal, tok::l_brace) ||
+            (Next.is(tok::l_square) &&
+             GetLookAheadToken(2).isNot(tok::l_square));
+      }
+    }
+  }
+
   // Forbid misplaced attributes. In cases of a reference, we pass attributes
   // to caller to handle.
   if (TUK != TagUseKind::Reference) {
@@ -2207,7 +2233,8 @@ void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
     // reference.  For example, we don't need the template parameters here:
     //   template <class T> class A *makeA(T t);
     MultiTemplateParamsArg TParams;
-    if (TUK != TagUseKind::Reference && TemplateParams)
+    if (TUK != TagUseKind::Reference && TemplateParams &&
+        !HasFollowingVariableDeclarator)
       TParams =
           MultiTemplateParamsArg(&(*TemplateParams)[0], TemplateParams->size());
 
@@ -2302,9 +2329,10 @@ void Parser::ParseClassSpecifier(tok::TokenKind TagTokKind,
   //
   // After a type-specifier, we don't expect a semicolon. This only happens in
   // C, since definitions are not permitted in this context in C++.
-  if (TUK == TagUseKind::Definition &&
+  if (TUK == TagUseKind::Definition && !HasFollowingVariableDeclarator &&
       (getLangOpts().CPlusPlus || !isTypeSpecifier(DSC)) &&
-      (TemplateInfo.Kind != ParsedTemplateKind::NonTemplate || !isValidAfterTypeSpecifier(false))) {
+      (TemplateInfo.Kind != ParsedTemplateKind::NonTemplate ||
+       !isValidAfterTypeSpecifier(false))) {
     if (Tok.isNot(tok::semi)) {
       const PrintingPolicy &PPol = Actions.getASTContext().getPrintingPolicy();
       ExpectAndConsume(tok::semi, diag::err_expected_after,
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 9417c101084edf..6b75de0de4d942 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -8041,6 +8041,14 @@ NamedDecl *Sema::ActOnVariableDeclarator(
              "should have a 'template<>' for this decl");
     }
 
+    if ((IsVariableTemplate || IsVariableTemplateSpecialization) &&
+        D.getDeclSpec().hasTagDefinition()) {
+      TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
+      Diag(Tag->getLocation(), diag::err_type_defined_in_variable_template)
+          << Context.getCanonicalTagType(Tag);
+      Invalid = true;
+    }
+
     bool IsExplicitSpecialization =
         IsVariableTemplateSpecialization && !IsPartialSpecialization;
 
diff --git a/clang/test/CXX/temp/p3.cpp b/clang/test/CXX/temp/p3.cpp
index 9e561d0b9a83b2..866aabcac5cacc 100644
--- a/clang/test/CXX/temp/p3.cpp
+++ b/clang/test/CXX/temp/p3.cpp
@@ -16,6 +16,23 @@ template<typename T> struct C { } // expected-error {{expected ';' after struct}
 
 A<int> c;
 
+namespace GH82499 {
+template <int>
+constexpr struct {} test; // expected-error {{cannot be defined in the type of a variable template}}
+
+template <int>
+struct Named { struct Nested {}; } named; // expected-error {{cannot be defined in the type of a variable template}}
+
+template <int>
+struct {} const qualified{}; // expected-error {{cannot be defined in the type of a variable template}}
+
+using Next = int;
+template <int> struct MissingSemi {} // expected-error {{expected ';' after struct}}
+Next next;
+
+template <int> struct {}; // expected-error {{cannot declare a class template with no name}}
+}
+
 struct D {
   template<typename T> static const int x = 0, f(); // expected-error {{can only declare a single entity}}
 



More information about the cfe-commits mailing list