1 |
| |
2 |
| |
3 |
| |
4 |
| |
5 |
| |
6 |
| |
7 |
| package net.sourceforge.pmd.rules; |
8 |
| |
9 |
| import net.sourceforge.pmd.AbstractRule; |
10 |
| import net.sourceforge.pmd.ast.ASTClassOrInterfaceDeclaration; |
11 |
| import net.sourceforge.pmd.ast.ASTConstructorDeclaration; |
12 |
| import net.sourceforge.pmd.ast.ASTFieldDeclaration; |
13 |
| import net.sourceforge.pmd.ast.ASTMethodDeclaration; |
14 |
| import net.sourceforge.pmd.ast.ASTMethodDeclarator; |
15 |
| import net.sourceforge.pmd.ast.ASTVariableDeclaratorId; |
16 |
| import org.jaxen.JaxenException; |
17 |
| |
18 |
| import java.util.List; |
19 |
| |
20 |
| |
21 |
| |
22 |
| |
23 |
| public class SingularField extends AbstractRule { |
24 |
| |
25 |
8
| public Object visit(ASTFieldDeclaration node, Object data) {
|
26 |
8
| if (node.isPrivate() && !node.isStatic()) {
|
27 |
4
| List list = node.findChildrenOfType(ASTVariableDeclaratorId.class);
|
28 |
4
| ASTVariableDeclaratorId decl = (ASTVariableDeclaratorId) list.get(0);
|
29 |
4
| String name = decl.getImage();
|
30 |
4
| String path = "//MethodDeclaration[.//PrimaryExpression[.//Name[@Image = \"" + name + "\" or substring-before(@Image, \".\") = \"" + name + "\"] or .//PrimarySuffix[@Image = \"" + name + "\"]]] |" +
|
31 |
| "//ConstructorDeclaration[.//PrimaryExpression[.//Name[@Image = \"" + name + "\" or substring-before(@Image, \".\") = \"" + name + "\"] or .//PrimarySuffix[@Image = \"" + name + "\"]]]"; |
32 |
4
| try {
|
33 |
4
| List nodes = node.findChildNodesWithXPath(path);
|
34 |
4
| if (nodes.size() == 1) {
|
35 |
1
| String method;
|
36 |
1
| if (nodes.get(0) instanceof ASTMethodDeclaration) {
|
37 |
1
| method = ((ASTMethodDeclarator) ((ASTMethodDeclaration) nodes.get(0)).findChildrenOfType(ASTMethodDeclarator.class).get(0)).getImage();
|
38 |
| } else { |
39 |
0
| ASTConstructorDeclaration astConstructorDeclaration = (ASTConstructorDeclaration) nodes.get(0);
|
40 |
0
| ASTClassOrInterfaceDeclaration astClassOrInterfaceDeclaration = (ASTClassOrInterfaceDeclaration) astConstructorDeclaration.getFirstParentOfType(ASTClassOrInterfaceDeclaration.class);
|
41 |
0
| if (astClassOrInterfaceDeclaration == null) {
|
42 |
0
| return data;
|
43 |
| } |
44 |
0
| method = astClassOrInterfaceDeclaration.getImage();
|
45 |
| } |
46 |
1
| addViolation(data, decl, new Object[]{name, method});
|
47 |
| } |
48 |
| } catch (JaxenException je) { |
49 |
0
| je.printStackTrace();
|
50 |
| } |
51 |
| } |
52 |
8
| return data;
|
53 |
| } |
54 |
| |
55 |
| } |