1 |
| |
2 |
| |
3 |
| |
4 |
| |
5 |
| |
6 |
| package net.sourceforge.pmd.rules; |
7 |
| |
8 |
| import net.sourceforge.pmd.AbstractRule; |
9 |
| import net.sourceforge.pmd.ast.ASTConstructorDeclaration; |
10 |
| import net.sourceforge.pmd.ast.ASTFieldDeclaration; |
11 |
| import net.sourceforge.pmd.ast.ASTInitializer; |
12 |
| import net.sourceforge.pmd.ast.ASTMethodDeclaration; |
13 |
| import net.sourceforge.pmd.ast.ASTVariableDeclaratorId; |
14 |
| import net.sourceforge.pmd.ast.SimpleNode; |
15 |
| import net.sourceforge.pmd.symboltable.NameOccurrence; |
16 |
| |
17 |
| import java.util.List; |
18 |
| |
19 |
| |
20 |
| |
21 |
| |
22 |
| public class SingularField extends AbstractRule { |
23 |
| |
24 |
23
| public Object visit(ASTFieldDeclaration node, Object data) {
|
25 |
23
| if (node.isPrivate() && !node.isStatic()) {
|
26 |
18
| List list = node.findChildrenOfType(ASTVariableDeclaratorId.class);
|
27 |
18
| ASTVariableDeclaratorId declaration = (ASTVariableDeclaratorId) list.get(0);
|
28 |
18
| List usages = declaration.getUsages();
|
29 |
18
| SimpleNode decl = null;
|
30 |
18
| boolean violation = true;
|
31 |
18
| for (int ix = 0; ix < usages.size(); ix++) {
|
32 |
32
| NameOccurrence no = (NameOccurrence) usages.get(ix);
|
33 |
32
| SimpleNode location = no.getLocation();
|
34 |
| |
35 |
32
| SimpleNode method = (SimpleNode) location.getFirstParentOfType(ASTMethodDeclaration.class);
|
36 |
32
| if (method == null) {
|
37 |
3
| method = (SimpleNode) location.getFirstParentOfType(ASTConstructorDeclaration.class);
|
38 |
3
| if (method == null) {
|
39 |
2
| method = (SimpleNode) location.getFirstParentOfType(ASTInitializer.class);
|
40 |
2
| if (method == null) {
|
41 |
0
| continue;
|
42 |
| } |
43 |
| } |
44 |
| } |
45 |
| |
46 |
32
| if (decl == null) {
|
47 |
17
| decl = method;
|
48 |
17
| continue;
|
49 |
15
| } else if (decl != method) {
|
50 |
| |
51 |
9
| violation = false;
|
52 |
| } |
53 |
| } |
54 |
| |
55 |
18
| if (violation && !usages.isEmpty()) {
|
56 |
10
| addViolation(data, node, new Object[] { declaration.getImage() });
|
57 |
| } |
58 |
| } |
59 |
23
| return data;
|
60 |
| } |
61 |
| } |