View Javadoc

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