[Clang][P1061] Fix template arguments in local classes (#121225)

In the development of P1061 (Structured Bindings Introduce a Patch), I
found this bug in the template instantiation of a
local class. The issue is caused by the instantiation of the original
template and not the partially instantiated template. In
the example (sans the fix) the instantiation uses the first template
parameter from the previous instantiation and not the current one so the
error hits an assertion when it is expecting an NTTP. If they were both
types then it might gladly accept the type from the wrong template which
is kind of scary.

In the test, the reference to `i` is substituted with a placeholder AST
object that represents the resolved value when instantiating `g`.
However, since the old template is used, the instantiation sees an AST
object that only contains the template argument index in the context of
instantiating the lambda which has a type template parameter (ie auto).

I question if we should use `getTemplateInstantiationPattern` at all
here. Other errors involving local classes in nested templates could
also be caused by the misuse of this function (because it gets the
uninstantiated template).
This commit is contained in:
Jason Rice 2025-07-12 20:17:41 -07:00 committed by GitHub
parent e2ddd147a5
commit 6f923134dd
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 20 additions and 1 deletions

View File

@ -955,6 +955,7 @@ Bug Fixes to C++ Support
consistently treat the initializer as manifestly constant-evaluated.
(#GH135281)
- Fix a crash in the presence of invalid base classes. (#GH147186)
- Fix a crash with NTTP when instantiating local class.
Bug Fixes to AST Handling
^^^^^^^^^^^^^^^^^^^^^^^^^

View File

@ -4412,8 +4412,12 @@ Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
// No need to instantiate in-class initializers during explicit
// instantiation.
if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
// Handle local classes which could have substituted template params.
CXXRecordDecl *ClassPattern =
Instantiation->getTemplateInstantiationPattern();
Instantiation->isLocalClass()
? Instantiation->getInstantiatedFromMemberClass()
: Instantiation->getTemplateInstantiationPattern();
DeclContext::lookup_result Lookup =
ClassPattern->lookup(Field->getDeclName());
FieldDecl *Pattern = Lookup.find_first<FieldDecl>();

View File

@ -0,0 +1,14 @@
// RUN: %clang_cc1 -fsyntax-only %s -verify
// expected-no-diagnostics
template <int i>
int g() {
return [] (auto) -> int {
struct L {
int m = i;
};
return 0;
} (42);
}
int v = g<1>();