View Javadoc

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