Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
166 changes: 117 additions & 49 deletions lib/templatesimplifier.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand Down Expand Up @@ -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<std::string> &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,
Expand All @@ -1665,6 +1702,27 @@ void TemplateSimplifier::expandTemplate(

std::vector<newInstantiation> 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<std::string> 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())
Expand Down Expand Up @@ -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)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

Resolving names through findTemplateDeclaration during the expansion creates the namespace-level B<int> in the same pass. The member's B<int>, which can only be resolved in the next pass, then appears to be dropped because the name is taken. So the template_namespace_15 case breaks as soon as the class template also uses NS::B<T>:

namespace NS {
    template<class T> struct B { T x; };
    template<class T> struct A {
        template<class U> struct B { U u; };
        B<T> b;
        NS::B<T> c;
    };
}
NS::A<int> a;
  • Base instantiates struct NS :: A<int> :: B<int> { int u ; }, so b is right.
  • The PR instantiates only struct NS :: B<int> { int x ; } and leaves template < class U > struct B { U u ; } uninstantiated inside A<int>.

The same happens with B<T> b; Inner::B<T> c; where Inner declares template<class U> struct B: base creates A<int> :: Inner :: B<int>, but the PR doesn't. Could you add these as tests?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed, thanks. With this PR both examples create NS :: B<int> and not the other B<int>. On main it is the other way round, so neither creates both.

The other instantiation is lost in replaceTemplateUsage. When NS :: B<int> is expanded, the usage of the other template is recorded with a different full name, but the "fallback to just matching name" renames it anyway, and that template is then never instantiated. main avoids this only because it never instantiates NS::B in these examples. With that fallback removed, both instantiations are created in both examples and testrunner passes.

That fallback is Trac #15263, so I've kept its fix out of this PR. I've added your two examples as template_namespace_16 and template_namespace_17 with TODO_ASSERT_EQUALS, giving the output wanted once that ticket is fixed.

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;
}
}
}

Expand Down
11 changes: 11 additions & 0 deletions lib/templatesimplifier.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down
127 changes: 127 additions & 0 deletions test/testsimplifytemplate.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,10 @@ 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_namespace_16); // #15263
TEST_CASE(template_namespace_17); // #15263
TEST_CASE(template_pointer_type);
TEST_CASE(template_array_type);

Expand Down Expand Up @@ -5518,6 +5522,129 @@ 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<class T> struct A0 { T t; };\n"
" template<class T> struct A1 { A0<T> m; };\n"
" template<class T> struct A2 { A1<T> m; };\n"
" template<class T> struct A3 { A2<T> m; };\n"
" template<class T> struct A4 { A3<T> m; };\n"
" template<class T> struct A5 { A4<T> m; };\n"
" template<class T> struct A6 { A5<T> m; };\n"
" template<class T> struct A7 { A6<T> m; };\n"
" template<class T> struct A8 { A7<T> m; };\n"
" template<class T> struct A9 { A8<T> m; };\n"
" template<class T> struct A10 { A9<T> m; };\n"
"}\n"
"NS::A10<int> x;\n";
ASSERT_EQUALS("namespace NS { "
"struct A0<int> ; "
"struct A1<int> ; "
"struct A2<int> ; "
"struct A3<int> ; "
"struct A4<int> ; "
"struct A5<int> ; "
"struct A6<int> ; "
"struct A7<int> ; "
"struct A8<int> ; "
"struct A9<int> ; "
"struct A10<int> ; "
"} "
"NS :: A10<int> x ; "
"struct NS :: A10<int> { A9<int> m ; } ; "
"struct NS :: A9<int> { A8<int> m ; } ; "
"struct NS :: A8<int> { A7<int> m ; } ; "
"struct NS :: A7<int> { A6<int> m ; } ; "
"struct NS :: A6<int> { A5<int> m ; } ; "
"struct NS :: A5<int> { A4<int> m ; } ; "
"struct NS :: A4<int> { A3<int> m ; } ; "
"struct NS :: A3<int> { A2<int> m ; } ; "
"struct NS :: A2<int> { A1<int> m ; } ; "
"struct NS :: A1<int> { A0<int> m ; } ; "
"struct NS :: A0<int> { int t ; } ;",
tok(code));
}

void template_namespace_15() {
// #15278: B<T> inside A names the member template A::B, which hides NS::B
const char code[] = "namespace NS {\n"
" template<class T> struct B { T x; };\n"
" template<class T> struct A {\n"
" template<class U> struct B { U u; };\n"
" B<T> b;\n"
" };\n"
"}\n"
"NS::A<int> a;\n";
ASSERT_EQUALS("namespace NS { "
"template < class T > struct B { T x ; } ; "
"struct A<int> ; "
"} "
"NS :: A<int> a ; "
"struct NS :: A<int> { struct B<int> ; B<int> b ; } ; "
"struct NS :: A<int> :: B<int> { int u ; } ;",
tok(code));
}

void template_namespace_16() {
// #15263: A uses its member template B and NS::B with the same argument
const char code[] = "namespace NS {\n"
" template<class T> struct B { T x; };\n"
" template<class T> struct A {\n"
" template<class U> struct B { U u; };\n"
" B<T> b;\n"
" NS::B<T> c;\n"
" };\n"
"}\n"
"NS::A<int> a;\n";
const char wanted[] = "namespace NS { "
"struct B<int> ; "
"struct A<int> ; "
"} "
"NS :: A<int> a ; "
"struct NS :: A<int> { struct B<int> ; B<int> b ; NS :: B<int> c ; } ; "
"struct NS :: B<int> { int x ; } ; "
"struct NS :: A<int> :: B<int> { int u ; } ;";
const char current[] = "namespace NS { "
"struct B<int> ; "
"struct A<int> ; "
"} "
"NS :: A<int> a ; "
"struct NS :: A<int> { template < class U > struct B { U u ; } ; B<int> b ; NS :: B<int> c ; } ; "
"struct NS :: B<int> { int x ; } ;";
TODO_ASSERT_EQUALS(wanted, current, tok(code));
}

void template_namespace_17() {
// #15263: A uses NS::B and a member template B of its nested class with the same argument
const char code[] = "namespace NS {\n"
" template<class T> struct B { T x; };\n"
" template<class T> struct A {\n"
" struct Inner { template<class U> struct B { U u; }; };\n"
" B<T> b;\n"
" Inner::B<T> c;\n"
" };\n"
"}\n"
"NS::A<int> a;\n";
const char wanted[] = "namespace NS { "
"struct B<int> ; "
"struct A<int> ; "
"} "
"NS :: A<int> a ; "
"struct NS :: A<int> { struct Inner { struct B<int> ; } ; B<int> b ; Inner :: B<int> c ; } ; "
"struct NS :: B<int> { int x ; } ; "
"struct NS :: A<int> :: Inner :: B<int> { int u ; } ;";
const char current[] = "namespace NS { "
"struct B<int> ; "
"struct A<int> ; "
"} "
"NS :: A<int> a ; "
"struct NS :: A<int> { struct Inner { template < class U > struct B { U u ; } ; } ; B<int> b ; Inner :: B<int> c ; } ; "
"struct NS :: B<int> { int x ; } ;";
TODO_ASSERT_EQUALS(wanted, current, tok(code));
}

void template_pointer_type() {
const char code[] = "template<class T> void foo(const T x) {}\n"
"void bar() { foo<int*>(0); }\n";
Expand Down