From 5e3f9f36a8dde7ed37fab7604b0646dac64ca584 Mon Sep 17 00:00:00 2001 From: Tom Sobczynski Date: Fri, 27 Nov 2026 12:50:09 -0500 Subject: [PATCH] Fix #15278 TemplateSimplifier: class templates nested in a namespace need one pass per level cppcheck instantiates class templates in at most 10 passes. Inside a namespace, each level of nesting cost a pass of its own, so from 11 levels the innermost template was never instantiated and bugs in it went unreported. When the simplifier copies a class template to make an instantiation such as NS::A1, it records each template the copy uses (A0) with the scope to find it in. It took that scope from the class's own scope by dropping the last component with find_last_of(" :: "), which finds the last space or colon character, not the separator. "NS :: A1" became "NS ::", which names no scope, so the lookup failed and was retried in the next pass. rfind(" :: ") gives "NS". But the failed lookup had also hidden a case that dropping the last component gets wrong, a member template with the same name as a namespace template: namespace NS { template struct B { T x; }; template struct A { template struct B { U u; }; B b; }; } B in A means the member A::B, but a lookup in NS finds NS::B. The member can't be found during the expansion of A, because a template nested in a class template is registered only once the class template is instantiated. The retry in the next pass came after A's copy of the member existed, which is why this used to come out right. So the dropped-component scope is replaced by a lookup. A template that the class template declares itself is looked up in the instantiation (NS :: A) in the next pass. Any other name is resolved at once by the inner-to-outer search of getTemplateInstantiations, now shared as findTemplateDeclaration. A name with no declaration keeps the old scope. Co-Authored-By: Claude Opus 5.5 --- lib/templatesimplifier.cpp | 166 ++++++++++++++++++++++++---------- lib/templatesimplifier.h | 11 +++ test/testsimplifytemplate.cpp | 67 ++++++++++++++ 3 files changed, 195 insertions(+), 49 deletions(-) diff --git a/lib/templatesimplifier.cpp b/lib/templatesimplifier.cpp index d28b350ea8b..8e1b73e880f 100644 --- a/lib/templatesimplifier.cpp +++ b/lib/templatesimplifier.cpp @@ -1006,52 +1006,60 @@ void TemplateSimplifier::getTemplateInstantiations() // Add outer template.. if (templateParameters(tok->next()) || tok->strAt(2) == ">") { - while (true) { - std::string fullName = scopeName + (scopeName.empty()?"":" :: ") + - qualification + (qualification.empty()?"":" :: ") + tok->str(); - const auto it = std::find_if(mTemplateDeclarations.cbegin(), mTemplateDeclarations.cend(), FindFullName(std::move(fullName))); - if (it != mTemplateDeclarations.end()) { - // full name matches - addInstantiation(tok, it->scope()); - break; - } - // full name doesn't match so try with using namespaces if available - bool found = false; - for (const auto & nameSpace : tok->scopeInfo()->usingNamespaces) { - std::string fullNameSpace = scopeName + (scopeName.empty()?"":" :: ") + - nameSpace + (qualification.empty()?"":" :: ") + qualification; - std::string newFullName = fullNameSpace + " :: " + tok->str(); - const auto it1 = std::find_if(mTemplateDeclarations.cbegin(), mTemplateDeclarations.cend(), FindFullName(std::move(newFullName))); - if (it1 != mTemplateDeclarations.end()) { - // insert using namespace into token stream - std::string::size_type offset = 0; - std::string::size_type pos = 0; - while ((pos = nameSpace.find(' ', offset)) != std::string::npos) { - qualificationTok->insertTokenBefore(nameSpace.substr(offset, pos - offset)); - offset = pos + 1; - } - qualificationTok->insertTokenBefore(nameSpace.substr(offset)); - qualificationTok->insertTokenBefore("::"); - addInstantiation(tok, it1->scope()); - found = true; - break; + std::string nameSpace; + const TokenAndName *declaration = findTemplateDeclaration(tok, qualification, &nameSpace); + if (!declaration) { + if (!qualification.empty()) + addInstantiation(tok, qualification); + else + addInstantiation(tok, tok->scopeInfo()->name); + } else { + if (!nameSpace.empty()) { + // insert using namespace into token stream + std::string::size_type offset = 0; + std::string::size_type pos = 0; + while ((pos = nameSpace.find(' ', offset)) != std::string::npos) { + qualificationTok->insertTokenBefore(nameSpace.substr(offset, pos - offset)); + offset = pos + 1; } + qualificationTok->insertTokenBefore(nameSpace.substr(offset)); + qualificationTok->insertTokenBefore("::"); } - if (found) - break; + addInstantiation(tok, declaration->scope()); + } + } + } + } +} - if (scopeName.empty()) { - if (!qualification.empty()) - addInstantiation(tok, qualification); - else - addInstantiation(tok, tok->scopeInfo()->name); - break; - } - const std::string::size_type pos = scopeName.rfind(" :: "); - scopeName = (pos == std::string::npos) ? std::string() : scopeName.substr(0,pos); +const TemplateSimplifier::TokenAndName *TemplateSimplifier::findTemplateDeclaration(const Token *tok, const std::string &qualification, std::string *usingNamespace) const +{ + std::string scopeName = tok->scopeInfo()->name; + while (true) { + std::string fullName = scopeName + (scopeName.empty()?"":" :: ") + + qualification + (qualification.empty()?"":" :: ") + tok->str(); + const auto it = std::find_if(mTemplateDeclarations.cbegin(), mTemplateDeclarations.cend(), FindFullName(std::move(fullName))); + if (it != mTemplateDeclarations.cend()) + return &*it; + + // full name doesn't match so try with using namespaces if available + if (usingNamespace) { + for (const auto & nameSpace : tok->scopeInfo()->usingNamespaces) { + std::string fullNameSpace = scopeName + (scopeName.empty()?"":" :: ") + + nameSpace + (qualification.empty()?"":" :: ") + qualification; + std::string newFullName = fullNameSpace + " :: " + tok->str(); + const auto it1 = std::find_if(mTemplateDeclarations.cbegin(), mTemplateDeclarations.cend(), FindFullName(std::move(newFullName))); + if (it1 != mTemplateDeclarations.cend()) { + *usingNamespace = nameSpace; + return &*it1; } } } + + if (scopeName.empty()) + return nullptr; + const std::string::size_type pos = scopeName.rfind(" :: "); + scopeName = (pos == std::string::npos) ? std::string() : scopeName.substr(0,pos); } } @@ -1646,6 +1654,35 @@ struct newInstantiation { std::string scope; }; +/** + * Find the member template that a template name used inside a class template refers to. The + * name is looked up in the scope of the usage first and then in each enclosing scope, out to the + * class template itself. + * @param memberTemplates full names of the templates declared inside the class template + * @param classTemplate full name of the class template + * @param scopeName scope of the usage + * @param qualification qualification written before the name, or empty + * @param name the template name + * @return the scope of the member template, or empty if the name does not refer to one + */ +static std::string findMemberTemplateScope(const std::set &memberTemplates, + const std::string &classTemplate, + std::string scopeName, + const std::string &qualification, + const std::string &name) +{ + if (memberTemplates.empty() || (scopeName != classTemplate && !startsWith(scopeName, classTemplate + " :: "))) + return ""; + while (true) { + std::string scope = scopeName + (qualification.empty() ? "" : " :: ") + qualification; + if (memberTemplates.count(scope + " :: " + name) > 0) + return scope; + if (scopeName.size() == classTemplate.size()) + return ""; + scopeName.resize(scopeName.rfind(" :: ")); + } +} + void TemplateSimplifier::expandTemplate( const TokenAndName &templateDeclaration, const TokenAndName &templateInstantiation, @@ -1665,6 +1702,27 @@ void TemplateSimplifier::expandTemplate( std::vector newInstantiations; + // Full names of the templates declared inside the class template. They hide templates of the + // same name in enclosing scopes, but they are not in mTemplateDeclarations until the class + // template has been instantiated. + std::set memberTemplates; + if (isClass) { + const Token * const end = findTemplateDeclarationEnd(templateDeclaration.token()); + for (const Token *tok = templateDeclarationToken->next(); tok && tok != end; tok = tok->next()) { + // skip template template parameters and the inner lists of "template <..> template <..>" + if (!Token::simpleMatch(tok, "template <") || Token::Match(tok->previous(), "<|,|>")) + continue; + const Token *parmEnd = tok->next()->findClosingBracket(); + while (Token::simpleMatch(parmEnd, "> template <")) + parmEnd = parmEnd->tokAt(2)->findClosingBracket(); + if (!parmEnd || !tok->scopeInfo()) + continue; + const int namepos = getTemplateNamePosition(parmEnd); + if (namepos > 0) + memberTemplates.insert(tok->scopeInfo()->name + " :: " + parmEnd->strAt(namepos)); + } + } + for (const Token* tok = templateInstantiation.token()->next()->findClosingBracket(); tok && tok != templateInstantiation.token(); tok = tok->previous()) { if (tok->isName()) @@ -2299,15 +2357,25 @@ void TemplateSimplifier::expandTemplate( // check for global scope if (prev->strAt(-1) != "::") { - // adjust for current scope - std::string token_scope = tok3->scopeInfo()->name; - const std::string::size_type end = token_scope.find_last_of(" :: "); - if (end != std::string::npos) { - token_scope.resize(end); - if (scope.empty()) - scope = std::move(token_scope); - else - scope = token_scope + " :: " + scope; + const std::string &generic = templateDeclaration.fullName(); + const std::string memberScope = findMemberTemplateScope(memberTemplates, generic, tok3->scopeInfo()->name, scope, tok3->str()); + if (!memberScope.empty()) { + // a member template of the new instantiation, which is declared in the next pass + const std::string instantiated = templateDeclaration.scope().empty() ? newName : (templateDeclaration.scope() + " :: " + newName); + scope = instantiated + memberScope.substr(generic.size()); + } else if (const TokenAndName *declaration = findTemplateDeclaration(tok3, scope, nullptr)) { + scope = declaration->scope(); + } else { + // adjust for current scope + std::string token_scope = tok3->scopeInfo()->name; + const std::string::size_type end = token_scope.rfind(" :: "); + if (end != std::string::npos) { + token_scope.resize(end); + if (scope.empty()) + scope = std::move(token_scope); + else + scope = token_scope + " :: " + scope; + } } } diff --git a/lib/templatesimplifier.h b/lib/templatesimplifier.h index 3dc8b6bf1fd..580b4bb3acf 100644 --- a/lib/templatesimplifier.h +++ b/lib/templatesimplifier.h @@ -355,6 +355,17 @@ class CPPCHECKLIB TemplateSimplifier { */ void addInstantiation(Token *token, const std::string &scope); + /** + * Find the template declaration that a template name refers to. The name is looked up in + * the scope of the usage first and then in each enclosing scope, innermost first. + * @param tok the template name at the usage + * @param qualification the qualification written before the name, or empty + * @param usingNamespace if not null, the using-directives in effect at the usage are tried + * too, and the one through which the declaration is found is stored here + * @return the declaration, or nullptr if there is none + */ + const TokenAndName *findTemplateDeclaration(const Token *tok, const std::string &qualification, std::string *usingNamespace) const; + /** * Get template instantiations */ diff --git a/test/testsimplifytemplate.cpp b/test/testsimplifytemplate.cpp index 407649e0c7f..2915463dfdb 100644 --- a/test/testsimplifytemplate.cpp +++ b/test/testsimplifytemplate.cpp @@ -251,6 +251,8 @@ class TestSimplifyTemplate : public TestFixture { TEST_CASE(template_namespace_11); // #7145 TEST_CASE(template_namespace_12); TEST_CASE(template_namespace_13); + TEST_CASE(template_namespace_14); // #15278 + TEST_CASE(template_namespace_15); // #15278 TEST_CASE(template_pointer_type); TEST_CASE(template_array_type); @@ -5518,6 +5520,71 @@ class TestSimplifyTemplate : public TestFixture { tok(code)); } + void template_namespace_14() { + // #15278: eleven levels, one more than the simplifier's pass limit, so A0 + // is instantiated only if each level does not cost an extra pass + const char code[] = "namespace NS {\n" + " template struct A0 { T t; };\n" + " template struct A1 { A0 m; };\n" + " template struct A2 { A1 m; };\n" + " template struct A3 { A2 m; };\n" + " template struct A4 { A3 m; };\n" + " template struct A5 { A4 m; };\n" + " template struct A6 { A5 m; };\n" + " template struct A7 { A6 m; };\n" + " template struct A8 { A7 m; };\n" + " template struct A9 { A8 m; };\n" + " template struct A10 { A9 m; };\n" + "}\n" + "NS::A10 x;\n"; + ASSERT_EQUALS("namespace NS { " + "struct A0 ; " + "struct A1 ; " + "struct A2 ; " + "struct A3 ; " + "struct A4 ; " + "struct A5 ; " + "struct A6 ; " + "struct A7 ; " + "struct A8 ; " + "struct A9 ; " + "struct A10 ; " + "} " + "NS :: A10 x ; " + "struct NS :: A10 { A9 m ; } ; " + "struct NS :: A9 { A8 m ; } ; " + "struct NS :: A8 { A7 m ; } ; " + "struct NS :: A7 { A6 m ; } ; " + "struct NS :: A6 { A5 m ; } ; " + "struct NS :: A5 { A4 m ; } ; " + "struct NS :: A4 { A3 m ; } ; " + "struct NS :: A3 { A2 m ; } ; " + "struct NS :: A2 { A1 m ; } ; " + "struct NS :: A1 { A0 m ; } ; " + "struct NS :: A0 { int t ; } ;", + tok(code)); + } + + void template_namespace_15() { + // #15278: B inside A names the member template A::B, which hides NS::B + const char code[] = "namespace NS {\n" + " template struct B { T x; };\n" + " template struct A {\n" + " template struct B { U u; };\n" + " B b;\n" + " };\n" + "}\n" + "NS::A a;\n"; + ASSERT_EQUALS("namespace NS { " + "template < class T > struct B { T x ; } ; " + "struct A ; " + "} " + "NS :: A a ; " + "struct NS :: A { struct B ; B b ; } ; " + "struct NS :: A :: B { int u ; } ;", + tok(code)); + } + void template_pointer_type() { const char code[] = "template void foo(const T x) {}\n" "void bar() { foo(0); }\n";