Skip to content

Commit 5e3f9f3

Browse files
tsobczynskiclaude
andcommitted
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<int>, it records each template the copy uses (A0<int>) 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<class T> struct B { T x; }; template<class T> struct A { template<class U> struct B { U u; }; B<T> b; }; } B<T> 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<int>'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<int>) 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 <noreply@anthropic.com>
1 parent 35e76b5 commit 5e3f9f3

3 files changed

Lines changed: 195 additions & 49 deletions

File tree

‎lib/templatesimplifier.cpp‎

Lines changed: 117 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1006,52 +1006,60 @@ void TemplateSimplifier::getTemplateInstantiations()
10061006

10071007
// Add outer template..
10081008
if (templateParameters(tok->next()) || tok->strAt(2) == ">") {
1009-
while (true) {
1010-
std::string fullName = scopeName + (scopeName.empty()?"":" :: ") +
1011-
qualification + (qualification.empty()?"":" :: ") + tok->str();
1012-
const auto it = std::find_if(mTemplateDeclarations.cbegin(), mTemplateDeclarations.cend(), FindFullName(std::move(fullName)));
1013-
if (it != mTemplateDeclarations.end()) {
1014-
// full name matches
1015-
addInstantiation(tok, it->scope());
1016-
break;
1017-
}
1018-
// full name doesn't match so try with using namespaces if available
1019-
bool found = false;
1020-
for (const auto & nameSpace : tok->scopeInfo()->usingNamespaces) {
1021-
std::string fullNameSpace = scopeName + (scopeName.empty()?"":" :: ") +
1022-
nameSpace + (qualification.empty()?"":" :: ") + qualification;
1023-
std::string newFullName = fullNameSpace + " :: " + tok->str();
1024-
const auto it1 = std::find_if(mTemplateDeclarations.cbegin(), mTemplateDeclarations.cend(), FindFullName(std::move(newFullName)));
1025-
if (it1 != mTemplateDeclarations.end()) {
1026-
// insert using namespace into token stream
1027-
std::string::size_type offset = 0;
1028-
std::string::size_type pos = 0;
1029-
while ((pos = nameSpace.find(' ', offset)) != std::string::npos) {
1030-
qualificationTok->insertTokenBefore(nameSpace.substr(offset, pos - offset));
1031-
offset = pos + 1;
1032-
}
1033-
qualificationTok->insertTokenBefore(nameSpace.substr(offset));
1034-
qualificationTok->insertTokenBefore("::");
1035-
addInstantiation(tok, it1->scope());
1036-
found = true;
1037-
break;
1009+
std::string nameSpace;
1010+
const TokenAndName *declaration = findTemplateDeclaration(tok, qualification, &nameSpace);
1011+
if (!declaration) {
1012+
if (!qualification.empty())
1013+
addInstantiation(tok, qualification);
1014+
else
1015+
addInstantiation(tok, tok->scopeInfo()->name);
1016+
} else {
1017+
if (!nameSpace.empty()) {
1018+
// insert using namespace into token stream
1019+
std::string::size_type offset = 0;
1020+
std::string::size_type pos = 0;
1021+
while ((pos = nameSpace.find(' ', offset)) != std::string::npos) {
1022+
qualificationTok->insertTokenBefore(nameSpace.substr(offset, pos - offset));
1023+
offset = pos + 1;
10381024
}
1025+
qualificationTok->insertTokenBefore(nameSpace.substr(offset));
1026+
qualificationTok->insertTokenBefore("::");
10391027
}
1040-
if (found)
1041-
break;
1028+
addInstantiation(tok, declaration->scope());
1029+
}
1030+
}
1031+
}
1032+
}
1033+
}
10421034

