Skip to content

Commit 29c331d

Browse files
committed
fix UsingNamespaceInHeaderCheck
1 parent 2f063fe commit 29c331d

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

cxx-checks/src/main/java/org/sonar/cxx/checks/UsingNamespaceInHeaderCheck.java

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -68,10 +68,14 @@ public void visitFile(AstNode astNode) {
6868
@Override
6969
public void visitNode(AstNode node) {
7070
if (isHeader) {
71-
final boolean containsNamespace = node.getChildren().stream()
72-
.anyMatch(childNode -> CxxKeyword.NAMESPACE.equals(childNode.getToken().getType()));
73-
if (containsNamespace) {
74-
getContext().createLineViolation(this, "Using namespace are not allowed in header files.", node);
71+
// declaration directly in translation unit
72+
if (node.getParent().is(CxxGrammarImpl.declaration)
73+
&& node.getParent().getParent().is(CxxGrammarImpl.translationUnit)) {
74+
final boolean containsNamespace = node.getChildren().stream()
75+
.anyMatch(childNode -> CxxKeyword.NAMESPACE.equals(childNode.getToken().getType()));
76+
if (containsNamespace) {
77+
getContext().createLineViolation(this, "Using namespace are not allowed in header files.", node);
78+
}
7579
}
7680
}
7781
}

cxx-checks/src/test/resources/checks/UsingNamespaceInHeader.h

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ namespace Foo
88
void fooFunc( );
99
}
1010

11-
using namespace std;
11+
using namespace std; // error
1212

1313
// alias for types or template shall not be detected
1414
// see more details http://en.cppreference.com/w/cpp/language/type_alias
@@ -30,3 +30,13 @@ namespace Foo
3030
privateFunction( );
3131
}
3232
}
33+
34+
void fooFunc()
35+
{
36+
using namespace std;
37+
}
38+
39+
namespace X
40+
{
41+
using namespace std;
42+
};

0 commit comments

Comments
 (0)