Simplify empty anonymous namespaces. (#2673)

This commit is contained in:
Simon Martin 2020-06-07 13:49:04 +02:00 committed by GitHub
parent a45c7752a5
commit 1705d096f7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 22 additions and 8 deletions

View File

@ -5375,10 +5375,11 @@ void Tokenizer::simplifyEmptyNamespaces()
tok = tok->link();
continue;
}
if (!Token::Match(tok, "namespace %name% {"))
if (!Token::Match(tok, "namespace %name%| {"))
continue;
if (tok->strAt(3) == "}") {
tok->deleteNext(3); // remove '%name% { }'
bool isAnonymousNS = tok->strAt(1) == "{";
if (tok->strAt(3 - isAnonymousNS) == "}") {
tok->deleteNext(3 - isAnonymousNS); // remove '%name%| { }'
if (!tok->previous()) {
// remove 'namespace' or replace it with ';' if isolated
tok->deleteThis();
@ -5386,9 +5387,14 @@ void Tokenizer::simplifyEmptyNamespaces()
} else { // '%any% namespace %any%'
tok = tok->previous(); // goto previous token
tok->deleteNext(); // remove next token: 'namespace'
if (tok->str() == "{") {
// Go back in case we were within a namespace that's empty now
tok = tok->tokAt(-2) ? tok->tokAt(-2) : tok->previous();
goback = true;
}
}
} else {
tok = tok->tokAt(2);
tok = tok->tokAt(2 - isAnonymousNS);
}
}
}

View File

@ -512,9 +512,7 @@ private:
" _LONG A;\n"
"}";
const char exp[] = "namespace NS1 { "
"} "
"void f1 ( ) { "
const char exp[] = "void f1 ( ) { "
"using namespace NS1 ; "
"signed long long A ; "
"} "

View File

@ -443,6 +443,8 @@ private:
TEST_CASE(simplifyCaseRange);
TEST_CASE(simplifyEmptyNamespaces);
TEST_CASE(compileLimits); // #5592 crash: gcc: testsuit: gcc.c-torture/compile/limits-declparen.c
TEST_CASE(prepareTernaryOpForAST);
@ -6621,7 +6623,7 @@ private:
// remove some unhandled macros in the global scope.
ASSERT_EQUALS("void f ( ) { }", tokenizeAndStringify("void f() NOTHROW { }"));
ASSERT_EQUALS("struct Foo { } ;", tokenizeAndStringify("struct __declspec(dllexport) Foo {};"));
ASSERT_EQUALS("namespace { }", tokenizeAndStringify("ABA() namespace { }"));
ASSERT_EQUALS("namespace { int a ; }", tokenizeAndStringify("ABA() namespace { int a ; }"));
// #3750
ASSERT_THROW(tokenizeAndStringify("; AB(foo*) foo::foo() { }"), InternalError);
@ -7365,6 +7367,14 @@ private:
ASSERT_EQUALS("void f ( ) { switch ( x ) { case '[' : case '\\\\' : case ']' : ; } }", tokenizeAndStringify("void f() { switch(x) { case '[' ... ']': } }"));
}
void simplifyEmptyNamespaces() {
ASSERT_EQUALS("", tokenizeAndStringify("namespace { }"));
ASSERT_EQUALS("", tokenizeAndStringify("namespace foo { }"));
ASSERT_EQUALS("", tokenizeAndStringify("namespace foo { namespace { } }"));
ASSERT_EQUALS("", tokenizeAndStringify("namespace { namespace { } }")); // Ticket #9512
ASSERT_EQUALS("", tokenizeAndStringify("namespace foo { namespace bar { } }"));
}
void prepareTernaryOpForAST() {
ASSERT_EQUALS("a ? b : c ;", tokenizeAndStringify("a ? b : c;"));