1043-
if (scopeName.empty()) {
1044-
if (!qualification.empty())
1045-
addInstantiation(tok, qualification);
1046-
else
1047-
addInstantiation(tok, tok->scopeInfo()->name);
1048-
break;
1049-
}
1050-
const std::string::size_type pos = scopeName.rfind(" :: ");
1051-
scopeName = (pos == std::string::npos) ? std::string() : scopeName.substr(0,pos);
1035+
const TemplateSimplifier::TokenAndName *TemplateSimplifier::findTemplateDeclaration(const Token *tok, const std::string &qualification, std::string *usingNamespace) const
1036+
{
1037+
std::string scopeName = tok->scopeInfo()->name;
1038+
while (true) {
1039+
std::string fullName = scopeName + (scopeName.empty()?"":" :: ") +
1040+
qualification + (qualification.empty()?"":" :: ") + tok->str();
1041+
const auto it = std::find_if(mTemplateDeclarations.cbegin(), mTemplateDeclarations.cend(), FindFullName(std::move(fullName)));
1042+
if (it != mTemplateDeclarations.cend())
1043+
return &*it;
1044+
1045+
// full name doesn't match so try with using namespaces if available
1046+
if (usingNamespace) {
1047+
for (const auto & nameSpace : tok->scopeInfo()->usingNamespaces) {
1048+
std::string fullNameSpace = scopeName + (scopeName.empty()?"":" :: ") +
1049+
nameSpace + (qualification.empty()?"":" :: ") + qualification;
1050+
std::string newFullName = fullNameSpace + " :: " + tok->str();
1051+
const auto it1 = std::find_if(mTemplateDeclarations.cbegin(), mTemplateDeclarations.cend(), FindFullName(std::move(newFullName)));
1052+
if (it1 != mTemplateDeclarations.cend()) {
1053+
*usingNamespace = nameSpace;
1054+
return &*it1;
10521055
}
10531056
}
10541057
}
1058+
1059+
if (scopeName.empty())
1060+
return nullptr;
1061+
const std::string::size_type pos = scopeName.rfind(" :: ");
1062+
scopeName = (pos == std::string::npos) ? std::string() : scopeName.substr(0,pos);
10551063
}
10561064
}
10571065

@@ -1646,6 +1654,35 @@ struct newInstantiation {
16461654
std::string scope;
16471655
};
16481656

