Skip to content

Commit a4b55a1

Browse files
authored
Merge pull request #1667 from guwirth/optimize-AST
optimize AST
2 parents 19be9a5 + 23bbf40 commit a4b55a1

File tree

4 files changed

+211
-96
lines changed

4 files changed

+211
-96
lines changed

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242
public class BooleanEqualityComparisonCheck extends SquidCheck<Grammar> {
4343

4444
private static boolean hasBooleanLiteralOperand(AstNode node) {
45-
return node.hasDirectChildren(CxxGrammarImpl.LITERAL, CxxGrammarImpl.BOOL)
45+
return node.hasDirectChildren(CxxGrammarImpl.BOOL)
4646
&& node.hasDescendant(CxxKeyword.TRUE, CxxKeyword.FALSE);
4747
}
4848

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

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ private static boolean isHeader(String name) {
5757

5858
@Override
5959
public void init() {
60-
subscribeTo(CxxGrammarImpl.blockDeclaration);
60+
subscribeTo(CxxGrammarImpl.usingDirective);
6161
}
6262

6363
@Override
@@ -67,11 +67,15 @@ public void visitFile(AstNode astNode) {
6767

6868
@Override
6969
public void visitNode(AstNode node) {
70-
if (isHeader && CxxKeyword.USING.equals(node.getToken().getType())) {
71-
final boolean containsNamespace = node.getFirstChild().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);
70+
if (isHeader) {
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)