1 package net.sourceforge.pmd.rules.strings;
2
3 import net.sourceforge.pmd.AbstractRule;
4 import net.sourceforge.pmd.ast.ASTAdditiveExpression;
5 import net.sourceforge.pmd.ast.ASTAllocationExpression;
6 import net.sourceforge.pmd.ast.ASTArrayDimsAndInits;
7 import net.sourceforge.pmd.ast.ASTClassOrInterfaceType;
8 import net.sourceforge.pmd.ast.ASTExpression;
9 import net.sourceforge.pmd.ast.ASTName;
10 import net.sourceforge.pmd.symboltable.NameDeclaration;
11 import net.sourceforge.pmd.symboltable.VariableNameDeclaration;
12 import net.sourceforge.pmd.typeresolution.TypeHelper;
13
14 import java.util.List;
15
16 public class StringInstantiation extends AbstractRule {
17
18 public Object visit(ASTAllocationExpression node, Object data) {
19 if (!(node.jjtGetChild(0) instanceof ASTClassOrInterfaceType)) {
20 return data;
21 }
22
23 if (!TypeHelper.isA((ASTClassOrInterfaceType) node.jjtGetChild(0), String.class)) {
24 return data;
25 }
26
27 List exp = node.findChildrenOfType(ASTExpression.class);
28 if (exp.size() >= 2) {
29 return data;
30 }
31
32 if (node.getFirstChildOfType(ASTArrayDimsAndInits.class) != null || node.getFirstChildOfType(ASTAdditiveExpression.class) != null) {
33 return data;
34 }
35
36 ASTName name =node.getFirstChildOfType(ASTName.class);
37
38 if (name == null) {
39 addViolation(data, node);
40 return data;
41 }
42
43 NameDeclaration nd = name.getNameDeclaration();
44 if (!(nd instanceof VariableNameDeclaration)) {
45 return data;
46 }
47
48 VariableNameDeclaration vnd = (VariableNameDeclaration) nd;
49
50 if (vnd == null || TypeHelper.isA(vnd, String.class)) {
51 addViolation(data, node);
52 }
53 return data;
54 }
55 }