Skip to content

Commit

Permalink
[clang-tidy] Fix nested namespaces in `readability-static-definition-…
Browse files Browse the repository at this point in the history
…in-anonymous-namespace` check

The check previously inspected only the immediate parent namespace.
`static` in a named namespace within an unnamed namespace is still
redundant.
We will use `Decl::isInAnonymousNamespace()` method that traverses the
namespaces hierarchy recursively.

Differential Revision: https://reviews.llvm.org/D118010
  • Loading branch information
Izaron authored and LegalizeAdulthood committed Jan 27, 2022
1 parent ecb5023 commit 836950c
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
Expand Up @@ -17,12 +17,16 @@ namespace clang {
namespace tidy {
namespace readability {

AST_MATCHER(NamedDecl, isInAnonymousNamespace) {
return Node.isInAnonymousNamespace();
}

void StaticDefinitionInAnonymousNamespaceCheck::registerMatchers(
MatchFinder *Finder) {
Finder->addMatcher(
namedDecl(anyOf(functionDecl(isDefinition(), isStaticStorageClass()),
varDecl(isDefinition(), isStaticStorageClass())),
hasParent(namespaceDecl(isAnonymous())))
isInAnonymousNamespace())
.bind("static-def"),
this);
}
Expand Down
Expand Up @@ -12,7 +12,10 @@ visibility of definitions to a single translation unit.

namespace {
static int a = 1; // Warning.
static const b = 1; // Warning.
static const int b = 1; // Warning.
namespace inner {
static int c = 1; // Warning.
}
}

The check will apply a fix by removing the redundant ``static`` qualifier.
Expand Up @@ -36,6 +36,21 @@ DEFINE_STATIC int h = 1;
DEFINE_STATIC_VAR(i);
// CHECK-FIXES: {{^}}DEFINE_STATIC_VAR(i);

namespace inner {
int a = 1;
const int b = 1;
static int c = 1;
// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: 'c' is a static definition in anonymous namespace; static is redundant here [readability-static-definition-in-anonymous-namespace]
// CHECK-FIXES: {{^}}int c = 1;
namespace deep_inner {
int a = 1;
const int b = 1;
static int c = 1;
// CHECK-MESSAGES: :[[@LINE-1]]:12: warning: 'c' is a static definition in anonymous namespace; static is redundant here [readability-static-definition-in-anonymous-namespace]
// CHECK-FIXES: {{^}}int c = 1;
} // namespace deep_inner
} // namespace inner

} // namespace

namespace N {
Expand Down

0 comments on commit 836950c

Please sign in to comment.