1657+
/**
1658+
* Find the member template that a template name used inside a class template refers to. The
1659+
* name is looked up in the scope of the usage first and then in each enclosing scope, out to the
1660+
* class template itself.
1661+
* @param memberTemplates full names of the templates declared inside the class template
1662+
* @param classTemplate full name of the class template
1663+
* @param scopeName scope of the usage
1664+
* @param qualification qualification written before the name, or empty
1665+
* @param name the template name
1666+
* @return the scope of the member template, or empty if the name does not refer to one
1667+
*/
1668+
static std::string findMemberTemplateScope(const std::set<std::string> &memberTemplates,
1669+
const std::string &classTemplate,
1670+
std::string scopeName,
1671+
const std::string &qualification,
1672+
const std::string &name)
1673+
{
1674+
if (memberTemplates.empty() || (scopeName != classTemplate && !startsWith(scopeName, classTemplate + " :: ")))
1675+
return "";
1676+
while (true) {
1677+
std::string scope = scopeName + (qualification.empty() ? "" : " :: ") + qualification;
1678+
if (memberTemplates.count(scope + " :: " + name) > 0)
1679+
return scope;
1680+
if (scopeName.size() == classTemplate.size())
1681+
return "";
1682+
scopeName.resize(scopeName.rfind(" :: "));
1683+
}
1684+
}
1685+
16491686
void TemplateSimplifier::expandTemplate(
16501687
const TokenAndName &templateDeclaration,
16511688
const TokenAndName &templateInstantiation,
@@ -1665,6 +1702,27 @@ void TemplateSimplifier::expandTemplate(
16651702

16661703
std::vector<newInstantiation> newInstantiations;
16671704

1705+
// Full names of the templates declared inside the class template. They hide templates of the
1706+
// same name in enclosing scopes, but they are not in mTemplateDeclarations until the class
1707+
// template has been instantiated.
1708+
std::set<std::string> memberTemplates;
1709+
if (isClass) {
1710+
const Token * const end = findTemplateDeclarationEnd(templateDeclaration.token());
1711+
for (const Token *tok = templateDeclarationToken->next(); tok && tok != end; tok = tok->next()) {
1712+
// skip template template parameters and the inner lists of "template <..> template <..>"
1713+
if (!Token::simpleMatch(tok, "template <") || Token::Match(tok->previous(), "<|,|>"))
1714+
continue;
1715+
const Token *parmEnd = tok->next()->findClosingBracket();
1716+
while (Token::simpleMatch(parmEnd, "> template <"))
1717+
parmEnd = parmEnd->tokAt(2)->findClosingBracket();
1718+
if (!parmEnd || !tok->scopeInfo())
1719+
continue;
1720+
const int namepos = getTemplateNamePosition(parmEnd);
1721+
if (namepos > 0)
1722+
memberTemplates.insert(tok->scopeInfo()->name + " :: " + parmEnd->strAt(namepos));
1723+
}
1724+
}
1725+
16681726
for (const Token* tok = templateInstantiation.token()->next()->findClosingBracket();
16691727
tok && tok != templateInstantiation.token(); tok = tok->previous()) {
16701728
if (tok->isName())
@@ -2299,15 +2357,25 @@ void TemplateSimplifier::expandTemplate(
22992357

23002358
// check for global scope
23012359
if (prev->strAt(-1) != "::") {
2302-
// adjust for current scope
2303-
std::string token_scope = tok3->scopeInfo()->name;
2304-
const std::string::size_type end = token_scope.find_last_of(" :: ");
2305-
if (end != std::string::npos) {
2306-
token_scope.resize(end);
2307-
if (scope.empty())
2308-
scope = std::move(token_scope);
2309-
else
2310-
scope = token_scope + " :: " + scope;
2360+
const std::string &generic = templateDeclaration.fullName();
2361+
const std::string memberScope = findMemberTemplateScope(memberTemplates, generic, tok3->scopeInfo()->name, scope, tok3->str());
2362+
if (!memberScope.empty()) {
2363+
// a member template of the new instantiation, which is declared in the next pass
2364+
const std::string instantiated = templateDeclaration.scope().empty() ? newName : (templateDeclaration.scope() + " :: " + newName);
2365+
scope = instantiated + memberScope.substr(generic.size());
2366+
} else if (const TokenAndName *declaration = findTemplateDeclaration(tok3, scope, nullptr)) {
2367+
scope = declaration->scope();
2368+
} else {
2369+
// adjust for current scope
2370+
std::string token_scope = tok3->scopeInfo()->name;
2371+
const std::string::size_type end = token_scope.rfind(" :: ");
2372+
if (end != std::string::npos) {
2373+
token_scope.resize(end);
2374+
if (scope.empty())
2375+
scope = std::move(token_scope);
2376+
else
2377+
scope = token_scope + " :: " + scope;
2378+
}
23112379
}
23122380
}
23132381

‎lib/templatesimplifier.h‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -355,6 +355,17 @@ class CPPCHECKLIB TemplateSimplifier {
355355
*/
356356
void addInstantiation(Token *token, const std::string &scope);
357357

358+
/**
359+
* Find the template declaration that a template name refers to. The name is looked up in
360+
* the scope of the usage first and then in each enclosing scope, innermost first.
361+
* @param tok the template name at the usage
362+
* @param qualification the qualification written before the name, or empty
363+
* @param usingNamespace if not null, the using-directives in effect at the usage are tried
364+
* too, and the one through which the declaration is found is stored here
365+
* @return the declaration, or nullptr if there is none
366+
*/
367+
const TokenAndName *findTemplateDeclaration(const Token *tok, const std::string &qualification, std::string *usingNamespace) const;
368+
358369
/**
359370
* Get template instantiations
360371
*/

‎test/testsimplifytemplate.cpp‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,8 @@ class TestSimplifyTemplate : public TestFixture {
251251
TEST_CASE(template_namespace_11); // #7145
252252
TEST_CASE(template_namespace_12);
253253
TEST_CASE(template_namespace_13);
254+
TEST_CASE(template_namespace_14); // #15278
255+
TEST_CASE(template_namespace_15); // #15278
254256
TEST_CASE(template_pointer_type);
255257
TEST_CASE(template_array_type);
256258

@@ -5518,6 +5520,71 @@ class TestSimplifyTemplate : public TestFixture {
55185520
tok(code));
55195521
}
55205522

5523+
void template_namespace_14() {
5524+
// #15278: eleven levels, one more than the simplifier's pass limit, so A0
5525+
// is instantiated only if each level does not cost an extra pass
5526+
const char code[] = "namespace NS {\n"
5527+
" template<class T> struct A0 { T t; };\n"
5528+
" template<class T> struct A1 { A0<T> m; };\n"
5529+
" template<class T> struct A2 { A1<T> m; };\n"
5530+
" template<class T> struct A3 { A2<T> m; };\n"
5531+
" template<class T> struct A4 { A3<T> m; };\n"
5532+
" template<class T> struct A5 { A4<T> m; };\n"
5533+
" template<class T> struct A6 { A5<T> m; };\n"
5534+
" template<class T> struct A7 { A6<T> m; };\n"
5535+
" template<class T> struct A8 { A7<T> m; };\n"
5536+
" template<class T> struct A9 { A8<T> m; };\n"
5537+
" template<class T> struct A10 { A9<T> m; };\n"
5538+
"}\n"
5539+
"NS::A10<int> x;\n";
5540+
ASSERT_EQUALS("namespace NS { "
5541+
"struct A0<int> ; "
5542+
"struct A1<int> ; "
5543+
"struct A2<int> ; "
5544+
"struct A3<int> ; "
5545+
"struct A4<int> ; "
5546+
"struct A5<int> ; "
5547+
"struct A6<int> ; "
5548+
"struct A7<int> ; "
5549+
"struct A8<int> ; "
5550+
"struct A9<int> ; "
5551+
"struct A10<int> ; "
5552+
"} "
5553+
"NS :: A10<int> x ; "
5554+
"struct NS :: A10<int> { A9<int> m ; } ; "
5555+
"struct NS :: A9<int> { A8<int> m ; } ; "
5556+
"struct NS :: A8<int> { A7<int> m ; } ; "
5557+
"struct NS :: A7<int> { A6<int> m ; } ; "
5558+
"struct NS :: A6<int> { A5<int> m ; } ; "
5559+
"struct NS :: A5<int> { A4<int> m ; } ; "
5560+
"struct NS :: A4<int> { A3<int> m ; } ; "
5561+
"struct NS :: A3<int> { A2<int> m ; } ; "
5562+
"struct NS :: A2<int> { A1<int> m ; } ; "
5563+
"struct NS :: A1<int> { A0<int> m ; } ; "
5564+
"struct NS :: A0<int> { int t ; } ;",
5565+
tok(code));
5566+
}
5567+
5568+
void template_namespace_15() {
5569+
// #15278: B<T> inside A names the member template A::B, which hides NS::B
5570+
const char code[] = "namespace NS {\n"
5571+
" template<class T> struct B { T x; };\n"
5572+
" template<class T> struct A {\n"
5573+
" template<class U> struct B { U u; };\n"
5574+
" B<T> b;\n"
5575+
" };\n"
5576+
"}\n"
5577+
"NS::A<int> a;\n";
5578+
ASSERT_EQUALS("namespace NS { "
5579+
"template < class T > struct B { T x ; } ; "
5580+
"struct A<int> ; "
5581+
"} "
5582+
"NS :: A<int> a ; "
5583+
"struct NS :: A<int> { struct B<int> ; B<int> b ; } ; "
5584+
"struct NS :: A<int> :: B<int> { int u ; } ;",
5585+
tok(code));
5586+
}
5587+
55215588
void template_pointer_type() {
55225589
const char code[] = "template<class T> void foo(const T x) {}\n"
55235590
"void bar() { foo<int*>(0); }\n";

0 commit comments

Comments
 (0)